Code

Modified certificate check.
[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       }
120     }
122     /* Create me for new accounts */
123     if ($dn == "new"){
124       $this->is_account= TRUE;
125     }
127     /* Make hash default to md5 if not set in config */
128     if (!isset($this->config->current['HASH'])){
129       $hash= "md5";
130     } else {
131       $hash= $this->config->current['HASH'];
132     }
134     /* Load data from LDAP? */
135     if ($dn != NULL){
137       /* Do base conversation */
138       if ($this->dn == "new"){
139         $ui= get_userinfo();
140         $this->base= dn2base($ui->dn);
141       } else {
142         $this->base= dn2base($dn);
143       }
145       /* get password storage type */
146       if (isset ($this->attrs['userPassword'][0])){
147         if (preg_match ("/^{([^}]+)}(.+)/", $this->attrs['userPassword'][0], $matches)){
148           $this->pw_storage= strtolower($matches[1]);
149         } else {
150           if ($this->attrs['userPassword'][0] != ""){
151             $this->pw_storage= "clear";
152           } else {
153             $this->pw_storage= $hash;
154           }
155         }
156       } else {
157         /* Preset with vaule from configuration */
158         $this->pw_storage= $hash;
159       }
161       /* Load extra attributes: certificate and picture */
162       $this->load_picture();
163       $this->load_cert();
164       if ($this->userCertificate != ""){
165         $this->had_userCertificate= TRUE;
166       }
167     }
169     /* Reset password storage indicator, used by password_change_needed() */
170     if ($dn == "new"){
171       $this->last_pw_storage= "unset";
172     } else {
173       $this->last_pw_storage= $this->pw_storage;
174     }
176     /* Generate dob entry */
177     if (isset ($this->attrs['dateOfBirth'])){
178       /* This entry is ISO 8601 conform */
179       list($year, $month, $day)= split("-", $this->attrs['dateOfBirth'][0], 3);
180       $this->dob= mktime ( 0, 0, 0, $month, $day, $year);
181       $this->use_dob= "1";
182     } else {
183       $this->use_dob= "0";
184     }
186     /* Put gender attribute to upper case */
187     if (isset ($this->attrs['gender'])){
188       $this->gender= strtoupper($this->attrs['gender'][0]);
189     }   
190   }
193   /* execute generates the html output for this node */
194   function execute()
195   {
196     $smarty= get_smarty();
198     /* Fill calendar */
199     if ($this->dob == "0"){
200       $date= getdate();
201     } else {
202       $date= getdate($this->dob);
203     }
205     $days= array();
206     for($d= 1; $d<32; $d++){
207       $days[$d]= $d;
208     }
209     $years= array();
210     for($y= $date['year']-100; $y<=$date['year']+100; $y++){
211       $years[]= $y;
212     }
213     $years['-']= "";
214     $months= array(_("January"), _("February"), _("March"), _("April"),
215         _("May"), _("June"), _("July"), _("August"), _("September"),
216         _("October"), _("November"), _("December"), '-' => '');
217     $smarty->assign("day", $date["mday"]);
218     $smarty->assign("days", $days);
219     $smarty->assign("months", $months);
220     $smarty->assign("month", $date["mon"]-1);
221     $smarty->assign("years", $years);
222     $smarty->assign("year", $date["year"]);
224     /* Assign sex */
225     $sex= array(0 => "", "F" => _("female"), "M" => _("male"));
226     $smarty->assign("gender_list", $sex);
228     /* Get random number for pictures */
229     srand((double)microtime()*1000000); 
230     $smarty->assign("rand", rand(0, 10000));
232     /* Do we represent a valid gosaAccount? */
233     if (!$this->is_account){
234       echo "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
235         _("This account has no valid GOsa extensions.")."</b>";
236       return;
237     }
239     /* Want picture edit dialog? */
240     if (isset($_POST['edit_picture'])){
241       /* Save values for later recovery, in case some presses
242          the cancel button. */
243       $this->old_jpegPhoto= $this->jpegPhoto;
244       $this->old_photoData= $this->photoData;
245       $this->picture_dialog= TRUE;
246       $this->dialog= TRUE;
247     }
249     /* Remove picture? */
250     if (isset($_POST['picture_remove'])){
251       $this->jpegPhoto= "*removed*";
252       $this->set_picture ("./images/default.jpg");
253       $this->is_modified= TRUE;
255       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
256     }
258     /* Save picture */
259     if (isset($_POST['picture_edit_finish'])){
261       /* Check for clean upload */
262       if ($_FILES['picture_file']['name'] != ""){
263         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
264           print_red(_("The specified file has not been uploaded via HTTP POST! Aborted."));
265           exit;
266         }
268         /* Activate new picture */
269         $this->set_picture($_FILES['picture_file']['tmp_name']);
270       }
271       $this->picture_dialog= FALSE;
272       $this->dialog= FALSE;
273       $this->is_modified= TRUE;
274     }
277     /* Cancel picture */
278     if (isset($_POST['picture_edit_cancel'])){
280       /* Restore values */
281       $this->jpegPhoto= $this->old_jpegPhoto;
282       $this->photoData= $this->old_photoData;
284       /* Update picture */
285       $_SESSION['picture']= $this->photoData;
286       $this->picture_dialog= FALSE;
287       $this->dialog= FALSE;
288     }
290     /* Toggle dob information */
291     if (isset($_POST['set_dob'])){
292       $this->use_dob= ($this->use_dob == "0")?"1":"0";
293     }
296     /* Want certificate= */
297     if (isset($_POST['edit_cert'])){
299       /* Save original values for later reconstruction */
300       foreach (array("certificateSerialNumber", "userCertificate",
301             "userSMIMECertificate", "userPKCS12") as $val){
303         $oval= "old_$val";
304         $this->$oval= $this->$val;
305       }
307       $this->cert_dialog= TRUE;
308       $this->dialog= TRUE;
309     }
312     /* Cancel certificate dialog */
313     if (isset($_POST['cert_edit_cancel'])){
315       /* Restore original values in case of 'cancel' */
316       foreach (array("certificateSerialNumber", "userCertificate",
317             "userSMIMECertificate", "userPKCS12") as $val){
319         $oval= "old_$val";
320         $this->$val= $this->$oval;
321       }
322       $this->cert_dialog= FALSE;
323       $this->dialog= FALSE;
324     }
327     /* Remove certificate? */
328     foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
329       if (isset($_POST["remove_$val"])){
331         /* Reset specified cert*/
332         $this->$val= "";
333         $this->is_modified= TRUE;
334       }
335     }
338     /* Upload new cert and close dialog? */     
339     if (isset($_POST['cert_edit_finish'])){
341       /* for all certificates do */
342       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
343           as $val){
345         /* Check for clean upload */
346         if (array_key_exists($val."_file", $_FILES) &&
347             array_key_exists('name', $_FILES[$val."_file"]) &&
348             $_FILES[$val."_file"]['name'] != "" &&
349             is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
350           $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
351         }
352       }
354       /* Save serial number */
355       if (isset($_POST["certificateSerialNumber"]) &&
356           $_POST["certificateSerialNumber"] != ""){
358         if (!is_id($_POST["certificateSerialNumber"])){
359           print_red (_("Please enter a valid serial number"));
361           foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
362             if ($this->$cert != ""){
363               $smarty->assign("$cert"."_state", "true");
364             } else {
365               $smarty->assign("$cert"."_state", "");
366             }
367           }
368           return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
369         }
371         $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
372         $this->is_modified= TRUE;
373       }
375       $this->cert_dialog= FALSE;
376       $this->dialog= FALSE;
377     }
379     /* Display picture dialog */
380     if ($this->picture_dialog){
381       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
382     }
384     /* Display cert dialog */
385     if ($this->cert_dialog){
386       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
387         if ($this->$cert != ""){
388           /* import certificate */
389           $certificate = new certificate;
390           $certificate->import($this->$cert);
391       
392           /* Read out data*/
393           $timeto   = $certificate->getvalidto_date();
394           $timefrom = $certificate->getvalidfrom_date();
395           $str = "<table border=0><tr><td style='vertical-align:top'>CN</td><td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td></tr>".
396                   "<tr><td>"._("Serial")."</td><td>#".$certificate->getSerialNumber()."</td></tr></table><br>".
397                   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>");
398           $smarty->assign($cert."info",$str);
399           $smarty->assign($cert."_state","true");
400         } else {
401           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
402           $smarty->assign($cert."_state","");
403         }
404       }
405       $smarty->assign("governmentmode", "false");
406       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
407     }
409     /* Show us the edit screen */
410     $smarty->assign("bases", $this->config->idepartments);
411     $smarty->assign("base_select", $this->base);
412     $smarty->assign("selectmode", chkacl($this->acl, "create"));
413     $smarty->assign("certificatesACL", chkacl($this->acl, "certificates"));
414     $smarty->assign("jpegPhotoACL", chkacl($this->acl, "jpegPhoto"));
416     /* Prepare password hashes */
417     if ($this->pw_storage == ""){
418       $this->pw_storage= $this->config->current['HASH'];
419     }
421     $temp   = passwordMethod::get_available_methods();
422     $hashes = $temp['name'];
423     
424     $smarty->assign("pwmode", $hashes);
425     $smarty->assign("pwmode_select", $this->pw_storage);
426     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
428     /* Load attributes and acl's */
429     foreach($this->attributes as $val){
430       $smarty->assign("$val", $this->$val);
431       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
432     }
434     /* Save government mode attributes */
435     if (isset($this->config->current['GOVERNMENTMODE']) &&
436         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
437       $smarty->assign("governmentmode", "true");
438       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
439           "internet,ivbv", "internet,testa", "internet,ivbv,testa", "ja");
440       $smarty->assign("ivbbmodes", $ivbbmodes);
441       foreach ($this->govattrs as $val){
442         $smarty->assign("$val", $this->$val);
443         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
444       }
445     } else {
446       $smarty->assign("governmentmode", "false");
447     }
449     /* Special mode for uid */
450     $uidACL= "";
451     if (isset ($this->dn)){
452       if ($this->dn != "new"){
453         $uidACL="readonly";
454       }
455     }  else {
456       $uidACL= "readonly";
457     }
458     if ($uidACL == ""){
459       $uidACL= chkacl($this->acl, "uid");
460     }
461     $smarty->assign("uidACL", $uidACL);
462     $smarty->assign("is_template", $this->is_template);
463     $smarty->assign("use_dob", $this->use_dob);
465     if (isset($this->parent)){
466       if (isset($this->parent->by_object['phoneAccount']) &&
467           $this->parent->by_object['phoneAccount']->is_account){
468         $smarty->assign("has_phoneaccount", "true");
469       } else {
470         $smarty->assign("has_phoneaccount", "false");
471       }
472     } else {
473         $smarty->assign("has_phoneaccount", "false");
474     }
476     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
477   }
480   /* remove object from parent */
481   function remove_from_parent()
482   {
483     $ldap= $this->config->get_ldap_link();
484     $ldap->rmdir ($this->dn);
486     /* Delete references to groups */
487     $ldap->cd ($this->config->current['BASE']);
488     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
489     while ($ldap->fetch()){
490       $g= new group($this->config, $ldap->getDN());
491       $g->removeUser($this->uid);
492       $g->save ();
493     }
495     /* Delete references to object groups */
496     $ldap->cd ($this->config->current['BASE']);
497     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
498     while ($ldap->fetch()){
499       $og= new ogroup($this->config, $ldap->getDN());
500       unset($og->member[$this->dn]);
501       $og->save ();
502     }
504     /* Optionally execute a command after we're done */
505     $this->handle_post_events("remove");
506   }
509   /* Save data to object */
510   function save_object()
511   {
512     if (isset($_POST['generic'])){
514       /* Parents save function */
515       plugin::save_object ();
517       /* Save government mode attributes */
518       if ($this->config->current['GOVERNMENTMODE']){
519         foreach ($this->govattrs as $val){
520           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
521             $data= stripcslashes($_POST["$val"]);
522             if ($data != $this->$val){
523               $this->is_modified= TRUE;
524             }
525             $this->$val= $data;
526           }
527         }
528       }
530       /* In template mode, the uid is autogenerated... */
531       if ($this->is_template){
532         $this->uid= strtolower($this->sn);
533         $this->givenName= $this->sn;
534       }
536       /* Save base and pw_storage, since these are no LDAP attributes */
537       if (isset($_POST['base'])){
538         foreach(array("base", "pw_storage") as $val){
539           $data= validate($_POST[$val]);
540           if ($data != $this->$val){
541             $this->is_modified= TRUE;
542           }
543           $this->$val= $data;
544         }
545       }
546     }
547   }
549   function rebind($ldap, $referral)
550   {
551     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
552     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
553       $this->error = "Success";
554       $this->hascon=true;
555       $this->reconnect= true;
556       return (0);
557     } else {
558       $this->error = "Could not bind to " . $binddn;
559       return NULL;
560     }
561   }
563   /* Save data to LDAP, depending on is_account we save or delete */
564   function save()
565   {
566     /* First use parents methods to do some basic fillup in $this->attrs */
567     plugin::save ();
569     /* Remove additional objectClasses */
570     $tmp= array();
571     foreach ($this->attrs['objectClass'] as $key => $set){
572       $found= false;
573       foreach (array("ivbbEntry", "gosaUserTemplate") as $val){
574         if (preg_match ("/^$set$/i", $val)){
575           $found= true;
576           break;
577         }
578       }
579       if (!$found){
580         $tmp[]= $set;
581       }
582     }
584     /* Replace the objectClass array. This is done because of the
585        separation into government and normal mode. */
586     $this->attrs['objectClass']= $tmp;
588     /* Add objectClasss for template mode? */
589     if ($this->is_template){
590       $this->attrs['objectClass'][]= "gosaUserTemplate";
591     }
593     /* Hard coded government mode? */
594     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
595       $this->attrs['objectClass'][]= "ivbbEntry";
597       /* Copy standard attributes */
598       foreach ($this->govattrs as $val){
599         if ($this->$val != ""){
600           $this->attrs["$val"]= $this->$val;
601         } elseif (!$this->new) {
602           $this->attrs["$val"]= array();
603         }
604       }
606     }
608     /* Special handling for attribute userCertificate needed */
609     if ($this->userCertificate != ""){
610       $this->attrs["userCertificate;binary"]= $this->userCertificate;
611       $remove_userCertificate= false;
612     } else {
613       $remove_userCertificate= true;
614     }
616     /* Special handling for dob value */
617     if ($this->use_dob == "1"){
618       $this->attrs["dob"]= date("Y-m-d", $this->dob);
619     } else {
620       if ($this->new) {
621         unset($this->attrs["dob"]);
622       } else {
623         $this->attrs["dob"]= array();
624       }
625     }
626     if ($this->gender == "0"){
627       if ($this->new) {
628         unset($this->attrs["gender"]);
629       } else {
630         $this->attrs["gender"]= array();
631       }
632     }
634     /* Special handling for attribute jpegPhote needed, scale image via
635        image magick to 147x200 pixels and inject resulting data. */
636     if ($this->jpegPhoto != "*removed*"){
638       /* Fallback if there's no image magick inside PHP */
639       if (!function_exists("imagick_blob2image")){
640         /* Get temporary file name for conversation */
641         $fname = tempnam ("/tmp", "GOsa");
643         /* Open file and write out photoData */
644         $fp = fopen ($fname, "w");
645         fwrite ($fp, $this->photoData);
646         fclose ($fp);
648         /* Build conversation query. Filename is generated automatically, so
649            we do not need any special security checks. Exec command and save
650            output. For PHP safe mode, you'll need a configuration which respects
651            image magick as executable... */
652         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
653         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
654             $query, "Execute");
656         /* Read data written by convert */
657         $output= "";
658         $sh= popen($query, 'r');
659         while (!feof($sh)){
660           $output.= fread($sh, 4096);
661         }
662         pclose($sh);
664         unlink($fname);
666         /* Save attribute */
667         $this->attrs["jpegPhoto"] = $output;
669       } else {
671         /* Load the new uploaded Photo */
672         if(!$handle  =  imagick_blob2image($this->photoData))  {
673           gosa_log("Can't Load image");
674         }
676         /* Resizing image to 147x200 and blur */
677         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
678           gosa_log("imagick_resize failed");
679         }
681         /* Converting image to JPEG */
682         if(!imagick_convert($handle,"JPEG")) {
683           gosa_log("Can't Convert to JPEG");
684         }
686         /* Creating binary Code for the Image */
687         if(!$dump = imagick_image2blob($handle)){
688           gosa_log("Can't create blob for image");
689         }
691         /* Sending Image */
692         $output=  $dump;
694         /* Save attribute */
695         $this->attrs["jpegPhoto"] = $output;
696       }
698     } elseif(!$this->new) {
699       $this->attrs["jpegPhoto"] = array();
700     }
702     /* Build new dn */
703     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
704       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
705     } else {
706       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
707     }
709     /* This only gets called when user is renaming himself */
710     $ldap= $this->config->get_ldap_link();
711     if ($this->dn != $new_dn){
713       /* Write entry on new 'dn' */
714       $this->move($this->dn, $new_dn);
716       /* Happen to use the new one */
717       change_ui_dn($this->dn, $new_dn);
718       $this->dn= $new_dn;
719     }
722     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
723        new entries. So do a check first... */
724     $ldap->cat ($this->dn);
725     if ($ldap->fetch()){
726       $mode= "modify";
727     } else {
728       $mode= "add";
729       $ldap->cd($this->config->current['BASE']);
730       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
731     }
733     /* Set password to some junk stuff in case of templates */
734     if ($this->is_template){
735       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
736     }
738     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
739         $this->attributes, "Save via $mode");
741     /* Finally write data with selected 'mode' */
742     $ldap->cd ($this->dn);
743     $ldap->$mode ($this->attrs);
744     if (show_ldap_error($ldap->get_error())){
745       return (1);
746     }
748     /* Remove cert? 
749        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
750        to work around myself. */
751     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
753       /* Reset array, assemble new, this should be reworked */
754       $this->attrs= array();
755       $this->attrs['userCertificate;binary']= array();
757       /* Prepare connection */
758       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
759         die ("Could not connect to LDAP server");
760       }
761       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
762       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
763         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
764         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
765       }
766       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
767         ldap_start_tls($ds);
768       }
769       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
770               $this->config->current['PASSWORD']))) {
771         die ("Could not bind to LDAP");
772       }
774       /* Modify using attrs */
775       ldap_mod_del($ds,$this->dn,$this->attrs);
776       ldap_close($ds);
777     }
779     /* Kerberos server defined? */
780     if (isset($this->config->data['SERVERS']['KERBEROS'])){
781       $cfg= $this->config->data['SERVERS']['KERBEROS'];
782     }
783     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
785       /* Connect to the admin interface */
786       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
787           $cfg['ADMIN'], $cfg['PASSWORD']);
789       /* Errors? */             
790       if ($handle === FALSE){
791         print_red (_("Kerberos database communication failed"));
792         return (2);
793       }
795       /* Build user principal, get list of existsing principals */
796       $principal= $this->uid."@".$cfg['REALM'];
797       $principals = kadm5_get_principals($handle);
799       /* User exists in database? */
800       if (in_array($principal, $principals)){
802         /* Ok. User exists. Remove him/her when pw_storage has
803            changed to be NOT kerberos. */
804         if ($this->pw_storage != "kerberos"){
805           $ret= kadm5_delete_principal ( $handle, $principal);
807           if ($ret === FALSE){
808             print_red (_("Can't remove user from kerberos database."));
809           }
810         }
812       } else {
814         /* User doesn't exists, create it when pw_storage is kerberos. */
815         if ($this->pw_storage == "kerberos"){
816           $ret= kadm5_create_principal ( $handle, $principal);
818           if ($ret === FALSE){
819             print_red (_("Can't add user to kerberos database."));
820           }
821         }
823       }
825       /* Free kerberos admin handle */
826       kadm5_destroy($handle);
827     }
829     /* Optionally execute a command after we're done */
830     if ($mode == "add"){
831       $this->handle_post_events("add");
832     } elseif ($this->is_modified){
833       $this->handle_post_events("modify");
834     }
836     return (0);
837   }
840   /* Check formular input */
841   function check()
842   {
843     $message= array();
845     /* Assemble cn */
846     $this->cn= $this->givenName." ".$this->sn;
848     /* Permissions for that base? */
849     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
850       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
851     } else {
852       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
853     }
855     $ui= get_userinfo();
856     $acl= get_permissions ($new_dn, $ui->subtreeACL);
857     $acl= get_module_permission($acl, "user", $new_dn);
858     if ($this->dn == "new" && chkacl($acl, "create") != ""){
859       $message[]= _("You have no permissions to create a user on this 'Base'.");
860     } elseif ($this->dn != $new_dn && $this->dn != "new"){
861       $acl= get_permissions ($this->dn, $ui->subtreeACL);
862       $acl= get_module_permission($acl, "user", $this->dn);
863       if (chkacl($acl, "create") != ""){
864         $message[]= _("You have no permissions to move a user from the original 'Base'.");
865       }
866     }
868     /* must: sn, givenName, uid */
869     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
870       $message[]= _("The required field 'Name' is not set.");
871     }
873     /* UID already used? */
874     $ldap= $this->config->get_ldap_link();
875     $ldap->cd($this->config->current['BASE']);
876     $ldap->search("(uid=$this->uid)", array("uid"));
877     $ldap->fetch();
878     if ($ldap->count() != 0 && $this->dn == 'new'){
879       $message[]= _("There's already a person with this 'Login' in the database.");
880     }
882     /* In template mode, the uid and givenName are autogenerated... */
883     if (!$this->is_template){
884       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
885         $message[]= _("The required field 'Given name' is not set.");
886       }
887       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
888         $message[]= _("The required field 'Login' is not set.");
889       }
890       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
891         $ldap->cd($this->config->current['BASE']);
892         $ldap->search("(cn=".$this->cn.")", array("uid"));
893         $ldap->fetch();
894         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
895           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
896         }
897       }
898     }
900     /* Check for valid input */
901     if (!is_uid($this->uid)){
902       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
903     }
904     if (!is_url($this->labeledURI)){
905       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
906     }
907     if (preg_match ("/[\\\\]/", $this->sn)){
908       $message[]= _("The field 'Name' contains invalid characters.");
909     }
910     if (preg_match ("/[\\\\]/", $this->givenName)){
911       $message[]= _("The field 'Given name' contains invalid characters.");
912     }
914     /* Check phone numbers */
915     if (!is_phone_nr($this->homePhone)){
916       $message[]= _("The field 'Phone' contains an invalid phone number.");
917     }
918     if (!is_phone_nr($this->telephoneNumber)){
919       $message[]= _("The field 'Phone' contains an invalid phone number.");
920     }
921     if (!is_phone_nr($this->facsimileTelephoneNumber)){
922       $message[]= _("The field 'Fax' contains an invalid phone number.");
923     }
924     if (!is_phone_nr($this->mobile)){
925       $message[]= _("The field 'Mobile' contains an invalid phone number.");
926     }
927     if (!is_phone_nr($this->pager)){
928       $message[]= _("The field 'Pager' contains an invalid phone number.");
929     }
931     /* Check for reserved characers */
932     if (preg_match ('/[,+"<>;]/', $this->givenName)){
933       $message[]= _("The field 'Given name' contains invalid characters.");
934   }
935   if (preg_match ('/[,+"<>;]/', $this->sn)){
936     $message[]= _("The field 'Name' contains invalid characters.");
937   }
939   return $message;
940   }
943   /* Indicate whether a password change is needed or not */
944   function password_change_needed()
945   {
946     return ($this->pw_storage != $this->last_pw_storage);
947   }
950   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
951   function load_picture()
952   {
953     /* make connection and read jpegPhoto */
954     $ds= ldap_connect($this->config->current['SERVER']);
955     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
956     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
957       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
958       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
959     }
961     if(isset($this->config->current['TLS']) &&
962         $this->config->current['TLS'] == "true"){
964       ldap_start_tls($ds);
965     }
967     $r= ldap_bind($ds);
968     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
970     /* in case we don't get an entry, load a default picture */
971     $this->set_picture ("./images/default.jpg");
972     $this->jpegPhoto= "*removed*";
974     /* fill data from LDAP */
975     if ($sr) {
976       $ei=ldap_first_entry($ds, $sr);
977       if ($ei) {
978         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
979           $this->photoData= $info[0];
980           $_SESSION['picture']= $this->photoData;
981           $this->jpegPhoto= "";
982         }
983       }
984     }
986     /* close conncetion */
987     ldap_unbind($ds);
988   }
991   /* Load a certificate from LDAP, this is going to be simplified later on */
992   function load_cert()
993   {
994     $ds= ldap_connect($this->config->current['SERVER']);
995     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
996     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
997       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
998       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
999     }
1000     if(isset($this->config->current['TLS']) &&
1001         $this->config->current['TLS'] == "true"){
1003       ldap_start_tls($ds);
1004     }
1006     $r= ldap_bind($ds);
1007     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1009     if ($sr) {
1010       $ei= @ldap_first_entry($ds, $sr);
1011       
1012       if ($ei) {
1013         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1014           $this->userCertificate= "";
1015         } else {
1016           $this->userCertificate= $info[0];
1017         }
1018       }
1019     } else {
1020       $this->userCertificate= "";
1021     }
1023     ldap_unbind($ds);
1024   }
1027   /* Load picture from file to object */
1028   function set_picture($filename)
1029   {
1030     if (!is_file($filename)){
1031       $filename= "./images/default.jpg";
1032       $this->jpegPhoto= "*removed*";
1033     }
1035     $fd = fopen ($filename, "rb");
1036     $this->photoData= fread ($fd, filesize ($filename));
1037     $_SESSION['picture']= $this->photoData;
1038     $this->jpegPhoto= "";
1040     fclose ($fd);
1041   }
1044   /* Load certificate from file to object */
1045   function set_cert($cert, $filename)
1046   {
1047     $fd = fopen ($filename, "rb");
1048     if (filesize($filename)>0) {
1049       $this->$cert= fread ($fd, filesize ($filename));
1050       fclose ($fd);
1051       $this->is_modified= TRUE;
1052     } else {
1053       print_red(_("Could not open specified certificate!"));
1054     }
1055   }
1057   /* Adapt from given 'dn' */
1058   function adapt_from_template($dn)
1059   {
1060     plugin::adapt_from_template($dn);
1062     /* Get base */
1063     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1065     if ($this->config->current['GOVERNMENTMODE']){
1067       /* Walk through govattrs */
1068       foreach ($this->govattrs as $val){
1070         if (isset($this->attrs["$val"][0])){
1072           /* If attribute is set, replace dynamic parts: 
1073              %sn, %givenName and %uid. Fill these in our local variables. */
1074           $value= $this->attrs["$val"][0];
1076           foreach (array("sn", "givenName", "uid") as $repl){
1077             if (preg_match("/%$repl/i", $value)){
1078               $value= preg_replace ("/%$repl/i",
1079                   $this->parent->$repl, $value);
1080             }
1081           }
1082           $this->$val= $value;
1083         }
1084       }
1085     }
1087     /* Get back uid/sn/givenName */
1088     if ($this->parent != NULL){
1089       $this->uid= $this->parent->uid;
1090       $this->sn= $this->parent->sn;
1091       $this->givenName= $this->parent->givenName;
1092     }
1093   }
1097 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1098 ?>