Code

99079e34de7b630f684a9ffb48c8dab25200d4e2
[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";
82   /* attribute list for save action */
83   var $attributes= array("sn", "givenName", "uid", "personalTitle", "academicTitle",
84       "homePostalAddress", "homePhone", "labeledURI", "o", "ou", "dob", "gender",
85       "departmentNumber", "employeeNumber", "employeeType", "l", "st",
86       "roomNumber", "telephoneNumber", "mobile", "pager", "cn", "userPKCS12",
87       "postalAddress", "facsimileTelephoneNumber", "userSMIMECertificate");
89   var $objectclasses= array("top", "person", "organizationalPerson", "inetOrgPerson",
90       "gosaAccount");
92   /* attributes that are part of the government mode */
93   var $govattrs= array("gouvernmentOrganizationalUnit", "houseIdentifier", "vocation",
94       "ivbbLastDeliveryCollective", "gouvernmentOrganizationalPersonLocality",
95       "gouvernmentOrganizationalUnitDescription","gouvernmentOrganizationalUnitSubjectArea",
96       "functionalTitle", "certificateSerialNumber", "publicVisible", "street", "role",
97       "postalCode");
100   /* constructor, if 'dn' is set, the node loads the given
101      'dn' from LDAP */
102   function user ($config, $dn= NULL)
103   {
104     /* Configuration is fine, allways */
105     $this->config= $config;
107     /* Load base attributes */
108     plugin::plugin ($config, $dn);
110     /* Load government mode attributes */
111     if ($this->config->current['GOVERNMENTMODE']){
113       /* Copy all attributs */
114       foreach ($this->govattrs as $val){
115         if (isset($this->attrs["$val"][0])){
116           $this->$val= $this->attrs["$val"][0];
117         }
118       }
119     }
121     /* Create me for new accounts */
122     if ($dn == "new"){
123       $this->is_account= TRUE;
124     }
126     /* Make hash default to md5 if not set in config */
127     if (!isset($this->config->current['HASH'])){
128       $hash= "md5";
129     } else {
130       $hash= $this->config->current['HASH'];
131     }
133     /* Load data from LDAP? */
134     if ($dn != NULL){
136       /* Do base conversation */
137       if ($this->dn == "new"){
138         $ui= get_userinfo();
139         $this->base= dn2base($ui->dn);
140       } else {
141         $this->base= dn2base($dn);
142       }
144       /* get password storage type */
145       if (isset ($this->attrs['userPassword'][0])){
146         if (preg_match ("/^{([^}]+)}(.+)/", $this->attrs['userPassword'][0], $matches)){
147           $this->pw_storage= strtolower($matches[1]);
148         } else {
149           if ($this->attrs['userPassword'][0] != ""){
150             $this->pw_storage= "clear";
151           } else {
152             $this->pw_storage= $hash;
153           }
154         }
155       } else {
156         /* Preset with vaule from configuration */
157         $this->pw_storage= $hash;
158       }
160       /* Load extra attributes: certificate and picture */
161       $this->load_cert();
162       $this->load_picture();
163     }
165     /* Reset password storage indicator, used by password_change_needed() */
166     if ($dn == "new"){
167       $this->last_pw_storage= "unset";
168     } else {
169       $this->last_pw_storage= $this->pw_storage;
170     }
172     /* Generate dob entry */
173     if (isset ($this->attrs['dateOfBirth'])){
174       /* This entry is ISO 8601 conform */
175       list($year, $month, $day)= split("-", $this->attrs['dateOfBirth'][0], 3);
176       $this->dob= mktime ( 0, 0, 0, $month, $day, $year);
177       $this->use_dob= "1";
178     } else {
179       $this->use_dob= "0";
180     }
182     /* Put gender attribute to upper case */
183     if (isset ($this->attrs['gender'])){
184       $this->gender= strtoupper($this->attrs['gender'][0]);
185     }   
186   }
189   /* execute generates the html output for this node */
190   function execute()
191   {
192     $smarty= get_smarty();
194     /* Fill calendar */
195     if ($this->dob == "0"){
196       $date= getdate();
197     } else {
198       $date= getdate($this->dob);
199     }
201     $days= array();
202     for($d= 1; $d<32; $d++){
203       $days[$d]= $d;
204     }
205     $years= array();
206     for($y= $date['year']-100; $y<=$date['year']+100; $y++){
207       $years[]= $y;
208     }
209     $years['-']= "";
210     $months= array(_("January"), _("February"), _("March"), _("April"),
211         _("May"), _("June"), _("July"), _("August"), _("September"),
212         _("October"), _("November"), _("December"), '-' => '');
213     $smarty->assign("day", $date["mday"]);
214     $smarty->assign("days", $days);
215     $smarty->assign("months", $months);
216     $smarty->assign("month", $date["mon"]-1);
217     $smarty->assign("years", $years);
218     $smarty->assign("year", $date["year"]);
220     /* Assign sex */
221     $sex= array(0 => "", "F" => _("female"), "M" => _("male"));
222     $smarty->assign("gender_list", $sex);
224     /* Get random number for pictures */
225     srand((double)microtime()*1000000); 
226     $smarty->assign("rand", rand(0, 10000));
228     /* Do we represent a valid gosaAccount? */
229     if (!$this->is_account){
230       echo "<img src=\"images/stop.png\" align=center>&nbsp;<b>".
231         _("This account has no valid GOsa extensions.")."</b>";
232       return;
233     }
235     /* Want picture edit dialog? */
236     if (isset($_POST['edit_picture'])){
237       /* Save values for later recovery, in case some presses
238          the cancel button. */
239       $this->old_jpegPhoto= $this->jpegPhoto;
240       $this->old_photoData= $this->photoData;
241       $this->picture_dialog= TRUE;
242       $this->dialog= TRUE;
243     }
245     /* Remove picture? */
246     if (isset($_POST['picture_remove'])){
247       $this->jpegPhoto= "*removed*";
248       $this->set_picture ("./images/default.jpg");
249       $this->is_modified= TRUE;
251       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
252     }
254     /* Save picture */
255     if (isset($_POST['picture_edit_finish'])){
257       /* Check for clean upload */
258       if ($_FILES['picture_file']['name'] != ""){
259         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
260           print_red(_("The specified file has not been uploaded via HTTP POST! Aborted."));
261           exit;
262         }
264         /* Activate new picture */
265         $this->set_picture($_FILES['picture_file']['tmp_name']);
266       }
267       $this->picture_dialog= FALSE;
268       $this->dialog= FALSE;
269       $this->is_modified= TRUE;
270     }
273     /* Cancel picture */
274     if (isset($_POST['picture_edit_cancel'])){
276       /* Restore values */
277       $this->jpegPhoto= $this->old_jpegPhoto;
278       $this->photoData= $this->old_photoData;
280       /* Update picture */
281       $_SESSION['picture']= $this->photoData;
282       $this->picture_dialog= FALSE;
283       $this->dialog= FALSE;
284     }
286     /* Toggle dob information */
287     if (isset($_POST['set_dob'])){
288       $this->use_dob= ($this->use_dob == "0")?"1":"0";
289     }
292     /* Want certificate= */
293     if (isset($_POST['edit_cert'])){
295       /* Save original values for later reconstruction */
296       foreach (array("certificateSerialNumber", "userCertificate",
297             "userSMIMECertificate", "userPKCS12") as $val){
299         $oval= "old_$val";
300         $this->$oval= $this->$val;
301       }
303       $this->cert_dialog= TRUE;
304       $this->dialog= TRUE;
305     }
308     /* Cancel certificate dialog */
309     if (isset($_POST['cert_edit_cancel'])){
311       /* Restore original values in case of 'cancel' */
312       foreach (array("certificateSerialNumber", "userCertificate",
313             "userSMIMECertificate", "userPKCS12") as $val){
315         $oval= "old_$val";
316         $this->$val= $this->$oval;
317       }
318       $this->cert_dialog= FALSE;
319       $this->dialog= FALSE;
320     }
323     /* Remove certificate? */
324     foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
325       if (isset($_POST["remove_$val"])){
327         /* Reset specified cert*/
328         $this->$val= "";
329         $this->is_modified= TRUE;
330       }
331     }
334     /* Upload new cert and close dialog? */     
335     if (isset($_POST['cert_edit_finish'])){
337       /* for all certificates do */
338       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
339           as $val){
341         /* Check for clean upload */
342         if ($_FILES[$val."_file"]['name'] != "" && 
343             is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
345           $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
346         }
347       }
349       /* Save serial number */
350       if (isset($_POST["certificateSerialNumber"]) &&
351           $_POST["certificateSerialNumber"] != ""){
353         if (!is_id($_POST["certificateSerialNumber"])){
354           print_red (_("Please enter a valid serial number"));
356           foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
357             if ($this->$cert != ""){
358               $smarty->assign("$cert"."_state", _("present"));
359             } else {
360               $smarty->assign("$cert"."_state", _("absent"));
361             }
362           }
363           return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
364         }
366         $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
367         $this->is_modified= TRUE;
368       }
370       $this->cert_dialog= FALSE;
371       $this->dialog= FALSE;
372     }
374     /* Display picture dialog */
375     if ($this->picture_dialog){
376       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
377     }
379     /* Display cert dialog */
380     if ($this->cert_dialog){
381       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
382         if ($this->$cert != ""){
383           $smarty->assign("$cert"."_state", _("present"));
384         } else {
385           $smarty->assign("$cert"."_state", _("absent"));
386         }
387       }
388       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
389     }
391     /* Show us the edit screen */
392     $smarty->assign("bases", $this->config->idepartments);
393     $smarty->assign("base_select", $this->base);
394     $smarty->assign("selectmode", chkacl($this->acl, "create"));
395     $smarty->assign("certificatesACL", chkacl($this->acl, "certificates"));
396     $smarty->assign("jpegPhotoACL", chkacl($this->acl, "jpegPhoto"));
398     /* Prepare password hashes */
399     if ($this->pw_storage == ""){
400       $this->pw_storage= $this->config->current['HASH'];
401     }
403     $temp   = passwordMethod::get_available_methods();
404     $hashes = $temp['name'];
405     
406     $smarty->assign("pwmode", $hashes);
407     $smarty->assign("pwmode_select", $this->pw_storage);
408     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
410     /* Load attributes and acl's */
411     foreach($this->attributes as $val){
412       $smarty->assign("$val", $this->$val);
413       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
414     }
416     /* Save government mode attributes */
417     if (isset($this->config->current['GOVERNMENTMODE']) &&
418         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
419       $smarty->assign("governmentmode", "true");
420       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
421           "internet,ivbv", "internet,testa", "internet,ivbv,testa", "ja");
422       $smarty->assign("ivbbmodes", $ivbbmodes);
423       foreach ($this->govattrs as $val){
424         $smarty->assign("$val", $this->$val);
425         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
426       }
427     } else {
428       $smarty->assign("governmentmode", "false");
429     }
431     /* Special mode for uid */
432     $uidACL= "";
433     if (isset ($this->dn)){
434       if ($this->dn != "new"){
435         $uidACL="readonly";
436       }
437     }  else {
438       $uidACL= "readonly";
439     }
440     if ($uidACL == ""){
441       $uidACL= chkacl($this->acl, "uid");
442     }
443     $smarty->assign("uidACL", $uidACL);
444     $smarty->assign("is_template", $this->is_template);
445     $smarty->assign("use_dob", $this->use_dob);
447     if (isset($this->parent)){
448       if (isset($this->parent->by_object['phoneAccount']) &&
449           $this->parent->by_object['phoneAccount']->is_account){
450         $smarty->assign("has_phoneaccount", "true");
451       } else {
452         $smarty->assign("has_phoneaccount", "false");
453       }
454     }
456     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
457   }
460   /* remove object from parent */
461   function remove_from_parent()
462   {
463     $ldap= $this->config->get_ldap_link();
464     $ldap->rmdir ($this->dn);
466     /* Delete references to groups */
467     $ldap->cd ($this->config->current['BASE']);
468     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
469     while ($ldap->fetch()){
470       $g= new group($this->config, $ldap->getDN());
471       $g->removeUser($this->uid);
472       $g->save ();
473     }
475     /* Delete references to object groups */
476     $ldap->cd ($this->config->current['BASE']);
477     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
478     while ($ldap->fetch()){
479       $og= new ogroup($this->config, $ldap->getDN());
480       unset($og->member[$this->dn]);
481       $og->save ();
482     }
484     /* Optionally execute a command after we're done */
485     $this->handle_post_events("remove");
486   }
489   /* Save data to object */
490   function save_object()
491   {
492     if (isset($_POST['generic'])){
494       /* Parents save function */
495       plugin::save_object ();
497       /* Save government mode attributes */
498       if ($this->config->current['GOVERNMENTMODE']){
499         foreach ($this->govattrs as $val){
500           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
501             $data= stripcslashes($_POST["$val"]);
502             if ($data != $this->$val){
503               $this->is_modified= TRUE;
504             }
505             $this->$val= $data;
506           }
507         }
508       }
510       /* In template mode, the uid is autogenerated... */
511       if ($this->is_template){
512         $this->uid= strtolower($this->sn);
513         $this->givenName= $this->sn;
514       }
516       /* Save base and pw_storage, since these are no LDAP attributes */
517       if (isset($_POST['base'])){
518         foreach(array("base", "pw_storage") as $val){
519           $data= validate($_POST[$val]);
520           if ($data != $this->$val){
521             $this->is_modified= TRUE;
522           }
523           $this->$val= $data;
524         }
525       }
526     }
527   }
529   function rebind($ldap, $referral)
530   {
531     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
532     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
533       $this->error = "Success";
534       $this->hascon=true;
535       $this->reconnect= true;
536       return (0);
537     } else {
538       $this->error = "Could not bind to " . $binddn;
539       return NULL;
540     }
541   }
543   /* Save data to LDAP, depending on is_account we save or delete */
544   function save()
545   {
546     /* First use parents methods to do some basic fillup in $this->attrs */
547     plugin::save ();
549     /* Remove additional objectClasses */
550     $tmp= array();
551     foreach ($this->attrs['objectClass'] as $key => $set){
552       $found= false;
553       foreach (array("ivbbEntry", "gosaUserTemplate") as $val){
554         if (preg_match ("/^$set$/i", $val)){
555           $found= true;
556           break;
557         }
558       }
559       if (!$found){
560         $tmp[]= $set;
561       }
562     }
564     /* Replace the objectClass array. This is done because of the
565        separation into government and normal mode. */
566     $this->attrs['objectClass']= $tmp;
568     /* Add objectClasss for template mode? */
569     if ($this->is_template){
570       $this->attrs['objectClass'][]= "gosaUserTemplate";
571     }
573     /* Hard coded government mode? */
574     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
575       $this->attrs['objectClass'][]= "ivbbEntry";
577       /* Copy standard attributes */
578       foreach ($this->govattrs as $val){
579         if ($this->$val != ""){
580           $this->attrs["$val"]= $this->$val;
581         } elseif (!$this->new) {
582           $this->attrs["$val"]= array();
583         }
584       }
586     }
588     /* Special handling for attribute userCertificate needed */
589     if ($this->userCertificate != ""){
590       $this->attrs["userCertificate;binary"]= $this->userCertificate;
591       $remove_userCertificate= false;
592     } else {
593       $remove_userCertificate= true;
594     }
596     /* Special handling for dob value */
597     if ($this->use_dob == "1"){
598       $this->attrs["dob"]= date("Y-m-d", $this->dob);
599     } else {
600       if ($this->new) {
601         unset($this->attrs["dob"]);
602       } else {
603         $this->attrs["dob"]= array();
604       }
605     }
606     if ($this->gender == "0"){
607       if ($this->new) {
608         unset($this->attrs["gender"]);
609       } else {
610         $this->attrs["gender"]= array();
611       }
612     }
614     /* Special handling for attribute jpegPhote needed, scale image via
615        image magick to 147x200 pixels and inject resulting data. */
616     if ($this->jpegPhoto != "*removed*"){
618       /* Fallback if there's no image magick inside PHP */
619       if (!function_exists("imagick_blob2image")){
620         /* Get temporary file name for conversation */
621         $fname = tempnam ("/tmp", "GOsa");
623         /* Open file and write out photoData */
624         $fp = fopen ($fname, "w");
625         fwrite ($fp, $this->photoData);
626         fclose ($fp);
628         /* Build conversation query. Filename is generated automatically, so
629            we do not need any special security checks. Exec command and save
630            output. For PHP safe mode, you'll need a configuration which respects
631            image magick as executable... */
632         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
633         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
634             $query, "Execute");
636         /* Read data written by convert */
637         $output= "";
638         $sh= popen($query, 'r');
639         while (!feof($sh)){
640           $output.= fread($sh, 4096);
641         }
642         pclose($sh);
644         unlink($fname);
646         /* Save attribute */
647         $this->attrs["jpegPhoto"] = $output;
649       } else {
651         /* Load the new uploaded Photo */
652         if(!$handle  =  imagick_blob2image($this->photoData))  {
653           gosa_log("Can't Load image");
654         }
656         /* Resizing image to 147x200 and blur */
657         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
658           gosa_log("imagick_resize failed");
659         }
661         /* Converting image to JPEG */
662         if(!imagick_convert($handle,"JPEG")) {
663           gosa_log("Can't Convert to JPEG");
664         }
666         /* Creating binary Code for the Image */
667         if(!$dump = imagick_image2blob($handle)){
668           gosa_log("Can't create blob for image");
669         }
671         /* Sending Image */
672         $output=  $dump;
674         /* Save attribute */
675         $this->attrs["jpegPhoto"] = $output;
676       }
678     } elseif(!$this->new) {
679       $this->attrs["jpegPhoto"] = array();
680     }
682     /* Build new dn */
683     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
684       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
685     } else {
686       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
687     }
689     /* This only gets called when user is renaming himself */
690     $ldap= $this->config->get_ldap_link();
691     if ($this->dn != $new_dn){
693       /* Write entry on new 'dn' */
694       $this->move($this->dn, $new_dn);
696       /* Happen to use the new one */
697       change_ui_dn($this->dn, $new_dn);
698       $this->dn= $new_dn;
699     }
702     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
703        new entries. So do a check first... */
704     $ldap->cat ($this->dn);
705     if ($ldap->fetch()){
706       $mode= "modify";
707     } else {
708       $mode= "add";
709       $ldap->cd($this->config->current['BASE']);
710       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
711     }
713     /* Set password to some junk stuff in case of templates */
714     if ($this->is_template){
715       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
716     }
718     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
719         $this->attributes, "Save via $mode");
721     /* Finally write data with selected 'mode' */
722     $ldap->cd ($this->dn);
723     $ldap->$mode ($this->attrs);
724     if (show_ldap_error($ldap->get_error())){
725       return (1);
726     }
728     /* Remove cert? 
729        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
730        to work around myself. */
731     if ($remove_userCertificate == true && !$this->new){
733       /* Reset array, assemble new, this should be reworked */
734       $this->attrs= array();
735       $this->attrs['userCertificate;binary']= array();
737       /* Prepare connection */
738       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
739         die ("Could not connect to LDAP server");
740       }
741       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
742       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
743         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
744         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
745       }
746       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
747         ldap_start_tls($ds);
748       }
749       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
750               $this->config->current['PASSWORD']))) {
751         die ("Could not bind to LDAP");
752       }
754       /* Modify using attrs */
755       @ldap_mod_del($ds,$this->dn,$this->attrs);
756       ldap_close($ds);
758     }
760     /* Kerberos server defined? */
761     if (isset($this->config->data['SERVERS']['KERBEROS'])){
762       $cfg= $this->config->data['SERVERS']['KERBEROS'];
763     }
764     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
766       /* Connect to the admin interface */
767       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
768           $cfg['ADMIN'], $cfg['PASSWORD']);
770       /* Errors? */             
771       if ($handle === FALSE){
772         print_red (_("Kerberos database communication failed"));
773         return (2);
774       }
776       /* Build user principal, get list of existsing principals */
777       $principal= $this->uid."@".$cfg['REALM'];
778       $principals = kadm5_get_principals($handle);
780       /* User exists in database? */
781       if (in_array($principal, $principals)){
783         /* Ok. User exists. Remove him/her when pw_storage has
784            changed to be NOT kerberos. */
785         if ($this->pw_storage != "kerberos"){
786           $ret= kadm5_delete_principal ( $handle, $principal);
788           if ($ret === FALSE){
789             print_red (_("Can't remove user from kerberos database."));
790           }
791         }
793       } else {
795         /* User doesn't exists, create it when pw_storage is kerberos. */
796         if ($this->pw_storage == "kerberos"){
797           $ret= kadm5_create_principal ( $handle, $principal);
799           if ($ret === FALSE){
800             print_red (_("Can't add user to kerberos database."));
801           }
802         }
804       }
806       /* Free kerberos admin handle */
807       kadm5_destroy($handle);
808     }
810     /* Optionally execute a command after we're done */
811     if ($mode == "add"){
812       $this->handle_post_events("add");
813     } elseif ($this->is_modified){
814       $this->handle_post_events("modify");
815     }
817     return (0);
818   }
821   /* Check formular input */
822   function check()
823   {
824     $message= array();
826     /* Assemble cn */
827     $this->cn= $this->givenName." ".$this->sn;
829     /* Permissions for that base? */
830     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
831       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
832     } else {
833       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
834     }
836     $ui= get_userinfo();
837     $acl= get_permissions ($new_dn, $ui->subtreeACL);
838     $acl= get_module_permission($acl, "user", $new_dn);
839     if ($this->dn == "new" && chkacl($acl, "create") != ""){
840       $message[]= _("You have no permissions to create a user on this 'Base'.");
841     } elseif ($this->dn != $new_dn){
842       $acl= get_permissions ($this->dn, $ui->subtreeACL);
843       $acl= get_module_permission($acl, "user", $this->dn);
844       if (chkacl($acl, "create") != ""){
845         $message[]= _("You have no permissions to move a user from the original 'Base'.");
846       }
847     }
849     /* must: sn, givenName, uid */
850     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
851       $message[]= _("The required field 'Name' is not set.");
852     }
854     /* UID already used? */
855     $ldap= $this->config->get_ldap_link();
856     $ldap->cd($this->config->current['BASE']);
857     $ldap->search("(uid=$this->uid)", array("uid"));
858     $ldap->fetch();
859     if ($ldap->count() != 0 && $this->dn == 'new'){
860       $message[]= _("There's already a person with this 'Login' in the database.");
861     }
863     /* In template mode, the uid and givenName are autogenerated... */
864     if (!$this->is_template){
865       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
866         $message[]= _("The required field 'Given name' is not set.");
867       }
868       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
869         $message[]= _("The required field 'Login' is not set.");
870       }
871       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
872         $ldap->cd($this->config->current['BASE']);
873         $ldap->search("(cn=".$this->cn.")", array("uid"));
874         $ldap->fetch();
875         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
876           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
877         }
878       }
879     }
881     /* Check for valid input */
882     if (!is_uid($this->uid)){
883       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
884     }
885     if (!is_url($this->labeledURI)){
886       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
887     }
888     if (preg_match ("/[\\\\]/", $this->sn)){
889       $message[]= _("The field 'Name' contains invalid characters.");
890     }
891     if (preg_match ("/[\\\\]/", $this->givenName)){
892       $message[]= _("The field 'Given name' contains invalid characters.");
893     }
895     /* Check phone numbers */
896     if (!is_phone_nr($this->homePhone)){
897       $message[]= _("The field 'Phone' contains an invalid phone number.");
898     }
899     if (!is_phone_nr($this->telephoneNumber)){
900       $message[]= _("The field 'Phone' contains an invalid phone number.");
901     }
902     if (!is_phone_nr($this->facsimileTelephoneNumber)){
903       $message[]= _("The field 'Fax' contains an invalid phone number.");
904     }
905     if (!is_phone_nr($this->mobile)){
906       $message[]= _("The field 'Mobile' contains an invalid phone number.");
907     }
908     if (!is_phone_nr($this->pager)){
909       $message[]= _("The field 'Pager' contains an invalid phone number.");
910     }
912     /* Check for reserved characers */
913     if (preg_match ('/[,+"<>;]/', $this->givenName)){
914       $message[]= _("The field 'Given name' contains invalid characters.");
915   }
916   if (preg_match ('/[,+"<>;]/', $this->sn)){
917     $message[]= _("The field 'Name' contains invalid characters.");
918   }
920   return $message;
921   }
924   /* Indicate whether a password change is needed or not */
925   function password_change_needed()
926   {
927     return ($this->pw_storage != $this->last_pw_storage);
928   }
931   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
932   function load_picture()
933   {
934     /* make connection and read jpegPhoto */
935     $ds= ldap_connect($this->config->current['SERVER']);
936     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
937     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
938       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
939       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
940     }
942     if(isset($this->config->current['TLS']) &&
943         $this->config->current['TLS'] == "true"){
945       ldap_start_tls($ds);
946     }
948     $r= ldap_bind($ds);
949     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
951     /* in case we don't get an entry, load a default picture */
952     $this->set_picture ("./images/default.jpg");
953     $this->jpegPhoto= "*removed*";
955     /* fill data from LDAP */
956     if ($sr) {
957       $ei=ldap_first_entry($ds, $sr);
958       if ($ei) {
959         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
960           $this->photoData= $info[0];
961           $_SESSION['picture']= $this->photoData;
962           $this->jpegPhoto= "";
963         }
964       }
965     }
967     /* close conncetion */
968     ldap_unbind($ds);
969   }
972   /* Load a certificate from LDAP, this is going to be simplified later on */
973   function load_cert()
974   {
975     $ds= ldap_connect($this->config->current['SERVER']);
976     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
977     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
978       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
979       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
980     }
981     if(isset($this->config->current['TLS']) &&
982         $this->config->current['TLS'] == "true"){
984       ldap_start_tls($ds);
985     }
987     $r= ldap_bind($ds);
988     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
990     if ($sr) {
991       $ei= @ldap_first_entry($ds, $sr);
992       
993       if ($ei) {
994         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
995           $this->userCertificate= "";
996         } else {
997           $this->userCertificate= $info[0];
998         }
999       }
1000     } else {
1001       $this->userCertificate= "";
1002     }
1004     ldap_unbind($ds);
1005   }
1008   /* Load picture from file to object */
1009   function set_picture($filename)
1010   {
1011     if (!is_file($filename)){
1012       $filename= "./images/default.jpg";
1013       $this->jpegPhoto= "*removed*";
1014     }
1016     $fd = fopen ($filename, "rb");
1017     $this->photoData= fread ($fd, filesize ($filename));
1018     $_SESSION['picture']= $this->photoData;
1019     $this->jpegPhoto= "";
1021     fclose ($fd);
1022   }
1025   /* Load certificate from file to object */
1026   function set_cert($cert, $filename)
1027   {
1028     $fd = fopen ($filename, "rb");
1029     $this->$cert= fread ($fd, filesize ($filename));
1030     fclose ($fd);
1031     $this->is_modified= TRUE;
1032   }
1034   /* Adapt from given 'dn' */
1035   function adapt_from_template($dn)
1036   {
1037     plugin::adapt_from_template($dn);
1039     /* Get base */
1040     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1042     if ($this->config->current['GOVERNMENTMODE']){
1044       /* Walk through govattrs */
1045       foreach ($this->govattrs as $val){
1047         if (isset($this->attrs["$val"][0])){
1049           /* If attribute is set, replace dynamic parts: 
1050              %sn, %givenName and %uid. Fill these in our local variables. */
1051           $value= $this->attrs["$val"][0];
1053           foreach (array("sn", "givenName", "uid") as $repl){
1054             if (preg_match("/%$repl/i", $value)){
1055               $value= preg_replace ("/%$repl/i",
1056                   $this->parent->$repl, $value);
1057             }
1058           }
1059           $this->$val= $value;
1060         }
1061       }
1062     }
1064     /* Get back uid/sn/givenName */
1065     if ($this->parent != NULL){
1066       $this->uid= $this->parent->uid;
1067       $this->sn= $this->parent->sn;
1068       $this->givenName= $this->parent->givenName;
1069     }
1070   }
1074 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1075 ?>