Code

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