Code

Updated workstation and environment plugins to handle shares correctly
[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['binary']= $this->photoData;
313       $_SESSION['binarytype']= "image/jpeg";
314       $this->picture_dialog= FALSE;
315       $this->dialog= FALSE;
316     }
318     /* Toggle dob information */
319     if (isset($_POST['set_dob'])){
320       $this->use_dob= ($this->use_dob == "0")?"1":"0";
321     }
324     /* Want certificate= */
325     if (isset($_POST['edit_cert'])){
327       /* Save original values for later reconstruction */
328       foreach (array("certificateSerialNumber", "userCertificate",
329             "userSMIMECertificate", "userPKCS12") as $val){
331         $oval= "old_$val";
332         $this->$oval= $this->$val;
333       }
335       $this->cert_dialog= TRUE;
336       $this->dialog= TRUE;
337     }
340     /* Cancel certificate dialog */
341     if (isset($_POST['cert_edit_cancel'])){
343       /* Restore original values in case of 'cancel' */
344       foreach (array("certificateSerialNumber", "userCertificate",
345             "userSMIMECertificate", "userPKCS12") as $val){
347         $oval= "old_$val";
348         $this->$val= $this->$oval;
349       }
350       $this->cert_dialog= FALSE;
351       $this->dialog= FALSE;
352     }
355     /* Remove certificate? */
356     foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
357       if (isset($_POST["remove_$val"])){
359         /* Reset specified cert*/
360         $this->$val= "";
361         $this->is_modified= TRUE;
362       }
363     }
366     /* Upload new cert and close dialog? */     
367     if (isset($_POST['cert_edit_finish'])){
369       /* for all certificates do */
370       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
371           as $val){
373         /* Check for clean upload */
374         if (array_key_exists($val."_file", $_FILES) &&
375             array_key_exists('name', $_FILES[$val."_file"]) &&
376             $_FILES[$val."_file"]['name'] != "" &&
377             is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
378           $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
379         }
380       }
382       /* Save serial number */
383       if (isset($_POST["certificateSerialNumber"]) &&
384           $_POST["certificateSerialNumber"] != ""){
386         if (!is_id($_POST["certificateSerialNumber"])){
387           print_red (_("Please enter a valid serial number"));
389           foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
390             if ($this->$cert != ""){
391               $smarty->assign("$cert"."_state", "true");
392             } else {
393               $smarty->assign("$cert"."_state", "");
394             }
395           }
396           return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
397         }
399         $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
400         $this->is_modified= TRUE;
401       }
403       $this->cert_dialog= FALSE;
404       $this->dialog= FALSE;
405     }
407     /* Display picture dialog */
408     if ($this->picture_dialog){
409       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
410     }
412     /* Display cert dialog */
413     if ($this->cert_dialog){
414       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
415         if ($this->$cert != ""){
416           /* import certificate */
417           $certificate = new certificate;
418           $certificate->import($this->$cert);
419       
420           /* Read out data*/
421           $timeto   = $certificate->getvalidto_date();
422           $timefrom = $certificate->getvalidfrom_date();
423           $str = "<table summary=\"\" border=0><tr><td style='vertical-align:top'>CN</td><td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td></tr></table><br>".
424                   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>");
425           $smarty->assign($cert."info",$str);
426           $smarty->assign($cert."_state","true");
427         } else {
428           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
429           $smarty->assign($cert."_state","");
430         }
431       }
432       $smarty->assign("governmentmode", "false");
433       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
434     }
436     /* Show us the edit screen */
437     $smarty->assign("bases", $this->config->idepartments);
438     $smarty->assign("base_select", $this->base);
439     $smarty->assign("selectmode", chkacl($this->acl, "create"));
440     $smarty->assign("certificatesACL", chkacl($this->acl, "certificates"));
441     $smarty->assign("jpegPhotoACL", chkacl($this->acl, "jpegPhoto"));
443     /* Prepare password hashes */
444     if ($this->pw_storage == ""){
445       $this->pw_storage= $this->config->current['HASH'];
446     }
448     $temp   = passwordMethod::get_available_methods();
449     $hashes = $temp['name'];
450     
451     $smarty->assign("pwmode", $hashes);
452     $smarty->assign("pwmode_select", $this->pw_storage);
453     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
455     /* Load attributes and acl's */
456     foreach($this->attributes as $val){
457       $smarty->assign("$val", $this->$val);
458       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
459     }
461     /* Save government mode attributes */
462     if (isset($this->config->current['GOVERNMENTMODE']) &&
463         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
464       $smarty->assign("governmentmode", "true");
465       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
466           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
467       $smarty->assign("ivbbmodes", $ivbbmodes);
468       foreach ($this->govattrs as $val){
469         $smarty->assign("$val", $this->$val);
470         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
471       }
472     } else {
473       $smarty->assign("governmentmode", "false");
474     }
476     /* Special mode for uid */
477     $uidACL= "";
478     if (isset ($this->dn)){
479       if ($this->dn != "new"){
480         $uidACL="readonly";
481       }
482     }  else {
483       $uidACL= "readonly";
484     }
485     $uidACL.= " ".chkacl($this->acl, "uid");
486     
487     $smarty->assign("uidACL", $uidACL);
488     $smarty->assign("is_template", $this->is_template);
489     $smarty->assign("use_dob", $this->use_dob);
491     if (isset($this->parent)){
492       if (isset($this->parent->by_object['phoneAccount']) &&
493           $this->parent->by_object['phoneAccount']->is_account){
494         $smarty->assign("has_phoneaccount", "true");
495       } else {
496         $smarty->assign("has_phoneaccount", "false");
497       }
498     } else {
499         $smarty->assign("has_phoneaccount", "false");
500     }
502     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
503   }
506   /* remove object from parent */
507   function remove_from_parent()
508   {
509     $ldap= $this->config->get_ldap_link();
510     $ldap->rmdir ($this->dn);
512     /* Delete references to groups */
513     $ldap->cd ($this->config->current['BASE']);
514     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
515     while ($ldap->fetch()){
516       $g= new group($this->config, $ldap->getDN());
517       $g->removeUser($this->uid);
518       $g->save ();
519     }
521     /* Delete references to object groups */
522     $ldap->cd ($this->config->current['BASE']);
523     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
524     while ($ldap->fetch()){
525       $og= new ogroup($this->config, $ldap->getDN());
526       unset($og->member[$this->dn]);
527       $og->save ();
528     }
530     /* Optionally execute a command after we're done */
531     $this->handle_post_events("remove");
532   }
535   /* Save data to object */
536   function save_object()
537   {
538     if (isset($_POST['generic'])){
540       /* Parents save function */
541       plugin::save_object ();
543       /* Save government mode attributes */
544       if ($this->config->current['GOVERNMENTMODE']){
545         foreach ($this->govattrs as $val){
546           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
547             $data= stripcslashes($_POST["$val"]);
548             if ($data != $this->$val){
549               $this->is_modified= TRUE;
550             }
551             $this->$val= $data;
552           }
553         }
554       }
556       /* In template mode, the uid is autogenerated... */
557       if ($this->is_template){
558         $this->uid= strtolower($this->sn);
559         $this->givenName= $this->sn;
560       }
562       /* Save base and pw_storage, since these are no LDAP attributes */
563       if (isset($_POST['base'])){
564         foreach(array("base", "pw_storage") as $val){
565           $data= validate($_POST[$val]);
566           if ($data != $this->$val){
567             $this->is_modified= TRUE;
568           }
569           $this->$val= $data;
570         }
571       }
572     }
573   }
575   function rebind($ldap, $referral)
576   {
577     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
578     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
579       $this->error = "Success";
580       $this->hascon=true;
581       $this->reconnect= true;
582       return (0);
583     } else {
584       $this->error = "Could not bind to " . $credentials['ADMIN'];
585       return NULL;
586     }
587   }
589   /* Save data to LDAP, depending on is_account we save or delete */
590   function save()
591   {
592     /* First use parents methods to do some basic fillup in $this->attrs */
593     plugin::save ();
595     /* Remove additional objectClasses */
596     $tmp= array();
597     foreach ($this->attrs['objectClass'] as $key => $set){
598       $found= false;
599       foreach (array("ivbbEntry", "gosaUserTemplate") as $val){
600         if (preg_match ("/^$set$/i", $val)){
601           $found= true;
602           break;
603         }
604       }
605       if (!$found){
606         $tmp[]= $set;
607       }
608     }
610     /* Replace the objectClass array. This is done because of the
611        separation into government and normal mode. */
612     $this->attrs['objectClass']= $tmp;
614     /* Add objectClasss for template mode? */
615     if ($this->is_template){
616       $this->attrs['objectClass'][]= "gosaUserTemplate";
617     }
619     /* Hard coded government mode? */
620     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
621       $this->attrs['objectClass'][]= "ivbbEntry";
623       /* Copy standard attributes */
624       foreach ($this->govattrs as $val){
625         if ($this->$val != ""){
626           $this->attrs["$val"]= $this->$val;
627         } elseif (!$this->new) {
628           $this->attrs["$val"]= array();
629         }
630       }
632       /* Remove attribute if set to "nein" */
633       if ($this->publicVisible == "nein"){
634         $this->attrs['publicVisible']= array();
635         if($this->new){
636           unset($this->attrs['publicVisible']);
637         }else{
638           $this->attrs['publicVisible']=array();
639         }
641       }
643     }
645     /* Special handling for attribute userCertificate needed */
646     if ($this->userCertificate != ""){
647       $this->attrs["userCertificate;binary"]= $this->userCertificate;
648       $remove_userCertificate= false;
649     } else {
650       $remove_userCertificate= true;
651     }
653     /* Special handling for dob value */
654     if ($this->use_dob == "1"){
655       $this->attrs["dob"]= date("Y-m-d", $this->dob);
656     } else {
657       if ($this->new) {
658         unset($this->attrs["dob"]);
659       } else {
660         $this->attrs["dob"]= array();
661       }
662     }
663     if ($this->gender == "0"){
664       if ($this->new) {
665         unset($this->attrs["gender"]);
666       } else {
667         $this->attrs["gender"]= array();
668       }
669     }
670       if ($this->preferredLanguage == "0"){
671       if ($this->new) {
672         unset($this->attrs["preferredLanguage"]);
673       } else {
674         $this->attrs["preferredLanguage"]= array();
675       }
676     }
678     /* Special handling for attribute jpegPhote needed, scale image via
679        image magick to 147x200 pixels and inject resulting data. */
680     if ($this->jpegPhoto != "*removed*"){
682       /* Fallback if there's no image magick inside PHP */
683       if (!function_exists("imagick_blob2image")){
684         /* Get temporary file name for conversation */
685         $fname = tempnam ("/tmp", "GOsa");
687         /* Open file and write out photoData */
688         $fp = fopen ($fname, "w");
689         fwrite ($fp, $this->photoData);
690         fclose ($fp);
692         /* Build conversation query. Filename is generated automatically, so
693            we do not need any special security checks. Exec command and save
694            output. For PHP safe mode, you'll need a configuration which respects
695            image magick as executable... */
696         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
697         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
698             $query, "Execute");
700         /* Read data written by convert */
701         $output= "";
702         $sh= popen($query, 'r');
703         while (!feof($sh)){
704           $output.= fread($sh, 4096);
705         }
706         pclose($sh);
708         unlink($fname);
710         /* Save attribute */
711         $this->attrs["jpegPhoto"] = $output;
713       } else {
715         /* Load the new uploaded Photo */
716         if(!$handle  =  imagick_blob2image($this->photoData))  {
717           gosa_log("Can't Load image");
718         }
720         /* Resizing image to 147x200 and blur */
721         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
722           gosa_log("imagick_resize failed");
723         }
725         /* Converting image to JPEG */
726         if(!imagick_convert($handle,"JPEG")) {
727           gosa_log("Can't Convert to JPEG");
728         }
730         /* Creating binary Code for the Image */
731         if(!$dump = imagick_image2blob($handle)){
732           gosa_log("Can't create blob for image");
733         }
735         /* Sending Image */
736         $output=  $dump;
738         /* Save attribute */
739         $this->attrs["jpegPhoto"] = $output;
740       }
742     } elseif(!$this->new) {
743       $this->attrs["jpegPhoto"] = array();
744     }
746     /* Build new dn */
747     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
748       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
749     } else {
750       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
751     }
753     /* This only gets called when user is renaming himself */
754     $ldap= $this->config->get_ldap_link();
755     if ($this->dn != $new_dn){
757       /* Write entry on new 'dn' */
758       $this->move($this->dn, $new_dn);
760       /* Happen to use the new one */
761       change_ui_dn($this->dn, $new_dn);
762       $this->dn= $new_dn;
763     }
766     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
767        new entries. So do a check first... */
768     $ldap->cat ($this->dn);
769     if ($ldap->fetch()){
770       $mode= "modify";
771     } else {
772       $mode= "add";
773       $ldap->cd($this->config->current['BASE']);
774       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
775     }
777     /* Set password to some junk stuff in case of templates */
778     if ($this->is_template){
779       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
780     }
782     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
783         $this->attributes, "Save via $mode");
785     /* Finally write data with selected 'mode' */
786     $ldap->cd ($this->dn);
787     $ldap->$mode ($this->attrs);
788     if (show_ldap_error($ldap->get_error())){
789       return (1);
790     }
792     /* Remove cert? 
793        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
794        to work around myself. */
795     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
797       /* Reset array, assemble new, this should be reworked */
798       $this->attrs= array();
799       $this->attrs['userCertificate;binary']= array();
801       /* Prepare connection */
802       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
803         die ("Could not connect to LDAP server");
804       }
805       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
806       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
807         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
808         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
809       }
810       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
811         ldap_start_tls($ds);
812       }
813       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
814               $this->config->current['PASSWORD']))) {
815         die ("Could not bind to LDAP");
816       }
818       /* Modify using attrs */
819       ldap_mod_del($ds,$this->dn,$this->attrs);
820       ldap_close($ds);
821     }
823     /* Kerberos server defined? */
824     if (isset($this->config->data['SERVERS']['KERBEROS'])){
825       $cfg= $this->config->data['SERVERS']['KERBEROS'];
826     }
827     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
829       /* Connect to the admin interface */
830       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
831           $cfg['ADMIN'], $cfg['PASSWORD']);
833       /* Errors? */             
834       if ($handle === FALSE){
835         print_red (_("Kerberos database communication failed"));
836         return (2);
837       }
839       /* Build user principal, get list of existsing principals */
840       $principal= $this->uid."@".$cfg['REALM'];
841       $principals = kadm5_get_principals($handle);
843       /* User exists in database? */
844       if (in_array($principal, $principals)){
846         /* Ok. User exists. Remove him/her when pw_storage has
847            changed to be NOT kerberos. */
848         if ($this->pw_storage != "kerberos"){
849           $ret= kadm5_delete_principal ( $handle, $principal);
851           if ($ret === FALSE){
852             print_red (_("Can't remove user from kerberos database."));
853           }
854         }
856       } else {
858         /* User doesn't exists, create it when pw_storage is kerberos. */
859         if ($this->pw_storage == "kerberos"){
860           $ret= kadm5_create_principal ( $handle, $principal);
862           if ($ret === FALSE){
863             print_red (_("Can't add user to kerberos database."));
864           }
865         }
867       }
869       /* Free kerberos admin handle */
870       kadm5_destroy($handle);
871     }
873     /* Optionally execute a command after we're done */
874     if ($mode == "add"){
875       $this->handle_post_events("add");
876     } elseif ($this->is_modified){
877       $this->handle_post_events("modify");
878     }
880     return (0);
881   }
884   /* Check formular input */
885   function check()
886   {
887     $message= array();
889     /* Assemble cn */
890     $this->cn= $this->givenName." ".$this->sn;
892     if(preg_match("/[^a-z0-9]/",$this->uid)){
893       $message[]=_("Invalid characters in uid.") ;
894     }
896     /* Permissions for that base? */
897     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
898       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
899     } else {
900       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
901     }
903     $ui= get_userinfo();
904     $acl= get_permissions ($new_dn, $ui->subtreeACL);
905     $acl= get_module_permission($acl, "user", $new_dn);
906     if ($this->dn == "new" && chkacl($acl, "create") != ""){
907       $message[]= _("You have no permissions to create a user on this 'Base'.");
908     } elseif ($this->dn != $new_dn && $this->dn != "new"){
909       $acl= get_permissions ($this->dn, $ui->subtreeACL);
910       $acl= get_module_permission($acl, "user", $this->dn);
911       if (chkacl($acl, "create") != ""){
912         $message[]= _("You have no permissions to move a user from the original 'Base'.");
913       }
914     }
916     /* must: sn, givenName, uid */
917     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
918       $message[]= _("The required field 'Name' is not set.");
919     }
921     /* UID already used? */
922     $ldap= $this->config->get_ldap_link();
923     $ldap->cd($this->config->current['BASE']);
924     $ldap->search("(uid=$this->uid)", array("uid"));
925     $ldap->fetch();
926     if ($ldap->count() != 0 && $this->dn == 'new'){
927       $message[]= _("There's already a person with this 'Login' in the database.");
928     }
930     /* In template mode, the uid and givenName are autogenerated... */
931     if (!$this->is_template){
932       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
933         $message[]= _("The required field 'Given name' is not set.");
934       }
935       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
936         $message[]= _("The required field 'Login' is not set.");
937       }
938       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
939         $ldap->cd($this->config->current['BASE']);
940         $ldap->search("(cn=".$this->cn.")", array("uid"));
941         $ldap->fetch();
942         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
943           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
944         }
945       }
946     }
948     /* Check for valid input */
949     if ($this->is_modified && !is_uid($this->uid)){
950       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
951     }
952     if (!is_url($this->labeledURI)){
953       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
954     }
955     if (preg_match ("/[\\\\]/", $this->sn)){
956       $message[]= _("The field 'Name' contains invalid characters.");
957     }
958     if (preg_match ("/[\\\\]/", $this->givenName)){
959       $message[]= _("The field 'Given name' contains invalid characters.");
960     }
962     /* Check phone numbers */
963     if (!is_phone_nr($this->homePhone)){
964       $message[]= _("The field 'Phone' contains an invalid phone number.");
965     }
966     if (!is_phone_nr($this->telephoneNumber)){
967       $message[]= _("The field 'Phone' contains an invalid phone number.");
968     }
969     if (!is_phone_nr($this->facsimileTelephoneNumber)){
970       $message[]= _("The field 'Fax' contains an invalid phone number.");
971     }
972     if (!is_phone_nr($this->mobile)){
973       $message[]= _("The field 'Mobile' contains an invalid phone number.");
974     }
975     if (!is_phone_nr($this->pager)){
976       $message[]= _("The field 'Pager' contains an invalid phone number.");
977     }
979     /* Check for reserved characers */
980     if (preg_match ('/[,+"?\'()=<>;]/', $this->givenName)){
981       $message[]= _("The field 'Given name' contains invalid characters.");
982     }
983     if (preg_match ('/[,+"?\'()=<>;]/', $this->sn)){
984       $message[]= _("The field 'Name' contains invalid characters.");
985     }
987   return $message;
988   }
991   /* Indicate whether a password change is needed or not */
992   function password_change_needed()
993   {
994     return ($this->pw_storage != $this->last_pw_storage);
995   }
998   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
999   function load_picture()
1000   {
1001     /* make connection and read jpegPhoto */
1002     $ds= ldap_connect($this->config->current['SERVER']);
1003     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1004     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1005       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1006       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1007     }
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, "jpegPhoto=*", array("jpegPhoto"));
1018     /* in case we don't get an entry, load a default picture */
1019     $this->set_picture ("./images/default.jpg");
1020     $this->jpegPhoto= "*removed*";
1022     /* fill data from LDAP */
1023     if ($sr) {
1024       $ei=ldap_first_entry($ds, $sr);
1025       if ($ei) {
1026         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
1027           $this->photoData= $info[0];
1028           $_SESSION['binary']= $this->photoData;
1029           $_SESSION['binarytype']= "image/jpeg";
1030           $this->jpegPhoto= "";
1031         }
1032       }
1033     }
1035     /* close conncetion */
1036     ldap_unbind($ds);
1037   }
1040   /* Load a certificate from LDAP, this is going to be simplified later on */
1041   function load_cert()
1042   {
1043     $ds= ldap_connect($this->config->current['SERVER']);
1044     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1045     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1046       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1047       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1048     }
1049     if(isset($this->config->current['TLS']) &&
1050         $this->config->current['TLS'] == "true"){
1052       ldap_start_tls($ds);
1053     }
1055     $r= ldap_bind($ds);
1056     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1058     if ($sr) {
1059       $ei= @ldap_first_entry($ds, $sr);
1060       
1061       if ($ei) {
1062         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1063           $this->userCertificate= "";
1064         } else {
1065           $this->userCertificate= $info[0];
1066         }
1067       }
1068     } else {
1069       $this->userCertificate= "";
1070     }
1072     ldap_unbind($ds);
1073   }
1076   /* Load picture from file to object */
1077   function set_picture($filename)
1078   {
1079     if (!is_file($filename)){
1080       $filename= "./images/default.jpg";
1081       $this->jpegPhoto= "*removed*";
1082     }
1084     $fd = fopen ($filename, "rb");
1085     $this->photoData= fread ($fd, filesize ($filename));
1086     $_SESSION['binary']= $this->photoData;
1087     $_SESSION['binarytype']= "image/jpeg";
1088     $this->jpegPhoto= "";
1090     fclose ($fd);
1091   }
1094   /* Load certificate from file to object */
1095   function set_cert($cert, $filename)
1096   {
1097     $fd = fopen ($filename, "rb");
1098     if (filesize($filename)>0) {
1099       $this->$cert= fread ($fd, filesize ($filename));
1100       fclose ($fd);
1101       $this->is_modified= TRUE;
1102     } else {
1103       print_red(_("Could not open specified certificate!"));
1104     }
1105   }
1107   /* Adapt from given 'dn' */
1108   function adapt_from_template($dn)
1109   {
1110     plugin::adapt_from_template($dn);
1112     /* Get base */
1113     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1115     if ($this->config->current['GOVERNMENTMODE']){
1117       /* Walk through govattrs */
1118       foreach ($this->govattrs as $val){
1120         if (isset($this->attrs["$val"][0])){
1122           /* If attribute is set, replace dynamic parts: 
1123              %sn, %givenName and %uid. Fill these in our local variables. */
1124           $value= $this->attrs["$val"][0];
1126           foreach (array("sn", "givenName", "uid") as $repl){
1127             if (preg_match("/%$repl/i", $value)){
1128               $value= preg_replace ("/%$repl/i",
1129                   $this->parent->$repl, $value);
1130             }
1131           }
1132           $this->$val= $value;
1133         }
1134       }
1135     }
1137     /* Get back uid/sn/givenName */
1138     if ($this->parent != NULL){
1139       $this->uid= $this->parent->uid;
1140       $this->sn= $this->parent->sn;
1141       $this->givenName= $this->parent->givenName;
1142     }
1143   }
1147 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1148 ?>