Code

Removed "ja" and "nein" attributes from publicVisible.
[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       }
121       /* Fix public visible attribute if unset */
122       if (!isset($this->attrs['publicVisible'])){
123         $this->publicVisible == "nein";
124       }
126     }
128     /* Create me for new accounts */
129     if ($dn == "new"){
130       $this->is_account= TRUE;
131     }
133     /* Make hash default to md5 if not set in config */
134     if (!isset($this->config->current['HASH'])){
135       $hash= "md5";
136     } else {
137       $hash= $this->config->current['HASH'];
138     }
140     /* Load data from LDAP? */
141     if ($dn != NULL){
143       /* Do base conversation */
144       if ($this->dn == "new"){
145         $ui= get_userinfo();
146         $this->base= dn2base($ui->dn);
147       } else {
148         $this->base= dn2base($dn);
149       }
151       /* get password storage type */
152       if (isset ($this->attrs['userPassword'][0])){
153         if (preg_match ("/^{([^}]+)}(.+)/", $this->attrs['userPassword'][0], $matches)){
154           $this->pw_storage= strtolower($matches[1]);
155         } else {
156           if ($this->attrs['userPassword'][0] != ""){
157             $this->pw_storage= "clear";
158           } else {
159             $this->pw_storage= $hash;
160           }
161         }
162       } else {
163         /* Preset with vaule from configuration */
164         $this->pw_storage= $hash;
165       }
167       /* Load extra attributes: certificate and picture */
168       $this->load_picture();
169       $this->load_cert();
170       if ($this->userCertificate != ""){
171         $this->had_userCertificate= TRUE;
172       }
173     }
175     /* Reset password storage indicator, used by password_change_needed() */
176     if ($dn == "new"){
177       $this->last_pw_storage= "unset";
178     } else {
179       $this->last_pw_storage= $this->pw_storage;
180     }
182     /* Generate dob entry */
183     if (isset ($this->attrs['dateOfBirth'])){
184       /* This entry is ISO 8601 conform */
185       list($year, $month, $day)= split("-", $this->attrs['dateOfBirth'][0], 3);
186       $this->dob= mktime ( 0, 0, 0, $month, $day, $year);
187       $this->use_dob= "1";
188     } else {
189       $this->use_dob= "0";
190     }
192     /* Put gender attribute to upper case */
193     if (isset ($this->attrs['gender'])){
194       $this->gender= strtoupper($this->attrs['gender'][0]);
195     }   
196   }
199   /* execute generates the html output for this node */
200   function execute()
201   {
202     $smarty= get_smarty();
204     /* Fill calendar */
205     if ($this->dob == "0"){
206       $date= getdate();
207     } else {
208       $date= getdate($this->dob);
209     }
211     $days= array();
212     for($d= 1; $d<32; $d++){
213       $days[$d]= $d;
214     }
215     $years= array();
216     for($y= $date['year']-100; $y<=$date['year']+100; $y++){
217       $years[]= $y;
218     }
219     $years['-']= "";
220     $months= array(_("January"), _("February"), _("March"), _("April"),
221         _("May"), _("June"), _("July"), _("August"), _("September"),
222         _("October"), _("November"), _("December"), '-' => '');
223     $smarty->assign("day", $date["mday"]);
224     $smarty->assign("days", $days);
225     $smarty->assign("months", $months);
226     $smarty->assign("month", $date["mon"]-1);
227     $smarty->assign("years", $years);
228     $smarty->assign("year", $date["year"]);
230     /* Assign sex */
231     $sex= array(0 => "", "F" => _("female"), "M" => _("male"));
232     $smarty->assign("gender_list", $sex);
234     /* Get random number for pictures */
235     srand((double)microtime()*1000000); 
236     $smarty->assign("rand", rand(0, 10000));
238     /* Do we represent a valid gosaAccount? */
239     if (!$this->is_account){
240       echo "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
241         _("This account has no valid GOsa extensions.")."</b>";
242       return;
243     }
245     /* Want picture edit dialog? */
246     if (isset($_POST['edit_picture'])){
247       /* Save values for later recovery, in case some presses
248          the cancel button. */
249       $this->old_jpegPhoto= $this->jpegPhoto;
250       $this->old_photoData= $this->photoData;
251       $this->picture_dialog= TRUE;
252       $this->dialog= TRUE;
253     }
255     /* Remove picture? */
256     if (isset($_POST['picture_remove'])){
257       $this->jpegPhoto= "*removed*";
258       $this->set_picture ("./images/default.jpg");
259       $this->is_modified= TRUE;
261       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
262     }
264     /* Save picture */
265     if (isset($_POST['picture_edit_finish'])){
267       /* Check for clean upload */
268       if ($_FILES['picture_file']['name'] != ""){
269         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
270           print_red(_("The specified file has not been uploaded via HTTP POST! Aborted."));
271           exit;
272         }
274         /* Activate new picture */
275         $this->set_picture($_FILES['picture_file']['tmp_name']);
276       }
277       $this->picture_dialog= FALSE;
278       $this->dialog= FALSE;
279       $this->is_modified= TRUE;
280     }
283     /* Cancel picture */
284     if (isset($_POST['picture_edit_cancel'])){
286       /* Restore values */
287       $this->jpegPhoto= $this->old_jpegPhoto;
288       $this->photoData= $this->old_photoData;
290       /* Update picture */
291       $_SESSION['picture']= $this->photoData;
292       $this->picture_dialog= FALSE;
293       $this->dialog= FALSE;
294     }
296     /* Toggle dob information */
297     if (isset($_POST['set_dob'])){
298       $this->use_dob= ($this->use_dob == "0")?"1":"0";
299     }
302     /* Want certificate= */
303     if (isset($_POST['edit_cert'])){
305       /* Save original values for later reconstruction */
306       foreach (array("certificateSerialNumber", "userCertificate",
307             "userSMIMECertificate", "userPKCS12") as $val){
309         $oval= "old_$val";
310         $this->$oval= $this->$val;
311       }
313       $this->cert_dialog= TRUE;
314       $this->dialog= TRUE;
315     }
318     /* Cancel certificate dialog */
319     if (isset($_POST['cert_edit_cancel'])){
321       /* Restore original values in case of 'cancel' */
322       foreach (array("certificateSerialNumber", "userCertificate",
323             "userSMIMECertificate", "userPKCS12") as $val){
325         $oval= "old_$val";
326         $this->$val= $this->$oval;
327       }
328       $this->cert_dialog= FALSE;
329       $this->dialog= FALSE;
330     }
333     /* Remove certificate? */
334     foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
335       if (isset($_POST["remove_$val"])){
337         /* Reset specified cert*/
338         $this->$val= "";
339         $this->is_modified= TRUE;
340       }
341     }
344     /* Upload new cert and close dialog? */     
345     if (isset($_POST['cert_edit_finish'])){
347       /* for all certificates do */
348       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
349           as $val){
351         /* Check for clean upload */
352         if (array_key_exists($val."_file", $_FILES) &&
353             array_key_exists('name', $_FILES[$val."_file"]) &&
354             $_FILES[$val."_file"]['name'] != "" &&
355             is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
356           $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
357         }
358       }
360       /* Save serial number */
361       if (isset($_POST["certificateSerialNumber"]) &&
362           $_POST["certificateSerialNumber"] != ""){
364         if (!is_id($_POST["certificateSerialNumber"])){
365           print_red (_("Please enter a valid serial number"));
367           foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
368             if ($this->$cert != ""){
369               $smarty->assign("$cert"."_state", "true");
370             } else {
371               $smarty->assign("$cert"."_state", "");
372             }
373           }
374           return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
375         }
377         $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
378         $this->is_modified= TRUE;
379       }
381       $this->cert_dialog= FALSE;
382       $this->dialog= FALSE;
383     }
385     /* Display picture dialog */
386     if ($this->picture_dialog){
387       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
388     }
390     /* Display cert dialog */
391     if ($this->cert_dialog){
392       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
393         if ($this->$cert != ""){
394           /* import certificate */
395           $certificate = new certificate;
396           $certificate->import($this->$cert);
397       
398           /* Read out data*/
399           $timeto   = $certificate->getvalidto_date();
400           $timefrom = $certificate->getvalidfrom_date();
401           $str = "<table summary=\"\" border=0><tr><td style='vertical-align:top'>CN</td><td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td></tr></table><br>".
402                   sprintf(_("Certificate is valid from <b>%s</b> to <b>%s</b> and is currently <b>%s</b>."), date('d M Y',$timefrom),date('d M Y',$timeto), $certificate->isvalid()?"<font style='color:green'>"._("valid")."</font>":"<font style='color:red'>"._("invalid")."</font>");
403           $smarty->assign($cert."info",$str);
404           $smarty->assign($cert."_state","true");
405         } else {
406           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
407           $smarty->assign($cert."_state","");
408         }
409       }
410       $smarty->assign("governmentmode", "false");
411       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
412     }
414     /* Show us the edit screen */
415     $smarty->assign("bases", $this->config->idepartments);
416     $smarty->assign("base_select", $this->base);
417     $smarty->assign("selectmode", chkacl($this->acl, "create"));
418     $smarty->assign("certificatesACL", chkacl($this->acl, "certificates"));
419     $smarty->assign("jpegPhotoACL", chkacl($this->acl, "jpegPhoto"));
421     /* Prepare password hashes */
422     if ($this->pw_storage == ""){
423       $this->pw_storage= $this->config->current['HASH'];
424     }
426     $temp   = passwordMethod::get_available_methods();
427     $hashes = $temp['name'];
428     
429     $smarty->assign("pwmode", $hashes);
430     $smarty->assign("pwmode_select", $this->pw_storage);
431     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
433     /* Load attributes and acl's */
434     foreach($this->attributes as $val){
435       $smarty->assign("$val", $this->$val);
436       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
437     }
439     /* Save government mode attributes */
440     if (isset($this->config->current['GOVERNMENTMODE']) &&
441         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
442       $smarty->assign("governmentmode", "true");
443       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
444           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
445       $smarty->assign("ivbbmodes", $ivbbmodes);
446       foreach ($this->govattrs as $val){
447         $smarty->assign("$val", $this->$val);
448         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
449       }
450     } else {
451       $smarty->assign("governmentmode", "false");
452     }
454     /* Special mode for uid */
455     $uidACL= "";
456     if (isset ($this->dn)){
457       if ($this->dn != "new"){
458         $uidACL="readonly";
459       }
460     }  else {
461       $uidACL= "readonly";
462     }
463     $uidACL.= " ".chkacl($this->acl, "uid");
464     
465     $smarty->assign("uidACL", $uidACL);
466     $smarty->assign("is_template", $this->is_template);
467     $smarty->assign("use_dob", $this->use_dob);
469     if (isset($this->parent)){
470       if (isset($this->parent->by_object['phoneAccount']) &&
471           $this->parent->by_object['phoneAccount']->is_account){
472         $smarty->assign("has_phoneaccount", "true");
473       } else {
474         $smarty->assign("has_phoneaccount", "false");
475       }
476     } else {
477         $smarty->assign("has_phoneaccount", "false");
478     }
480     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
481   }
484   /* remove object from parent */
485   function remove_from_parent()
486   {
487     $ldap= $this->config->get_ldap_link();
488     $ldap->rmdir ($this->dn);
490     /* Delete references to groups */
491     $ldap->cd ($this->config->current['BASE']);
492     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
493     while ($ldap->fetch()){
494       $g= new group($this->config, $ldap->getDN());
495       $g->removeUser($this->uid);
496       $g->save ();
497     }
499     /* Delete references to object groups */
500     $ldap->cd ($this->config->current['BASE']);
501     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
502     while ($ldap->fetch()){
503       $og= new ogroup($this->config, $ldap->getDN());
504       unset($og->member[$this->dn]);
505       $og->save ();
506     }
508     /* Optionally execute a command after we're done */
509     $this->handle_post_events("remove");
510   }
513   /* Save data to object */
514   function save_object()
515   {
516     if (isset($_POST['generic'])){
518       /* Parents save function */
519       plugin::save_object ();
521       /* Save government mode attributes */
522       if ($this->config->current['GOVERNMENTMODE']){
523         foreach ($this->govattrs as $val){
524           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
525             $data= stripcslashes($_POST["$val"]);
526             if ($data != $this->$val){
527               $this->is_modified= TRUE;
528             }
529             $this->$val= $data;
530           }
531         }
532       }
534       /* In template mode, the uid is autogenerated... */
535       if ($this->is_template){
536         $this->uid= strtolower($this->sn);
537         $this->givenName= $this->sn;
538       }
540       /* Save base and pw_storage, since these are no LDAP attributes */
541       if (isset($_POST['base'])){
542         foreach(array("base", "pw_storage") as $val){
543           $data= validate($_POST[$val]);
544           if ($data != $this->$val){
545             $this->is_modified= TRUE;
546           }
547           $this->$val= $data;
548         }
549       }
550     }
551   }
553   function rebind($ldap, $referral)
554   {
555     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
556     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
557       $this->error = "Success";
558       $this->hascon=true;
559       $this->reconnect= true;
560       return (0);
561     } else {
562       $this->error = "Could not bind to " . $binddn;
563       return NULL;
564     }
565   }
567   /* Save data to LDAP, depending on is_account we save or delete */
568   function save()
569   {
570     /* First use parents methods to do some basic fillup in $this->attrs */
571     plugin::save ();
573     /* Remove additional objectClasses */
574     $tmp= array();
575     foreach ($this->attrs['objectClass'] as $key => $set){
576       $found= false;
577       foreach (array("ivbbEntry", "gosaUserTemplate") as $val){
578         if (preg_match ("/^$set$/i", $val)){
579           $found= true;
580           break;
581         }
582       }
583       if (!$found){
584         $tmp[]= $set;
585       }
586     }
588     /* Replace the objectClass array. This is done because of the
589        separation into government and normal mode. */
590     $this->attrs['objectClass']= $tmp;
592     /* Add objectClasss for template mode? */
593     if ($this->is_template){
594       $this->attrs['objectClass'][]= "gosaUserTemplate";
595     }
597     /* Hard coded government mode? */
598     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
599       $this->attrs['objectClass'][]= "ivbbEntry";
601       /* Copy standard attributes */
602       foreach ($this->govattrs as $val){
603         if ($this->$val != ""){
604           $this->attrs["$val"]= $this->$val;
605         } elseif (!$this->new) {
606           $this->attrs["$val"]= array();
607         }
608       }
610       /* Remove attribute if set to "nein" */
611       if ($this->publicVisible == "nein"){
612         $this->attrs['publicVisible']= array();
613       }
615     }
617     /* Special handling for attribute userCertificate needed */
618     if ($this->userCertificate != ""){
619       $this->attrs["userCertificate;binary"]= $this->userCertificate;
620       $remove_userCertificate= false;
621     } else {
622       $remove_userCertificate= true;
623     }
625     /* Special handling for dob value */
626     if ($this->use_dob == "1"){
627       $this->attrs["dob"]= date("Y-m-d", $this->dob);
628     } else {
629       if ($this->new) {
630         unset($this->attrs["dob"]);
631       } else {
632         $this->attrs["dob"]= array();
633       }
634     }
635     if ($this->gender == "0"){
636       if ($this->new) {
637         unset($this->attrs["gender"]);
638       } else {
639         $this->attrs["gender"]= array();
640       }
641     }
643     /* Special handling for attribute jpegPhote needed, scale image via
644        image magick to 147x200 pixels and inject resulting data. */
645     if ($this->jpegPhoto != "*removed*"){
647       /* Fallback if there's no image magick inside PHP */
648       if (!function_exists("imagick_blob2image")){
649         /* Get temporary file name for conversation */
650         $fname = tempnam ("/tmp", "GOsa");
652         /* Open file and write out photoData */
653         $fp = fopen ($fname, "w");
654         fwrite ($fp, $this->photoData);
655         fclose ($fp);
657         /* Build conversation query. Filename is generated automatically, so
658            we do not need any special security checks. Exec command and save
659            output. For PHP safe mode, you'll need a configuration which respects
660            image magick as executable... */
661         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
662         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
663             $query, "Execute");
665         /* Read data written by convert */
666         $output= "";
667         $sh= popen($query, 'r');
668         while (!feof($sh)){
669           $output.= fread($sh, 4096);
670         }
671         pclose($sh);
673         unlink($fname);
675         /* Save attribute */
676         $this->attrs["jpegPhoto"] = $output;
678       } else {
680         /* Load the new uploaded Photo */
681         if(!$handle  =  imagick_blob2image($this->photoData))  {
682           gosa_log("Can't Load image");
683         }
685         /* Resizing image to 147x200 and blur */
686         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
687           gosa_log("imagick_resize failed");
688         }
690         /* Converting image to JPEG */
691         if(!imagick_convert($handle,"JPEG")) {
692           gosa_log("Can't Convert to JPEG");
693         }
695         /* Creating binary Code for the Image */
696         if(!$dump = imagick_image2blob($handle)){
697           gosa_log("Can't create blob for image");
698         }
700         /* Sending Image */
701         $output=  $dump;
703         /* Save attribute */
704         $this->attrs["jpegPhoto"] = $output;
705       }
707     } elseif(!$this->new) {
708       $this->attrs["jpegPhoto"] = array();
709     }
711     /* Build new dn */
712     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
713       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
714     } else {
715       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
716     }
718     /* This only gets called when user is renaming himself */
719     $ldap= $this->config->get_ldap_link();
720     if ($this->dn != $new_dn){
722       /* Write entry on new 'dn' */
723       $this->move($this->dn, $new_dn);
725       /* Happen to use the new one */
726       change_ui_dn($this->dn, $new_dn);
727       $this->dn= $new_dn;
728     }
731     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
732        new entries. So do a check first... */
733     $ldap->cat ($this->dn);
734     if ($ldap->fetch()){
735       $mode= "modify";
736     } else {
737       $mode= "add";
738       $ldap->cd($this->config->current['BASE']);
739       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
740     }
742     /* Set password to some junk stuff in case of templates */
743     if ($this->is_template){
744       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
745     }
747     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
748         $this->attributes, "Save via $mode");
750     /* Finally write data with selected 'mode' */
751     $ldap->cd ($this->dn);
752     $ldap->$mode ($this->attrs);
753     if (show_ldap_error($ldap->get_error())){
754       return (1);
755     }
757     /* Remove cert? 
758        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
759        to work around myself. */
760     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
762       /* Reset array, assemble new, this should be reworked */
763       $this->attrs= array();
764       $this->attrs['userCertificate;binary']= array();
766       /* Prepare connection */
767       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
768         die ("Could not connect to LDAP server");
769       }
770       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
771       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
772         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
773         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
774       }
775       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
776         ldap_start_tls($ds);
777       }
778       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
779               $this->config->current['PASSWORD']))) {
780         die ("Could not bind to LDAP");
781       }
783       /* Modify using attrs */
784       ldap_mod_del($ds,$this->dn,$this->attrs);
785       ldap_close($ds);
786     }
788     /* Kerberos server defined? */
789     if (isset($this->config->data['SERVERS']['KERBEROS'])){
790       $cfg= $this->config->data['SERVERS']['KERBEROS'];
791     }
792     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
794       /* Connect to the admin interface */
795       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
796           $cfg['ADMIN'], $cfg['PASSWORD']);
798       /* Errors? */             
799       if ($handle === FALSE){
800         print_red (_("Kerberos database communication failed"));
801         return (2);
802       }
804       /* Build user principal, get list of existsing principals */
805       $principal= $this->uid."@".$cfg['REALM'];
806       $principals = kadm5_get_principals($handle);
808       /* User exists in database? */
809       if (in_array($principal, $principals)){
811         /* Ok. User exists. Remove him/her when pw_storage has
812            changed to be NOT kerberos. */
813         if ($this->pw_storage != "kerberos"){
814           $ret= kadm5_delete_principal ( $handle, $principal);
816           if ($ret === FALSE){
817             print_red (_("Can't remove user from kerberos database."));
818           }
819         }
821       } else {
823         /* User doesn't exists, create it when pw_storage is kerberos. */
824         if ($this->pw_storage == "kerberos"){
825           $ret= kadm5_create_principal ( $handle, $principal);
827           if ($ret === FALSE){
828             print_red (_("Can't add user to kerberos database."));
829           }
830         }
832       }
834       /* Free kerberos admin handle */
835       kadm5_destroy($handle);
836     }
838     /* Optionally execute a command after we're done */
839     if ($mode == "add"){
840       $this->handle_post_events("add");
841     } elseif ($this->is_modified){
842       $this->handle_post_events("modify");
843     }
845     return (0);
846   }
849   /* Check formular input */
850   function check()
851   {
852     $message= array();
854     /* Assemble cn */
855     $this->cn= $this->givenName." ".$this->sn;
857     /* Permissions for that base? */
858     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
859       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
860     } else {
861       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
862     }
864     $ui= get_userinfo();
865     $acl= get_permissions ($new_dn, $ui->subtreeACL);
866     $acl= get_module_permission($acl, "user", $new_dn);
867     if ($this->dn == "new" && chkacl($acl, "create") != ""){
868       $message[]= _("You have no permissions to create a user on this 'Base'.");
869     } elseif ($this->dn != $new_dn && $this->dn != "new"){
870       $acl= get_permissions ($this->dn, $ui->subtreeACL);
871       $acl= get_module_permission($acl, "user", $this->dn);
872       if (chkacl($acl, "create") != ""){
873         $message[]= _("You have no permissions to move a user from the original 'Base'.");
874       }
875     }
877     /* must: sn, givenName, uid */
878     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
879       $message[]= _("The required field 'Name' is not set.");
880     }
882     /* UID already used? */
883     $ldap= $this->config->get_ldap_link();
884     $ldap->cd($this->config->current['BASE']);
885     $ldap->search("(uid=$this->uid)", array("uid"));
886     $ldap->fetch();
887     if ($ldap->count() != 0 && $this->dn == 'new'){
888       $message[]= _("There's already a person with this 'Login' in the database.");
889     }
891     /* In template mode, the uid and givenName are autogenerated... */
892     if (!$this->is_template){
893       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
894         $message[]= _("The required field 'Given name' is not set.");
895       }
896       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
897         $message[]= _("The required field 'Login' is not set.");
898       }
899       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
900         $ldap->cd($this->config->current['BASE']);
901         $ldap->search("(cn=".$this->cn.")", array("uid"));
902         $ldap->fetch();
903         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
904           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
905         }
906       }
907     }
909     /* Check for valid input */
910     if (!is_uid($this->uid)){
911       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
912     }
913     if (!is_url($this->labeledURI)){
914       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
915     }
916     if (preg_match ("/[\\\\]/", $this->sn)){
917       $message[]= _("The field 'Name' contains invalid characters.");
918     }
919     if (preg_match ("/[\\\\]/", $this->givenName)){
920       $message[]= _("The field 'Given name' contains invalid characters.");
921     }
923     /* Check phone numbers */
924     if (!is_phone_nr($this->homePhone)){
925       $message[]= _("The field 'Phone' contains an invalid phone number.");
926     }
927     if (!is_phone_nr($this->telephoneNumber)){
928       $message[]= _("The field 'Phone' contains an invalid phone number.");
929     }
930     if (!is_phone_nr($this->facsimileTelephoneNumber)){
931       $message[]= _("The field 'Fax' contains an invalid phone number.");
932     }
933     if (!is_phone_nr($this->mobile)){
934       $message[]= _("The field 'Mobile' contains an invalid phone number.");
935     }
936     if (!is_phone_nr($this->pager)){
937       $message[]= _("The field 'Pager' contains an invalid phone number.");
938     }
940     /* Check for reserved characers */
941     if (preg_match ('/[,+"<>;]/', $this->givenName)){
942       $message[]= _("The field 'Given name' contains invalid characters.");
943   }
944   if (preg_match ('/[,+"<>;]/', $this->sn)){
945     $message[]= _("The field 'Name' contains invalid characters.");
946   }
948   return $message;
949   }
952   /* Indicate whether a password change is needed or not */
953   function password_change_needed()
954   {
955     return ($this->pw_storage != $this->last_pw_storage);
956   }
959   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
960   function load_picture()
961   {
962     /* make connection and read jpegPhoto */
963     $ds= ldap_connect($this->config->current['SERVER']);
964     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
965     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
966       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
967       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
968     }
970     if(isset($this->config->current['TLS']) &&
971         $this->config->current['TLS'] == "true"){
973       ldap_start_tls($ds);
974     }
976     $r= ldap_bind($ds);
977     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
979     /* in case we don't get an entry, load a default picture */
980     $this->set_picture ("./images/default.jpg");
981     $this->jpegPhoto= "*removed*";
983     /* fill data from LDAP */
984     if ($sr) {
985       $ei=ldap_first_entry($ds, $sr);
986       if ($ei) {
987         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
988           $this->photoData= $info[0];
989           $_SESSION['picture']= $this->photoData;
990           $this->jpegPhoto= "";
991         }
992       }
993     }
995     /* close conncetion */
996     ldap_unbind($ds);
997   }
1000   /* Load a certificate from LDAP, this is going to be simplified later on */
1001   function load_cert()
1002   {
1003     $ds= ldap_connect($this->config->current['SERVER']);
1004     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1005     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1006       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1007       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1008     }
1009     if(isset($this->config->current['TLS']) &&
1010         $this->config->current['TLS'] == "true"){
1012       ldap_start_tls($ds);
1013     }
1015     $r= ldap_bind($ds);
1016     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1018     if ($sr) {
1019       $ei= @ldap_first_entry($ds, $sr);
1020       
1021       if ($ei) {
1022         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1023           $this->userCertificate= "";
1024         } else {
1025           $this->userCertificate= $info[0];
1026         }
1027       }
1028     } else {
1029       $this->userCertificate= "";
1030     }
1032     ldap_unbind($ds);
1033   }
1036   /* Load picture from file to object */
1037   function set_picture($filename)
1038   {
1039     if (!is_file($filename)){
1040       $filename= "./images/default.jpg";
1041       $this->jpegPhoto= "*removed*";
1042     }
1044     $fd = fopen ($filename, "rb");
1045     $this->photoData= fread ($fd, filesize ($filename));
1046     $_SESSION['picture']= $this->photoData;
1047     $this->jpegPhoto= "";
1049     fclose ($fd);
1050   }
1053   /* Load certificate from file to object */
1054   function set_cert($cert, $filename)
1055   {
1056     $fd = fopen ($filename, "rb");
1057     if (filesize($filename)>0) {
1058       $this->$cert= fread ($fd, filesize ($filename));
1059       fclose ($fd);
1060       $this->is_modified= TRUE;
1061     } else {
1062       print_red(_("Could not open specified certificate!"));
1063     }
1064   }
1066   /* Adapt from given 'dn' */
1067   function adapt_from_template($dn)
1068   {
1069     plugin::adapt_from_template($dn);
1071     /* Get base */
1072     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1074     if ($this->config->current['GOVERNMENTMODE']){
1076       /* Walk through govattrs */
1077       foreach ($this->govattrs as $val){
1079         if (isset($this->attrs["$val"][0])){
1081           /* If attribute is set, replace dynamic parts: 
1082              %sn, %givenName and %uid. Fill these in our local variables. */
1083           $value= $this->attrs["$val"][0];
1085           foreach (array("sn", "givenName", "uid") as $repl){
1086             if (preg_match("/%$repl/i", $value)){
1087               $value= preg_replace ("/%$repl/i",
1088                   $this->parent->$repl, $value);
1089             }
1090           }
1091           $this->$val= $value;
1092         }
1093       }
1094     }
1096     /* Get back uid/sn/givenName */
1097     if ($this->parent != NULL){
1098       $this->uid= $this->parent->uid;
1099       $this->sn= $this->parent->sn;
1100       $this->givenName= $this->parent->givenName;
1101     }
1102   }
1106 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1107 ?>