Code

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