Code

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