Code

8de21f7e6bdea9449806a6e73c45d4e2ce689432
[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->allowedBasesToMoveTo());
441 #  $smarty->assign("bases", $this->config->idepartments);
442     $smarty->assign("base_select", $this->base);
443     $smarty->assign("selectmode",       chkacl($this->acl, "create"));
444     $smarty->assign("certificatesACL",  chkacl($this->acl, "certificates"));
445     $smarty->assign("jpegPhotoACL",     chkacl($this->acl, "jpegPhoto"));
447     /* Prepare password hashes */
448     if ($this->pw_storage == ""){
449       $this->pw_storage= $this->config->current['HASH'];
450     }
452     $temp   = passwordMethod::get_available_methods();
453     $hashes = $temp['name'];
454     
455     $smarty->assign("pwmode", $hashes);
456     $smarty->assign("pwmode_select", $this->pw_storage);
457     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
459     /* Load attributes and acl's */
460     foreach($this->attributes as $val){
461       $smarty->assign("$val", $this->$val);
462       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
463     }
465     /* Save government mode attributes */
466     if (isset($this->config->current['GOVERNMENTMODE']) &&
467         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
468       $smarty->assign("governmentmode", "true");
469       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
470           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
471       $smarty->assign("ivbbmodes", $ivbbmodes);
472       foreach ($this->govattrs as $val){
473         $smarty->assign("$val", $this->$val);
474         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
475       }
476     } else {
477       $smarty->assign("governmentmode", "false");
478     }
480     /* Special mode for uid */
481     $uidACL= "";
482     if (isset ($this->dn)){
483       if ($this->dn != "new"){
484         $uidACL="readonly";
485       }
486     }  else {
487       $uidACL= "readonly";
488     }
489     $uidACL.= " ".chkacl($this->acl, "uid");
490     
491     $smarty->assign("uidACL", $uidACL);
492     $smarty->assign("is_template", $this->is_template);
493     $smarty->assign("use_dob", $this->use_dob);
495     if (isset($this->parent)){
496       if (isset($this->parent->by_object['phoneAccount']) &&
497           $this->parent->by_object['phoneAccount']->is_account){
498         $smarty->assign("has_phoneaccount", "true");
499       } else {
500         $smarty->assign("has_phoneaccount", "false");
501       }
502     } else {
503       $smarty->assign("has_phoneaccount", "false");
504     }
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           if(isset($_POST[$val])){
569             $data= validate($_POST[$val]);
570             if ($data != $this->$val){
571               $this->is_modified= TRUE;
572             }
573             $this->$val= $data;
574           }
575         }
576       }
577     }
578   }
580   function rebind($ldap, $referral)
581   {
582     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
583     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
584       $this->error = "Success";
585       $this->hascon=true;
586       $this->reconnect= true;
587       return (0);
588     } else {
589       $this->error = "Could not bind to " . $credentials['ADMIN'];
590       return NULL;
591     }
592   }
594   /* Save data to LDAP, depending on is_account we save or delete */
595   function save()
596   {
597     /* First use parents methods to do some basic fillup in $this->attrs */
598     plugin::save ();
600     /* Remove additional objectClasses */
601     $tmp= array();
602     foreach ($this->attrs['objectClass'] as $key => $set){
603       $found= false;
604       foreach (array("ivbbEntry", "gosaUserTemplate") as $val){
605         if (preg_match ("/^$set$/i", $val)){
606           $found= true;
607           break;
608         }
609       }
610       if (!$found){
611         $tmp[]= $set;
612       }
613     }
615     /* Replace the objectClass array. This is done because of the
616        separation into government and normal mode. */
617     $this->attrs['objectClass']= $tmp;
619     /* Add objectClasss for template mode? */
620     if ($this->is_template){
621       $this->attrs['objectClass'][]= "gosaUserTemplate";
622     }
624     /* Hard coded government mode? */
625     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
626       $this->attrs['objectClass'][]= "ivbbEntry";
628       /* Copy standard attributes */
629       foreach ($this->govattrs as $val){
630         if ($this->$val != ""){
631           $this->attrs["$val"]= $this->$val;
632         } elseif (!$this->new) {
633           $this->attrs["$val"]= array();
634         }
635       }
637       /* Remove attribute if set to "nein" */
638       if ($this->publicVisible == "nein"){
639         $this->attrs['publicVisible']= array();
640         if($this->new){
641           unset($this->attrs['publicVisible']);
642         }else{
643           $this->attrs['publicVisible']=array();
644         }
646       }
648     }
650     /* Special handling for attribute userCertificate needed */
651     if ($this->userCertificate != ""){
652       $this->attrs["userCertificate;binary"]= $this->userCertificate;
653       $remove_userCertificate= false;
654     } else {
655       $remove_userCertificate= true;
656     }
658     /* Special handling for dob value */
659     if ($this->use_dob == "1"){
660       $this->attrs["dob"]= date("Y-m-d", $this->dob);
661     } else {
662       if ($this->new) {
663         unset($this->attrs["dob"]);
664       } else {
665         $this->attrs["dob"]= array();
666       }
667     }
668     if ($this->gender == "0"){
669       if ($this->new) {
670         unset($this->attrs["gender"]);
671       } else {
672         $this->attrs["gender"]= array();
673       }
674     }
675       if ($this->preferredLanguage == "0"){
676       if ($this->new) {
677         unset($this->attrs["preferredLanguage"]);
678       } else {
679         $this->attrs["preferredLanguage"]= array();
680       }
681     }
683     /* Special handling for attribute jpegPhote needed, scale image via
684        image magick to 147x200 pixels and inject resulting data. */
685     if ($this->jpegPhoto != "*removed*"){
687       /* Fallback if there's no image magick inside PHP */
688       if (!function_exists("imagick_blob2image")){
689         /* Get temporary file name for conversation */
690         $fname = tempnam ("/tmp", "GOsa");
692         /* Open file and write out photoData */
693         $fp = fopen ($fname, "w");
694         fwrite ($fp, $this->photoData);
695         fclose ($fp);
697         /* Build conversation query. Filename is generated automatically, so
698            we do not need any special security checks. Exec command and save
699            output. For PHP safe mode, you'll need a configuration which respects
700            image magick as executable... */
701         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
702         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
703             $query, "Execute");
705         /* Read data written by convert */
706         $output= "";
707         $sh= popen($query, 'r');
708         while (!feof($sh)){
709           $output.= fread($sh, 4096);
710         }
711         pclose($sh);
713         unlink($fname);
715         /* Save attribute */
716         $this->attrs["jpegPhoto"] = $output;
718       } else {
720         /* Load the new uploaded Photo */
721         if(!$handle  =  imagick_blob2image($this->photoData))  {
722           gosa_log("Can't Load image");
723         }
725         /* Resizing image to 147x200 and blur */
726         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
727           gosa_log("imagick_resize failed");
728         }
730         /* Converting image to JPEG */
731         if(!imagick_convert($handle,"JPEG")) {
732           gosa_log("Can't Convert to JPEG");
733         }
735         /* Creating binary Code for the Image */
736         if(!$dump = imagick_image2blob($handle)){
737           gosa_log("Can't create blob for image");
738         }
740         /* Sending Image */
741         $output=  $dump;
743         /* Save attribute */
744         $this->attrs["jpegPhoto"] = $output;
745       }
747     } elseif(!$this->new) {
748       $this->attrs["jpegPhoto"] = array();
749     }
751     /* Build new dn */
752     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
753       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
754     } else {
755       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
756     }
758     /* This only gets called when user is renaming himself */
759     $ldap= $this->config->get_ldap_link();
760     if ($this->dn != $new_dn){
762       /* Write entry on new 'dn' */
763       $this->move($this->dn, $new_dn);
765       /* Happen to use the new one */
766       change_ui_dn($this->dn, $new_dn);
767       $this->dn= $new_dn;
768     }
771     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
772        new entries. So do a check first... */
773     $ldap->cat ($this->dn);
774     if ($ldap->fetch()){
775       $mode= "modify";
776     } else {
777       $mode= "add";
778       $ldap->cd($this->config->current['BASE']);
779       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
780     }
782     /* Set password to some junk stuff in case of templates */
783     if ($this->is_template){
784       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
785     }
787     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
788         $this->attributes, "Save via $mode");
790     /* Finally write data with selected 'mode' */
791     $ldap->cd ($this->dn);
792     $ldap->$mode ($this->attrs);
793     if (show_ldap_error($ldap->get_error())){
794       return (1);
795     }
797     /* Remove cert? 
798        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
799        to work around myself. */
800     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
802       /* Reset array, assemble new, this should be reworked */
803       $this->attrs= array();
804       $this->attrs['userCertificate;binary']= array();
806       /* Prepare connection */
807       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
808         die ("Could not connect to LDAP server");
809       }
810       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
811       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
812         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
813         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
814       }
815       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
816         ldap_start_tls($ds);
817       }
818       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
819               $this->config->current['PASSWORD']))) {
820         die ("Could not bind to LDAP");
821       }
823       /* Modify using attrs */
824       ldap_mod_del($ds,$this->dn,$this->attrs);
825       ldap_close($ds);
826     }
828     /* Kerberos server defined? */
829     if (isset($this->config->data['SERVERS']['KERBEROS'])){
830       $cfg= $this->config->data['SERVERS']['KERBEROS'];
831     }
832     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
834       /* Connect to the admin interface */
835       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
836           $cfg['ADMIN'], $cfg['PASSWORD']);
838       /* Errors? */             
839       if ($handle === FALSE){
840         print_red (_("Kerberos database communication failed"));
841         return (2);
842       }
844       /* Build user principal, get list of existsing principals */
845       $principal= $this->uid."@".$cfg['REALM'];
846       $principals = kadm5_get_principals($handle);
848       /* User exists in database? */
849       if (in_array($principal, $principals)){
851         /* Ok. User exists. Remove him/her when pw_storage has
852            changed to be NOT kerberos. */
853         if ($this->pw_storage != "kerberos"){
854           $ret= kadm5_delete_principal ( $handle, $principal);
856           if ($ret === FALSE){
857             print_red (_("Can't remove user from kerberos database."));
858           }
859         }
861       } else {
863         /* User doesn't exists, create it when pw_storage is kerberos. */
864         if ($this->pw_storage == "kerberos"){
865           $ret= kadm5_create_principal ( $handle, $principal);
867           if ($ret === FALSE){
868             print_red (_("Can't add user to kerberos database."));
869           }
870         }
872       }
874       /* Free kerberos admin handle */
875       kadm5_destroy($handle);
876     }
878     /* Optionally execute a command after we're done */
879     if ($mode == "add"){
880       $this->handle_post_events("add");
881     } elseif ($this->is_modified){
882       $this->handle_post_events("modify");
883     }
885     return (0);
886   }
889   /* Check formular input */
890   function check()
891   {
892     $message= array();
894     /* Assemble cn */
895     $this->cn= $this->givenName." ".$this->sn;
897     if(preg_match("/[^a-z0-9]/",$this->uid)){
898       $message[]=_("Invalid characters in uid.") ;
899     }
901     /* Permissions for that base? */
902     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
903       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
904     } else {
905       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
906     }
908     $ui= get_userinfo();
909     $acl= get_permissions ($new_dn, $ui->subtreeACL);
910     $acl= get_module_permission($acl, "user", $new_dn);
911     if ($this->dn == "new" && chkacl($acl, "create") != ""){
912       $message[]= _("You have no permissions to create a user on this 'Base'.");
913     } elseif ($this->dn != $new_dn && $this->dn != "new"){
914       $acl= get_permissions ($this->dn, $ui->subtreeACL);
915       $acl= get_module_permission($acl, "user", $this->dn);
916       if (chkacl($acl, "create") != ""){
917         $message[]= _("You have no permissions to move a user from the original 'Base'.");
918       }
919     }
921     /* must: sn, givenName, uid */
922     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
923       $message[]= _("The required field 'Name' is not set.");
924     }
926     /* UID already used? */
927     $ldap= $this->config->get_ldap_link();
928     $ldap->cd($this->config->current['BASE']);
929     $ldap->search("(uid=$this->uid)", array("uid"));
930     $ldap->fetch();
931     if ($ldap->count() != 0 && $this->dn == 'new'){
932       $message[]= _("There's already a person with this 'Login' in the database.");
933     }
935     /* In template mode, the uid and givenName are autogenerated... */
936     if (!$this->is_template){
937       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
938         $message[]= _("The required field 'Given name' is not set.");
939       }
940       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
941         $message[]= _("The required field 'Login' is not set.");
942       }
943       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
944         $ldap->cd($this->config->current['BASE']);
945         $ldap->search("(cn=".$this->cn.")", array("uid"));
946         $ldap->fetch();
947         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
948           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
949         }
950       }
951     }
953     /* Check for valid input */
954     if ($this->is_modified && !is_uid($this->uid)){
955       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
956     }
957     if (!is_url($this->labeledURI)){
958       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
959     }
960     if (preg_match ("/[\\\\]/", $this->sn)){
961       $message[]= _("The field 'Name' contains invalid characters.");
962     }
963     if (preg_match ("/[\\\\]/", $this->givenName)){
964       $message[]= _("The field 'Given name' contains invalid characters.");
965     }
967     /* Check phone numbers */
968     if (!is_phone_nr($this->homePhone)){
969       $message[]= _("The field 'Phone' contains an invalid phone number.");
970     }
971     if (!is_phone_nr($this->telephoneNumber)){
972       $message[]= _("The field 'Phone' contains an invalid phone number.");
973     }
974     if (!is_phone_nr($this->facsimileTelephoneNumber)){
975       $message[]= _("The field 'Fax' contains an invalid phone number.");
976     }
977     if (!is_phone_nr($this->mobile)){
978       $message[]= _("The field 'Mobile' contains an invalid phone number.");
979     }
980     if (!is_phone_nr($this->pager)){
981       $message[]= _("The field 'Pager' contains an invalid phone number.");
982     }
984     /* Check for reserved characers */
985     if (preg_match ('/[,+"?\'()=<>;]/', $this->givenName)){
986       $message[]= _("The field 'Given name' contains invalid characters.");
987     }
988     if (preg_match ('/[,+"?\'()=<>;]/', $this->sn)){
989       $message[]= _("The field 'Name' contains invalid characters.");
990     }
992   return $message;
993   }
996   /* Indicate whether a password change is needed or not */
997   function password_change_needed()
998   {
999     return ($this->pw_storage != $this->last_pw_storage);
1000   }
1003   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1004   function load_picture()
1005   {
1006     /* make connection and read jpegPhoto */
1007     $ds= ldap_connect($this->config->current['SERVER']);
1008     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1009     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1010       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1011       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1012     }
1014     if(isset($this->config->current['TLS']) &&
1015         $this->config->current['TLS'] == "true"){
1017       ldap_start_tls($ds);
1018     }
1020     $r= ldap_bind($ds);
1021     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
1023     /* in case we don't get an entry, load a default picture */
1024     $this->set_picture ("./images/default.jpg");
1025     $this->jpegPhoto= "*removed*";
1027     /* fill data from LDAP */
1028     if ($sr) {
1029       $ei=ldap_first_entry($ds, $sr);
1030       if ($ei) {
1031         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
1032           $this->photoData= $info[0];
1033           $_SESSION['binary']= $this->photoData;
1034           $_SESSION['binarytype']= "image/jpeg";
1035           $this->jpegPhoto= "";
1036         }
1037       }
1038     }
1040     /* close conncetion */
1041     ldap_unbind($ds);
1042   }
1045   /* Load a certificate from LDAP, this is going to be simplified later on */
1046   function load_cert()
1047   {
1048     $ds= ldap_connect($this->config->current['SERVER']);
1049     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1050     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1051       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1052       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1053     }
1054     if(isset($this->config->current['TLS']) &&
1055         $this->config->current['TLS'] == "true"){
1057       ldap_start_tls($ds);
1058     }
1060     $r= ldap_bind($ds);
1061     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1063     if ($sr) {
1064       $ei= @ldap_first_entry($ds, $sr);
1065       
1066       if ($ei) {
1067         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1068           $this->userCertificate= "";
1069         } else {
1070           $this->userCertificate= $info[0];
1071         }
1072       }
1073     } else {
1074       $this->userCertificate= "";
1075     }
1077     ldap_unbind($ds);
1078   }
1081   /* Load picture from file to object */
1082   function set_picture($filename)
1083   {
1084     if (!is_file($filename)){
1085       $filename= "./images/default.jpg";
1086       $this->jpegPhoto= "*removed*";
1087     }
1089     $fd = fopen ($filename, "rb");
1090     $this->photoData= fread ($fd, filesize ($filename));
1091     $_SESSION['binary']= $this->photoData;
1092     $_SESSION['binarytype']= "image/jpeg";
1093     $this->jpegPhoto= "";
1095     fclose ($fd);
1096   }
1099   /* Load certificate from file to object */
1100   function set_cert($cert, $filename)
1101   {
1102     $fd = fopen ($filename, "rb");
1103     if (filesize($filename)>0) {
1104       $this->$cert= fread ($fd, filesize ($filename));
1105       fclose ($fd);
1106       $this->is_modified= TRUE;
1107     } else {
1108       print_red(_("Could not open specified certificate!"));
1109     }
1110   }
1112   /* Adapt from given 'dn' */
1113   function adapt_from_template($dn)
1114   {
1115     plugin::adapt_from_template($dn);
1117     /* Get base */
1118     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1120     if ($this->config->current['GOVERNMENTMODE']){
1122       /* Walk through govattrs */
1123       foreach ($this->govattrs as $val){
1125         if (isset($this->attrs["$val"][0])){
1127           /* If attribute is set, replace dynamic parts: 
1128              %sn, %givenName and %uid. Fill these in our local variables. */
1129           $value= $this->attrs["$val"][0];
1131           foreach (array("sn", "givenName", "uid") as $repl){
1132             if (preg_match("/%$repl/i", $value)){
1133               $value= preg_replace ("/%$repl/i",
1134                   $this->parent->$repl, $value);
1135             }
1136           }
1137           $this->$val= $value;
1138         }
1139       }
1140     }
1142     /* Get back uid/sn/givenName */
1143     if ($this->parent != NULL){
1144       $this->uid= $this->parent->uid;
1145       $this->sn= $this->parent->sn;
1146       $this->givenName= $this->parent->givenName;
1147     }
1148   }
1150  
1151   /* This avoids that users move themselves out of their rights. 
1152    */
1153   function allowedBasesToMoveTo()
1154   {
1155     $allowed = array();
1156     $ret_all = false;
1157     if($this->uid == $_SESSION['ui']->username){
1158       $ldap= $this->config->get_ldap_link(); 
1159       $ldap->cd($this->config->current['BASE']); 
1160       $ldap->search("(&(objectClass=posixGroup)(memberUid=".$_SESSION['ui']->username."))",array("gosaSubtreeACL"));
1161        
1162       while($attrs = $ldap->fetch()){
1163         foreach($attrs['gosaSubtreeACL'] as $attr){
1164           if((preg_match("/:user#/",$attr))||(preg_match("/:all/",$attr))){
1165             $s =  preg_replace("/^.*ou=groups,/","",$attrs['dn']);
1167             foreach($this->config->idepartments as $key => $dep) {
1168               if(preg_match("/".$s."/i",$key)){
1169                 $allowed[$key] = $dep;
1170               }
1171             }
1172           }
1173         }
1174       }
1175       if(count($allowed) == 0){
1176         foreach($this->config->idepartments as $key => $dep) {
1177           if($this->base==$key){
1178             $allowed[$key] = $dep;
1179           }
1180         }
1181       }  
1182   
1183       return($allowed);
1184       
1185     }else{
1186       return($this->config->idepartments);
1187     }
1188   } 
1197 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1198 ?>