Code

12e96ec915bc8ce5e1147222b2a7c168403437ae
[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 gosaLastSystemLogin 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 $gosaLastSystemLogin = "";
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 gosaLastSystemLogin is available read it from ldap and create a readable 
121          date time string.
122      */
123     if(isset($this->attrs['gosaLastSystemLogin'][0]) && preg_match("/^[0-9]*$/",$this->attrs['gosaLastSystemLogin'][0])){
124       $this->gosaLastSystemLogin = date("d.m.Y H:i:s", $this->attrs['gosaLastSystemLogin'][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("gosaLastSystemLogin",$this->gosaLastSystemLogin);
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     $ldap= $this->config->get_ldap_link();
582     $ldap->rmdir ($this->dn);
583     show_ldap_error($ldap->get_error(), _("Removing generic user account failed"));
585     /* Delete references to groups */
586     $ldap->cd ($this->config->current['BASE']);
587     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
588     while ($ldap->fetch()){
589       $g= new group($this->config, $ldap->getDN());
590       $g->removeUser($this->uid);
591       $g->save ();
592     }
594     /* Delete references to object groups */
595     $ldap->cd ($this->config->current['BASE']);
596     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".@LDAP::prepare4filter($this->dn)."))", array("cn"));
597     while ($ldap->fetch()){
598       $og= new ogroup($this->config, $ldap->getDN());
599       unset($og->member[$this->dn]);
600       $og->save ();
601     }
603     /* Kerberos server defined? */
604     if (isset($this->config->data['SERVERS']['KERBEROS'])){
605       $cfg= $this->config->data['SERVERS']['KERBEROS'];
606     }
607     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
609       /* Connect to the admin interface */
610       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
611           $cfg['ADMIN'], $cfg['PASSWORD']);
613       /* Errors? */             
614       if ($handle === FALSE){
615         print_red (_("Kerberos database communication failed"));
616         return (2);
617       }
619       /* Build user principal, get list of existsing principals */
620       $principal= $this->uid."@".$cfg['REALM'];
621       $principals = kadm5_get_principals($handle);
623       /* User exists in database? */
624       if (in_array($principal, $principals)){
626         /* Ok. User exists. Remove him/her */
627           $ret= kadm5_delete_principal ( $handle, $principal);
628           if ($ret === FALSE){
629             print_red (_("Can't remove user from kerberos database."));
630           }
631       }
633       /* Free kerberos admin handle */
634       kadm5_destroy($handle);
635     }
638     /* Optionally execute a command after we're done */
639     $this->handle_post_events("remove",array("uid" => $this->uid));
640   }
643   /* Save data to object */
644   function save_object()
645   {
646     if (isset($_POST['generic'])){
648       /* Parents save function */
649       plugin::save_object ();
651       /* Save government mode attributes */
652       if ($this->config->current['GOVERNMENTMODE']){
653         foreach ($this->govattrs as $val){
654           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
655             $data= stripcslashes($_POST["$val"]);
656             if ($data != $this->$val){
657               $this->is_modified= TRUE;
658             }
659             $this->$val= $data;
660           }
661         }
662       }
664       /* In template mode, the uid is autogenerated... */
665       if ($this->is_template){
666         $this->uid= strtolower($this->sn);
667         $this->givenName= $this->sn;
668       }
670       /* Save base and pw_storage, since these are no LDAP attributes */
671       if (isset($_POST['base'])){
672         foreach(array("base", "pw_storage") as $val){
674           if(isset($_POST[$val]) && chkacl ($this->acl, "$val") == ""){
675             $data= validate($_POST[$val]);
676             if ($data != $this->$val){
677               $this->is_modified= TRUE;
678             }
679             $this->$val= $data;
680           }
681         }
682       }
683     }
684   }
686   function rebind($ldap, $referral)
687   {
688     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
689     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
690       $this->error = "Success";
691       $this->hascon=true;
692       $this->reconnect= true;
693       return (0);
694     } else {
695       $this->error = "Could not bind to " . $credentials['ADMIN'];
696       return NULL;
697     }
698   }
700   /* Save data to LDAP, depending on is_account we save or delete */
701   function save()
702   {
703     /* Only force save of changes .... 
704        If this attributes aren't changed, avoid saving.
705      */
706     if($this->gender=="0") $this->gender ="";
707     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
708     
709  
710     /* First use parents methods to do some basic fillup in $this->attrs */
711     plugin::save ();
713     if ($this->use_dob == "1"){
714       /* 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. */
715       if(!is_array($this->attrs['dateOfBirth'])) {
716         $this->attrs['dateOfBirth']= date("Y-m-d", $this->attrs['dateOfBirth']);
717       }
718     }
719     /* Remove additional objectClasses */
720     $tmp= array();
721     foreach ($this->attrs['objectClass'] as $key => $set){
722       $found= false;
723       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
724         if (preg_match ("/^$set$/i", $val)){
725           $found= true;
726           break;
727         }
728       }
729       if (!$found){
730         $tmp[]= $set;
731       }
732     }
734     /* Replace the objectClass array. This is done because of the
735        separation into government and normal mode. */
736     $this->attrs['objectClass']= $tmp;
738     /* Add objectClasss for template mode? */
739     if ($this->is_template){
740       $this->attrs['objectClass'][]= "gosaUserTemplate";
741     }
743     /* Hard coded government mode? */
744     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
745       $this->attrs['objectClass'][]= "ivbbentry";
747       /* Copy standard attributes */
748       foreach ($this->govattrs as $val){
749         if ($this->$val != ""){
750           $this->attrs["$val"]= $this->$val;
751         } elseif (!$this->new) {
752           $this->attrs["$val"]= array();
753         }
754       }
756       /* Remove attribute if set to "nein" */
757       if ($this->publicVisible == "nein"){
758         $this->attrs['publicVisible']= array();
759         if($this->new){
760           unset($this->attrs['publicVisible']);
761         }else{
762           $this->attrs['publicVisible']=array();
763         }
765       }
767     }
769     /* Special handling for attribute userCertificate needed */
770     if ($this->userCertificate != ""){
771       $this->attrs["userCertificate;binary"]= $this->userCertificate;
772       $remove_userCertificate= false;
773     } else {
774       $remove_userCertificate= true;
775     }
777     /* Special handling for dateOfBirth value */
778     if ($this->use_dob != "1"){
779       if ($this->new) {
780         unset($this->attrs["dateOfBirth"]);
781       } else {
782         $this->attrs["dateOfBirth"]= array();
783       }
784     }
785     if (!$this->gender){
786       if ($this->new) {
787         unset($this->attrs["gender"]);
788       } else {
789         $this->attrs["gender"]= array();
790       }
791     }
792     if (!$this->preferredLanguage){
793       if ($this->new) {
794         unset($this->attrs["preferredLanguage"]);
795       } else {
796         $this->attrs["preferredLanguage"]= array();
797       }
798     }
800     /* Special handling for attribute jpegPhote needed, scale image via
801        image magick to 147x200 pixels and inject resulting data. */
802     if ($this->jpegPhoto != "*removed*"){
804       /* Fallback if there's no image magick inside PHP */
805       if (!function_exists("imagick_blob2image")){
806         /* Get temporary file name for conversation */
807         $fname = tempnam ("/tmp", "GOsa");
809         /* Open file and write out photoData */
810         $fp = fopen ($fname, "w");
811         fwrite ($fp, $this->photoData);
812         fclose ($fp);
814         /* Build conversation query. Filename is generated automatically, so
815            we do not need any special security checks. Exec command and save
816            output. For PHP safe mode, you'll need a configuration which respects
817            image magick as executable... */
818         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
819         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
820             $query, "Execute");
822         /* Read data written by convert */
823         $output= "";
824         $sh= popen($query, 'r');
825         while (!feof($sh)){
826           $output.= fread($sh, 4096);
827         }
828         pclose($sh);
830         unlink($fname);
832         /* Save attribute */
833         $this->attrs["jpegPhoto"] = $output;
835       } else {
837         /* Load the new uploaded Photo */
838         if(!$handle  =  imagick_blob2image($this->photoData))  {
839           gosa_log("Can't Load image");
840         }
842         /* Resizing image to 147x200 and blur */
843         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
844           gosa_log("imagick_resize failed");
845         }
847         /* Converting image to JPEG */
848         if(!imagick_convert($handle,"JPEG")) {
849           gosa_log("Can't Convert to JPEG");
850         }
852         /* Creating binary Code for the Image */
853         if(!$dump = imagick_image2blob($handle)){
854           gosa_log("Can't create blob for image");
855         }
857         /* Sending Image */
858         $output=  $dump;
860         /* Save attribute */
861         $this->attrs["jpegPhoto"] = $output;
862       }
864     } else{
865       $this->attrs["jpegPhoto"] = array();
866     }
868     /* This only gets called when user is renaming himself */
869     $ldap= $this->config->get_ldap_link();
870     if ($this->dn != $this->new_dn){
872       /* Write entry on new 'dn' */
873       $this->move($this->dn, $this->new_dn);
875       /* Happen to use the new one */
876       change_ui_dn($this->dn, $this->new_dn);
877       $this->dn= $this->new_dn;
878     }
881     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
882        new entries. So do a check first... */
883     $ldap->cat ($this->dn, array('dn'));
884     if ($ldap->fetch()){
885       $mode= "modify";
886     } else {
887       $mode= "add";
888       $ldap->cd($this->config->current['BASE']);
889       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
890     }
892     /* Set password to some junk stuff in case of templates */
893     if ($this->is_template){
894       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
895     }
897     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
898         $this->attributes, "Save via $mode");
900     /* Finally write data with selected 'mode' */
901     $this->cleanup();
903     if(isset($this->attrs['preferredLanguage'])){
904       $_SESSION['ui']->language = $this->preferredLanguage;
905       $_SESSION['Last_init_lang'] = "update";
906     }
908     $ldap->cd ($this->dn);
909     $ldap->$mode ($this->attrs);
910     if (show_ldap_error($ldap->get_error(), _("Saving generic user account failed"))){
911       return (1);
912     }
914     /* Remove cert? 
915        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
916        to work around myself. */
917     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
919       /* Reset array, assemble new, this should be reworked */
920       $this->attrs= array();
921       $this->attrs['userCertificate;binary']= array();
923       /* Prepare connection */
924       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
925         die ("Could not connect to LDAP server");
926       }
927       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
928       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
929         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
930         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
931       }
932       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
933         ldap_start_tls($ds);
934       }
935       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
936               $this->config->current['PASSWORD']))) {
937         die ("Could not bind to LDAP");
938       }
940       /* Modify using attrs */
941       ldap_mod_del($ds,$this->dn,$this->attrs);
942       ldap_close($ds);
943     }
945     /* Kerberos server defined? */
946     if (isset($this->config->data['SERVERS']['KERBEROS'])){
947       $cfg= $this->config->data['SERVERS']['KERBEROS'];
948     }
949     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
951       /* Connect to the admin interface */
952       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
953           $cfg['ADMIN'], $cfg['PASSWORD']);
955       /* Errors? */             
956       if ($handle === FALSE){
957         print_red (_("Kerberos database communication failed"));
958         return (2);
959       }
961       /* Build user principal, get list of existsing principals */
962       $principal= $this->uid."@".$cfg['REALM'];
963       $principals = kadm5_get_principals($handle);
965       /* User exists in database? */
966       if (in_array($principal, $principals)){
968         /* Ok. User exists. Remove him/her when pw_storage has
969            changed to be NOT kerberos. */
970         if ($this->pw_storage != $this->config->current['KRBSASL']){
971           $ret= kadm5_delete_principal ( $handle, $principal);
973           if ($ret === FALSE){
974             print_red (_("Can't remove user from kerberos database."));
975           }
976         }
978       } else {
980         /* User doesn't exists, create it when pw_storage is kerberos or SASL. */
981         if ($this->pw_storage == "kerberos" || $this->pw_storage == "sasl" ){
982           $ret= kadm5_create_principal ( $handle, $principal);
984           if ($ret === FALSE){
985             print_red (_("Can't add user to kerberos database."));
986           }
987         }
989       }
991       /* Free kerberos admin handle */
992       kadm5_destroy($handle);
993     }
995     /* Optionally execute a command after we're done */
996     if ($mode == "add"){
997       $this->handle_post_events("add",array("uid" => $this->uid));
998     } elseif ($this->is_modified){
999       $this->handle_post_events("modify",array("uid" => $this->uid));
1000     }
1002     return (0);
1003   }
1006   /* Check formular input */
1007   function check()
1008   {
1009     /* Call common method to give check the hook */
1010     $message= plugin::check();
1012     /* Assemble cn */
1013     $pt= "";
1014     if(isset($this->config->current['INCLUDE_PERSONAL_TITLE']) && preg_match("/true/i",$this->config->current['INCLUDE_PERSONAL_TITLE'])){
1015       if(!empty($this->personalTitle)){
1016         $pt = $this->personalTitle." ";
1017       }
1018     }
1019     
1020     $this->cn= $pt.$this->givenName." ".$this->sn;
1022     /* Permissions for that base? */
1023     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
1024       $this->new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
1025     } else {
1026       /* Don't touch dn, if cn hasn't changed */
1027       if (isset($this->saved_attributes['cn']) && $this->saved_attributes['cn'] == $this->cn &&
1028           $this->orig_base == $this->base){
1029         $this->new_dn= $this->dn;
1030       } else {
1031         $this->new_dn= $this->create_unique_dn('cn', get_people_ou().$this->base);
1032       }
1033     }
1035     $ui= get_userinfo();
1036     $acl= get_permissions ($this->new_dn, $ui->subtreeACL);
1037     $acl= get_module_permission($acl, "user", $this->new_dn);
1038     if ($this->dn == "new" && chkacl($acl, "create") != ""){
1039       $message[]= _("You have no permissions to create a user on this 'Base'.");
1040     } elseif ($this->dn != $this->new_dn && $this->dn != "new"){
1041       $acl= get_permissions ($this->new_dn, $ui->subtreeACL);
1042       $acl= get_module_permission($acl, "user", $this->new_dn);
1043       if (chkacl($acl, "create") != ""){
1044         $message[]= _("You have no permissions to move a user from the original 'Base'.");
1045       }
1046     }
1048     /* must: sn, givenName, uid */
1049     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
1050       $message[]= _("The required field 'Name' is not set.");
1051     }
1053     /* UID already used? */
1054     $ldap= $this->config->get_ldap_link();
1055     $ldap->cd($this->config->current['BASE']);
1056     $ldap->search("(uid=$this->uid)", array("uid"));
1057     $ldap->fetch();
1058     if ($ldap->count() != 0 && $this->dn == 'new'){
1059       $message[]= _("There's already a person with this 'Login' in the database.");
1060     }
1062     /* In template mode, the uid and givenName are autogenerated... */
1063     if (!$this->is_template){
1064       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
1065         $message[]= _("The required field 'Given name' is not set.");
1066       }
1067       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
1068         $message[]= _("The required field 'Login' is not set.");
1069       }
1070       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
1071         $ldap->cat($this->new_dn);
1072         if ($ldap->count() != 0 && $this->dn != $this->new_dn && $this->dn == 'new'){
1073           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
1074         }
1075       }
1076     }
1078     /* Check for valid input */
1079     if ($this->is_modified && !is_uid($this->uid)){
1080       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
1081     }
1082     if (!is_url($this->labeledURI)){
1083       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
1084     }
1085     if (preg_match ("/[\\\\]/", $this->sn)){
1086       $message[]= _("The field 'Name' contains invalid characters.");
1087     }
1088     if (preg_match ("/[\\\\]/", $this->givenName)){
1089       $message[]= _("The field 'Given name' contains invalid characters.");
1090     }
1092     /* Check phone numbers */
1093     if (!is_phone_nr($this->telephoneNumber)){
1094       $message[]= _("The field 'Phone' contains an invalid phone number.");
1095     }
1096     if (!is_phone_nr($this->facsimileTelephoneNumber)){
1097       $message[]= _("The field 'Fax' contains an invalid phone number.");
1098     }
1099     if (!is_phone_nr($this->mobile)){
1100       $message[]= _("The field 'Mobile' contains an invalid phone number.");
1101     }
1102     if (!is_phone_nr($this->pager)){
1103       $message[]= _("The field 'Pager' contains an invalid phone number.");
1104     }
1106     /* Check for reserved characers */
1107     if (preg_match ('/[,+"?\'()=<>;]/', $this->givenName)){
1108       $message[]= _("The field 'Given name' contains invalid characters.");
1109     }
1110     if (preg_match ('/[,+"?\'()=<>;]/', $this->sn)){
1111       $message[]= _("The field 'Name' contains invalid characters.");
1112     }
1114   return $message;
1115   }
1118   /* Indicate whether a password change is needed or not */
1119   function password_change_needed()
1120   {
1121     return ($this->pw_storage != $this->last_pw_storage);
1122   }
1125   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1126   function load_picture()
1127   {
1128     /* make connection and read jpegPhoto */
1129     $ds= ldap_connect($this->config->current['SERVER']);
1130     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1131     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1132       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1133       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1134     }
1136     if(isset($this->config->current['TLS']) &&
1137         $this->config->current['TLS'] == "true"){
1139       ldap_start_tls($ds);
1140     }
1142     $r= ldap_bind($ds);
1143     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
1145     /* in case we don't get an entry, load a default picture */
1146     $this->set_picture ("./images/default.jpg");
1147     $this->jpegPhoto= "*removed*";
1149     /* fill data from LDAP */
1150     if ($sr) {
1151       $ei=ldap_first_entry($ds, $sr);
1152       if ($ei) {
1153         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
1154           $this->photoData= $info[0];
1155           $_SESSION['binary']= $this->photoData;
1156           $_SESSION['binarytype']= "image/jpeg";
1157           $this->jpegPhoto= "";
1158         }
1159       }
1160     }
1162     /* close conncetion */
1163     ldap_unbind($ds);
1164   }
1167   /* Load a certificate from LDAP, this is going to be simplified later on */
1168   function load_cert()
1169   {
1170     $ds= ldap_connect($this->config->current['SERVER']);
1171     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1172     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1173       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1174       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1175     }
1176     if(isset($this->config->current['TLS']) &&
1177         $this->config->current['TLS'] == "true"){
1179       ldap_start_tls($ds);
1180     }
1182     $r= ldap_bind($ds);
1183     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1185     if ($sr) {
1186       $ei= @ldap_first_entry($ds, $sr);
1187       
1188       if ($ei) {
1189         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1190           $this->userCertificate= "";
1191         } else {
1192           $this->userCertificate= $info[0];
1193         }
1194       }
1195     } else {
1196       $this->userCertificate= "";
1197     }
1199     ldap_unbind($ds);
1200   }
1203   /* Load picture from file to object */
1204   function set_picture($filename ="")
1205   {
1206     if (!is_file($filename) || $filename == ""){
1207       $filename= "./images/default.jpg";
1208       $this->jpegPhoto= "*removed*";
1209     }
1211     $fd = fopen ($filename, "rb");
1212     $this->photoData= fread ($fd, filesize ($filename));
1213     $_SESSION['binary']= $this->photoData;
1214     $_SESSION['binarytype']= "image/jpeg";
1215     $this->jpegPhoto= "";
1217     fclose ($fd);
1218   }
1221   /* Load certificate from file to object */
1222   function set_cert($cert, $filename)
1223   {
1224     $fd = fopen ($filename, "rb");
1225     if (filesize($filename)>0) {
1226       $this->$cert= fread ($fd, filesize ($filename));
1227       fclose ($fd);
1228       $this->is_modified= TRUE;
1229     } else {
1230       print_red(_("Could not open specified certificate!"));
1231     }
1232   }
1234   /* Adapt from given 'dn' */
1235   function adapt_from_template($dn)
1236   {
1237     plugin::adapt_from_template($dn);
1239     /* Get base */
1240     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1242     if ($this->config->current['GOVERNMENTMODE']){
1244       /* Walk through govattrs */
1245       foreach ($this->govattrs as $val){
1247         if (isset($this->attrs["$val"][0])){
1249           /* If attribute is set, replace dynamic parts: 
1250              %sn, %givenName and %uid. Fill these in our local variables. */
1251           $value= $this->attrs["$val"][0];
1253           foreach (array("sn", "givenName", "uid") as $repl){
1254             if (preg_match("/%$repl/i", $value)){
1255               $value= preg_replace ("/%$repl/i",
1256                   $this->parent->$repl, $value);
1257             }
1258           }
1259           $this->$val= $value;
1260         }
1261       }
1262     }
1264     /* Get back uid/sn/givenName */
1265     if ($this->parent != NULL){
1266       $this->uid= $this->parent->uid;
1267       $this->sn= $this->parent->sn;
1268       $this->givenName= $this->parent->givenName;
1269     }
1270   }
1272  
1273   /* This avoids that users move themselves out of their rights. 
1274    */
1275   function allowedBasesToMoveTo()
1276   {
1277     $allowed = array();
1278     $ret_all = false;
1279     if($this->uid == $_SESSION['ui']->username){
1280       $ldap= $this->config->get_ldap_link(); 
1281       $ldap->cd($this->config->current['BASE']); 
1282       $ldap->search("(&(objectClass=posixGroup)(memberUid=".$_SESSION['ui']->username."))",array("gosaSubtreeACL"));
1283        
1284       while($attrs = $ldap->fetch()){
1285     
1286         if(isset($attrs['gosaSubtreeACL'])){
1287         
1288           foreach($attrs['gosaSubtreeACL'] as $attr){
1289             if((preg_match("/:user#/",$attr))||(preg_match("/:all/",$attr))){
1290               $s =  preg_replace("/^.*".get_groups_ou().",/","",$attrs['dn']);
1292               foreach($this->config->idepartments as $key => $dep) {
1293                 if(preg_match("/".$s."/i",$key)){
1294                   $allowed[$key] = $dep;
1295                 }
1296               }
1297             }
1298           }
1299         }
1300       }
1301       if(count($allowed) == 0){
1302         foreach($this->config->idepartments as $key => $dep) {
1303           if($this->base==$key){
1304             $allowed[$key] = $dep;
1305           }
1306         }
1307       }  
1308   
1309       return($allowed);
1310       
1311     }else{
1312       return($this->config->idepartments);
1313     }
1314   } 
1317   function getCopyDialog()
1318   {
1319     $str = "";
1321     $_SESSION['binary'] = $this->photoData; 
1322     $_SESSION['binarytype']= "image/jpeg";
1324     /* Get random number for pictures */
1325     srand((double)microtime()*1000000); 
1326     $rand = rand(0, 10000);
1328     $smarty = get_smarty();
1330     $smarty->assign("passwordTodo","clear");
1332     if(isset($_POST['passwordTodo'])){
1333       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1334     }
1336     $smarty->assign("sn",       $this->sn);
1337     $smarty->assign("givenName",$this->givenName);
1338     $smarty->assign("uid",      $this->uid);
1339     $smarty->assign("rand",     $rand);
1340     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1343     $ret = array();
1344     $ret['string'] = $str;
1345     $ret['status'] = "";  
1346     return($ret);
1347   }
1349   function saveCopyDialog()
1350   {
1352     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1353       $this->set_picture($_FILES['picture_file']['tmp_name']);
1354     }
1356     /* Remove picture? */
1357     if (isset($_POST['picture_remove'])){
1358       $this->jpegPhoto= "*removed*";
1359       $this->set_picture ("./images/default.jpg");
1360       $this->is_modified= TRUE;
1361     }
1363     $attrs = array("uid","givenName","sn");
1364     foreach($attrs as $attr){
1365       if(isset($_POST[$attr])){
1366         $this->$attr = $_POST[$attr];
1367       }
1368     } 
1369   }
1372   function PrepareForCopyPaste($source)
1373   {
1374     plugin::PrepareForCopyPaste($source);
1376     /* Reset certificate information addepted from source user
1377         to avoid setting the same user certificate for the destination user. */
1378     $this->userPKCS12= "";
1379     $this->userSMIMECertificate= "";
1380     $this->userCertificate= "";
1381     $this->certificateSerialNumber= "";
1382     $this->old_certificateSerialNumber= "";
1383     $this->old_userPKCS12= "";
1384     $this->old_userSMIMECertificate= "";
1385     $this->old_userCertificate= "";
1386   }
1389 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1390 ?>