Code

Do not remove invalid user accounts.
[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   /* The attribute gotoLastSystemLogin represents the timestamp of the last 
20       successfull login on the users workstation. 
21      Read the FAQ to get a hint about how to configure this.
22    */
23   var $gotoLastSystemLogin = "";
25   /* Plugin specific values */
26   var $base= "";
27   var $orig_base= "";
28   var $cn= "";
29   var $new_dn= "";
30   var $personalTitle= "";
31   var $academicTitle= "";
32   var $homePostalAddress= "";
33   var $homePhone= "";
34   var $labeledURI= "";
35   var $o= "";
36   var $ou= "";
37   var $departmentNumber= "";
38   var $employeeNumber= "";
39   var $employeeType= "";
40   var $roomNumber= "";
41   var $telephoneNumber= "";
42   var $facsimileTelephoneNumber= "";
43   var $mobile= "";
44   var $pager= "";
45   var $l= "";
46   var $st= "";
47   var $postalAddress= "";
48   var $dateOfBirth;
49   var $use_dob= "0";
50   var $gender="0";
51   var $preferredLanguage="0";
53   var $jpegPhoto= "*removed*";
54   var $photoData= "";
55   var $old_jpegPhoto= "";
56   var $old_photoData= "";
57   var $cert_dialog= FALSE;
58   var $picture_dialog= FALSE;
60   var $userPKCS12= "";
61   var $userSMIMECertificate= "";
62   var $userCertificate= "";
63   var $certificateSerialNumber= "";
64   var $old_certificateSerialNumber= "";
65   var $old_userPKCS12= "";
66   var $old_userSMIMECertificate= "";
67   var $old_userCertificate= "";
69   var $gouvernmentOrganizationalUnit= "";
70   var $houseIdentifier= "";
71   var $street= "";
72   var $postalCode= "";
73   var $vocation= "";
74   var $ivbbLastDeliveryCollective= "";
75   var $gouvernmentOrganizationalPersonLocality= "";
76   var $gouvernmentOrganizationalUnitDescription= "";
77   var $gouvernmentOrganizationalUnitSubjectArea= "";
78   var $functionalTitle= "";
79   var $role= "";
80   var $publicVisible= "";
82   var $dialog;
84   /* variables to trigger password changes */
85   var $pw_storage= "crypt";
86   var $last_pw_storage= "unset";
87   var $had_userCertificate= FALSE;
89   /* attribute list for save action */
90   var $attributes= array("sn", "givenName", "uid", "personalTitle", "academicTitle",
91       "homePostalAddress", "homePhone", "labeledURI", "ou", "o", "dateOfBirth", "gender","preferredLanguage",
92       "departmentNumber", "employeeNumber", "employeeType", "l", "st","jpegPhoto",
93       "roomNumber", "telephoneNumber", "mobile", "pager", "cn", "userPKCS12",
94       "postalAddress", "facsimileTelephoneNumber", "userSMIMECertificate");
96   var $objectclasses= array("top", "person", "organizationalPerson", "inetOrgPerson",
97       "gosaAccount");
99   /* attributes that are part of the government mode */
100   var $govattrs= array("gouvernmentOrganizationalUnit", "houseIdentifier", "vocation",
101       "ivbbLastDeliveryCollective", "gouvernmentOrganizationalPersonLocality",
102       "gouvernmentOrganizationalUnitDescription","gouvernmentOrganizationalUnitSubjectArea",
103       "functionalTitle", "certificateSerialNumber", "publicVisible", "street", "role",
104       "postalCode");
107   /* constructor, if 'dn' is set, the node loads the given
108      'dn' from LDAP */
109   function user ($config, $dn= NULL)
110   {
111     $this->config= $config;
112     /* Configuration is fine, allways */
113     if ($this->config->current['GOVERNMENTMODE']){
114       $this->attributes=array_merge($this->attributes,$this->govattrs);
115     }
117     /* Load base attributes */
118     plugin::plugin ($config, $dn);
120     /*  If gotoLastSystemLogin is available read it from ldap and create a readable 
121          date time string.
122      */
123     if(isset($this->attrs['gotoLastSystemLogin'][0]) && preg_match("/^[0-9]*$/",$this->attrs['gotoLastSystemLogin'][0])){
124       $this->gotoLastSystemLogin = date("d.m.Y H:i:s", $this->attrs['gotoLastSystemLogin'][0]);
125     }
127     $this->new_dn = $dn;
129     if ($this->config->current['GOVERNMENTMODE']){
130       /* Fix public visible attribute if unset */
131       if (!isset($this->attrs['publicVisible'])){
132         $this->publicVisible == "nein";
133       }
134     }
136     /* Load government mode attributes */
137     if ($this->config->current['GOVERNMENTMODE']){
138       /* Copy all attributs */
139       foreach ($this->govattrs as $val){
140         if (isset($this->attrs["$val"][0])){
141           $this->$val= $this->attrs["$val"][0];
142         }
143       }
144     }
146     /* Create me for new accounts */
147     if ($dn == "new"){
148       $this->is_account= TRUE;
149     }
151     /* Make hash default to md5 if not set in config */
152     if (!isset($this->config->current['HASH'])){
153       $hash= "md5";
154     } else {
155       $hash= $this->config->current['HASH'];
156     }
158     /* Load data from LDAP? */
159     if ($dn != NULL){
161       /* Do base conversation */
162       if ($this->dn == "new"){
163         $ui= get_userinfo();
164         $this->base= dn2base($ui->dn);
165       } else {
166         $this->base= dn2base($dn);
167       }
169       /* get password storage type */
170       if (isset ($this->attrs['userPassword'][0])){
171         /* Initialize local array */
172         $matches= array();
173         if (preg_match ("/^{([^}]+)}(.+)/", $this->attrs['userPassword'][0], $matches)){
174           $this->pw_storage= strtolower($matches[1]);
175         } else {
176           if ($this->attrs['userPassword'][0] != ""){
177             $this->pw_storage= "clear";
178           } else {
179             $this->pw_storage= $hash;
180           }
181         }
182       } else {
183         /* Preset with vaule from configuration */
184         $this->pw_storage= $hash;
185       }
187       /* Load extra attributes: certificate and picture */
188       $this->load_picture();
189       $this->load_cert();
190       if ($this->userCertificate != ""){
191         $this->had_userCertificate= TRUE;
192       }
193     }
195     /* Reset password storage indicator, used by password_change_needed() */
196     if ($dn == "new"){
197       $this->last_pw_storage= "unset";
198     } else {
199       $this->last_pw_storage= $this->pw_storage;
200     }
202     /* Generate dateOfBirth entry */
203     if (isset ($this->attrs['dateOfBirth'])){
204       /* This entry is ISO 8601 conform */
205       list($year, $month, $day)= split("-", $this->attrs['dateOfBirth'][0], 3);
206     
207       $this->dateOfBirth=array( 'mon'=> $month,"mday"=> $day,"year"=> $year);
208       $this->use_dob= "1";
209     } else {
210       $this->use_dob= "0";
211     }
213     /* Put gender attribute to upper case */
214     if (isset ($this->attrs['gender'])){
215       $this->gender= strtoupper($this->attrs['gender'][0]);
216     }
218     $this->orig_base = $this->base;
219   }
222   /* execute generates the html output for this node */
223   function execute()
224   {
225     /* Call parent execute */
226     plugin::execute();
228     $smarty= get_smarty();
229     $smarty->assign("gotoLastSystemLogin",$this->gotoLastSystemLogin);
231     /* Fill calendar */
232     if ($this->dateOfBirth == "0"){
233       $date= getdate();
234     } else {
235       if(is_array($this->dateOfBirth)){
236         $date = $this->dateOfBirth;
237   
238         // Trigger on dates like 1985-04-01, getdate only understands timestamps
239       } else if (!empty($this->dateOfBirth) && !is_numeric($this->dateOfBirth)){
240         $date= getdate(strtotime($this->dateOfBirth));
242       } else {
243         $date = getdate($this->dateOfBirth);
244       } 
245     }
247     $days= array();
248     for($d= 1; $d<32; $d++){
249       $days[$d]= $d;
250     }
251     $years= array();
253     if(($date['year']-100)<1901){
254       $start = 1901;
255     }else{
256       $start = $date['year']-100;
257     }
259     $end = $start +100;
260     
261     for($y= $start; $y<=$end; $y++){
262       $years[]= $y;
263     }
264     $years['-']= "-&nbsp;";
265     $months= array(_("January"), _("February"), _("March"), _("April"),
266         _("May"), _("June"), _("July"), _("August"), _("September"),
267         _("October"), _("November"), _("December"), '-' => '-&nbsp;');
268     $smarty->assign("day", $date["mday"]);
269     $smarty->assign("days", $days);
270     $smarty->assign("months", $months);
271     $smarty->assign("month", $date["mon"]-1);
272     $smarty->assign("years", $years);
273     $smarty->assign("year", $date["year"]);
275     /* Assign sex */
276     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
277     $smarty->assign("gender_list", $sex);
279     /* Assign prefered langage */
281     
282     $language= array_merge(array(0 => "&nbsp;") ,get_languages(TRUE));
283     $smarty->assign("preferredLanguage_list", $language);
285     /* Get random number for pictures */
286     srand((double)microtime()*1000000); 
287     $smarty->assign("rand", rand(0, 10000));
289     /* Do we represent a valid gosaAccount? */
290     if (!$this->is_account){
291       echo "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
292         _("This account has no valid GOsa extensions.")."</b>";
293       return;
294     }
296     /* Base select dialog */
297     $once = true;
298     foreach($_POST as $name => $value){
299       if(preg_match("/^chooseBase/",$name) && $once){
300         $once = false;
301         $this->dialog = new baseSelectDialog($this->config,$this->allowedBasesToMoveTo());
302         $this->dialog->setCurrentBase($this->base);
303       }
304     }
306     /* Dialog handling */
307     if(is_object($this->dialog)){
308       /* Must be called before save_object */
309       $this->dialog->save_object();
310    
311       if($this->dialog->isClosed()){
312         $this->dialog = false;
313       }elseif($this->dialog->isSelected()){
314         $this->base = $this->dialog->isSelected();
315         $this->dialog= false;
316       }else{
317         return($this->dialog->execute());
318       }
319     }
321     /* Want picture edit dialog? */
322     if (isset($_POST['edit_picture'])){
323       /* Save values for later recovery, in case some presses
324          the cancel button. */
325       $this->old_jpegPhoto= $this->jpegPhoto;
326       $this->old_photoData= $this->photoData;
327       $this->picture_dialog= TRUE;
328       $this->dialog= TRUE;
329     }
331     /* Remove picture? */
332     if (isset($_POST['picture_remove'])){
333       $this->set_picture ();
334       $this->jpegPhoto= "*removed*";
335       $this->is_modified= TRUE;
337       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
338     }
340     /* Save picture */
341     if (isset($_POST['picture_edit_finish'])){
343       /* Check for clean upload */
344       if ($_FILES['picture_file']['name'] != ""){
345         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
346           print_red(_("The specified file has not been uploaded via HTTP POST! Aborted."));
347           exit;
348         }
350         /* Activate new picture */
351         $this->set_picture($_FILES['picture_file']['tmp_name']);
352       }
353       $this->picture_dialog= FALSE;
354       $this->dialog= FALSE;
355       $this->is_modified= TRUE;
356     }
359     /* Cancel picture */
360     if (isset($_POST['picture_edit_cancel'])){
362       /* Restore values */
363       $this->jpegPhoto= $this->old_jpegPhoto;
364       $this->photoData= $this->old_photoData;
366       /* Update picture */
367       $_SESSION['binary']= $this->photoData;
368       $_SESSION['binarytype']= "image/jpeg";
369       $this->picture_dialog= FALSE;
370       $this->dialog= FALSE;
371     }
373     /* Toggle dateOfBirth information */
374     if (isset($_POST['set_dob'])){
375       $this->use_dob= ($this->use_dob == "0")?"1":"0";
376     }
379     /* Want certificate= */
380     if (isset($_POST['edit_cert'])){
382       /* Save original values for later reconstruction */
383       foreach (array("certificateSerialNumber", "userCertificate",
384             "userSMIMECertificate", "userPKCS12") as $val){
386         $oval= "old_$val";
387         $this->$oval= $this->$val;
388       }
390       $this->cert_dialog= TRUE;
391       $this->dialog= TRUE;
392     }
395     /* Cancel certificate dialog */
396     if (isset($_POST['cert_edit_cancel'])){
398       /* Restore original values in case of 'cancel' */
399       foreach (array("certificateSerialNumber", "userCertificate",
400             "userSMIMECertificate", "userPKCS12") as $val){
402         $oval= "old_$val";
403         $this->$val= $this->$oval;
404       }
405       $this->cert_dialog= FALSE;
406       $this->dialog= FALSE;
407     }
410     /* Remove certificate? */
411     foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
412       if (isset($_POST["remove_$val"])){
414         /* Reset specified cert*/
415         $this->$val= "";
416         $this->is_modified= TRUE;
417       }
418     }
421     /* Upload new cert and close dialog? */     
422     if (isset($_POST['cert_edit_finish'])){
424       /* for all certificates do */
425       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
426           as $val){
428         /* Check for clean upload */
429         if (array_key_exists($val."_file", $_FILES) &&
430             array_key_exists('name', $_FILES[$val."_file"]) &&
431             $_FILES[$val."_file"]['name'] != "" &&
432             is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
433           $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
434         }
435       }
437       /* Save serial number */
438       if (isset($_POST["certificateSerialNumber"]) &&
439           $_POST["certificateSerialNumber"] != ""){
441         if (!is_id($_POST["certificateSerialNumber"])){
442           print_red (_("Please enter a valid serial number"));
444           foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
445             if ($this->$cert != ""){
446               $smarty->assign("$cert"."_state", "true");
447             } else {
448               $smarty->assign("$cert"."_state", "");
449             }
450           }
451           return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
452         }
454         $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
455         $this->is_modified= TRUE;
456       }
458       $this->cert_dialog= FALSE;
459       $this->dialog= FALSE;
460     }
462     /* Display picture dialog */
463     if ($this->picture_dialog){
464       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
465     }
467     /* Display cert dialog */
468     if ($this->cert_dialog){
469       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
470         if ($this->$cert != ""){
471           /* import certificate */
472           $certificate = new certificate;
473           $certificate->import($this->$cert);
474       
475           /* Read out data*/
476           $timeto   = $certificate->getvalidto_date();
477           $timefrom = $certificate->getvalidfrom_date();
479           /* Additional info if start end time is '0' */
480           $add_str_info = "";
481           if($timeto == 0 && $timefrom == 0){
482             $add_str_info = "<br><i>"._("(Some types of certificates are currently not supported and may be displayed as 'invalid'.)")."</i>";
483           }
485           $str = "<table summary=\"\" border=0>
486                     <tr>
487                       <td style='vertical-align:top'>CN</td>
488                       <td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td>
489                     </tr>
490                   </table><br>".
491                   
492                   sprintf(_("Certificate is valid from %s to %s and is currently %s."), 
493                         "<b>".date('d M Y',$timefrom)."</b>",
494                         "<b>".date('d M Y',$timeto)."</b>", 
495                         $certificate->isvalid()?"<b><font style='color:green'>"._("valid")."</font></b>": 
496                                                 "<b><font style='color:red'>"._("invalid")."</font></b>").$add_str_info;
497           $smarty->assign($cert."info",$str);
498           $smarty->assign($cert."_state","true");
499         } else {
500           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
501           $smarty->assign($cert."_state","");
502         }
503       }
504       $smarty->assign("governmentmode", "false");
505       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
506     }
508     /* Show us the edit screen */
509     @$smarty->assign("bases", $this->allowedBasesToMoveTo());
510 #  $smarty->assign("bases", $this->config->idepartments);
511     $smarty->assign("base_select",      $this->base);
512     $smarty->assign("selectmode",       chkacl($this->acl, "create"));
513     $smarty->assign("certificatesACL",  chkacl($this->acl, "certificates"));
514     $smarty->assign("jpegPhotoACL",     chkacl($this->acl, "jpegPhoto"));
516     /* Prepare password hashes */
517     if ($this->pw_storage == ""){
518       $this->pw_storage= $this->config->current['HASH'];
519     }
521     $temp   = @passwordMethod::get_available_methods();
522     $hashes = $temp['name'];
523     
524     $smarty->assign("pwmode", $hashes);
525     $smarty->assign("pwmode_select", $this->pw_storage);
526     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
528     /* Load attributes and acl's */
529     foreach($this->attributes as $val){
530       $smarty->assign("$val", $this->$val);
531       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
532     }
534     /* Save government mode attributes */
535     if (isset($this->config->current['GOVERNMENTMODE']) &&
536         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
537       $smarty->assign("governmentmode", "true");
538       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
539           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
540       $smarty->assign("ivbbmodes", $ivbbmodes);
541       foreach ($this->govattrs as $val){
542         $smarty->assign("$val", $this->$val);
543         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
544       }
545     } else {
546       $smarty->assign("governmentmode", "false");
547     }
549     /* Special mode for uid */
550     $uidACL= "";
551     if (isset ($this->dn)){
552       if ($this->dn != "new"){
553         $uidACL="readonly";
554       }
555     }  else {
556       $uidACL= "readonly";
557     }
558     $uidACL.= " ".chkacl($this->acl, "uid");
559     
560     $smarty->assign("uidACL", $uidACL);
561     $smarty->assign("is_template", $this->is_template);
562     $smarty->assign("use_dob", $this->use_dob);
564     if (isset($this->parent)){
565       if (isset($this->parent->by_object['phoneAccount']) &&
566           $this->parent->by_object['phoneAccount']->is_account){
567         $smarty->assign("has_phoneaccount", "true");
568       } else {
569         $smarty->assign("has_phoneaccount", "false");
570       }
571     } else {
572       $smarty->assign("has_phoneaccount", "false");
573     }
574     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
575   }
578   /* remove object from parent */
579   function remove_from_parent()
580   {
581     if(!$this->initially_was_account) return;
583     $ldap= $this->config->get_ldap_link();
584     $ldap->rmdir ($this->dn);
585     show_ldap_error($ldap->get_error(), _("Removing generic user account failed"));
587     /* Delete references to groups */
588     $ldap->cd ($this->config->current['BASE']);
589     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
590     while ($ldap->fetch()){
591       $g= new group($this->config, $ldap->getDN());
592       $g->removeUser($this->uid);
593       $g->save ();
594     }
596     /* Delete references to object groups */
597     $ldap->cd ($this->config->current['BASE']);
598     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".@LDAP::prepare4filter($this->dn)."))", array("cn"));
599     while ($ldap->fetch()){
600       $og= new ogroup($this->config, $ldap->getDN());
601       unset($og->member[$this->dn]);
602       $og->save ();
603     }
605     /* Kerberos server defined? */
606     if (isset($this->config->data['SERVERS']['KERBEROS'])){
607       $cfg= $this->config->data['SERVERS']['KERBEROS'];
608     }
609     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
611       /* Connect to the admin interface */
612       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
613           $cfg['ADMIN'], $cfg['PASSWORD']);
615       /* Errors? */             
616       if ($handle === FALSE){
617         print_red (_("Kerberos database communication failed"));
618         return (2);
619       }
621       /* Build user principal, get list of existsing principals */
622       $principal= $this->uid."@".$cfg['REALM'];
623       $principals = kadm5_get_principals($handle);
625       /* User exists in database? */
626       if (in_array($principal, $principals)){
628         /* Ok. User exists. Remove him/her */
629           $ret= kadm5_delete_principal ( $handle, $principal);
630           if ($ret === FALSE){
631             print_red (_("Can't remove user from kerberos database."));
632           }
633       }
635       /* Free kerberos admin handle */
636       kadm5_destroy($handle);
637     }
640     /* Optionally execute a command after we're done */
641     $this->handle_post_events("remove",array("uid" => $this->uid));
642   }
645   /* Save data to object */
646   function save_object()
647   {
648     if (isset($_POST['generic'])){
650       /* Parents save function */
651       plugin::save_object ();
653       /* Save government mode attributes */
654       if ($this->config->current['GOVERNMENTMODE']){
655         foreach ($this->govattrs as $val){
656           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
657             $data= stripcslashes($_POST["$val"]);
658             if ($data != $this->$val){
659               $this->is_modified= TRUE;
660             }
661             $this->$val= $data;
662           }
663         }
664       }
666       /* In template mode, the uid is autogenerated... */
667       if ($this->is_template){
668         $this->uid= strtolower($this->sn);
669         $this->givenName= $this->sn;
670       }
672       /* Save base and pw_storage, since these are no LDAP attributes */
673       if (isset($_POST['base'])){
674         foreach(array("base", "pw_storage") as $val){
676           if(isset($_POST[$val]) && chkacl ($this->acl, "$val") == ""){
677             $data= validate($_POST[$val]);
678             if ($data != $this->$val){
679               $this->is_modified= TRUE;
680             }
681             $this->$val= $data;
682           }
683         }
684       }
685     }
686   }
688   function rebind($ldap, $referral)
689   {
690     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
691     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
692       $this->error = "Success";
693       $this->hascon=true;
694       $this->reconnect= true;
695       return (0);
696     } else {
697       $this->error = "Could not bind to " . $credentials['ADMIN'];
698       return NULL;
699     }
700   }
702   /* Save data to LDAP, depending on is_account we save or delete */
703   function save()
704   {
705     /* Only force save of changes .... 
706        If this attributes aren't changed, avoid saving.
707      */
708     if($this->gender=="0") $this->gender ="";
709     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
710     
711  
712     /* First use parents methods to do some basic fillup in $this->attrs */
713     plugin::save ();
715     if ($this->use_dob == "1"){
716       /* If it is an array, the generic page has never been loaded - so there's no difference. Using an array would cause an error btw. */
717       if(!is_array($this->attrs['dateOfBirth'])) {
718         $this->attrs['dateOfBirth']= date("Y-m-d", $this->attrs['dateOfBirth']);
719       }
720     }
721     /* Remove additional objectClasses */
722     $tmp= array();
723     foreach ($this->attrs['objectClass'] as $key => $set){
724       $found= false;
725       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
726         if (preg_match ("/^$set$/i", $val)){
727           $found= true;
728           break;
729         }
730       }
731       if (!$found){
732         $tmp[]= $set;
733       }
734     }
736     /* Replace the objectClass array. This is done because of the
737        separation into government and normal mode. */
738     $this->attrs['objectClass']= $tmp;
740     /* Add objectClasss for template mode? */
741     if ($this->is_template){
742       $this->attrs['objectClass'][]= "gosaUserTemplate";
743     }
745     /* Hard coded government mode? */
746     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
747       $this->attrs['objectClass'][]= "ivbbentry";
749       /* Copy standard attributes */
750       foreach ($this->govattrs as $val){
751         if ($this->$val != ""){
752           $this->attrs["$val"]= $this->$val;
753         } elseif (!$this->new) {
754           $this->attrs["$val"]= array();
755         }
756       }
758       /* Remove attribute if set to "nein" */
759       if ($this->publicVisible == "nein"){
760         $this->attrs['publicVisible']= array();
761         if($this->new){
762           unset($this->attrs['publicVisible']);
763         }else{
764           $this->attrs['publicVisible']=array();
765         }
767       }
769     }
771     /* Special handling for attribute userCertificate needed */
772     if ($this->userCertificate != ""){
773       $this->attrs["userCertificate;binary"]= $this->userCertificate;
774       $remove_userCertificate= false;
775     } else {
776       $remove_userCertificate= true;
777     }
779     /* Special handling for dateOfBirth value */
780     if ($this->use_dob != "1"){
781       if ($this->new) {
782         unset($this->attrs["dateOfBirth"]);
783       } else {
784         $this->attrs["dateOfBirth"]= array();
785       }
786     }
787     if (!$this->gender){
788       if ($this->new) {
789         unset($this->attrs["gender"]);
790       } else {
791         $this->attrs["gender"]= array();
792       }
793     }
794     if (!$this->preferredLanguage){
795       if ($this->new) {
796         unset($this->attrs["preferredLanguage"]);
797       } else {
798         $this->attrs["preferredLanguage"]= array();
799       }
800     }
802     /* Special handling for attribute jpegPhote needed, scale image via
803        image magick to 147x200 pixels and inject resulting data. */
804     if ($this->jpegPhoto != "*removed*"){
806       /* Fallback if there's no image magick inside PHP */
807       if (!function_exists("imagick_blob2image")){
808         /* Get temporary file name for conversation */
809         $fname = tempnam ("/tmp", "GOsa");
811         /* Open file and write out photoData */
812         $fp = fopen ($fname, "w");
813         fwrite ($fp, $this->photoData);
814         fclose ($fp);
816         /* Build conversation query. Filename is generated automatically, so
817            we do not need any special security checks. Exec command and save
818            output. For PHP safe mode, you'll need a configuration which respects
819            image magick as executable... */
820         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
821         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
822             $query, "Execute");
824         /* Read data written by convert */
825         $output= "";
826         $sh= popen($query, 'r');
827         while (!feof($sh)){
828           $output.= fread($sh, 4096);
829         }
830         pclose($sh);
832         unlink($fname);
834         /* Save attribute */
835         $this->attrs["jpegPhoto"] = $output;
837       } else {
839         /* Load the new uploaded Photo */
840         if(!$handle  =  imagick_blob2image($this->photoData))  {
841           gosa_log("Can't Load image");
842         }
844         /* Resizing image to 147x200 and blur */
845         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
846           gosa_log("imagick_resize failed");
847         }
849         /* Converting image to JPEG */
850         if(!imagick_convert($handle,"JPEG")) {
851           gosa_log("Can't Convert to JPEG");
852         }
854         /* Creating binary Code for the Image */
855         if(!$dump = imagick_image2blob($handle)){
856           gosa_log("Can't create blob for image");
857         }
859         /* Sending Image */
860         $output=  $dump;
862         /* Save attribute */
863         $this->attrs["jpegPhoto"] = $output;
864       }
866     } else{
867       $this->attrs["jpegPhoto"] = array();
868     }
870     /* This only gets called when user is renaming himself */
871     $ldap= $this->config->get_ldap_link();
872     if ($this->dn != $this->new_dn){
874       /* Write entry on new 'dn' */
875       $this->move($this->dn, $this->new_dn);
877       /* Happen to use the new one */
878       change_ui_dn($this->dn, $this->new_dn);
879       $this->dn= $this->new_dn;
880     }
883     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
884        new entries. So do a check first... */
885     $ldap->cat ($this->dn, array('dn'));
886     if ($ldap->fetch()){
887       $mode= "modify";
888     } else {
889       $mode= "add";
890       $ldap->cd($this->config->current['BASE']);
891       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
892     }
894     /* Set password to some junk stuff in case of templates */
895     if ($this->is_template){
896       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
897     }
899     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
900         $this->attributes, "Save via $mode");
902     /* Finally write data with selected 'mode' */
903     $this->cleanup();
905     if(isset($this->attrs['preferredLanguage'])){
906       $_SESSION['ui']->language = $this->preferredLanguage;
907       $_SESSION['Last_init_lang'] = "update";
908     }
910     $ldap->cd ($this->dn);
911     $ldap->$mode ($this->attrs);
912     if (show_ldap_error($ldap->get_error(), _("Saving generic user account failed"))){
913       return (1);
914     }
916     /* Remove cert? 
917        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
918        to work around myself. */
919     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
921       /* Reset array, assemble new, this should be reworked */
922       $this->attrs= array();
923       $this->attrs['userCertificate;binary']= array();
925       /* Prepare connection */
926       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
927         die ("Could not connect to LDAP server");
928       }
929       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
930       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
931         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
932         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
933       }
934       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
935         ldap_start_tls($ds);
936       }
937       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
938               $this->config->current['PASSWORD']))) {
939         die ("Could not bind to LDAP");
940       }
942       /* Modify using attrs */
943       ldap_mod_del($ds,$this->dn,$this->attrs);
944       ldap_close($ds);
945     }
947     /* Kerberos server defined? */
948     if (isset($this->config->data['SERVERS']['KERBEROS'])){
949       $cfg= $this->config->data['SERVERS']['KERBEROS'];
950     }
951     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
953       /* Connect to the admin interface */
954       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
955           $cfg['ADMIN'], $cfg['PASSWORD']);
957       /* Errors? */             
958       if ($handle === FALSE){
959         print_red (_("Kerberos database communication failed"));
960         return (2);
961       }
963       /* Build user principal, get list of existsing principals */
964       $principal= $this->uid."@".$cfg['REALM'];
965       $principals = kadm5_get_principals($handle);
967       /* User exists in database? */
968       if (in_array($principal, $principals)){
970         /* Ok. User exists. Remove him/her when pw_storage has
971            changed to be NOT kerberos. */
972         if ($this->pw_storage != $this->config->current['KRBSASL']){
973           $ret= kadm5_delete_principal ( $handle, $principal);
975           if ($ret === FALSE){
976             print_red (_("Can't remove user from kerberos database."));
977           }
978         }
980       } else {
982         /* User doesn't exists, create it when pw_storage is kerberos or SASL. */
983         if ($this->pw_storage == "kerberos" || $this->pw_storage == "sasl" ){
984           $ret= kadm5_create_principal ( $handle, $principal);
986           if ($ret === FALSE){
987             print_red (_("Can't add user to kerberos database."));
988           }
989         }
991       }
993       /* Free kerberos admin handle */
994       kadm5_destroy($handle);
995     }
997     /* Optionally execute a command after we're done */
998     if ($mode == "add"){
999       $this->handle_post_events("add",array("uid" => $this->uid));
1000     } elseif ($this->is_modified){
1001       $this->handle_post_events("modify",array("uid" => $this->uid));
1002     }
1004     return (0);
1005   }
1008   /* Check formular input */
1009   function check()
1010   {
1011     /* Call common method to give check the hook */
1012     $message= plugin::check();
1014     /* Assemble cn */
1015     $pt= "";
1016     if(isset($this->config->current['INCLUDE_PERSONAL_TITLE']) && preg_match("/true/i",$this->config->current['INCLUDE_PERSONAL_TITLE'])){
1017       if(!empty($this->personalTitle)){
1018         $pt = $this->personalTitle." ";
1019       }
1020     }
1021     
1022     $this->cn= $pt.$this->givenName." ".$this->sn;
1024     /* Permissions for that base? */
1025     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
1026       $this->new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
1027     } else {
1028       /* Don't touch dn, if cn hasn't changed */
1029       if (isset($this->saved_attributes['cn']) && $this->saved_attributes['cn'] == $this->cn &&
1030           $this->orig_base == $this->base){
1031         $this->new_dn= $this->dn;
1032       } else {
1033         $this->new_dn= $this->create_unique_dn('cn', get_people_ou().$this->base);
1034       }
1035     }
1037     $ui= get_userinfo();
1038     $acl= get_permissions ($this->new_dn, $ui->subtreeACL);
1039     $acl= get_module_permission($acl, "user", $this->new_dn);
1040     if ($this->dn == "new" && chkacl($acl, "create") != ""){
1041       $message[]= _("You have no permissions to create a user on this 'Base'.");
1042     } elseif ($this->dn != $this->new_dn && $this->dn != "new"){
1043       $acl= get_permissions ($this->new_dn, $ui->subtreeACL);
1044       $acl= get_module_permission($acl, "user", $this->new_dn);
1045       if (chkacl($acl, "create") != ""){
1046         $message[]= _("You have no permissions to move a user from the original 'Base'.");
1047       }
1048     }
1050     /* must: sn, givenName, uid */
1051     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
1052       $message[]= _("The required field 'Name' is not set.");
1053     }
1055     /* UID already used? */
1056     $ldap= $this->config->get_ldap_link();
1057     $ldap->cd($this->config->current['BASE']);
1058     $ldap->search("(uid=$this->uid)", array("uid"));
1059     $ldap->fetch();
1060     if ($ldap->count() != 0 && $this->dn == 'new'){
1061       $message[]= _("There's already a person with this 'Login' in the database.");
1062     }
1064     /* In template mode, the uid and givenName are autogenerated... */
1065     if (!$this->is_template){
1066       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
1067         $message[]= _("The required field 'Given name' is not set.");
1068       }
1069       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
1070         $message[]= _("The required field 'Login' is not set.");
1071       }
1072       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
1073         $ldap->cat($this->new_dn);
1074         if ($ldap->count() != 0 && $this->dn != $this->new_dn && $this->dn == 'new'){
1075           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
1076         }
1077       }
1078     }
1080     /* Check for valid input */
1081     if ($this->is_modified && !is_uid($this->uid)){
1082       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
1083     }
1084     if (!is_url($this->labeledURI)){
1085       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
1086     }
1087     if (preg_match ("/[\\\\]/", $this->sn)){
1088       $message[]= _("The field 'Name' contains invalid characters.");
1089     }
1090     if (preg_match ("/[\\\\]/", $this->givenName)){
1091       $message[]= _("The field 'Given name' contains invalid characters.");
1092     }
1094     /* Check phone numbers */
1095     if (!is_phone_nr($this->telephoneNumber)){
1096       $message[]= _("The field 'Phone' contains an invalid phone number.");
1097     }
1098     if (!is_phone_nr($this->facsimileTelephoneNumber)){
1099       $message[]= _("The field 'Fax' contains an invalid phone number.");
1100     }
1101     if (!is_phone_nr($this->mobile)){
1102       $message[]= _("The field 'Mobile' contains an invalid phone number.");
1103     }
1104     if (!is_phone_nr($this->pager)){
1105       $message[]= _("The field 'Pager' contains an invalid phone number.");
1106     }
1108     /* Check for reserved characers */
1109     if (preg_match ('/[,+"?\'()=<>;]/', $this->givenName)){
1110       $message[]= _("The field 'Given name' contains invalid characters.");
1111     }
1112     if (preg_match ('/[,+"?\'()=<>;]/', $this->sn)){
1113       $message[]= _("The field 'Name' contains invalid characters.");
1114     }
1116   return $message;
1117   }
1120   /* Indicate whether a password change is needed or not */
1121   function password_change_needed()
1122   {
1123     return ($this->pw_storage != $this->last_pw_storage);
1124   }
1127   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1128   function load_picture()
1129   {
1130     /* make connection and read jpegPhoto */
1131     $ds= ldap_connect($this->config->current['SERVER']);
1132     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1133     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1134       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1135       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1136     }
1138     if(isset($this->config->current['TLS']) &&
1139         $this->config->current['TLS'] == "true"){
1141       ldap_start_tls($ds);
1142     }
1144     $r= ldap_bind($ds);
1145     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
1147     /* in case we don't get an entry, load a default picture */
1148     $this->set_picture ("./images/default.jpg");
1149     $this->jpegPhoto= "*removed*";
1151     /* fill data from LDAP */
1152     if ($sr) {
1153       $ei=ldap_first_entry($ds, $sr);
1154       if ($ei) {
1155         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
1156           $this->photoData= $info[0];
1157           $_SESSION['binary']= $this->photoData;
1158           $_SESSION['binarytype']= "image/jpeg";
1159           $this->jpegPhoto= "";
1160         }
1161       }
1162     }
1164     /* close conncetion */
1165     ldap_unbind($ds);
1166   }
1169   /* Load a certificate from LDAP, this is going to be simplified later on */
1170   function load_cert()
1171   {
1172     $ds= ldap_connect($this->config->current['SERVER']);
1173     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1174     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1175       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1176       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1177     }
1178     if(isset($this->config->current['TLS']) &&
1179         $this->config->current['TLS'] == "true"){
1181       ldap_start_tls($ds);
1182     }
1184     $r= ldap_bind($ds);
1185     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1187     if ($sr) {
1188       $ei= @ldap_first_entry($ds, $sr);
1189       
1190       if ($ei) {
1191         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1192           $this->userCertificate= "";
1193         } else {
1194           $this->userCertificate= $info[0];
1195         }
1196       }
1197     } else {
1198       $this->userCertificate= "";
1199     }
1201     ldap_unbind($ds);
1202   }
1205   /* Load picture from file to object */
1206   function set_picture($filename ="")
1207   {
1208     if (!is_file($filename) || $filename == ""){
1209       $filename= "./images/default.jpg";
1210       $this->jpegPhoto= "*removed*";
1211     }
1213     $fd = fopen ($filename, "rb");
1214     $this->photoData= fread ($fd, filesize ($filename));
1215     $_SESSION['binary']= $this->photoData;
1216     $_SESSION['binarytype']= "image/jpeg";
1217     $this->jpegPhoto= "";
1219     fclose ($fd);
1220   }
1223   /* Load certificate from file to object */
1224   function set_cert($cert, $filename)
1225   {
1226     $fd = fopen ($filename, "rb");
1227     if (filesize($filename)>0) {
1228       $this->$cert= fread ($fd, filesize ($filename));
1229       fclose ($fd);
1230       $this->is_modified= TRUE;
1231     } else {
1232       print_red(_("Could not open specified certificate!"));
1233     }
1234   }
1236   /* Adapt from given 'dn' */
1237   function adapt_from_template($dn)
1238   {
1239     plugin::adapt_from_template($dn);
1241     /* Get base */
1242     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1244     if ($this->config->current['GOVERNMENTMODE']){
1246       /* Walk through govattrs */
1247       foreach ($this->govattrs as $val){
1249         if (isset($this->attrs["$val"][0])){
1251           /* If attribute is set, replace dynamic parts: 
1252              %sn, %givenName and %uid. Fill these in our local variables. */
1253           $value= $this->attrs["$val"][0];
1255           foreach (array("sn", "givenName", "uid") as $repl){
1256             if (preg_match("/%$repl/i", $value)){
1257               $value= preg_replace ("/%$repl/i",
1258                   $this->parent->$repl, $value);
1259             }
1260           }
1261           $this->$val= $value;
1262         }
1263       }
1264     }
1266     /* Get back uid/sn/givenName */
1267     if ($this->parent != NULL){
1268       $this->uid= $this->parent->uid;
1269       $this->sn= $this->parent->sn;
1270       $this->givenName= $this->parent->givenName;
1271     }
1272   }
1274  
1275   /* This avoids that users move themselves out of their rights. 
1276    */
1277   function allowedBasesToMoveTo()
1278   {
1279     $allowed = array();
1280     $ret_all = false;
1281     if($this->uid == $_SESSION['ui']->username){
1282       $ldap= $this->config->get_ldap_link(); 
1283       $ldap->cd($this->config->current['BASE']); 
1284       $ldap->search("(&(objectClass=posixGroup)(memberUid=".$_SESSION['ui']->username."))",array("gosaSubtreeACL"));
1285        
1286       while($attrs = $ldap->fetch()){
1287     
1288         if(isset($attrs['gosaSubtreeACL'])){
1289         
1290           foreach($attrs['gosaSubtreeACL'] as $attr){
1291             if((preg_match("/:user#/",$attr))||(preg_match("/:all/",$attr))){
1292               $s =  preg_replace("/^.*".get_groups_ou().",/","",$attrs['dn']);
1294               foreach($this->config->idepartments as $key => $dep) {
1295                 if(preg_match("/".$s."/i",$key)){
1296                   $allowed[$key] = $dep;
1297                 }
1298               }
1299             }
1300           }
1301         }
1302       }
1303       if(count($allowed) == 0){
1304         foreach($this->config->idepartments as $key => $dep) {
1305           if($this->base==$key){
1306             $allowed[$key] = $dep;
1307           }
1308         }
1309       }  
1310   
1311       return($allowed);
1312       
1313     }else{
1314       return($this->config->idepartments);
1315     }
1316   } 
1319   function getCopyDialog()
1320   {
1321     $str = "";
1323     $_SESSION['binary'] = $this->photoData; 
1324     $_SESSION['binarytype']= "image/jpeg";
1326     /* Get random number for pictures */
1327     srand((double)microtime()*1000000); 
1328     $rand = rand(0, 10000);
1330     $smarty = get_smarty();
1332     $smarty->assign("passwordTodo","clear");
1334     if(isset($_POST['passwordTodo'])){
1335       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1336     }
1338     $smarty->assign("sn",       $this->sn);
1339     $smarty->assign("givenName",$this->givenName);
1340     $smarty->assign("uid",      $this->uid);
1341     $smarty->assign("rand",     $rand);
1342     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1345     $ret = array();
1346     $ret['string'] = $str;
1347     $ret['status'] = "";  
1348     return($ret);
1349   }
1351   function saveCopyDialog()
1352   {
1354     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1355       $this->set_picture($_FILES['picture_file']['tmp_name']);
1356     }
1358     /* Remove picture? */
1359     if (isset($_POST['picture_remove'])){
1360       $this->jpegPhoto= "*removed*";
1361       $this->set_picture ("./images/default.jpg");
1362       $this->is_modified= TRUE;
1363     }
1365     $attrs = array("uid","givenName","sn");
1366     foreach($attrs as $attr){
1367       if(isset($_POST[$attr])){
1368         $this->$attr = $_POST[$attr];
1369       }
1370     } 
1371   }
1374   function PrepareForCopyPaste($source)
1375   {
1376     plugin::PrepareForCopyPaste($source);
1378     /* Reset certificate information addepted from source user
1379         to avoid setting the same user certificate for the destination user. */
1380     $this->userPKCS12= "";
1381     $this->userSMIMECertificate= "";
1382     $this->userCertificate= "";
1383     $this->certificateSerialNumber= "";
1384     $this->old_certificateSerialNumber= "";
1385     $this->old_userPKCS12= "";
1386     $this->old_userSMIMECertificate= "";
1387     $this->old_userCertificate= "";
1388   }
1391 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1392 ?>