Code

add dropdown with preferred language for the mediawiki authorization
[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";
48   var $preferredLanguage= "";
50   var $jpegPhoto= "*removed*";
51   var $photoData= "";
52   var $old_jpegPhoto= "";
53   var $old_photoData= "";
54   var $cert_dialog= FALSE;
55   var $picture_dialog= FALSE;
57   var $userPKCS12= "";
58   var $userSMIMECertificate= "";
59   var $userCertificate= "";
60   var $certificateSerialNumber= "";
61   var $old_certificateSerialNumber= "";
62   var $old_userPKCS12= "";
63   var $old_userSMIMECertificate= "";
64   var $old_userCertificate= "";
66   var $gouvernmentOrganizationalUnit= "";
67   var $houseIdentifier= "";
68   var $street= "";
69   var $postalCode= "";
70   var $vocation= "";
71   var $ivbbLastDeliveryCollective= "";
72   var $gouvernmentOrganizationalPersonLocality= "";
73   var $gouvernmentOrganizationalUnitDescription= "";
74   var $gouvernmentOrganizationalUnitSubjectArea= "";
75   var $functionalTitle= "";
76   var $role= "";
77   var $publicVisible= "";
79   /* variables to trigger password changes */
80   var $pw_storage= "crypt";
81   var $last_pw_storage= "unset";
82   var $had_userCertificate= FALSE;
84   /* attribute list for save action */
85   var $attributes= array("sn", "givenName", "uid", "personalTitle", "academicTitle",
86       "homePostalAddress", "homePhone", "labeledURI", "o", "ou", "dob", "gender","preferredLanguage",
87       "departmentNumber", "employeeNumber", "employeeType", "l", "st",
88       "roomNumber", "telephoneNumber", "mobile", "pager", "cn", "userPKCS12",
89       "postalAddress", "facsimileTelephoneNumber", "userSMIMECertificate");
91   var $objectclasses= array("top", "person", "organizationalPerson", "inetOrgPerson",
92       "gosaAccount");
94   /* attributes that are part of the government mode */
95   var $govattrs= array("gouvernmentOrganizationalUnit", "houseIdentifier", "vocation",
96       "ivbbLastDeliveryCollective", "gouvernmentOrganizationalPersonLocality",
97       "gouvernmentOrganizationalUnitDescription","gouvernmentOrganizationalUnitSubjectArea",
98       "functionalTitle", "certificateSerialNumber", "publicVisible", "street", "role",
99       "postalCode");
102   /* constructor, if 'dn' is set, the node loads the given
103      'dn' from LDAP */
104   function user ($config, $dn= NULL)
105   {
106     /* Configuration is fine, allways */
107     $this->config= $config;
109     /* Load base attributes */
110     plugin::plugin ($config, $dn);
112     /* Load government mode attributes */
113     if ($this->config->current['GOVERNMENTMODE']){
115       /* Copy all attributs */
116       foreach ($this->govattrs as $val){
117         if (isset($this->attrs["$val"][0])){
118           $this->$val= $this->attrs["$val"][0];
119         }
120       }
122       /* Fix public visible attribute if unset */
123       if (!isset($this->attrs['publicVisible'])){
124         $this->publicVisible == "nein";
125       }
127     }
129     /* Create me for new accounts */
130     if ($dn == "new"){
131       $this->is_account= TRUE;
132     }
134     /* Make hash default to md5 if not set in config */
135     if (!isset($this->config->current['HASH'])){
136       $hash= "md5";
137     } else {
138       $hash= $this->config->current['HASH'];
139     }
141     /* Load data from LDAP? */
142     if ($dn != NULL){
144       /* Do base conversation */
145       if ($this->dn == "new"){
146         $ui= get_userinfo();
147         $this->base= dn2base($ui->dn);
148       } else {
149         $this->base= dn2base($dn);
150       }
152       /* get password storage type */
153       if (isset ($this->attrs['userPassword'][0])){
154         /* Initialize local array */
155         $matches= array();
156         if (preg_match ("/^{([^}]+)}(.+)/", $this->attrs['userPassword'][0], $matches)){
157           $this->pw_storage= strtolower($matches[1]);
158         } else {
159           if ($this->attrs['userPassword'][0] != ""){
160             $this->pw_storage= "clear";
161           } else {
162             $this->pw_storage= $hash;
163           }
164         }
165       } else {
166         /* Preset with vaule from configuration */
167         $this->pw_storage= $hash;
168       }
170       /* Load extra attributes: certificate and picture */
171       $this->load_picture();
172       $this->load_cert();
173       if ($this->userCertificate != ""){
174         $this->had_userCertificate= TRUE;
175       }
176     }
178     /* Reset password storage indicator, used by password_change_needed() */
179     if ($dn == "new"){
180       $this->last_pw_storage= "unset";
181     } else {
182       $this->last_pw_storage= $this->pw_storage;
183     }
185     /* Generate dob entry */
186     if (isset ($this->attrs['dateOfBirth'])){
187       /* This entry is ISO 8601 conform */
188       list($year, $month, $day)= split("-", $this->attrs['dateOfBirth'][0], 3);
189     
190       $this->dob=array( 'mon'=> $month,"mday"=> $day,"year"=> $year);
191       $this->use_dob= "1";
192     } else {
193       $this->use_dob= "0";
194     }
196     /* Put gender attribute to upper case */
197     if (isset ($this->attrs['gender'])){
198       $this->gender= strtoupper($this->attrs['gender'][0]);
199     }   
200   }
203   /* execute generates the html output for this node */
204   function execute()
205   {
206     $smarty= get_smarty();
208     /* Fill calendar */
209     if ($this->dob == "0"){
210       $date= getdate();
211     } else {
212       if(is_array($this->dob)){
213         $date = $this->dob;
214       }else{
215         $date = getdate($this->dob);
216       } 
217     }
219     $days= array();
220     for($d= 1; $d<32; $d++){
221       $days[$d]= $d;
222     }
223     $years= array();
225     if(($date['year']-100)<1901){
226       $start = 1901;
227     }else{
228       $start = $date['year']-100;
229     }
231     $end = $start +100;
232     
233     for($y= $start; $y<=$end; $y++){
234       $years[]= $y;
235     }
236     $years['-']= "-&nbsp;";
237     $months= array(_("January"), _("February"), _("March"), _("April"),
238         _("May"), _("June"), _("July"), _("August"), _("September"),
239         _("October"), _("November"), _("December"), '-' => '-&nbsp;');
240     $smarty->assign("day", $date["mday"]);
241     $smarty->assign("days", $days);
242     $smarty->assign("months", $months);
243     $smarty->assign("month", $date["mon"]-1);
244     $smarty->assign("years", $years);
245     $smarty->assign("year", $date["year"]);
247     /* Assign sex */
248     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
249     $smarty->assign("gender_list", $sex);
251     /* Assign prefered langage */
252     $language= array(0 => "&nbsp;", "fr_FR" => _("fr_FR"), "en_EN" => _("en_EN"), "de_DE" => _("de_DE"), "it_IT" => _("it_IT"));
253     $smarty->assign("preferredLanguage_list", $language);
255     /* Get random number for pictures */
256     srand((double)microtime()*1000000); 
257     $smarty->assign("rand", rand(0, 10000));
259     /* Do we represent a valid gosaAccount? */
260     if (!$this->is_account){
261       echo "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
262         _("This account has no valid GOsa extensions.")."</b>";
263       return;
264     }
266     /* Want picture edit dialog? */
267     if (isset($_POST['edit_picture'])){
268       /* Save values for later recovery, in case some presses
269          the cancel button. */
270       $this->old_jpegPhoto= $this->jpegPhoto;
271       $this->old_photoData= $this->photoData;
272       $this->picture_dialog= TRUE;
273       $this->dialog= TRUE;
274     }
276     /* Remove picture? */
277     if (isset($_POST['picture_remove'])){
278       $this->jpegPhoto= "*removed*";
279       $this->set_picture ("./images/default.jpg");
280       $this->is_modified= TRUE;
282       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
283     }
285     /* Save picture */
286     if (isset($_POST['picture_edit_finish'])){
288       /* Check for clean upload */
289       if ($_FILES['picture_file']['name'] != ""){
290         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
291           print_red(_("The specified file has not been uploaded via HTTP POST! Aborted."));
292           exit;
293         }
295         /* Activate new picture */
296         $this->set_picture($_FILES['picture_file']['tmp_name']);
297       }
298       $this->picture_dialog= FALSE;
299       $this->dialog= FALSE;
300       $this->is_modified= TRUE;
301     }
304     /* Cancel picture */
305     if (isset($_POST['picture_edit_cancel'])){
307       /* Restore values */
308       $this->jpegPhoto= $this->old_jpegPhoto;
309       $this->photoData= $this->old_photoData;
311       /* Update picture */
312       $_SESSION['picture']= $this->photoData;
313       $this->picture_dialog= FALSE;
314       $this->dialog= FALSE;
315     }
317     /* Toggle dob information */
318     if (isset($_POST['set_dob'])){
319       $this->use_dob= ($this->use_dob == "0")?"1":"0";
320     }
323     /* Want certificate= */
324     if (isset($_POST['edit_cert'])){
326       /* Save original values for later reconstruction */
327       foreach (array("certificateSerialNumber", "userCertificate",
328             "userSMIMECertificate", "userPKCS12") as $val){
330         $oval= "old_$val";
331         $this->$oval= $this->$val;
332       }
334       $this->cert_dialog= TRUE;
335       $this->dialog= TRUE;
336     }
339     /* Cancel certificate dialog */
340     if (isset($_POST['cert_edit_cancel'])){
342       /* Restore original values in case of 'cancel' */
343       foreach (array("certificateSerialNumber", "userCertificate",
344             "userSMIMECertificate", "userPKCS12") as $val){
346         $oval= "old_$val";
347         $this->$val= $this->$oval;
348       }
349       $this->cert_dialog= FALSE;
350       $this->dialog= FALSE;
351     }
354     /* Remove certificate? */
355     foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
356       if (isset($_POST["remove_$val"])){
358         /* Reset specified cert*/
359         $this->$val= "";
360         $this->is_modified= TRUE;
361       }
362     }
365     /* Upload new cert and close dialog? */     
366     if (isset($_POST['cert_edit_finish'])){
368       /* for all certificates do */
369       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
370           as $val){
372         /* Check for clean upload */
373         if (array_key_exists($val."_file", $_FILES) &&
374             array_key_exists('name', $_FILES[$val."_file"]) &&
375             $_FILES[$val."_file"]['name'] != "" &&
376             is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
377           $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
378         }
379       }
381       /* Save serial number */
382       if (isset($_POST["certificateSerialNumber"]) &&
383           $_POST["certificateSerialNumber"] != ""){
385         if (!is_id($_POST["certificateSerialNumber"])){
386           print_red (_("Please enter a valid serial number"));
388           foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
389             if ($this->$cert != ""){
390               $smarty->assign("$cert"."_state", "true");
391             } else {
392               $smarty->assign("$cert"."_state", "");
393             }
394           }
395           return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
396         }
398         $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
399         $this->is_modified= TRUE;
400       }
402       $this->cert_dialog= FALSE;
403       $this->dialog= FALSE;
404     }
406     /* Display picture dialog */
407     if ($this->picture_dialog){
408       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
409     }
411     /* Display cert dialog */
412     if ($this->cert_dialog){
413       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
414         if ($this->$cert != ""){
415           /* import certificate */
416           $certificate = new certificate;
417           $certificate->import($this->$cert);
418       
419           /* Read out data*/
420           $timeto   = $certificate->getvalidto_date();
421           $timefrom = $certificate->getvalidfrom_date();
422           $str = "<table summary=\"\" border=0><tr><td style='vertical-align:top'>CN</td><td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td></tr></table><br>".
423                   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>");
424           $smarty->assign($cert."info",$str);
425           $smarty->assign($cert."_state","true");
426         } else {
427           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
428           $smarty->assign($cert."_state","");
429         }
430       }
431       $smarty->assign("governmentmode", "false");
432       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
433     }
435     /* Show us the edit screen */
436     $smarty->assign("bases", $this->config->idepartments);
437     $smarty->assign("base_select", $this->base);
438     $smarty->assign("selectmode", chkacl($this->acl, "create"));
439     $smarty->assign("certificatesACL", chkacl($this->acl, "certificates"));
440     $smarty->assign("jpegPhotoACL", chkacl($this->acl, "jpegPhoto"));
442     /* Prepare password hashes */
443     if ($this->pw_storage == ""){
444       $this->pw_storage= $this->config->current['HASH'];
445     }
447     $temp   = passwordMethod::get_available_methods();
448     $hashes = $temp['name'];
449     
450     $smarty->assign("pwmode", $hashes);
451     $smarty->assign("pwmode_select", $this->pw_storage);
452     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
454     /* Load attributes and acl's */
455     foreach($this->attributes as $val){
456       $smarty->assign("$val", $this->$val);
457       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
458     }
460     /* Save government mode attributes */
461     if (isset($this->config->current['GOVERNMENTMODE']) &&
462         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
463       $smarty->assign("governmentmode", "true");
464       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
465           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
466       $smarty->assign("ivbbmodes", $ivbbmodes);
467       foreach ($this->govattrs as $val){
468         $smarty->assign("$val", $this->$val);
469         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
470       }
471     } else {
472       $smarty->assign("governmentmode", "false");
473     }
475     /* Special mode for uid */
476     $uidACL= "";
477     if (isset ($this->dn)){
478       if ($this->dn != "new"){
479         $uidACL="readonly";
480       }
481     }  else {
482       $uidACL= "readonly";
483     }
484     $uidACL.= " ".chkacl($this->acl, "uid");
485     
486     $smarty->assign("uidACL", $uidACL);
487     $smarty->assign("is_template", $this->is_template);
488     $smarty->assign("use_dob", $this->use_dob);
490     if (isset($this->parent)){
491       if (isset($this->parent->by_object['phoneAccount']) &&
492           $this->parent->by_object['phoneAccount']->is_account){
493         $smarty->assign("has_phoneaccount", "true");
494       } else {
495         $smarty->assign("has_phoneaccount", "false");
496       }
497     } else {
498         $smarty->assign("has_phoneaccount", "false");
499     }
501     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
502   }
505   /* remove object from parent */
506   function remove_from_parent()
507   {
508     $ldap= $this->config->get_ldap_link();
509     $ldap->rmdir ($this->dn);
511     /* Delete references to groups */
512     $ldap->cd ($this->config->current['BASE']);
513     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
514     while ($ldap->fetch()){
515       $g= new group($this->config, $ldap->getDN());
516       $g->removeUser($this->uid);
517       $g->save ();
518     }
520     /* Delete references to object groups */
521     $ldap->cd ($this->config->current['BASE']);
522     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
523     while ($ldap->fetch()){
524       $og= new ogroup($this->config, $ldap->getDN());
525       unset($og->member[$this->dn]);
526       $og->save ();
527     }
529     /* Optionally execute a command after we're done */
530     $this->handle_post_events("remove");
531   }
534   /* Save data to object */
535   function save_object()
536   {
537     if (isset($_POST['generic'])){
539       /* Parents save function */
540       plugin::save_object ();
542       /* Save government mode attributes */
543       if ($this->config->current['GOVERNMENTMODE']){
544         foreach ($this->govattrs as $val){
545           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
546             $data= stripcslashes($_POST["$val"]);
547             if ($data != $this->$val){
548               $this->is_modified= TRUE;
549             }
550             $this->$val= $data;
551           }
552         }
553       }
555       /* In template mode, the uid is autogenerated... */
556       if ($this->is_template){
557         $this->uid= strtolower($this->sn);
558         $this->givenName= $this->sn;
559       }
561       /* Save base and pw_storage, since these are no LDAP attributes */
562       if (isset($_POST['base'])){
563         foreach(array("base", "pw_storage") as $val){
564           $data= validate($_POST[$val]);
565           if ($data != $this->$val){
566             $this->is_modified= TRUE;
567           }
568           $this->$val= $data;
569         }
570       }
571     }
572   }
574   function rebind($ldap, $referral)
575   {
576     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
577     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
578       $this->error = "Success";
579       $this->hascon=true;
580       $this->reconnect= true;
581       return (0);
582     } else {
583       $this->error = "Could not bind to " . $credentials['ADMIN'];
584       return NULL;
585     }
586   }
588   /* Save data to LDAP, depending on is_account we save or delete */
589   function save()
590   {
591     /* First use parents methods to do some basic fillup in $this->attrs */
592     plugin::save ();
594     /* Remove additional objectClasses */
595     $tmp= array();
596     foreach ($this->attrs['objectClass'] as $key => $set){
597       $found= false;
598       foreach (array("ivbbEntry", "gosaUserTemplate") as $val){
599         if (preg_match ("/^$set$/i", $val)){
600           $found= true;
601           break;
602         }
603       }
604       if (!$found){
605         $tmp[]= $set;
606       }
607     }
609     /* Replace the objectClass array. This is done because of the
610        separation into government and normal mode. */
611     $this->attrs['objectClass']= $tmp;
613     /* Add objectClasss for template mode? */
614     if ($this->is_template){
615       $this->attrs['objectClass'][]= "gosaUserTemplate";
616     }
618     /* Hard coded government mode? */
619     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
620       $this->attrs['objectClass'][]= "ivbbEntry";
622       /* Copy standard attributes */
623       foreach ($this->govattrs as $val){
624         if ($this->$val != ""){
625           $this->attrs["$val"]= $this->$val;
626         } elseif (!$this->new) {
627           $this->attrs["$val"]= array();
628         }
629       }
631       /* Remove attribute if set to "nein" */
632       if ($this->publicVisible == "nein"){
633         $this->attrs['publicVisible']= array();
634         if($this->new){
635           unset($this->attrs['publicVisible']);
636         }else{
637           $this->attrs['publicVisible']=array();
638         }
640       }
642     }
644     /* Special handling for attribute userCertificate needed */
645     if ($this->userCertificate != ""){
646       $this->attrs["userCertificate;binary"]= $this->userCertificate;
647       $remove_userCertificate= false;
648     } else {
649       $remove_userCertificate= true;
650     }
652     /* Special handling for dob value */
653     if ($this->use_dob == "1"){
654       $this->attrs["dob"]= date("Y-m-d", $this->dob);
655     } else {
656       if ($this->new) {
657         unset($this->attrs["dob"]);
658       } else {
659         $this->attrs["dob"]= array();
660       }
661     }
662     if ($this->gender == "0"){
663       if ($this->new) {
664         unset($this->attrs["gender"]);
665       } else {
666         $this->attrs["gender"]= array();
667       }
668     }
669       if ($this->preferredLanguage == "0"){
670       if ($this->new) {
671         unset($this->attrs["preferredLanguage"]);
672       } else {
673         $this->attrs["preferredLanguage"]= array();
674       }
675     }
677     /* Special handling for attribute jpegPhote needed, scale image via
678        image magick to 147x200 pixels and inject resulting data. */
679     if ($this->jpegPhoto != "*removed*"){
681       /* Fallback if there's no image magick inside PHP */
682       if (!function_exists("imagick_blob2image")){
683         /* Get temporary file name for conversation */
684         $fname = tempnam ("/tmp", "GOsa");
686         /* Open file and write out photoData */
687         $fp = fopen ($fname, "w");
688         fwrite ($fp, $this->photoData);
689         fclose ($fp);
691         /* Build conversation query. Filename is generated automatically, so
692            we do not need any special security checks. Exec command and save
693            output. For PHP safe mode, you'll need a configuration which respects
694            image magick as executable... */
695         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
696         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
697             $query, "Execute");
699         /* Read data written by convert */
700         $output= "";
701         $sh= popen($query, 'r');
702         while (!feof($sh)){
703           $output.= fread($sh, 4096);
704         }
705         pclose($sh);
707         unlink($fname);
709         /* Save attribute */
710         $this->attrs["jpegPhoto"] = $output;
712       } else {
714         /* Load the new uploaded Photo */
715         if(!$handle  =  imagick_blob2image($this->photoData))  {
716           gosa_log("Can't Load image");
717         }
719         /* Resizing image to 147x200 and blur */
720         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
721           gosa_log("imagick_resize failed");
722         }
724         /* Converting image to JPEG */
725         if(!imagick_convert($handle,"JPEG")) {
726           gosa_log("Can't Convert to JPEG");
727         }
729         /* Creating binary Code for the Image */
730         if(!$dump = imagick_image2blob($handle)){
731           gosa_log("Can't create blob for image");
732         }
734         /* Sending Image */
735         $output=  $dump;
737         /* Save attribute */
738         $this->attrs["jpegPhoto"] = $output;
739       }
741     } elseif(!$this->new) {
742       $this->attrs["jpegPhoto"] = array();
743     }
745     /* Build new dn */
746     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
747       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
748     } else {
749       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
750     }
752     /* This only gets called when user is renaming himself */
753     $ldap= $this->config->get_ldap_link();
754     if ($this->dn != $new_dn){
756       /* Write entry on new 'dn' */
757       $this->move($this->dn, $new_dn);
759       /* Happen to use the new one */
760       change_ui_dn($this->dn, $new_dn);
761       $this->dn= $new_dn;
762     }
765     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
766        new entries. So do a check first... */
767     $ldap->cat ($this->dn);
768     if ($ldap->fetch()){
769       $mode= "modify";
770     } else {
771       $mode= "add";
772       $ldap->cd($this->config->current['BASE']);
773       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
774     }
776     /* Set password to some junk stuff in case of templates */
777     if ($this->is_template){
778       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
779     }
781     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
782         $this->attributes, "Save via $mode");
784     /* Finally write data with selected 'mode' */
785     $ldap->cd ($this->dn);
786     $ldap->$mode ($this->attrs);
787     if (show_ldap_error($ldap->get_error())){
788       return (1);
789     }
791     /* Remove cert? 
792        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
793        to work around myself. */
794     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
796       /* Reset array, assemble new, this should be reworked */
797       $this->attrs= array();
798       $this->attrs['userCertificate;binary']= array();
800       /* Prepare connection */
801       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
802         die ("Could not connect to LDAP server");
803       }
804       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
805       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
806         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
807         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
808       }
809       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
810         ldap_start_tls($ds);
811       }
812       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
813               $this->config->current['PASSWORD']))) {
814         die ("Could not bind to LDAP");
815       }
817       /* Modify using attrs */
818       ldap_mod_del($ds,$this->dn,$this->attrs);
819       ldap_close($ds);
820     }
822     /* Kerberos server defined? */
823     if (isset($this->config->data['SERVERS']['KERBEROS'])){
824       $cfg= $this->config->data['SERVERS']['KERBEROS'];
825     }
826     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
828       /* Connect to the admin interface */
829       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
830           $cfg['ADMIN'], $cfg['PASSWORD']);
832       /* Errors? */             
833       if ($handle === FALSE){
834         print_red (_("Kerberos database communication failed"));
835         return (2);
836       }
838       /* Build user principal, get list of existsing principals */
839       $principal= $this->uid."@".$cfg['REALM'];
840       $principals = kadm5_get_principals($handle);
842       /* User exists in database? */
843       if (in_array($principal, $principals)){
845         /* Ok. User exists. Remove him/her when pw_storage has
846            changed to be NOT kerberos. */
847         if ($this->pw_storage != "kerberos"){
848           $ret= kadm5_delete_principal ( $handle, $principal);
850           if ($ret === FALSE){
851             print_red (_("Can't remove user from kerberos database."));
852           }
853         }
855       } else {
857         /* User doesn't exists, create it when pw_storage is kerberos. */
858         if ($this->pw_storage == "kerberos"){
859           $ret= kadm5_create_principal ( $handle, $principal);
861           if ($ret === FALSE){
862             print_red (_("Can't add user to kerberos database."));
863           }
864         }
866       }
868       /* Free kerberos admin handle */
869       kadm5_destroy($handle);
870     }
872     /* Optionally execute a command after we're done */
873     if ($mode == "add"){
874       $this->handle_post_events("add");
875     } elseif ($this->is_modified){
876       $this->handle_post_events("modify");
877     }
879     return (0);
880   }
883   /* Check formular input */
884   function check()
885   {
886     $message= array();
888     /* Assemble cn */
889     $this->cn= $this->givenName." ".$this->sn;
891     if(preg_match("/[^a-z0-9]/",$this->uid)){
892       $message[]=_("Invalid characters in uid.") ;
893     }
895     /* Permissions for that base? */
896     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
897       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
898     } else {
899       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
900     }
902     $ui= get_userinfo();
903     $acl= get_permissions ($new_dn, $ui->subtreeACL);
904     $acl= get_module_permission($acl, "user", $new_dn);
905     if ($this->dn == "new" && chkacl($acl, "create") != ""){
906       $message[]= _("You have no permissions to create a user on this 'Base'.");
907     } elseif ($this->dn != $new_dn && $this->dn != "new"){
908       $acl= get_permissions ($this->dn, $ui->subtreeACL);
909       $acl= get_module_permission($acl, "user", $this->dn);
910       if (chkacl($acl, "create") != ""){
911         $message[]= _("You have no permissions to move a user from the original 'Base'.");
912       }
913     }
915     /* must: sn, givenName, uid */
916     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
917       $message[]= _("The required field 'Name' is not set.");
918     }
920     /* UID already used? */
921     $ldap= $this->config->get_ldap_link();
922     $ldap->cd($this->config->current['BASE']);
923     $ldap->search("(uid=$this->uid)", array("uid"));
924     $ldap->fetch();
925     if ($ldap->count() != 0 && $this->dn == 'new'){
926       $message[]= _("There's already a person with this 'Login' in the database.");
927     }
929     /* In template mode, the uid and givenName are autogenerated... */
930     if (!$this->is_template){
931       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
932         $message[]= _("The required field 'Given name' is not set.");
933       }
934       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
935         $message[]= _("The required field 'Login' is not set.");
936       }
937       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
938         $ldap->cd($this->config->current['BASE']);
939         $ldap->search("(cn=".$this->cn.")", array("uid"));
940         $ldap->fetch();
941         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
942           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
943         }
944       }
945     }
947     /* Check for valid input */
948     if ($this->is_modified && !is_uid($this->uid)){
949       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
950     }
951     if (!is_url($this->labeledURI)){
952       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
953     }
954     if (preg_match ("/[\\\\]/", $this->sn)){
955       $message[]= _("The field 'Name' contains invalid characters.");
956     }
957     if (preg_match ("/[\\\\]/", $this->givenName)){
958       $message[]= _("The field 'Given name' contains invalid characters.");
959     }
961     /* Check phone numbers */
962     if (!is_phone_nr($this->homePhone)){
963       $message[]= _("The field 'Phone' contains an invalid phone number.");
964     }
965     if (!is_phone_nr($this->telephoneNumber)){
966       $message[]= _("The field 'Phone' contains an invalid phone number.");
967     }
968     if (!is_phone_nr($this->facsimileTelephoneNumber)){
969       $message[]= _("The field 'Fax' contains an invalid phone number.");
970     }
971     if (!is_phone_nr($this->mobile)){
972       $message[]= _("The field 'Mobile' contains an invalid phone number.");
973     }
974     if (!is_phone_nr($this->pager)){
975       $message[]= _("The field 'Pager' contains an invalid phone number.");
976     }
978     /* Check for reserved characers */
979     if (preg_match ('/[,+"?\'()=<>;]/', $this->givenName)){
980       $message[]= _("The field 'Given name' contains invalid characters.");
981     }
982     if (preg_match ('/[,+"?\'()=<>;]/', $this->sn)){
983       $message[]= _("The field 'Name' contains invalid characters.");
984     }
986   return $message;
987   }
990   /* Indicate whether a password change is needed or not */
991   function password_change_needed()
992   {
993     return ($this->pw_storage != $this->last_pw_storage);
994   }
997   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
998   function load_picture()
999   {
1000     /* make connection and read jpegPhoto */
1001     $ds= ldap_connect($this->config->current['SERVER']);
1002     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1003     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1004       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1005       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1006     }
1008     if(isset($this->config->current['TLS']) &&
1009         $this->config->current['TLS'] == "true"){
1011       ldap_start_tls($ds);
1012     }
1014     $r= ldap_bind($ds);
1015     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
1017     /* in case we don't get an entry, load a default picture */
1018     $this->set_picture ("./images/default.jpg");
1019     $this->jpegPhoto= "*removed*";
1021     /* fill data from LDAP */
1022     if ($sr) {
1023       $ei=ldap_first_entry($ds, $sr);
1024       if ($ei) {
1025         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
1026           $this->photoData= $info[0];
1027           $_SESSION['picture']= $this->photoData;
1028           $this->jpegPhoto= "";
1029         }
1030       }
1031     }
1033     /* close conncetion */
1034     ldap_unbind($ds);
1035   }
1038   /* Load a certificate from LDAP, this is going to be simplified later on */
1039   function load_cert()
1040   {
1041     $ds= ldap_connect($this->config->current['SERVER']);
1042     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1043     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1044       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1045       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1046     }
1047     if(isset($this->config->current['TLS']) &&
1048         $this->config->current['TLS'] == "true"){
1050       ldap_start_tls($ds);
1051     }
1053     $r= ldap_bind($ds);
1054     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1056     if ($sr) {
1057       $ei= @ldap_first_entry($ds, $sr);
1058       
1059       if ($ei) {
1060         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1061           $this->userCertificate= "";
1062         } else {
1063           $this->userCertificate= $info[0];
1064         }
1065       }
1066     } else {
1067       $this->userCertificate= "";
1068     }
1070     ldap_unbind($ds);
1071   }
1074   /* Load picture from file to object */
1075   function set_picture($filename)
1076   {
1077     if (!is_file($filename)){
1078       $filename= "./images/default.jpg";
1079       $this->jpegPhoto= "*removed*";
1080     }
1082     $fd = fopen ($filename, "rb");
1083     $this->photoData= fread ($fd, filesize ($filename));
1084     $_SESSION['picture']= $this->photoData;
1085     $this->jpegPhoto= "";
1087     fclose ($fd);
1088   }
1091   /* Load certificate from file to object */
1092   function set_cert($cert, $filename)
1093   {
1094     $fd = fopen ($filename, "rb");
1095     if (filesize($filename)>0) {
1096       $this->$cert= fread ($fd, filesize ($filename));
1097       fclose ($fd);
1098       $this->is_modified= TRUE;
1099     } else {
1100       print_red(_("Could not open specified certificate!"));
1101     }
1102   }
1104   /* Adapt from given 'dn' */
1105   function adapt_from_template($dn)
1106   {
1107     plugin::adapt_from_template($dn);
1109     /* Get base */
1110     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1112     if ($this->config->current['GOVERNMENTMODE']){
1114       /* Walk through govattrs */
1115       foreach ($this->govattrs as $val){
1117         if (isset($this->attrs["$val"][0])){
1119           /* If attribute is set, replace dynamic parts: 
1120              %sn, %givenName and %uid. Fill these in our local variables. */
1121           $value= $this->attrs["$val"][0];
1123           foreach (array("sn", "givenName", "uid") as $repl){
1124             if (preg_match("/%$repl/i", $value)){
1125               $value= preg_replace ("/%$repl/i",
1126                   $this->parent->$repl, $value);
1127             }
1128           }
1129           $this->$val= $value;
1130         }
1131       }
1132     }
1134     /* Get back uid/sn/givenName */
1135     if ($this->parent != NULL){
1136       $this->uid= $this->parent->uid;
1137       $this->sn= $this->parent->sn;
1138       $this->givenName= $this->parent->givenName;
1139     }
1140   }
1144 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1145 ?>