Code

Added empty lines
[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         /* Call parent execute */
207         plugin::execute();
209     $smarty= get_smarty();
211     /* Fill calendar */
212     if ($this->dob == "0"){
213       $date= getdate();
214     } else {
215       if(is_array($this->dob)){
216         $date = $this->dob;
217       }else{
218         $date = getdate($this->dob);
219       } 
220     }
222     $days= array();
223     for($d= 1; $d<32; $d++){
224       $days[$d]= $d;
225     }
226     $years= array();
228     if(($date['year']-100)<1901){
229       $start = 1901;
230     }else{
231       $start = $date['year']-100;
232     }
234     $end = $start +100;
235     
236     for($y= $start; $y<=$end; $y++){
237       $years[]= $y;
238     }
239     $years['-']= "-&nbsp;";
240     $months= array(_("January"), _("February"), _("March"), _("April"),
241         _("May"), _("June"), _("July"), _("August"), _("September"),
242         _("October"), _("November"), _("December"), '-' => '-&nbsp;');
243     $smarty->assign("day", $date["mday"]);
244     $smarty->assign("days", $days);
245     $smarty->assign("months", $months);
246     $smarty->assign("month", $date["mon"]-1);
247     $smarty->assign("years", $years);
248     $smarty->assign("year", $date["year"]);
250     /* Assign sex */
251     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
252     $smarty->assign("gender_list", $sex);
254     /* Assign prefered langage */
255     $language= array(0 => "&nbsp;", "fr_FR" => ("fr_FR"), "en_EN" => ("en_EN"), "de_DE" => ("de_DE"), "it_IT" => ("it_IT"), "nl_NL" => ("nl_NL"));
256     $smarty->assign("preferredLanguage_list", $language);
258     /* Get random number for pictures */
259     srand((double)microtime()*1000000); 
260     $smarty->assign("rand", rand(0, 10000));
262     /* Do we represent a valid gosaAccount? */
263     if (!$this->is_account){
264       echo "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
265         _("This account has no valid GOsa extensions.")."</b>";
266       return;
267     }
269     /* Want picture edit dialog? */
270     if (isset($_POST['edit_picture'])){
271       /* Save values for later recovery, in case some presses
272          the cancel button. */
273       $this->old_jpegPhoto= $this->jpegPhoto;
274       $this->old_photoData= $this->photoData;
275       $this->picture_dialog= TRUE;
276       $this->dialog= TRUE;
277     }
279     /* Remove picture? */
280     if (isset($_POST['picture_remove'])){
281       $this->jpegPhoto= "*removed*";
282       $this->set_picture ("./images/default.jpg");
283       $this->is_modified= TRUE;
285       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
286     }
288     /* Save picture */
289     if (isset($_POST['picture_edit_finish'])){
291       /* Check for clean upload */
292       if ($_FILES['picture_file']['name'] != ""){
293         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
294           print_red(_("The specified file has not been uploaded via HTTP POST! Aborted."));
295           exit;
296         }
298         /* Activate new picture */
299         $this->set_picture($_FILES['picture_file']['tmp_name']);
300       }
301       $this->picture_dialog= FALSE;
302       $this->dialog= FALSE;
303       $this->is_modified= TRUE;
304     }
307     /* Cancel picture */
308     if (isset($_POST['picture_edit_cancel'])){
310       /* Restore values */
311       $this->jpegPhoto= $this->old_jpegPhoto;
312       $this->photoData= $this->old_photoData;
314       /* Update picture */
315       $_SESSION['binary']= $this->photoData;
316       $_SESSION['binarytype']= "image/jpeg";
317       $this->picture_dialog= FALSE;
318       $this->dialog= FALSE;
319     }
321     /* Toggle dob information */
322     if (isset($_POST['set_dob'])){
323       $this->use_dob= ($this->use_dob == "0")?"1":"0";
324     }
327     /* Want certificate= */
328     if (isset($_POST['edit_cert'])){
330       /* Save original values for later reconstruction */
331       foreach (array("certificateSerialNumber", "userCertificate",
332             "userSMIMECertificate", "userPKCS12") as $val){
334         $oval= "old_$val";
335         $this->$oval= $this->$val;
336       }
338       $this->cert_dialog= TRUE;
339       $this->dialog= TRUE;
340     }
343     /* Cancel certificate dialog */
344     if (isset($_POST['cert_edit_cancel'])){
346       /* Restore original values in case of 'cancel' */
347       foreach (array("certificateSerialNumber", "userCertificate",
348             "userSMIMECertificate", "userPKCS12") as $val){
350         $oval= "old_$val";
351         $this->$val= $this->$oval;
352       }
353       $this->cert_dialog= FALSE;
354       $this->dialog= FALSE;
355     }
358     /* Remove certificate? */
359     foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
360       if (isset($_POST["remove_$val"])){
362         /* Reset specified cert*/
363         $this->$val= "";
364         $this->is_modified= TRUE;
365       }
366     }
369     /* Upload new cert and close dialog? */     
370     if (isset($_POST['cert_edit_finish'])){
372       /* for all certificates do */
373       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
374           as $val){
376         /* Check for clean upload */
377         if (array_key_exists($val."_file", $_FILES) &&
378             array_key_exists('name', $_FILES[$val."_file"]) &&
379             $_FILES[$val."_file"]['name'] != "" &&
380             is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
381           $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
382         }
383       }
385       /* Save serial number */
386       if (isset($_POST["certificateSerialNumber"]) &&
387           $_POST["certificateSerialNumber"] != ""){
389         if (!is_id($_POST["certificateSerialNumber"])){
390           print_red (_("Please enter a valid serial number"));
392           foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
393             if ($this->$cert != ""){
394               $smarty->assign("$cert"."_state", "true");
395             } else {
396               $smarty->assign("$cert"."_state", "");
397             }
398           }
399           return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
400         }
402         $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
403         $this->is_modified= TRUE;
404       }
406       $this->cert_dialog= FALSE;
407       $this->dialog= FALSE;
408     }
410     /* Display picture dialog */
411     if ($this->picture_dialog){
412       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
413     }
415     /* Display cert dialog */
416     if ($this->cert_dialog){
417       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
418         if ($this->$cert != ""){
419           /* import certificate */
420           $certificate = new certificate;
421           $certificate->import($this->$cert);
422       
423           /* Read out data*/
424           $timeto   = $certificate->getvalidto_date();
425           $timefrom = $certificate->getvalidfrom_date();
426           $str = "<table summary=\"\" border=0><tr><td style='vertical-align:top'>CN</td><td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td></tr></table><br>".
427                   sprintf(_("Certificate is valid from %s to %s and is currently %s."), "<b>".date('d M Y',$timefrom)."</b>","<b>".date('d M Y',$timeto)."</b>", $certificate->isvalid()?"<b><font style='color:green'>"._("valid")."</font></b>":"<b><font style='color:red'>"._("invalid")."</font></b>");
428           $smarty->assign($cert."info",$str);
429           $smarty->assign($cert."_state","true");
430         } else {
431           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
432           $smarty->assign($cert."_state","");
433         }
434       }
435       $smarty->assign("governmentmode", "false");
436       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
437     }
439     /* Show us the edit screen */
440     $smarty->assign("bases", $this->config->idepartments);
441     $smarty->assign("base_select", $this->base);
442     $smarty->assign("selectmode", chkacl($this->acl, "create"));
443     $smarty->assign("certificatesACL", chkacl($this->acl, "certificates"));
444     $smarty->assign("jpegPhotoACL", chkacl($this->acl, "jpegPhoto"));
446     /* Prepare password hashes */
447     if ($this->pw_storage == ""){
448       $this->pw_storage= $this->config->current['HASH'];
449     }
451     $temp   = passwordMethod::get_available_methods();
452     $hashes = $temp['name'];
453     
454     $smarty->assign("pwmode", $hashes);
455     $smarty->assign("pwmode_select", $this->pw_storage);
456     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
458     /* Load attributes and acl's */
459     foreach($this->attributes as $val){
460       $smarty->assign("$val", $this->$val);
461       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
462     }
464     /* Save government mode attributes */
465     if (isset($this->config->current['GOVERNMENTMODE']) &&
466         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
467       $smarty->assign("governmentmode", "true");
468       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
469           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
470       $smarty->assign("ivbbmodes", $ivbbmodes);
471       foreach ($this->govattrs as $val){
472         $smarty->assign("$val", $this->$val);
473         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
474       }
475     } else {
476       $smarty->assign("governmentmode", "false");
477     }
479     /* Special mode for uid */
480     $uidACL= "";
481     if (isset ($this->dn)){
482       if ($this->dn != "new"){
483         $uidACL="readonly";
484       }
485     }  else {
486       $uidACL= "readonly";
487     }
488     $uidACL.= " ".chkacl($this->acl, "uid");
489     
490     $smarty->assign("uidACL", $uidACL);
491     $smarty->assign("is_template", $this->is_template);
492     $smarty->assign("use_dob", $this->use_dob);
494     if (isset($this->parent)){
495       if (isset($this->parent->by_object['phoneAccount']) &&
496           $this->parent->by_object['phoneAccount']->is_account){
497         $smarty->assign("has_phoneaccount", "true");
498       } else {
499         $smarty->assign("has_phoneaccount", "false");
500       }
501     } else {
502         $smarty->assign("has_phoneaccount", "false");
503     }
505     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
506   }
509   /* remove object from parent */
510   function remove_from_parent()
511   {
512     $ldap= $this->config->get_ldap_link();
513     $ldap->rmdir ($this->dn);
515     /* Delete references to groups */
516     $ldap->cd ($this->config->current['BASE']);
517     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
518     while ($ldap->fetch()){
519       $g= new group($this->config, $ldap->getDN());
520       $g->removeUser($this->uid);
521       $g->save ();
522     }
524     /* Delete references to object groups */
525     $ldap->cd ($this->config->current['BASE']);
526     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
527     while ($ldap->fetch()){
528       $og= new ogroup($this->config, $ldap->getDN());
529       unset($og->member[$this->dn]);
530       $og->save ();
531     }
533     /* Optionally execute a command after we're done */
534     $this->handle_post_events("remove");
535   }
538   /* Save data to object */
539   function save_object()
540   {
541     if (isset($_POST['generic'])){
543       /* Parents save function */
544       plugin::save_object ();
546       /* Save government mode attributes */
547       if ($this->config->current['GOVERNMENTMODE']){
548         foreach ($this->govattrs as $val){
549           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
550             $data= stripcslashes($_POST["$val"]);
551             if ($data != $this->$val){
552               $this->is_modified= TRUE;
553             }
554             $this->$val= $data;
555           }
556         }
557       }
559       /* In template mode, the uid is autogenerated... */
560       if ($this->is_template){
561         $this->uid= strtolower($this->sn);
562         $this->givenName= $this->sn;
563       }
565       /* Save base and pw_storage, since these are no LDAP attributes */
566       if (isset($_POST['base'])){
567         foreach(array("base", "pw_storage") as $val){
568           $data= validate($_POST[$val]);
569           if ($data != $this->$val){
570             $this->is_modified= TRUE;
571           }
572           $this->$val= $data;
573         }
574       }
575     }
576   }
578   function rebind($ldap, $referral)
579   {
580     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
581     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
582       $this->error = "Success";
583       $this->hascon=true;
584       $this->reconnect= true;
585       return (0);
586     } else {
587       $this->error = "Could not bind to " . $credentials['ADMIN'];
588       return NULL;
589     }
590   }
592   /* Save data to LDAP, depending on is_account we save or delete */
593   function save()
594   {
595     /* First use parents methods to do some basic fillup in $this->attrs */
596     plugin::save ();
598     /* Remove additional objectClasses */
599     $tmp= array();
600     foreach ($this->attrs['objectClass'] as $key => $set){
601       $found= false;
602       foreach (array("ivbbEntry", "gosaUserTemplate") as $val){
603         if (preg_match ("/^$set$/i", $val)){
604           $found= true;
605           break;
606         }
607       }
608       if (!$found){
609         $tmp[]= $set;
610       }
611     }
613     /* Replace the objectClass array. This is done because of the
614        separation into government and normal mode. */
615     $this->attrs['objectClass']= $tmp;
617     /* Add objectClasss for template mode? */
618     if ($this->is_template){
619       $this->attrs['objectClass'][]= "gosaUserTemplate";
620     }
622     /* Hard coded government mode? */
623     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
624       $this->attrs['objectClass'][]= "ivbbEntry";
626       /* Copy standard attributes */
627       foreach ($this->govattrs as $val){
628         if ($this->$val != ""){
629           $this->attrs["$val"]= $this->$val;
630         } elseif (!$this->new) {
631           $this->attrs["$val"]= array();
632         }
633       }
635       /* Remove attribute if set to "nein" */
636       if ($this->publicVisible == "nein"){
637         $this->attrs['publicVisible']= array();
638         if($this->new){
639           unset($this->attrs['publicVisible']);
640         }else{
641           $this->attrs['publicVisible']=array();
642         }
644       }
646     }
648     /* Special handling for attribute userCertificate needed */
649     if ($this->userCertificate != ""){
650       $this->attrs["userCertificate;binary"]= $this->userCertificate;
651       $remove_userCertificate= false;
652     } else {
653       $remove_userCertificate= true;
654     }
656     /* Special handling for dob value */
657     if ($this->use_dob == "1"){
658       $this->attrs["dob"]= date("Y-m-d", $this->dob);
659     } else {
660       if ($this->new) {
661         unset($this->attrs["dob"]);
662       } else {
663         $this->attrs["dob"]= array();
664       }
665     }
666     if ($this->gender == "0"){
667       if ($this->new) {
668         unset($this->attrs["gender"]);
669       } else {
670         $this->attrs["gender"]= array();
671       }
672     }
673       if ($this->preferredLanguage == "0"){
674       if ($this->new) {
675         unset($this->attrs["preferredLanguage"]);
676       } else {
677         $this->attrs["preferredLanguage"]= array();
678       }
679     }
681     /* Special handling for attribute jpegPhote needed, scale image via
682        image magick to 147x200 pixels and inject resulting data. */
683     if ($this->jpegPhoto != "*removed*"){
685       /* Fallback if there's no image magick inside PHP */
686       if (!function_exists("imagick_blob2image")){
687         /* Get temporary file name for conversation */
688         $fname = tempnam ("/tmp", "GOsa");
690         /* Open file and write out photoData */
691         $fp = fopen ($fname, "w");
692         fwrite ($fp, $this->photoData);
693         fclose ($fp);
695         /* Build conversation query. Filename is generated automatically, so
696            we do not need any special security checks. Exec command and save
697            output. For PHP safe mode, you'll need a configuration which respects
698            image magick as executable... */
699         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
700         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
701             $query, "Execute");
703         /* Read data written by convert */
704         $output= "";
705         $sh= popen($query, 'r');
706         while (!feof($sh)){
707           $output.= fread($sh, 4096);
708         }
709         pclose($sh);
711         unlink($fname);
713         /* Save attribute */
714         $this->attrs["jpegPhoto"] = $output;
716       } else {
718         /* Load the new uploaded Photo */
719         if(!$handle  =  imagick_blob2image($this->photoData))  {
720           gosa_log("Can't Load image");
721         }
723         /* Resizing image to 147x200 and blur */
724         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
725           gosa_log("imagick_resize failed");
726         }
728         /* Converting image to JPEG */
729         if(!imagick_convert($handle,"JPEG")) {
730           gosa_log("Can't Convert to JPEG");
731         }
733         /* Creating binary Code for the Image */
734         if(!$dump = imagick_image2blob($handle)){
735           gosa_log("Can't create blob for image");
736         }
738         /* Sending Image */
739         $output=  $dump;
741         /* Save attribute */
742         $this->attrs["jpegPhoto"] = $output;
743       }
745     } elseif(!$this->new) {
746       $this->attrs["jpegPhoto"] = array();
747     }
749     /* Build new dn */
750     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
751       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
752     } else {
753       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
754     }
756     /* This only gets called when user is renaming himself */
757     $ldap= $this->config->get_ldap_link();
758     if ($this->dn != $new_dn){
760       /* Write entry on new 'dn' */
761       $this->move($this->dn, $new_dn);
763       /* Happen to use the new one */
764       change_ui_dn($this->dn, $new_dn);
765       $this->dn= $new_dn;
766     }
769     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
770        new entries. So do a check first... */
771     $ldap->cat ($this->dn);
772     if ($ldap->fetch()){
773       $mode= "modify";
774     } else {
775       $mode= "add";
776       $ldap->cd($this->config->current['BASE']);
777       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
778     }
780     /* Set password to some junk stuff in case of templates */
781     if ($this->is_template){
782       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
783     }
785     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
786         $this->attributes, "Save via $mode");
788     /* Finally write data with selected 'mode' */
789     $ldap->cd ($this->dn);
790     $ldap->$mode ($this->attrs);
791     if (show_ldap_error($ldap->get_error())){
792       return (1);
793     }
795     /* Remove cert? 
796        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
797        to work around myself. */
798     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
800       /* Reset array, assemble new, this should be reworked */
801       $this->attrs= array();
802       $this->attrs['userCertificate;binary']= array();
804       /* Prepare connection */
805       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
806         die ("Could not connect to LDAP server");
807       }
808       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
809       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
810         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
811         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
812       }
813       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
814         ldap_start_tls($ds);
815       }
816       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
817               $this->config->current['PASSWORD']))) {
818         die ("Could not bind to LDAP");
819       }
821       /* Modify using attrs */
822       ldap_mod_del($ds,$this->dn,$this->attrs);
823       ldap_close($ds);
824     }
826     /* Kerberos server defined? */
827     if (isset($this->config->data['SERVERS']['KERBEROS'])){
828       $cfg= $this->config->data['SERVERS']['KERBEROS'];
829     }
830     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
832       /* Connect to the admin interface */
833       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
834           $cfg['ADMIN'], $cfg['PASSWORD']);
836       /* Errors? */             
837       if ($handle === FALSE){
838         print_red (_("Kerberos database communication failed"));
839         return (2);
840       }
842       /* Build user principal, get list of existsing principals */
843       $principal= $this->uid."@".$cfg['REALM'];
844       $principals = kadm5_get_principals($handle);
846       /* User exists in database? */
847       if (in_array($principal, $principals)){
849         /* Ok. User exists. Remove him/her when pw_storage has
850            changed to be NOT kerberos. */
851         if ($this->pw_storage != "kerberos"){
852           $ret= kadm5_delete_principal ( $handle, $principal);
854           if ($ret === FALSE){
855             print_red (_("Can't remove user from kerberos database."));
856           }
857         }
859       } else {
861         /* User doesn't exists, create it when pw_storage is kerberos. */
862         if ($this->pw_storage == "kerberos"){
863           $ret= kadm5_create_principal ( $handle, $principal);
865           if ($ret === FALSE){
866             print_red (_("Can't add user to kerberos database."));
867           }
868         }
870       }
872       /* Free kerberos admin handle */
873       kadm5_destroy($handle);
874     }
876     /* Optionally execute a command after we're done */
877     if ($mode == "add"){
878       $this->handle_post_events("add");
879     } elseif ($this->is_modified){
880       $this->handle_post_events("modify");
881     }
883     return (0);
884   }
887   /* Check formular input */
888   function check()
889   {
890     $message= array();
892     /* Assemble cn */
893     $this->cn= $this->givenName." ".$this->sn;
895     if(preg_match("/[^a-z0-9]/",$this->uid)){
896       $message[]=_("Invalid characters in uid.") ;
897     }
899     /* Permissions for that base? */
900     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
901       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
902     } else {
903       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
904     }
906     $ui= get_userinfo();
907     $acl= get_permissions ($new_dn, $ui->subtreeACL);
908     $acl= get_module_permission($acl, "user", $new_dn);
909     if ($this->dn == "new" && chkacl($acl, "create") != ""){
910       $message[]= _("You have no permissions to create a user on this 'Base'.");
911     } elseif ($this->dn != $new_dn && $this->dn != "new"){
912       $acl= get_permissions ($this->dn, $ui->subtreeACL);
913       $acl= get_module_permission($acl, "user", $this->dn);
914       if (chkacl($acl, "create") != ""){
915         $message[]= _("You have no permissions to move a user from the original 'Base'.");
916       }
917     }
919     /* must: sn, givenName, uid */
920     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
921       $message[]= _("The required field 'Name' is not set.");
922     }
924     /* UID already used? */
925     $ldap= $this->config->get_ldap_link();
926     $ldap->cd($this->config->current['BASE']);
927     $ldap->search("(uid=$this->uid)", array("uid"));
928     $ldap->fetch();
929     if ($ldap->count() != 0 && $this->dn == 'new'){
930       $message[]= _("There's already a person with this 'Login' in the database.");
931     }
933     /* In template mode, the uid and givenName are autogenerated... */
934     if (!$this->is_template){
935       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
936         $message[]= _("The required field 'Given name' is not set.");
937       }
938       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
939         $message[]= _("The required field 'Login' is not set.");
940       }
941       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
942         $ldap->cd($this->config->current['BASE']);
943         $ldap->search("(cn=".$this->cn.")", array("uid"));
944         $ldap->fetch();
945         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
946           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
947         }
948       }
949     }
951     /* Check for valid input */
952     if ($this->is_modified && !is_uid($this->uid)){
953       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
954     }
955     if (!is_url($this->labeledURI)){
956       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
957     }
958     if (preg_match ("/[\\\\]/", $this->sn)){
959       $message[]= _("The field 'Name' contains invalid characters.");
960     }
961     if (preg_match ("/[\\\\]/", $this->givenName)){
962       $message[]= _("The field 'Given name' contains invalid characters.");
963     }
965     /* Check phone numbers */
966     if (!is_phone_nr($this->homePhone)){
967       $message[]= _("The field 'Phone' contains an invalid phone number.");
968     }
969     if (!is_phone_nr($this->telephoneNumber)){
970       $message[]= _("The field 'Phone' contains an invalid phone number.");
971     }
972     if (!is_phone_nr($this->facsimileTelephoneNumber)){
973       $message[]= _("The field 'Fax' contains an invalid phone number.");
974     }
975     if (!is_phone_nr($this->mobile)){
976       $message[]= _("The field 'Mobile' contains an invalid phone number.");
977     }
978     if (!is_phone_nr($this->pager)){
979       $message[]= _("The field 'Pager' contains an invalid phone number.");
980     }
982     /* Check for reserved characers */
983     if (preg_match ('/[,+"?\'()=<>;]/', $this->givenName)){
984       $message[]= _("The field 'Given name' contains invalid characters.");
985     }
986     if (preg_match ('/[,+"?\'()=<>;]/', $this->sn)){
987       $message[]= _("The field 'Name' contains invalid characters.");
988     }
990   return $message;
991   }
994   /* Indicate whether a password change is needed or not */
995   function password_change_needed()
996   {
997     return ($this->pw_storage != $this->last_pw_storage);
998   }
1001   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1002   function load_picture()
1003   {
1004     /* make connection and read jpegPhoto */
1005     $ds= ldap_connect($this->config->current['SERVER']);
1006     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1007     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1008       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1009       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1010     }
1012     if(isset($this->config->current['TLS']) &&
1013         $this->config->current['TLS'] == "true"){
1015       ldap_start_tls($ds);
1016     }
1018     $r= ldap_bind($ds);
1019     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
1021     /* in case we don't get an entry, load a default picture */
1022     $this->set_picture ("./images/default.jpg");
1023     $this->jpegPhoto= "*removed*";
1025     /* fill data from LDAP */
1026     if ($sr) {
1027       $ei=ldap_first_entry($ds, $sr);
1028       if ($ei) {
1029         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
1030           $this->photoData= $info[0];
1031           $_SESSION['binary']= $this->photoData;
1032           $_SESSION['binarytype']= "image/jpeg";
1033           $this->jpegPhoto= "";
1034         }
1035       }
1036     }
1038     /* close conncetion */
1039     ldap_unbind($ds);
1040   }
1043   /* Load a certificate from LDAP, this is going to be simplified later on */
1044   function load_cert()
1045   {
1046     $ds= ldap_connect($this->config->current['SERVER']);
1047     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1048     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1049       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1050       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1051     }
1052     if(isset($this->config->current['TLS']) &&
1053         $this->config->current['TLS'] == "true"){
1055       ldap_start_tls($ds);
1056     }
1058     $r= ldap_bind($ds);
1059     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1061     if ($sr) {
1062       $ei= @ldap_first_entry($ds, $sr);
1063       
1064       if ($ei) {
1065         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1066           $this->userCertificate= "";
1067         } else {
1068           $this->userCertificate= $info[0];
1069         }
1070       }
1071     } else {
1072       $this->userCertificate= "";
1073     }
1075     ldap_unbind($ds);
1076   }
1079   /* Load picture from file to object */
1080   function set_picture($filename)
1081   {
1082     if (!is_file($filename)){
1083       $filename= "./images/default.jpg";
1084       $this->jpegPhoto= "*removed*";
1085     }
1087     $fd = fopen ($filename, "rb");
1088     $this->photoData= fread ($fd, filesize ($filename));
1089     $_SESSION['binary']= $this->photoData;
1090     $_SESSION['binarytype']= "image/jpeg";
1091     $this->jpegPhoto= "";
1093     fclose ($fd);
1094   }
1097   /* Load certificate from file to object */
1098   function set_cert($cert, $filename)
1099   {
1100     $fd = fopen ($filename, "rb");
1101     if (filesize($filename)>0) {
1102       $this->$cert= fread ($fd, filesize ($filename));
1103       fclose ($fd);
1104       $this->is_modified= TRUE;
1105     } else {
1106       print_red(_("Could not open specified certificate!"));
1107     }
1108   }
1110   /* Adapt from given 'dn' */
1111   function adapt_from_template($dn)
1112   {
1113     plugin::adapt_from_template($dn);
1115     /* Get base */
1116     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1118     if ($this->config->current['GOVERNMENTMODE']){
1120       /* Walk through govattrs */
1121       foreach ($this->govattrs as $val){
1123         if (isset($this->attrs["$val"][0])){
1125           /* If attribute is set, replace dynamic parts: 
1126              %sn, %givenName and %uid. Fill these in our local variables. */
1127           $value= $this->attrs["$val"][0];
1129           foreach (array("sn", "givenName", "uid") as $repl){
1130             if (preg_match("/%$repl/i", $value)){
1131               $value= preg_replace ("/%$repl/i",
1132                   $this->parent->$repl, $value);
1133             }
1134           }
1135           $this->$val= $value;
1136         }
1137       }
1138     }
1140     /* Get back uid/sn/givenName */
1141     if ($this->parent != NULL){
1142       $this->uid= $this->parent->uid;
1143       $this->sn= $this->parent->sn;
1144       $this->givenName= $this->parent->givenName;
1145     }
1146   }
1150 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1151 ?>