Code

Fix user->generic, to support new cleanup system, government attributes wasn't stored...
[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 $dateOfBirth;
46   var $use_dob= "0";
47   var $gender="0";
48   var $preferredLanguage="0";
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", "dateOfBirth", "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     $this->config= $config;
107     /* Configuration is fine, allways */
108     if ($this->config->current['GOVERNMENTMODE']){
109       $this->attributes=array_merge($this->attributes,$this->govattrs);
110     }
112     /* Load base attributes */
113     plugin::plugin ($config, $dn);
115     if ($this->config->current['GOVERNMENTMODE']){
116       /* Fix public visible attribute if unset */
117       if (!isset($this->attrs['publicVisible'])){
118         $this->publicVisible == "nein";
119       }
120     }
122     /* Load government mode attributes */
123     if ($this->config->current['GOVERNMENTMODE']){
124       /* Copy all attributs */
125       foreach ($this->govattrs as $val){
126         if (isset($this->attrs["$val"][0])){
127           $this->$val= $this->attrs["$val"][0];
128         }
129       }
130     }
132     /* Create me for new accounts */
133     if ($dn == "new"){
134       $this->is_account= TRUE;
135     }
137     /* Make hash default to md5 if not set in config */
138     if (!isset($this->config->current['HASH'])){
139       $hash= "md5";
140     } else {
141       $hash= $this->config->current['HASH'];
142     }
144     /* Load data from LDAP? */
145     if ($dn != NULL){
147       /* Do base conversation */
148       if ($this->dn == "new"){
149         $ui= get_userinfo();
150         $this->base= dn2base($ui->dn);
151       } else {
152         $this->base= dn2base($dn);
153       }
155       /* get password storage type */
156       if (isset ($this->attrs['userPassword'][0])){
157         /* Initialize local array */
158         $matches= array();
159         if (preg_match ("/^{([^}]+)}(.+)/", $this->attrs['userPassword'][0], $matches)){
160           $this->pw_storage= strtolower($matches[1]);
161         } else {
162           if ($this->attrs['userPassword'][0] != ""){
163             $this->pw_storage= "clear";
164           } else {
165             $this->pw_storage= $hash;
166           }
167         }
168       } else {
169         /* Preset with vaule from configuration */
170         $this->pw_storage= $hash;
171       }
173       /* Load extra attributes: certificate and picture */
174       $this->load_picture();
175       $this->load_cert();
176       if ($this->userCertificate != ""){
177         $this->had_userCertificate= TRUE;
178       }
179     }
181     /* Reset password storage indicator, used by password_change_needed() */
182     if ($dn == "new"){
183       $this->last_pw_storage= "unset";
184     } else {
185       $this->last_pw_storage= $this->pw_storage;
186     }
188     /* Generate dateOfBirth entry */
189     if (isset ($this->attrs['dateOfBirth'])){
190       /* This entry is ISO 8601 conform */
191       list($year, $month, $day)= split("-", $this->attrs['dateOfBirth'][0], 3);
192     
193       $this->dateOfBirth=array( 'mon'=> $month,"mday"=> $day,"year"=> $year);
194       $this->use_dob= "1";
195     } else {
196       $this->use_dob= "0";
197     }
199     /* Put gender attribute to upper case */
200     if (isset ($this->attrs['gender'])){
201       $this->gender= strtoupper($this->attrs['gender'][0]);
202     }   
203   }
206   /* execute generates the html output for this node */
207   function execute()
208   {
209         /* Call parent execute */
210         plugin::execute();
212     $smarty= get_smarty();
214     /* Fill calendar */
215     if ($this->dateOfBirth == "0"){
216       $date= getdate();
217     } else {
218       if(is_array($this->dateOfBirth)){
219         $date = $this->dateOfBirth;
220       }else{
221         $date = getdate($this->dateOfBirth);
222       } 
223     }
225     $days= array();
226     for($d= 1; $d<32; $d++){
227       $days[$d]= $d;
228     }
229     $years= array();
231     if(($date['year']-100)<1901){
232       $start = 1901;
233     }else{
234       $start = $date['year']-100;
235     }
237     $end = $start +100;
238     
239     for($y= $start; $y<=$end; $y++){
240       $years[]= $y;
241     }
242     $years['-']= "-&nbsp;";
243     $months= array(_("January"), _("February"), _("March"), _("April"),
244         _("May"), _("June"), _("July"), _("August"), _("September"),
245         _("October"), _("November"), _("December"), '-' => '-&nbsp;');
246     $smarty->assign("day", $date["mday"]);
247     $smarty->assign("days", $days);
248     $smarty->assign("months", $months);
249     $smarty->assign("month", $date["mon"]-1);
250     $smarty->assign("years", $years);
251     $smarty->assign("year", $date["year"]);
253     /* Assign sex */
254     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
255     $smarty->assign("gender_list", $sex);
257     /* Assign prefered langage */
258     $language= array(0 => "&nbsp;", "fr_FR" => ("fr_FR"), "en_EN" => ("en_EN"), "de_DE" => ("de_DE"), "it_IT" => ("it_IT"), "nl_NL" => ("nl_NL"));
259     $smarty->assign("preferredLanguage_list", $language);
261     /* Get random number for pictures */
262     srand((double)microtime()*1000000); 
263     $smarty->assign("rand", rand(0, 10000));
265     /* Do we represent a valid gosaAccount? */
266     if (!$this->is_account){
267       echo "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
268         _("This account has no valid GOsa extensions.")."</b>";
269       return;
270     }
272     /* Want picture edit dialog? */
273     if (isset($_POST['edit_picture'])){
274       /* Save values for later recovery, in case some presses
275          the cancel button. */
276       $this->old_jpegPhoto= $this->jpegPhoto;
277       $this->old_photoData= $this->photoData;
278       $this->picture_dialog= TRUE;
279       $this->dialog= TRUE;
280     }
282     /* Remove picture? */
283     if (isset($_POST['picture_remove'])){
284       $this->jpegPhoto= "*removed*";
285       $this->set_picture ("./images/default.jpg");
286       $this->is_modified= TRUE;
288       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
289     }
291     /* Save picture */
292     if (isset($_POST['picture_edit_finish'])){
294       /* Check for clean upload */
295       if ($_FILES['picture_file']['name'] != ""){
296         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
297           print_red(_("The specified file has not been uploaded via HTTP POST! Aborted."));
298           exit;
299         }
301         /* Activate new picture */
302         $this->set_picture($_FILES['picture_file']['tmp_name']);
303       }
304       $this->picture_dialog= FALSE;
305       $this->dialog= FALSE;
306       $this->is_modified= TRUE;
307     }
310     /* Cancel picture */
311     if (isset($_POST['picture_edit_cancel'])){
313       /* Restore values */
314       $this->jpegPhoto= $this->old_jpegPhoto;
315       $this->photoData= $this->old_photoData;
317       /* Update picture */
318       $_SESSION['binary']= $this->photoData;
319       $_SESSION['binarytype']= "image/jpeg";
320       $this->picture_dialog= FALSE;
321       $this->dialog= FALSE;
322     }
324     /* Toggle dateOfBirth information */
325     if (isset($_POST['set_dob'])){
326       $this->use_dob= ($this->use_dob == "0")?"1":"0";
327     }
330     /* Want certificate= */
331     if (isset($_POST['edit_cert'])){
333       /* Save original values for later reconstruction */
334       foreach (array("certificateSerialNumber", "userCertificate",
335             "userSMIMECertificate", "userPKCS12") as $val){
337         $oval= "old_$val";
338         $this->$oval= $this->$val;
339       }
341       $this->cert_dialog= TRUE;
342       $this->dialog= TRUE;
343     }
346     /* Cancel certificate dialog */
347     if (isset($_POST['cert_edit_cancel'])){
349       /* Restore original values in case of 'cancel' */
350       foreach (array("certificateSerialNumber", "userCertificate",
351             "userSMIMECertificate", "userPKCS12") as $val){
353         $oval= "old_$val";
354         $this->$val= $this->$oval;
355       }
356       $this->cert_dialog= FALSE;
357       $this->dialog= FALSE;
358     }
361     /* Remove certificate? */
362     foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
363       if (isset($_POST["remove_$val"])){
365         /* Reset specified cert*/
366         $this->$val= "";
367         $this->is_modified= TRUE;
368       }
369     }
372     /* Upload new cert and close dialog? */     
373     if (isset($_POST['cert_edit_finish'])){
375       /* for all certificates do */
376       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
377           as $val){
379         /* Check for clean upload */
380         if (array_key_exists($val."_file", $_FILES) &&
381             array_key_exists('name', $_FILES[$val."_file"]) &&
382             $_FILES[$val."_file"]['name'] != "" &&
383             is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
384           $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
385         }
386       }
388       /* Save serial number */
389       if (isset($_POST["certificateSerialNumber"]) &&
390           $_POST["certificateSerialNumber"] != ""){
392         if (!is_id($_POST["certificateSerialNumber"])){
393           print_red (_("Please enter a valid serial number"));
395           foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
396             if ($this->$cert != ""){
397               $smarty->assign("$cert"."_state", "true");
398             } else {
399               $smarty->assign("$cert"."_state", "");
400             }
401           }
402           return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
403         }
405         $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
406         $this->is_modified= TRUE;
407       }
409       $this->cert_dialog= FALSE;
410       $this->dialog= FALSE;
411     }
413     /* Display picture dialog */
414     if ($this->picture_dialog){
415       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
416     }
418     /* Display cert dialog */
419     if ($this->cert_dialog){
420       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
421         if ($this->$cert != ""){
422           /* import certificate */
423           $certificate = new certificate;
424           $certificate->import($this->$cert);
425       
426           /* Read out data*/
427           $timeto   = $certificate->getvalidto_date();
428           $timefrom = $certificate->getvalidfrom_date();
429           $str = "<table summary=\"\" border=0><tr><td style='vertical-align:top'>CN</td><td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td></tr></table><br>".
430                   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>");
431           $smarty->assign($cert."info",$str);
432           $smarty->assign($cert."_state","true");
433         } else {
434           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
435           $smarty->assign($cert."_state","");
436         }
437       }
438       $smarty->assign("governmentmode", "false");
439       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
440     }
442     /* Show us the edit screen */
443     @$smarty->assign("bases", $this->allowedBasesToMoveTo());
444 #  $smarty->assign("bases", $this->config->idepartments);
445     $smarty->assign("base_select", $this->base);
446     $smarty->assign("selectmode",       chkacl($this->acl, "create"));
447     $smarty->assign("certificatesACL",  chkacl($this->acl, "certificates"));
448     $smarty->assign("jpegPhotoACL",     chkacl($this->acl, "jpegPhoto"));
450     /* Prepare password hashes */
451     if ($this->pw_storage == ""){
452       $this->pw_storage= $this->config->current['HASH'];
453     }
455     $temp   = passwordMethod::get_available_methods();
456     $hashes = $temp['name'];
457     
458     $smarty->assign("pwmode", $hashes);
459     $smarty->assign("pwmode_select", $this->pw_storage);
460     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
462     /* Load attributes and acl's */
463     foreach($this->attributes as $val){
464       $smarty->assign("$val", $this->$val);
465       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
466     }
468     /* Save government mode attributes */
469     if (isset($this->config->current['GOVERNMENTMODE']) &&
470         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
471       $smarty->assign("governmentmode", "true");
472       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
473           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
474       $smarty->assign("ivbbmodes", $ivbbmodes);
475       foreach ($this->govattrs as $val){
476         $smarty->assign("$val", $this->$val);
477         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
478       }
479     } else {
480       $smarty->assign("governmentmode", "false");
481     }
483     /* Special mode for uid */
484     $uidACL= "";
485     if (isset ($this->dn)){
486       if ($this->dn != "new"){
487         $uidACL="readonly";
488       }
489     }  else {
490       $uidACL= "readonly";
491     }
492     $uidACL.= " ".chkacl($this->acl, "uid");
493     
494     $smarty->assign("uidACL", $uidACL);
495     $smarty->assign("is_template", $this->is_template);
496     $smarty->assign("use_dob", $this->use_dob);
498     if (isset($this->parent)){
499       if (isset($this->parent->by_object['phoneAccount']) &&
500           $this->parent->by_object['phoneAccount']->is_account){
501         $smarty->assign("has_phoneaccount", "true");
502       } else {
503         $smarty->assign("has_phoneaccount", "false");
504       }
505     } else {
506       $smarty->assign("has_phoneaccount", "false");
507     }
508     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
509   }
512   /* remove object from parent */
513   function remove_from_parent()
514   {
515     $ldap= $this->config->get_ldap_link();
516     $ldap->rmdir ($this->dn);
518     /* Delete references to groups */
519     $ldap->cd ($this->config->current['BASE']);
520     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
521     while ($ldap->fetch()){
522       $g= new group($this->config, $ldap->getDN());
523       $g->removeUser($this->uid);
524       $g->save ();
525     }
527     /* Delete references to object groups */
528     $ldap->cd ($this->config->current['BASE']);
529     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
530     while ($ldap->fetch()){
531       $og= new ogroup($this->config, $ldap->getDN());
532       unset($og->member[$this->dn]);
533       $og->save ();
534     }
536     /* Optionally execute a command after we're done */
537     $this->handle_post_events("remove");
538   }
541   /* Save data to object */
542   function save_object()
543   {
544     if (isset($_POST['generic'])){
546       /* Parents save function */
547       plugin::save_object ();
549       /* Save government mode attributes */
550       if ($this->config->current['GOVERNMENTMODE']){
551         foreach ($this->govattrs as $val){
552           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
553             $data= stripcslashes($_POST["$val"]);
554             if ($data != $this->$val){
555               $this->is_modified= TRUE;
556             }
557             $this->$val= $data;
558           }
559         }
560       }
562       /* In template mode, the uid is autogenerated... */
563       if ($this->is_template){
564         $this->uid= strtolower($this->sn);
565         $this->givenName= $this->sn;
566       }
568       /* Save base and pw_storage, since these are no LDAP attributes */
569       if (isset($_POST['base'])){
570         foreach(array("base", "pw_storage") as $val){
571           if(isset($_POST[$val])){
572             $data= validate($_POST[$val]);
573             if ($data != $this->$val){
574               $this->is_modified= TRUE;
575             }
576             $this->$val= $data;
577           }
578         }
579       }
580     }
581   }
583   function rebind($ldap, $referral)
584   {
585     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
586     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
587       $this->error = "Success";
588       $this->hascon=true;
589       $this->reconnect= true;
590       return (0);
591     } else {
592       $this->error = "Could not bind to " . $credentials['ADMIN'];
593       return NULL;
594     }
595   }
597   /* Save data to LDAP, depending on is_account we save or delete */
598   function save()
599   {
600     /* Only force save of changes .... 
601        If this attributes aren't changed, avoid saving.
602      */
603     if ($this->use_dob == "1"){
604       $this->dateOfBirth= date("Y-m-d", $this->dateOfBirth);
605     }
606     if($this->gender=="0") $this->gender ="";
607     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
608     
609  
610     /* First use parents methods to do some basic fillup in $this->attrs */
611     plugin::save ();
613     /* Remove additional objectClasses */
614     $tmp= array();
615     foreach ($this->attrs['objectClass'] as $key => $set){
616       $found= false;
617       foreach (array("ivbbEntry", "gosaUserTemplate") as $val){
618         if (preg_match ("/^$set$/i", $val)){
619           $found= true;
620           break;
621         }
622       }
623       if (!$found){
624         $tmp[]= $set;
625       }
626     }
628     /* Replace the objectClass array. This is done because of the
629        separation into government and normal mode. */
630     $this->attrs['objectClass']= $tmp;
632     /* Add objectClasss for template mode? */
633     if ($this->is_template){
634       $this->attrs['objectClass'][]= "gosaUserTemplate";
635     }
637     /* Hard coded government mode? */
638     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
639       $this->attrs['objectClass'][]= "ivbbEntry";
641       /* Copy standard attributes */
642       foreach ($this->govattrs as $val){
643         if ($this->$val != ""){
644           $this->attrs["$val"]= $this->$val;
645         } elseif (!$this->new) {
646           $this->attrs["$val"]= array();
647         }
648       }
650       /* Remove attribute if set to "nein" */
651       if ($this->publicVisible == "nein"){
652         $this->attrs['publicVisible']= array();
653         if($this->new){
654           unset($this->attrs['publicVisible']);
655         }else{
656           $this->attrs['publicVisible']=array();
657         }
659       }
661     }
663     /* Special handling for attribute userCertificate needed */
664     if ($this->userCertificate != ""){
665       $this->attrs["userCertificate;binary"]= $this->userCertificate;
666       $remove_userCertificate= false;
667     } else {
668       $remove_userCertificate= true;
669     }
671     /* Special handling for dateOfBirth value */
672     if ($this->use_dob != "1"){
673       if ($this->new) {
674         unset($this->attrs["dateOfBirth"]);
675       } else {
676         $this->attrs["dateOfBirth"]= array();
677       }
678     }
679     if (!$this->gender){
680       if ($this->new) {
681         unset($this->attrs["gender"]);
682       } else {
683         $this->attrs["gender"]= array();
684       }
685     }
686     if (!$this->preferredLanguage){
687       if ($this->new) {
688         unset($this->attrs["preferredLanguage"]);
689       } else {
690         $this->attrs["preferredLanguage"]= array();
691       }
692     }
694     /* Special handling for attribute jpegPhote needed, scale image via
695        image magick to 147x200 pixels and inject resulting data. */
696     if ($this->jpegPhoto != "*removed*"){
698       /* Fallback if there's no image magick inside PHP */
699       if (!function_exists("imagick_blob2image")){
700         /* Get temporary file name for conversation */
701         $fname = tempnam ("/tmp", "GOsa");
703         /* Open file and write out photoData */
704         $fp = fopen ($fname, "w");
705         fwrite ($fp, $this->photoData);
706         fclose ($fp);
708         /* Build conversation query. Filename is generated automatically, so
709            we do not need any special security checks. Exec command and save
710            output. For PHP safe mode, you'll need a configuration which respects
711            image magick as executable... */
712         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
713         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
714             $query, "Execute");
716         /* Read data written by convert */
717         $output= "";
718         $sh= popen($query, 'r');
719         while (!feof($sh)){
720           $output.= fread($sh, 4096);
721         }
722         pclose($sh);
724         unlink($fname);
726         /* Save attribute */
727         $this->attrs["jpegPhoto"] = $output;
729       } else {
731         /* Load the new uploaded Photo */
732         if(!$handle  =  imagick_blob2image($this->photoData))  {
733           gosa_log("Can't Load image");
734         }
736         /* Resizing image to 147x200 and blur */
737         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
738           gosa_log("imagick_resize failed");
739         }
741         /* Converting image to JPEG */
742         if(!imagick_convert($handle,"JPEG")) {
743           gosa_log("Can't Convert to JPEG");
744         }
746         /* Creating binary Code for the Image */
747         if(!$dump = imagick_image2blob($handle)){
748           gosa_log("Can't create blob for image");
749         }
751         /* Sending Image */
752         $output=  $dump;
754         /* Save attribute */
755         $this->attrs["jpegPhoto"] = $output;
756       }
758     } elseif(!$this->new) {
759       $this->attrs["jpegPhoto"] = array();
760     }
762     /* Build new dn */
763     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
764       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
765     } else {
766       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
767     }
769     /* This only gets called when user is renaming himself */
770     $ldap= $this->config->get_ldap_link();
771     if ($this->dn != $new_dn){
773       /* Write entry on new 'dn' */
774       $this->move($this->dn, $new_dn);
776       /* Happen to use the new one */
777       change_ui_dn($this->dn, $new_dn);
778       $this->dn= $new_dn;
779     }
782     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
783        new entries. So do a check first... */
784     $ldap->cat ($this->dn);
785     if ($ldap->fetch()){
786       $mode= "modify";
787     } else {
788       $mode= "add";
789       $ldap->cd($this->config->current['BASE']);
790       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
791     }
793     /* Set password to some junk stuff in case of templates */
794     if ($this->is_template){
795       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
796     }
798     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
799         $this->attributes, "Save via $mode");
801     /* Finally write data with selected 'mode' */
802     $this->cleanup();
803     $ldap->cd ($this->dn);
804     $ldap->$mode ($this->attrs);
805     if (show_ldap_error($ldap->get_error())){
806       return (1);
807     }
809     /* Remove cert? 
810        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
811        to work around myself. */
812     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
814       /* Reset array, assemble new, this should be reworked */
815       $this->attrs= array();
816       $this->attrs['userCertificate;binary']= array();
818       /* Prepare connection */
819       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
820         die ("Could not connect to LDAP server");
821       }
822       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
823       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
824         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
825         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
826       }
827       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
828         ldap_start_tls($ds);
829       }
830       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
831               $this->config->current['PASSWORD']))) {
832         die ("Could not bind to LDAP");
833       }
835       /* Modify using attrs */
836       ldap_mod_del($ds,$this->dn,$this->attrs);
837       ldap_close($ds);
838     }
840     /* Kerberos server defined? */
841     if (isset($this->config->data['SERVERS']['KERBEROS'])){
842       $cfg= $this->config->data['SERVERS']['KERBEROS'];
843     }
844     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
846       /* Connect to the admin interface */
847       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
848           $cfg['ADMIN'], $cfg['PASSWORD']);
850       /* Errors? */             
851       if ($handle === FALSE){
852         print_red (_("Kerberos database communication failed"));
853         return (2);
854       }
856       /* Build user principal, get list of existsing principals */
857       $principal= $this->uid."@".$cfg['REALM'];
858       $principals = kadm5_get_principals($handle);
860       /* User exists in database? */
861       if (in_array($principal, $principals)){
863         /* Ok. User exists. Remove him/her when pw_storage has
864            changed to be NOT kerberos. */
865         if ($this->pw_storage != "kerberos"){
866           $ret= kadm5_delete_principal ( $handle, $principal);
868           if ($ret === FALSE){
869             print_red (_("Can't remove user from kerberos database."));
870           }
871         }
873       } else {
875         /* User doesn't exists, create it when pw_storage is kerberos. */
876         if ($this->pw_storage == "kerberos"){
877           $ret= kadm5_create_principal ( $handle, $principal);
879           if ($ret === FALSE){
880             print_red (_("Can't add user to kerberos database."));
881           }
882         }
884       }
886       /* Free kerberos admin handle */
887       kadm5_destroy($handle);
888     }
890     /* Optionally execute a command after we're done */
891     if ($mode == "add"){
892       $this->handle_post_events("add");
893     } elseif ($this->is_modified){
894       $this->handle_post_events("modify");
895     }
897     return (0);
898   }
901   /* Check formular input */
902   function check()
903   {
904     $message= array();
906     /* Assemble cn */
907     $this->cn= $this->givenName." ".$this->sn;
909     /* Permissions for that base? */
910     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
911       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
912     } else {
913       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
914     }
916     $ui= get_userinfo();
917     $acl= get_permissions ($new_dn, $ui->subtreeACL);
918     $acl= get_module_permission($acl, "user", $new_dn);
919     if ($this->dn == "new" && chkacl($acl, "create") != ""){
920       $message[]= _("You have no permissions to create a user on this 'Base'.");
921     } elseif ($this->dn != $new_dn && $this->dn != "new"){
922       $acl= get_permissions ($this->dn, $ui->subtreeACL);
923       $acl= get_module_permission($acl, "user", $this->dn);
924       if (chkacl($acl, "create") != ""){
925         $message[]= _("You have no permissions to move a user from the original 'Base'.");
926       }
927     }
929     /* must: sn, givenName, uid */
930     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
931       $message[]= _("The required field 'Name' is not set.");
932     }
934     /* UID already used? */
935     $ldap= $this->config->get_ldap_link();
936     $ldap->cd($this->config->current['BASE']);
937     $ldap->search("(uid=$this->uid)", array("uid"));
938     $ldap->fetch();
939     if ($ldap->count() != 0 && $this->dn == 'new'){
940       $message[]= _("There's already a person with this 'Login' in the database.");
941     }
943     /* In template mode, the uid and givenName are autogenerated... */
944     if (!$this->is_template){
945       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
946         $message[]= _("The required field 'Given name' is not set.");
947       }
948       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
949         $message[]= _("The required field 'Login' is not set.");
950       }
951       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
952         $ldap->cd($this->config->current['BASE']);
953         $ldap->search("(cn=".$this->cn.")", array("uid"));
954         $ldap->fetch();
955         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
956           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
957         }
958       }
959     }
961     /* Check for valid input */
962     if ($this->is_modified && !is_uid($this->uid)){
963       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
964     }
965     if (!is_url($this->labeledURI)){
966       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
967     }
968     if (preg_match ("/[\\\\]/", $this->sn)){
969       $message[]= _("The field 'Name' contains invalid characters.");
970     }
971     if (preg_match ("/[\\\\]/", $this->givenName)){
972       $message[]= _("The field 'Given name' contains invalid characters.");
973     }
975     /* Check phone numbers */
976     if (!is_phone_nr($this->telephoneNumber)){
977       $message[]= _("The field 'Phone' contains an invalid phone number.");
978     }
979     if (!is_phone_nr($this->facsimileTelephoneNumber)){
980       $message[]= _("The field 'Fax' contains an invalid phone number.");
981     }
982     if (!is_phone_nr($this->mobile)){
983       $message[]= _("The field 'Mobile' contains an invalid phone number.");
984     }
985     if (!is_phone_nr($this->pager)){
986       $message[]= _("The field 'Pager' contains an invalid phone number.");
987     }
989     /* Check for reserved characers */
990     if (preg_match ('/[,+"?\'()=<>;]/', $this->givenName)){
991       $message[]= _("The field 'Given name' contains invalid characters.");
992     }
993     if (preg_match ('/[,+"?\'()=<>;]/', $this->sn)){
994       $message[]= _("The field 'Name' contains invalid characters.");
995     }
997   return $message;
998   }
1001   /* Indicate whether a password change is needed or not */
1002   function password_change_needed()
1003   {
1004     return ($this->pw_storage != $this->last_pw_storage);
1005   }
1008   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1009   function load_picture()
1010   {
1011     /* make connection and read jpegPhoto */
1012     $ds= ldap_connect($this->config->current['SERVER']);
1013     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1014     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1015       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1016       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1017     }
1019     if(isset($this->config->current['TLS']) &&
1020         $this->config->current['TLS'] == "true"){
1022       ldap_start_tls($ds);
1023     }
1025     $r= ldap_bind($ds);
1026     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
1028     /* in case we don't get an entry, load a default picture */
1029     $this->set_picture ("./images/default.jpg");
1030     $this->jpegPhoto= "*removed*";
1032     /* fill data from LDAP */
1033     if ($sr) {
1034       $ei=ldap_first_entry($ds, $sr);
1035       if ($ei) {
1036         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
1037           $this->photoData= $info[0];
1038           $_SESSION['binary']= $this->photoData;
1039           $_SESSION['binarytype']= "image/jpeg";
1040           $this->jpegPhoto= "";
1041         }
1042       }
1043     }
1045     /* close conncetion */
1046     ldap_unbind($ds);
1047   }
1050   /* Load a certificate from LDAP, this is going to be simplified later on */
1051   function load_cert()
1052   {
1053     $ds= ldap_connect($this->config->current['SERVER']);
1054     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1055     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1056       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1057       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1058     }
1059     if(isset($this->config->current['TLS']) &&
1060         $this->config->current['TLS'] == "true"){
1062       ldap_start_tls($ds);
1063     }
1065     $r= ldap_bind($ds);
1066     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1068     if ($sr) {
1069       $ei= @ldap_first_entry($ds, $sr);
1070       
1071       if ($ei) {
1072         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1073           $this->userCertificate= "";
1074         } else {
1075           $this->userCertificate= $info[0];
1076         }
1077       }
1078     } else {
1079       $this->userCertificate= "";
1080     }
1082     ldap_unbind($ds);
1083   }
1086   /* Load picture from file to object */
1087   function set_picture($filename)
1088   {
1089     if (!is_file($filename)){
1090       $filename= "./images/default.jpg";
1091       $this->jpegPhoto= "*removed*";
1092     }
1094     $fd = fopen ($filename, "rb");
1095     $this->photoData= fread ($fd, filesize ($filename));
1096     $_SESSION['binary']= $this->photoData;
1097     $_SESSION['binarytype']= "image/jpeg";
1098     $this->jpegPhoto= "";
1100     fclose ($fd);
1101   }
1104   /* Load certificate from file to object */
1105   function set_cert($cert, $filename)
1106   {
1107     $fd = fopen ($filename, "rb");
1108     if (filesize($filename)>0) {
1109       $this->$cert= fread ($fd, filesize ($filename));
1110       fclose ($fd);
1111       $this->is_modified= TRUE;
1112     } else {
1113       print_red(_("Could not open specified certificate!"));
1114     }
1115   }
1117   /* Adapt from given 'dn' */
1118   function adapt_from_template($dn)
1119   {
1120     plugin::adapt_from_template($dn);
1122     /* Get base */
1123     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1125     if ($this->config->current['GOVERNMENTMODE']){
1127       /* Walk through govattrs */
1128       foreach ($this->govattrs as $val){
1130         if (isset($this->attrs["$val"][0])){
1132           /* If attribute is set, replace dynamic parts: 
1133              %sn, %givenName and %uid. Fill these in our local variables. */
1134           $value= $this->attrs["$val"][0];
1136           foreach (array("sn", "givenName", "uid") as $repl){
1137             if (preg_match("/%$repl/i", $value)){
1138               $value= preg_replace ("/%$repl/i",
1139                   $this->parent->$repl, $value);
1140             }
1141           }
1142           $this->$val= $value;
1143         }
1144       }
1145     }
1147     /* Get back uid/sn/givenName */
1148     if ($this->parent != NULL){
1149       $this->uid= $this->parent->uid;
1150       $this->sn= $this->parent->sn;
1151       $this->givenName= $this->parent->givenName;
1152     }
1153   }
1155  
1156   /* This avoids that users move themselves out of their rights. 
1157    */
1158   function allowedBasesToMoveTo()
1159   {
1160     $allowed = array();
1161     $ret_all = false;
1162     if($this->uid == $_SESSION['ui']->username){
1163       $ldap= $this->config->get_ldap_link(); 
1164       $ldap->cd($this->config->current['BASE']); 
1165       $ldap->search("(&(objectClass=posixGroup)(memberUid=".$_SESSION['ui']->username."))",array("gosaSubtreeACL"));
1166        
1167       while($attrs = $ldap->fetch()){
1168         foreach($attrs['gosaSubtreeACL'] as $attr){
1169           if((preg_match("/:user#/",$attr))||(preg_match("/:all/",$attr))){
1170             $s =  preg_replace("/^.*ou=groups,/","",$attrs['dn']);
1172             foreach($this->config->idepartments as $key => $dep) {
1173               if(preg_match("/".$s."/i",$key)){
1174                 $allowed[$key] = $dep;
1175               }
1176             }
1177           }
1178         }
1179       }
1180       if(count($allowed) == 0){
1181         foreach($this->config->idepartments as $key => $dep) {
1182           if($this->base==$key){
1183             $allowed[$key] = $dep;
1184           }
1185         }
1186       }  
1187   
1188       return($allowed);
1189       
1190     }else{
1191       return($this->config->idepartments);
1192     }
1193   } 
1202 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1203 ?>