Code

Certificate informations shown now
[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", _("present"));
363             } else {
364               $smarty->assign("$cert"."_state", _("absent"));
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           $smarty->assign("$cert"."_state", _("present"));
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 = _("This Certificate is valid till ").date('d M Y',$timeto)." - ".str_replace("/"," , ",$certificate->getCN());
396           $smarty->assign($cert."info",$str);
397         } else {
398           $smarty->assign($cert."info","");
399           $smarty->assign("$cert"."_state", _("absent"));
400         }
401       }
402       $smarty->assign("governmentmode", "false");
403       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
404     }
406     /* Show us the edit screen */
407     $smarty->assign("bases", $this->config->idepartments);
408     $smarty->assign("base_select", $this->base);
409     $smarty->assign("selectmode", chkacl($this->acl, "create"));
410     $smarty->assign("certificatesACL", chkacl($this->acl, "certificates"));
411     $smarty->assign("jpegPhotoACL", chkacl($this->acl, "jpegPhoto"));
413     /* Prepare password hashes */
414     if ($this->pw_storage == ""){
415       $this->pw_storage= $this->config->current['HASH'];
416     }
418     $temp   = passwordMethod::get_available_methods();
419     $hashes = $temp['name'];
420     
421     $smarty->assign("pwmode", $hashes);
422     $smarty->assign("pwmode_select", $this->pw_storage);
423     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
425     /* Load attributes and acl's */
426     foreach($this->attributes as $val){
427       $smarty->assign("$val", $this->$val);
428       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
429     }
431     /* Save government mode attributes */
432     if (isset($this->config->current['GOVERNMENTMODE']) &&
433         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
434       $smarty->assign("governmentmode", "true");
435       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
436           "internet,ivbv", "internet,testa", "internet,ivbv,testa", "ja");
437       $smarty->assign("ivbbmodes", $ivbbmodes);
438       foreach ($this->govattrs as $val){
439         $smarty->assign("$val", $this->$val);
440         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
441       }
442     } else {
443       $smarty->assign("governmentmode", "false");
444     }
446     /* Special mode for uid */
447     $uidACL= "";
448     if (isset ($this->dn)){
449       if ($this->dn != "new"){
450         $uidACL="readonly";
451       }
452     }  else {
453       $uidACL= "readonly";
454     }
455     if ($uidACL == ""){
456       $uidACL= chkacl($this->acl, "uid");
457     }
458     $smarty->assign("uidACL", $uidACL);
459     $smarty->assign("is_template", $this->is_template);
460     $smarty->assign("use_dob", $this->use_dob);
462     if (isset($this->parent)){
463       if (isset($this->parent->by_object['phoneAccount']) &&
464           $this->parent->by_object['phoneAccount']->is_account){
465         $smarty->assign("has_phoneaccount", "true");
466       } else {
467         $smarty->assign("has_phoneaccount", "false");
468       }
469     } else {
470         $smarty->assign("has_phoneaccount", "false");
471     }
473     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
474   }
477   /* remove object from parent */
478   function remove_from_parent()
479   {
480     $ldap= $this->config->get_ldap_link();
481     $ldap->rmdir ($this->dn);
483     /* Delete references to groups */
484     $ldap->cd ($this->config->current['BASE']);
485     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
486     while ($ldap->fetch()){
487       $g= new group($this->config, $ldap->getDN());
488       $g->removeUser($this->uid);
489       $g->save ();
490     }
492     /* Delete references to object groups */
493     $ldap->cd ($this->config->current['BASE']);
494     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
495     while ($ldap->fetch()){
496       $og= new ogroup($this->config, $ldap->getDN());
497       unset($og->member[$this->dn]);
498       $og->save ();
499     }
501     /* Optionally execute a command after we're done */
502     $this->handle_post_events("remove");
503   }
506   /* Save data to object */
507   function save_object()
508   {
509     if (isset($_POST['generic'])){
511       /* Parents save function */
512       plugin::save_object ();
514       /* Save government mode attributes */
515       if ($this->config->current['GOVERNMENTMODE']){
516         foreach ($this->govattrs as $val){
517           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
518             $data= stripcslashes($_POST["$val"]);
519             if ($data != $this->$val){
520               $this->is_modified= TRUE;
521             }
522             $this->$val= $data;
523           }
524         }
525       }
527       /* In template mode, the uid is autogenerated... */
528       if ($this->is_template){
529         $this->uid= strtolower($this->sn);
530         $this->givenName= $this->sn;
531       }
533       /* Save base and pw_storage, since these are no LDAP attributes */
534       if (isset($_POST['base'])){
535         foreach(array("base", "pw_storage") as $val){
536           $data= validate($_POST[$val]);
537           if ($data != $this->$val){
538             $this->is_modified= TRUE;
539           }
540           $this->$val= $data;
541         }
542       }
543     }
544   }
546   function rebind($ldap, $referral)
547   {
548     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
549     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
550       $this->error = "Success";
551       $this->hascon=true;
552       $this->reconnect= true;
553       return (0);
554     } else {
555       $this->error = "Could not bind to " . $binddn;
556       return NULL;
557     }
558   }
560   /* Save data to LDAP, depending on is_account we save or delete */
561   function save()
562   {
563     /* First use parents methods to do some basic fillup in $this->attrs */
564     plugin::save ();
566     /* Remove additional objectClasses */
567     $tmp= array();
568     foreach ($this->attrs['objectClass'] as $key => $set){
569       $found= false;
570       foreach (array("ivbbEntry", "gosaUserTemplate") as $val){
571         if (preg_match ("/^$set$/i", $val)){
572           $found= true;
573           break;
574         }
575       }
576       if (!$found){
577         $tmp[]= $set;
578       }
579     }
581     /* Replace the objectClass array. This is done because of the
582        separation into government and normal mode. */
583     $this->attrs['objectClass']= $tmp;
585     /* Add objectClasss for template mode? */
586     if ($this->is_template){
587       $this->attrs['objectClass'][]= "gosaUserTemplate";
588     }
590     /* Hard coded government mode? */
591     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
592       $this->attrs['objectClass'][]= "ivbbEntry";
594       /* Copy standard attributes */
595       foreach ($this->govattrs as $val){
596         if ($this->$val != ""){
597           $this->attrs["$val"]= $this->$val;
598         } elseif (!$this->new) {
599           $this->attrs["$val"]= array();
600         }
601       }
603     }
605     /* Special handling for attribute userCertificate needed */
606     if ($this->userCertificate != ""){
607       $this->attrs["userCertificate;binary"]= $this->userCertificate;
608       $remove_userCertificate= false;
609     } else {
610       $remove_userCertificate= true;
611     }
613     /* Special handling for dob value */
614     if ($this->use_dob == "1"){
615       $this->attrs["dob"]= date("Y-m-d", $this->dob);
616     } else {
617       if ($this->new) {
618         unset($this->attrs["dob"]);
619       } else {
620         $this->attrs["dob"]= array();
621       }
622     }
623     if ($this->gender == "0"){
624       if ($this->new) {
625         unset($this->attrs["gender"]);
626       } else {
627         $this->attrs["gender"]= array();
628       }
629     }
631     /* Special handling for attribute jpegPhote needed, scale image via
632        image magick to 147x200 pixels and inject resulting data. */
633     if ($this->jpegPhoto != "*removed*"){
635       /* Fallback if there's no image magick inside PHP */
636       if (!function_exists("imagick_blob2image")){
637         /* Get temporary file name for conversation */
638         $fname = tempnam ("/tmp", "GOsa");
640         /* Open file and write out photoData */
641         $fp = fopen ($fname, "w");
642         fwrite ($fp, $this->photoData);
643         fclose ($fp);
645         /* Build conversation query. Filename is generated automatically, so
646            we do not need any special security checks. Exec command and save
647            output. For PHP safe mode, you'll need a configuration which respects
648            image magick as executable... */
649         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
650         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
651             $query, "Execute");
653         /* Read data written by convert */
654         $output= "";
655         $sh= popen($query, 'r');
656         while (!feof($sh)){
657           $output.= fread($sh, 4096);
658         }
659         pclose($sh);
661         unlink($fname);
663         /* Save attribute */
664         $this->attrs["jpegPhoto"] = $output;
666       } else {
668         /* Load the new uploaded Photo */
669         if(!$handle  =  imagick_blob2image($this->photoData))  {
670           gosa_log("Can't Load image");
671         }
673         /* Resizing image to 147x200 and blur */
674         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
675           gosa_log("imagick_resize failed");
676         }
678         /* Converting image to JPEG */
679         if(!imagick_convert($handle,"JPEG")) {
680           gosa_log("Can't Convert to JPEG");
681         }
683         /* Creating binary Code for the Image */
684         if(!$dump = imagick_image2blob($handle)){
685           gosa_log("Can't create blob for image");
686         }
688         /* Sending Image */
689         $output=  $dump;
691         /* Save attribute */
692         $this->attrs["jpegPhoto"] = $output;
693       }
695     } elseif(!$this->new) {
696       $this->attrs["jpegPhoto"] = array();
697     }
699     /* Build new dn */
700     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
701       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
702     } else {
703       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
704     }
706     /* This only gets called when user is renaming himself */
707     $ldap= $this->config->get_ldap_link();
708     if ($this->dn != $new_dn){
710       /* Write entry on new 'dn' */
711       $this->move($this->dn, $new_dn);
713       /* Happen to use the new one */
714       change_ui_dn($this->dn, $new_dn);
715       $this->dn= $new_dn;
716     }
719     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
720        new entries. So do a check first... */
721     $ldap->cat ($this->dn);
722     if ($ldap->fetch()){
723       $mode= "modify";
724     } else {
725       $mode= "add";
726       $ldap->cd($this->config->current['BASE']);
727       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
728     }
730     /* Set password to some junk stuff in case of templates */
731     if ($this->is_template){
732       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
733     }
735     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
736         $this->attributes, "Save via $mode");
738     /* Finally write data with selected 'mode' */
739     $ldap->cd ($this->dn);
740     $ldap->$mode ($this->attrs);
741     if (show_ldap_error($ldap->get_error())){
742       return (1);
743     }
745     /* Remove cert? 
746        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
747        to work around myself. */
748     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
750       /* Reset array, assemble new, this should be reworked */
751       $this->attrs= array();
752       $this->attrs['userCertificate;binary']= array();
754       /* Prepare connection */
755       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
756         die ("Could not connect to LDAP server");
757       }
758       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
759       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
760         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
761         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
762       }
763       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
764         ldap_start_tls($ds);
765       }
766       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
767               $this->config->current['PASSWORD']))) {
768         die ("Could not bind to LDAP");
769       }
771       /* Modify using attrs */
772       ldap_mod_del($ds,$this->dn,$this->attrs);
773       ldap_close($ds);
774     }
776     /* Kerberos server defined? */
777     if (isset($this->config->data['SERVERS']['KERBEROS'])){
778       $cfg= $this->config->data['SERVERS']['KERBEROS'];
779     }
780     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
782       /* Connect to the admin interface */
783       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
784           $cfg['ADMIN'], $cfg['PASSWORD']);
786       /* Errors? */             
787       if ($handle === FALSE){
788         print_red (_("Kerberos database communication failed"));
789         return (2);
790       }
792       /* Build user principal, get list of existsing principals */
793       $principal= $this->uid."@".$cfg['REALM'];
794       $principals = kadm5_get_principals($handle);
796       /* User exists in database? */
797       if (in_array($principal, $principals)){
799         /* Ok. User exists. Remove him/her when pw_storage has
800            changed to be NOT kerberos. */
801         if ($this->pw_storage != "kerberos"){
802           $ret= kadm5_delete_principal ( $handle, $principal);
804           if ($ret === FALSE){
805             print_red (_("Can't remove user from kerberos database."));
806           }
807         }
809       } else {
811         /* User doesn't exists, create it when pw_storage is kerberos. */
812         if ($this->pw_storage == "kerberos"){
813           $ret= kadm5_create_principal ( $handle, $principal);
815           if ($ret === FALSE){
816             print_red (_("Can't add user to kerberos database."));
817           }
818         }
820       }
822       /* Free kerberos admin handle */
823       kadm5_destroy($handle);
824     }
826     /* Optionally execute a command after we're done */
827     if ($mode == "add"){
828       $this->handle_post_events("add");
829     } elseif ($this->is_modified){
830       $this->handle_post_events("modify");
831     }
833     return (0);
834   }
837   /* Check formular input */
838   function check()
839   {
840     $message= array();
842     /* Assemble cn */
843     $this->cn= $this->givenName." ".$this->sn;
845     /* Permissions for that base? */
846     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
847       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
848     } else {
849       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
850     }
852     $ui= get_userinfo();
853     $acl= get_permissions ($new_dn, $ui->subtreeACL);
854     $acl= get_module_permission($acl, "user", $new_dn);
855     if ($this->dn == "new" && chkacl($acl, "create") != ""){
856       $message[]= _("You have no permissions to create a user on this 'Base'.");
857     } elseif ($this->dn != $new_dn && $this->dn != "new"){
858       $acl= get_permissions ($this->dn, $ui->subtreeACL);
859       $acl= get_module_permission($acl, "user", $this->dn);
860       if (chkacl($acl, "create") != ""){
861         $message[]= _("You have no permissions to move a user from the original 'Base'.");
862       }
863     }
865     /* must: sn, givenName, uid */
866     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
867       $message[]= _("The required field 'Name' is not set.");
868     }
870     /* UID already used? */
871     $ldap= $this->config->get_ldap_link();
872     $ldap->cd($this->config->current['BASE']);
873     $ldap->search("(uid=$this->uid)", array("uid"));
874     $ldap->fetch();
875     if ($ldap->count() != 0 && $this->dn == 'new'){
876       $message[]= _("There's already a person with this 'Login' in the database.");
877     }
879     /* In template mode, the uid and givenName are autogenerated... */
880     if (!$this->is_template){
881       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
882         $message[]= _("The required field 'Given name' is not set.");
883       }
884       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
885         $message[]= _("The required field 'Login' is not set.");
886       }
887       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
888         $ldap->cd($this->config->current['BASE']);
889         $ldap->search("(cn=".$this->cn.")", array("uid"));
890         $ldap->fetch();
891         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
892           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
893         }
894       }
895     }
897     /* Check for valid input */
898     if (!is_uid($this->uid)){
899       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
900     }
901     if (!is_url($this->labeledURI)){
902       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
903     }
904     if (preg_match ("/[\\\\]/", $this->sn)){
905       $message[]= _("The field 'Name' contains invalid characters.");
906     }
907     if (preg_match ("/[\\\\]/", $this->givenName)){
908       $message[]= _("The field 'Given name' contains invalid characters.");
909     }
911     /* Check phone numbers */
912     if (!is_phone_nr($this->homePhone)){
913       $message[]= _("The field 'Phone' contains an invalid phone number.");
914     }
915     if (!is_phone_nr($this->telephoneNumber)){
916       $message[]= _("The field 'Phone' contains an invalid phone number.");
917     }
918     if (!is_phone_nr($this->facsimileTelephoneNumber)){
919       $message[]= _("The field 'Fax' contains an invalid phone number.");
920     }
921     if (!is_phone_nr($this->mobile)){
922       $message[]= _("The field 'Mobile' contains an invalid phone number.");
923     }
924     if (!is_phone_nr($this->pager)){
925       $message[]= _("The field 'Pager' contains an invalid phone number.");
926     }
928     /* Check for reserved characers */
929     if (preg_match ('/[,+"<>;]/', $this->givenName)){
930       $message[]= _("The field 'Given name' contains invalid characters.");
931   }
932   if (preg_match ('/[,+"<>;]/', $this->sn)){
933     $message[]= _("The field 'Name' contains invalid characters.");
934   }
936   return $message;
937   }
940   /* Indicate whether a password change is needed or not */
941   function password_change_needed()
942   {
943     return ($this->pw_storage != $this->last_pw_storage);
944   }
947   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
948   function load_picture()
949   {
950     /* make connection and read jpegPhoto */
951     $ds= ldap_connect($this->config->current['SERVER']);
952     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
953     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
954       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
955       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
956     }
958     if(isset($this->config->current['TLS']) &&
959         $this->config->current['TLS'] == "true"){
961       ldap_start_tls($ds);
962     }
964     $r= ldap_bind($ds);
965     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
967     /* in case we don't get an entry, load a default picture */
968     $this->set_picture ("./images/default.jpg");
969     $this->jpegPhoto= "*removed*";
971     /* fill data from LDAP */
972     if ($sr) {
973       $ei=ldap_first_entry($ds, $sr);
974       if ($ei) {
975         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
976           $this->photoData= $info[0];
977           $_SESSION['picture']= $this->photoData;
978           $this->jpegPhoto= "";
979         }
980       }
981     }
983     /* close conncetion */
984     ldap_unbind($ds);
985   }
988   /* Load a certificate from LDAP, this is going to be simplified later on */
989   function load_cert()
990   {
991     $ds= ldap_connect($this->config->current['SERVER']);
992     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
993     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
994       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
995       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
996     }
997     if(isset($this->config->current['TLS']) &&
998         $this->config->current['TLS'] == "true"){
1000       ldap_start_tls($ds);
1001     }
1003     $r= ldap_bind($ds);
1004     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1006     if ($sr) {
1007       $ei= @ldap_first_entry($ds, $sr);
1008       
1009       if ($ei) {
1010         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1011           $this->userCertificate= "";
1012         } else {
1013           $this->userCertificate= $info[0];
1014         }
1015       }
1016     } else {
1017       $this->userCertificate= "";
1018     }
1020     ldap_unbind($ds);
1021   }
1024   /* Load picture from file to object */
1025   function set_picture($filename)
1026   {
1027     if (!is_file($filename)){
1028       $filename= "./images/default.jpg";
1029       $this->jpegPhoto= "*removed*";
1030     }
1032     $fd = fopen ($filename, "rb");
1033     $this->photoData= fread ($fd, filesize ($filename));
1034     $_SESSION['picture']= $this->photoData;
1035     $this->jpegPhoto= "";
1037     fclose ($fd);
1038   }
1041   /* Load certificate from file to object */
1042   function set_cert($cert, $filename)
1043   {
1044     $fd = fopen ($filename, "rb");
1045     $this->$cert= fread ($fd, filesize ($filename));
1046     fclose ($fd);
1047     $this->is_modified= TRUE;
1048   }
1050   /* Adapt from given 'dn' */
1051   function adapt_from_template($dn)
1052   {
1053     plugin::adapt_from_template($dn);
1055     /* Get base */
1056     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1058     if ($this->config->current['GOVERNMENTMODE']){
1060       /* Walk through govattrs */
1061       foreach ($this->govattrs as $val){
1063         if (isset($this->attrs["$val"][0])){
1065           /* If attribute is set, replace dynamic parts: 
1066              %sn, %givenName and %uid. Fill these in our local variables. */
1067           $value= $this->attrs["$val"][0];
1069           foreach (array("sn", "givenName", "uid") as $repl){
1070             if (preg_match("/%$repl/i", $value)){
1071               $value= preg_replace ("/%$repl/i",
1072                   $this->parent->$repl, $value);
1073             }
1074           }
1075           $this->$val= $value;
1076         }
1077       }
1078     }
1080     /* Get back uid/sn/givenName */
1081     if ($this->parent != NULL){
1082       $this->uid= $this->parent->uid;
1083       $this->sn= $this->parent->sn;
1084       $this->givenName= $this->parent->givenName;
1085     }
1086   }
1090 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1091 ?>