Code

Fixed cert layout
[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 ($_FILES[$val."_file"]['name'] != "" && 
347             is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
349           $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
350         }
351       }
353       /* Save serial number */
354       if (isset($_POST["certificateSerialNumber"]) &&
355           $_POST["certificateSerialNumber"] != ""){
357         if (!is_id($_POST["certificateSerialNumber"])){
358           print_red (_("Please enter a valid serial number"));
360           foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
361             if ($this->$cert != ""){
362               $smarty->assign("$cert"."_state", "true");
363             } else {
364               $smarty->assign("$cert"."_state", "");
365             }
366           }
367           return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
368         }
370         $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
371         $this->is_modified= TRUE;
372       }
374       $this->cert_dialog= FALSE;
375       $this->dialog= FALSE;
376     }
378     /* Display picture dialog */
379     if ($this->picture_dialog){
380       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
381     }
383     /* Display cert dialog */
384     if ($this->cert_dialog){
385       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
386         if ($this->$cert != ""){
387           /* import certificate */
388           $certificate = new certificate;
389           $certificate->import($this->$cert);
390       
391           /* Read out data*/
392           $timeto   = $certificate->getvalidto_date();
393           $timefrom = $certificate->getvalidfrom_date();
394           $str = $certificate->getname()."<br>".
395                   _("Serialnumber")." : ".$certificate->getSerialNumber()."<br>".
396                   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()?_("valid"):_("invalid"));
397           $smarty->assign($cert."info",$str);
398           $smarty->assign($cert."_state","true");
399         } else {
400           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
401           $smarty->assign($cert."_state","");
402         }
403       }
404       $smarty->assign("governmentmode", "false");
405       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
406     }
408     /* Show us the edit screen */
409     $smarty->assign("bases", $this->config->idepartments);
410     $smarty->assign("base_select", $this->base);
411     $smarty->assign("selectmode", chkacl($this->acl, "create"));
412     $smarty->assign("certificatesACL", chkacl($this->acl, "certificates"));
413     $smarty->assign("jpegPhotoACL", chkacl($this->acl, "jpegPhoto"));
415     /* Prepare password hashes */
416     if ($this->pw_storage == ""){
417       $this->pw_storage= $this->config->current['HASH'];
418     }
420     $temp   = passwordMethod::get_available_methods();
421     $hashes = $temp['name'];
422     
423     $smarty->assign("pwmode", $hashes);
424     $smarty->assign("pwmode_select", $this->pw_storage);
425     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
427     /* Load attributes and acl's */
428     foreach($this->attributes as $val){
429       $smarty->assign("$val", $this->$val);
430       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
431     }
433     /* Save government mode attributes */
434     if (isset($this->config->current['GOVERNMENTMODE']) &&
435         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
436       $smarty->assign("governmentmode", "true");
437       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
438           "internet,ivbv", "internet,testa", "internet,ivbv,testa", "ja");
439       $smarty->assign("ivbbmodes", $ivbbmodes);
440       foreach ($this->govattrs as $val){
441         $smarty->assign("$val", $this->$val);
442         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
443       }
444     } else {
445       $smarty->assign("governmentmode", "false");
446     }
448     /* Special mode for uid */
449     $uidACL= "";
450     if (isset ($this->dn)){
451       if ($this->dn != "new"){
452         $uidACL="readonly";
453       }
454     }  else {
455       $uidACL= "readonly";
456     }
457     if ($uidACL == ""){
458       $uidACL= chkacl($this->acl, "uid");
459     }
460     $smarty->assign("uidACL", $uidACL);
461     $smarty->assign("is_template", $this->is_template);
462     $smarty->assign("use_dob", $this->use_dob);
464     if (isset($this->parent)){
465       if (isset($this->parent->by_object['phoneAccount']) &&
466           $this->parent->by_object['phoneAccount']->is_account){
467         $smarty->assign("has_phoneaccount", "true");
468       } else {
469         $smarty->assign("has_phoneaccount", "false");
470       }
471     } else {
472         $smarty->assign("has_phoneaccount", "false");
473     }
475     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
476   }
479   /* remove object from parent */
480   function remove_from_parent()
481   {
482     $ldap= $this->config->get_ldap_link();
483     $ldap->rmdir ($this->dn);
485     /* Delete references to groups */
486     $ldap->cd ($this->config->current['BASE']);
487     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
488     while ($ldap->fetch()){
489       $g= new group($this->config, $ldap->getDN());
490       $g->removeUser($this->uid);
491       $g->save ();
492     }
494     /* Delete references to object groups */
495     $ldap->cd ($this->config->current['BASE']);
496     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
497     while ($ldap->fetch()){
498       $og= new ogroup($this->config, $ldap->getDN());
499       unset($og->member[$this->dn]);
500       $og->save ();
501     }
503     /* Optionally execute a command after we're done */
504     $this->handle_post_events("remove");
505   }
508   /* Save data to object */
509   function save_object()
510   {
511     if (isset($_POST['generic'])){
513       /* Parents save function */
514       plugin::save_object ();
516       /* Save government mode attributes */
517       if ($this->config->current['GOVERNMENTMODE']){
518         foreach ($this->govattrs as $val){
519           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
520             $data= stripcslashes($_POST["$val"]);
521             if ($data != $this->$val){
522               $this->is_modified= TRUE;
523             }
524             $this->$val= $data;
525           }
526         }
527       }
529       /* In template mode, the uid is autogenerated... */
530       if ($this->is_template){
531         $this->uid= strtolower($this->sn);
532         $this->givenName= $this->sn;
533       }
535       /* Save base and pw_storage, since these are no LDAP attributes */
536       if (isset($_POST['base'])){
537         foreach(array("base", "pw_storage") as $val){
538           $data= validate($_POST[$val]);
539           if ($data != $this->$val){
540             $this->is_modified= TRUE;
541           }
542           $this->$val= $data;
543         }
544       }
545     }
546   }
548   function rebind($ldap, $referral)
549   {
550     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
551     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
552       $this->error = "Success";
553       $this->hascon=true;
554       $this->reconnect= true;
555       return (0);
556     } else {
557       $this->error = "Could not bind to " . $binddn;
558       return NULL;
559     }
560   }
562   /* Save data to LDAP, depending on is_account we save or delete */
563   function save()
564   {
565     /* First use parents methods to do some basic fillup in $this->attrs */
566     plugin::save ();
568     /* Remove additional objectClasses */
569     $tmp= array();
570     foreach ($this->attrs['objectClass'] as $key => $set){
571       $found= false;
572       foreach (array("ivbbEntry", "gosaUserTemplate") as $val){
573         if (preg_match ("/^$set$/i", $val)){
574           $found= true;
575           break;
576         }
577       }
578       if (!$found){
579         $tmp[]= $set;
580       }
581     }
583     /* Replace the objectClass array. This is done because of the
584        separation into government and normal mode. */
585     $this->attrs['objectClass']= $tmp;
587     /* Add objectClasss for template mode? */
588     if ($this->is_template){
589       $this->attrs['objectClass'][]= "gosaUserTemplate";
590     }
592     /* Hard coded government mode? */
593     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
594       $this->attrs['objectClass'][]= "ivbbEntry";
596       /* Copy standard attributes */
597       foreach ($this->govattrs as $val){
598         if ($this->$val != ""){
599           $this->attrs["$val"]= $this->$val;
600         } elseif (!$this->new) {
601           $this->attrs["$val"]= array();
602         }
603       }
605     }
607     /* Special handling for attribute userCertificate needed */
608     if ($this->userCertificate != ""){
609       $this->attrs["userCertificate;binary"]= $this->userCertificate;
610       $remove_userCertificate= false;
611     } else {
612       $remove_userCertificate= true;
613     }
615     /* Special handling for dob value */
616     if ($this->use_dob == "1"){
617       $this->attrs["dob"]= date("Y-m-d", $this->dob);
618     } else {
619       if ($this->new) {
620         unset($this->attrs["dob"]);
621       } else {
622         $this->attrs["dob"]= array();
623       }
624     }
625     if ($this->gender == "0"){
626       if ($this->new) {
627         unset($this->attrs["gender"]);
628       } else {
629         $this->attrs["gender"]= array();
630       }
631     }
633     /* Special handling for attribute jpegPhote needed, scale image via
634        image magick to 147x200 pixels and inject resulting data. */
635     if ($this->jpegPhoto != "*removed*"){
637       /* Fallback if there's no image magick inside PHP */
638       if (!function_exists("imagick_blob2image")){
639         /* Get temporary file name for conversation */
640         $fname = tempnam ("/tmp", "GOsa");
642         /* Open file and write out photoData */
643         $fp = fopen ($fname, "w");
644         fwrite ($fp, $this->photoData);
645         fclose ($fp);
647         /* Build conversation query. Filename is generated automatically, so
648            we do not need any special security checks. Exec command and save
649            output. For PHP safe mode, you'll need a configuration which respects
650            image magick as executable... */
651         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
652         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
653             $query, "Execute");
655         /* Read data written by convert */
656         $output= "";
657         $sh= popen($query, 'r');
658         while (!feof($sh)){
659           $output.= fread($sh, 4096);
660         }
661         pclose($sh);
663         unlink($fname);
665         /* Save attribute */
666         $this->attrs["jpegPhoto"] = $output;
668       } else {
670         /* Load the new uploaded Photo */
671         if(!$handle  =  imagick_blob2image($this->photoData))  {
672           gosa_log("Can't Load image");
673         }
675         /* Resizing image to 147x200 and blur */
676         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
677           gosa_log("imagick_resize failed");
678         }
680         /* Converting image to JPEG */
681         if(!imagick_convert($handle,"JPEG")) {
682           gosa_log("Can't Convert to JPEG");
683         }
685         /* Creating binary Code for the Image */
686         if(!$dump = imagick_image2blob($handle)){
687           gosa_log("Can't create blob for image");
688         }
690         /* Sending Image */
691         $output=  $dump;
693         /* Save attribute */
694         $this->attrs["jpegPhoto"] = $output;
695       }
697     } elseif(!$this->new) {
698       $this->attrs["jpegPhoto"] = array();
699     }
701     /* Build new dn */
702     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
703       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
704     } else {
705       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
706     }
708     /* This only gets called when user is renaming himself */
709     $ldap= $this->config->get_ldap_link();
710     if ($this->dn != $new_dn){
712       /* Write entry on new 'dn' */
713       $this->move($this->dn, $new_dn);
715       /* Happen to use the new one */
716       change_ui_dn($this->dn, $new_dn);
717       $this->dn= $new_dn;
718     }
721     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
722        new entries. So do a check first... */
723     $ldap->cat ($this->dn);
724     if ($ldap->fetch()){
725       $mode= "modify";
726     } else {
727       $mode= "add";
728       $ldap->cd($this->config->current['BASE']);
729       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
730     }
732     /* Set password to some junk stuff in case of templates */
733     if ($this->is_template){
734       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
735     }
737     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
738         $this->attributes, "Save via $mode");
740     /* Finally write data with selected 'mode' */
741     $ldap->cd ($this->dn);
742     $ldap->$mode ($this->attrs);
743     if (show_ldap_error($ldap->get_error())){
744       return (1);
745     }
747     /* Remove cert? 
748        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
749        to work around myself. */
750     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
752       /* Reset array, assemble new, this should be reworked */
753       $this->attrs= array();
754       $this->attrs['userCertificate;binary']= array();
756       /* Prepare connection */
757       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
758         die ("Could not connect to LDAP server");
759       }
760       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
761       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
762         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
763         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
764       }
765       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
766         ldap_start_tls($ds);
767       }
768       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
769               $this->config->current['PASSWORD']))) {
770         die ("Could not bind to LDAP");
771       }
773       /* Modify using attrs */
774       ldap_mod_del($ds,$this->dn,$this->attrs);
775       ldap_close($ds);
776     }
778     /* Kerberos server defined? */
779     if (isset($this->config->data['SERVERS']['KERBEROS'])){
780       $cfg= $this->config->data['SERVERS']['KERBEROS'];
781     }
782     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
784       /* Connect to the admin interface */
785       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
786           $cfg['ADMIN'], $cfg['PASSWORD']);
788       /* Errors? */             
789       if ($handle === FALSE){
790         print_red (_("Kerberos database communication failed"));
791         return (2);
792       }
794       /* Build user principal, get list of existsing principals */
795       $principal= $this->uid."@".$cfg['REALM'];
796       $principals = kadm5_get_principals($handle);
798       /* User exists in database? */
799       if (in_array($principal, $principals)){
801         /* Ok. User exists. Remove him/her when pw_storage has
802            changed to be NOT kerberos. */
803         if ($this->pw_storage != "kerberos"){
804           $ret= kadm5_delete_principal ( $handle, $principal);
806           if ($ret === FALSE){
807             print_red (_("Can't remove user from kerberos database."));
808           }
809         }
811       } else {
813         /* User doesn't exists, create it when pw_storage is kerberos. */
814         if ($this->pw_storage == "kerberos"){
815           $ret= kadm5_create_principal ( $handle, $principal);
817           if ($ret === FALSE){
818             print_red (_("Can't add user to kerberos database."));
819           }
820         }
822       }
824       /* Free kerberos admin handle */
825       kadm5_destroy($handle);
826     }
828     /* Optionally execute a command after we're done */
829     if ($mode == "add"){
830       $this->handle_post_events("add");
831     } elseif ($this->is_modified){
832       $this->handle_post_events("modify");
833     }
835     return (0);
836   }
839   /* Check formular input */
840   function check()
841   {
842     $message= array();
844     /* Assemble cn */
845     $this->cn= $this->givenName." ".$this->sn;
847     /* Permissions for that base? */
848     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
849       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
850     } else {
851       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
852     }
854     $ui= get_userinfo();
855     $acl= get_permissions ($new_dn, $ui->subtreeACL);
856     $acl= get_module_permission($acl, "user", $new_dn);
857     if ($this->dn == "new" && chkacl($acl, "create") != ""){
858       $message[]= _("You have no permissions to create a user on this 'Base'.");
859     } elseif ($this->dn != $new_dn && $this->dn != "new"){
860       $acl= get_permissions ($this->dn, $ui->subtreeACL);
861       $acl= get_module_permission($acl, "user", $this->dn);
862       if (chkacl($acl, "create") != ""){
863         $message[]= _("You have no permissions to move a user from the original 'Base'.");
864       }
865     }
867     /* must: sn, givenName, uid */
868     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
869       $message[]= _("The required field 'Name' is not set.");
870     }
872     /* UID already used? */
873     $ldap= $this->config->get_ldap_link();
874     $ldap->cd($this->config->current['BASE']);
875     $ldap->search("(uid=$this->uid)", array("uid"));
876     $ldap->fetch();
877     if ($ldap->count() != 0 && $this->dn == 'new'){
878       $message[]= _("There's already a person with this 'Login' in the database.");
879     }
881     /* In template mode, the uid and givenName are autogenerated... */
882     if (!$this->is_template){
883       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
884         $message[]= _("The required field 'Given name' is not set.");
885       }
886       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
887         $message[]= _("The required field 'Login' is not set.");
888       }
889       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
890         $ldap->cd($this->config->current['BASE']);
891         $ldap->search("(cn=".$this->cn.")", array("uid"));
892         $ldap->fetch();
893         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
894           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
895         }
896       }
897     }
899     /* Check for valid input */
900     if (!is_uid($this->uid)){
901       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
902     }
903     if (!is_url($this->labeledURI)){
904       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
905     }
906     if (preg_match ("/[\\\\]/", $this->sn)){
907       $message[]= _("The field 'Name' contains invalid characters.");
908     }
909     if (preg_match ("/[\\\\]/", $this->givenName)){
910       $message[]= _("The field 'Given name' contains invalid characters.");
911     }
913     /* Check phone numbers */
914     if (!is_phone_nr($this->homePhone)){
915       $message[]= _("The field 'Phone' contains an invalid phone number.");
916     }
917     if (!is_phone_nr($this->telephoneNumber)){
918       $message[]= _("The field 'Phone' contains an invalid phone number.");
919     }
920     if (!is_phone_nr($this->facsimileTelephoneNumber)){
921       $message[]= _("The field 'Fax' contains an invalid phone number.");
922     }
923     if (!is_phone_nr($this->mobile)){
924       $message[]= _("The field 'Mobile' contains an invalid phone number.");
925     }
926     if (!is_phone_nr($this->pager)){
927       $message[]= _("The field 'Pager' contains an invalid phone number.");
928     }
930     /* Check for reserved characers */
931     if (preg_match ('/[,+"<>;]/', $this->givenName)){
932       $message[]= _("The field 'Given name' contains invalid characters.");
933   }
934   if (preg_match ('/[,+"<>;]/', $this->sn)){
935     $message[]= _("The field 'Name' contains invalid characters.");
936   }
938   return $message;
939   }
942   /* Indicate whether a password change is needed or not */
943   function password_change_needed()
944   {
945     return ($this->pw_storage != $this->last_pw_storage);
946   }
949   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
950   function load_picture()
951   {
952     /* make connection and read jpegPhoto */
953     $ds= ldap_connect($this->config->current['SERVER']);
954     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
955     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
956       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
957       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
958     }
960     if(isset($this->config->current['TLS']) &&
961         $this->config->current['TLS'] == "true"){
963       ldap_start_tls($ds);
964     }
966     $r= ldap_bind($ds);
967     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
969     /* in case we don't get an entry, load a default picture */
970     $this->set_picture ("./images/default.jpg");
971     $this->jpegPhoto= "*removed*";
973     /* fill data from LDAP */
974     if ($sr) {
975       $ei=ldap_first_entry($ds, $sr);
976       if ($ei) {
977         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
978           $this->photoData= $info[0];
979           $_SESSION['picture']= $this->photoData;
980           $this->jpegPhoto= "";
981         }
982       }
983     }
985     /* close conncetion */
986     ldap_unbind($ds);
987   }
990   /* Load a certificate from LDAP, this is going to be simplified later on */
991   function load_cert()
992   {
993     $ds= ldap_connect($this->config->current['SERVER']);
994     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
995     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
996       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
997       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
998     }
999     if(isset($this->config->current['TLS']) &&
1000         $this->config->current['TLS'] == "true"){
1002       ldap_start_tls($ds);
1003     }
1005     $r= ldap_bind($ds);
1006     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1008     if ($sr) {
1009       $ei= @ldap_first_entry($ds, $sr);
1010       
1011       if ($ei) {
1012         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1013           $this->userCertificate= "";
1014         } else {
1015           $this->userCertificate= $info[0];
1016         }
1017       }
1018     } else {
1019       $this->userCertificate= "";
1020     }
1022     ldap_unbind($ds);
1023   }
1026   /* Load picture from file to object */
1027   function set_picture($filename)
1028   {
1029     if (!is_file($filename)){
1030       $filename= "./images/default.jpg";
1031       $this->jpegPhoto= "*removed*";
1032     }
1034     $fd = fopen ($filename, "rb");
1035     $this->photoData= fread ($fd, filesize ($filename));
1036     $_SESSION['picture']= $this->photoData;
1037     $this->jpegPhoto= "";
1039     fclose ($fd);
1040   }
1043   /* Load certificate from file to object */
1044   function set_cert($cert, $filename)
1045   {
1046     $fd = fopen ($filename, "rb");
1047     $this->$cert= fread ($fd, filesize ($filename));
1048     fclose ($fd);
1049     $this->is_modified= TRUE;
1050   }
1052   /* Adapt from given 'dn' */
1053   function adapt_from_template($dn)
1054   {
1055     plugin::adapt_from_template($dn);
1057     /* Get base */
1058     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1060     if ($this->config->current['GOVERNMENTMODE']){
1062       /* Walk through govattrs */
1063       foreach ($this->govattrs as $val){
1065         if (isset($this->attrs["$val"][0])){
1067           /* If attribute is set, replace dynamic parts: 
1068              %sn, %givenName and %uid. Fill these in our local variables. */
1069           $value= $this->attrs["$val"][0];
1071           foreach (array("sn", "givenName", "uid") as $repl){
1072             if (preg_match("/%$repl/i", $value)){
1073               $value= preg_replace ("/%$repl/i",
1074                   $this->parent->$repl, $value);
1075             }
1076           }
1077           $this->$val= $value;
1078         }
1079       }
1080     }
1082     /* Get back uid/sn/givenName */
1083     if ($this->parent != NULL){
1084       $this->uid= $this->parent->uid;
1085       $this->sn= $this->parent->sn;
1086       $this->givenName= $this->parent->givenName;
1087     }
1088   }
1092 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1093 ?>