Code

e24e928e034e461dc7495bbfc327e99737c7a7cc
[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     if ($this->config->current['GOVERNMENTMODE']){
115       /* Fix public visible attribute if unset */
116       if (!isset($this->attrs['publicVisible'])){
117         $this->publicVisible == "nein";
118       }
119     }
121     /* Load government mode attributes */
122     if ($this->config->current['GOVERNMENTMODE']){
123       /* Copy all attributs */
124       foreach ($this->govattrs as $val){
125         if (isset($this->attrs["$val"][0])){
126           $this->$val= $this->attrs["$val"][0];
127         }
128       }
129     }
131     /* Create me for new accounts */
132     if ($dn == "new"){
133       $this->is_account= TRUE;
134     }
136     /* Make hash default to md5 if not set in config */
137     if (!isset($this->config->current['HASH'])){
138       $hash= "md5";
139     } else {
140       $hash= $this->config->current['HASH'];
141     }
143     /* Load data from LDAP? */
144     if ($dn != NULL){
146       /* Do base conversation */
147       if ($this->dn == "new"){
148         $ui= get_userinfo();
149         $this->base= dn2base($ui->dn);
150       } else {
151         $this->base= dn2base($dn);
152       }
154       /* get password storage type */
155       if (isset ($this->attrs['userPassword'][0])){
156         /* Initialize local array */
157         $matches= array();
158         if (preg_match ("/^{([^}]+)}(.+)/", $this->attrs['userPassword'][0], $matches)){
159           $this->pw_storage= strtolower($matches[1]);
160         } else {
161           if ($this->attrs['userPassword'][0] != ""){
162             $this->pw_storage= "clear";
163           } else {
164             $this->pw_storage= $hash;
165           }
166         }
167       } else {
168         /* Preset with vaule from configuration */
169         $this->pw_storage= $hash;
170       }
172       /* Load extra attributes: certificate and picture */
173       $this->load_picture();
174       $this->load_cert();
175       if ($this->userCertificate != ""){
176         $this->had_userCertificate= TRUE;
177       }
178     }
180     /* Reset password storage indicator, used by password_change_needed() */
181     if ($dn == "new"){
182       $this->last_pw_storage= "unset";
183     } else {
184       $this->last_pw_storage= $this->pw_storage;
185     }
187     /* Generate dateOfBirth entry */
188     if (isset ($this->attrs['dateOfBirth'])){
189       /* This entry is ISO 8601 conform */
190       list($year, $month, $day)= split("-", $this->attrs['dateOfBirth'][0], 3);
191     
192       $this->dateOfBirth=array( 'mon'=> $month,"mday"=> $day,"year"=> $year);
193       $this->use_dob= "1";
194     } else {
195       $this->use_dob= "0";
196     }
198     /* Put gender attribute to upper case */
199     if (isset ($this->attrs['gender'])){
200       $this->gender= strtoupper($this->attrs['gender'][0]);
201     }
203     $this->orig_base = $this->base;
204   }
207   /* execute generates the html output for this node */
208   function execute()
209   {
210     /* Call parent execute */
211     plugin::execute();
213     $smarty= get_smarty();
215     /* Fill calendar */
216     if ($this->dateOfBirth == "0"){
217       $date= getdate();
218     } else {
219       if(is_array($this->dateOfBirth)){
220         $date = $this->dateOfBirth;
221   
222         // Trigger on dates like 1985-04-01, getdate only understands timestamps
223       } else if (!empty($this->dateOfBirth) && !is_numeric($this->dateOfBirth)){
224         $date= getdate(strtotime($this->dateOfBirth));
226       } else {
227         $date = getdate($this->dateOfBirth);
228       } 
229     }
231     $days= array();
232     for($d= 1; $d<32; $d++){
233       $days[$d]= $d;
234     }
235     $years= array();
237     if(($date['year']-100)<1901){
238       $start = 1901;
239     }else{
240       $start = $date['year']-100;
241     }
243     $end = $start +100;
244     
245     for($y= $start; $y<=$end; $y++){
246       $years[]= $y;
247     }
248     $years['-']= "-&nbsp;";
249     $months= array(_("January"), _("February"), _("March"), _("April"),
250         _("May"), _("June"), _("July"), _("August"), _("September"),
251         _("October"), _("November"), _("December"), '-' => '-&nbsp;');
252     $smarty->assign("day", $date["mday"]);
253     $smarty->assign("days", $days);
254     $smarty->assign("months", $months);
255     $smarty->assign("month", $date["mon"]-1);
256     $smarty->assign("years", $years);
257     $smarty->assign("year", $date["year"]);
259     /* Assign sex */
260     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
261     $smarty->assign("gender_list", $sex);
263     /* Assign prefered langage */
264     $language= array(0 => "&nbsp;", "fr_FR" => ("fr_FR"), "en_EN" => ("en_EN"), 
265                                     "de_DE" => ("de_DE"), "it_IT" => ("it_IT"), 
266                                     "nl_NL" => ("nl_NL"), "ru_RU" => ("ru_RU"),
267                                     "zh_CN" => ("zh_CN"), "pl_PL" => ("pl_PL"),
268                                     "sv_SE" => ("sv_SE"), "es_ES" => ("es_ES"));
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();
888     $ldap->cd ($this->dn);
889     $ldap->$mode ($this->attrs);
890     if (show_ldap_error($ldap->get_error(), _("Saving generic user account failed"))){
891       return (1);
892     }
894     /* Remove cert? 
895        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
896        to work around myself. */
897     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
899       /* Reset array, assemble new, this should be reworked */
900       $this->attrs= array();
901       $this->attrs['userCertificate;binary']= array();
903       /* Prepare connection */
904       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
905         die ("Could not connect to LDAP server");
906       }
907       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
908       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
909         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
910         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
911       }
912       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
913         ldap_start_tls($ds);
914       }
915       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
916               $this->config->current['PASSWORD']))) {
917         die ("Could not bind to LDAP");
918       }
920       /* Modify using attrs */
921       ldap_mod_del($ds,$this->dn,$this->attrs);
922       ldap_close($ds);
923     }
925     /* Kerberos server defined? */
926     if (isset($this->config->data['SERVERS']['KERBEROS'])){
927       $cfg= $this->config->data['SERVERS']['KERBEROS'];
928     }
929     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
931       /* Connect to the admin interface */
932       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
933           $cfg['ADMIN'], $cfg['PASSWORD']);
935       /* Errors? */             
936       if ($handle === FALSE){
937         print_red (_("Kerberos database communication failed"));
938         return (2);
939       }
941       /* Build user principal, get list of existsing principals */
942       $principal= $this->uid."@".$cfg['REALM'];
943       $principals = kadm5_get_principals($handle);
945       /* User exists in database? */
946       if (in_array($principal, $principals)){
948         /* Ok. User exists. Remove him/her when pw_storage has
949            changed to be NOT kerberos. */
950         if ($this->pw_storage != $this->config->current['KRBSASL']){
951           $ret= kadm5_delete_principal ( $handle, $principal);
953           if ($ret === FALSE){
954             print_red (_("Can't remove user from kerberos database."));
955           }
956         }
958       } else {
960         /* User doesn't exists, create it when pw_storage is kerberos or SASL. */
961         if ($this->pw_storage == "kerberos" || $this->pw_storage == "sasl" ){
962           $ret= kadm5_create_principal ( $handle, $principal);
964           if ($ret === FALSE){
965             print_red (_("Can't add user to kerberos database."));
966           }
967         }
969       }
971       /* Free kerberos admin handle */
972       kadm5_destroy($handle);
973     }
975     /* Optionally execute a command after we're done */
976     if ($mode == "add"){
977       $this->handle_post_events("add",array("uid" => $this->uid));
978     } elseif ($this->is_modified){
979       $this->handle_post_events("modify",array("uid" => $this->uid));
980     }
982     /* Fix tagging if needed */
983     $this->handle_object_tagging();
985     return (0);
986   }
989   /* Check formular input */
990   function check()
991   {
992     /* Call common method to give check the hook */
993     $message= plugin::check();
995     /* Assemble cn */
996     $pt= "";
997     if(isset($this->config->current['INCLUDE_PERSONAL_TITLE']) && preg_match("/true/i",$this->config->current['INCLUDE_PERSONAL_TITLE'])){
998       if(!empty($this->personalTitle)){
999         $pt = $this->personalTitle." ";
1000       }
1001     }
1002     
1003     $this->cn= $pt.$this->givenName." ".$this->sn;
1005     /* Permissions for that base? */
1006     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
1007       $this->new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
1008     } else {
1009       /* Don't touch dn, if cn hasn't changed */
1010       if (isset($this->saved_attributes['cn']) && $this->saved_attributes['cn'] == $this->cn &&
1011           $this->orig_base == $this->base){
1012         $this->new_dn= $this->dn;
1013       } else {
1014         $this->new_dn= $this->create_unique_dn('cn', get_people_ou().$this->base);
1015       }
1016     }
1018     $ui= get_userinfo();
1019     $acl= get_permissions ($this->new_dn, $ui->subtreeACL);
1020     $acl= get_module_permission($acl, "user", $this->new_dn);
1021     if ($this->dn == "new" && chkacl($acl, "create") != ""){
1022       $message[]= _("You have no permissions to create a user on this 'Base'.");
1023     } elseif ($this->dn != $this->new_dn && $this->dn != "new"){
1024       $acl= get_permissions ($this->new_dn, $ui->subtreeACL);
1025       $acl= get_module_permission($acl, "user", $this->new_dn);
1026       if (chkacl($acl, "create") != ""){
1027         $message[]= _("You have no permissions to move a user from the original 'Base'.");
1028       }
1029     }
1031     /* must: sn, givenName, uid */
1032     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
1033       $message[]= _("The required field 'Name' is not set.");
1034     }
1036     /* UID already used? */
1037     $ldap= $this->config->get_ldap_link();
1038     $ldap->cd($this->config->current['BASE']);
1039     $ldap->search("(uid=$this->uid)", array("uid"));
1040     $ldap->fetch();
1041     if ($ldap->count() != 0 && $this->dn == 'new'){
1042       $message[]= _("There's already a person with this 'Login' in the database.");
1043     }
1045     /* In template mode, the uid and givenName are autogenerated... */
1046     if (!$this->is_template){
1047       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
1048         $message[]= _("The required field 'Given name' is not set.");
1049       }
1050       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
1051         $message[]= _("The required field 'Login' is not set.");
1052       }
1053       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
1054         $ldap->cat($this->new_dn);
1055         if ($ldap->count() != 0 && $this->dn != $this->new_dn && $this->dn == 'new'){
1056           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
1057         }
1058       }
1059     }
1061     /* Check for valid input */
1062     if ($this->is_modified && !is_uid($this->uid)){
1063       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
1064     }
1065     if (!is_url($this->labeledURI)){
1066       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
1067     }
1068     if (preg_match ("/[\\\\]/", $this->sn)){
1069       $message[]= _("The field 'Name' contains invalid characters.");
1070     }
1071     if (preg_match ("/[\\\\]/", $this->givenName)){
1072       $message[]= _("The field 'Given name' contains invalid characters.");
1073     }
1075     /* Check phone numbers */
1076     if (!is_phone_nr($this->telephoneNumber)){
1077       $message[]= _("The field 'Phone' contains an invalid phone number.");
1078     }
1079     if (!is_phone_nr($this->facsimileTelephoneNumber)){
1080       $message[]= _("The field 'Fax' contains an invalid phone number.");
1081     }
1082     if (!is_phone_nr($this->mobile)){
1083       $message[]= _("The field 'Mobile' contains an invalid phone number.");
1084     }
1085     if (!is_phone_nr($this->pager)){
1086       $message[]= _("The field 'Pager' contains an invalid phone number.");
1087     }
1089     /* Check for reserved characers */
1090     if (preg_match ('/[,+"?\'()=<>;]/', $this->givenName)){
1091       $message[]= _("The field 'Given name' contains invalid characters.");
1092     }
1093     if (preg_match ('/[,+"?\'()=<>;]/', $this->sn)){
1094       $message[]= _("The field 'Name' contains invalid characters.");
1095     }
1097   return $message;
1098   }
1101   /* Indicate whether a password change is needed or not */
1102   function password_change_needed()
1103   {
1104     return ($this->pw_storage != $this->last_pw_storage);
1105   }
1108   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1109   function load_picture()
1110   {
1111     /* make connection and read jpegPhoto */
1112     $ds= ldap_connect($this->config->current['SERVER']);
1113     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1114     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1115       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1116       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1117     }
1119     if(isset($this->config->current['TLS']) &&
1120         $this->config->current['TLS'] == "true"){
1122       ldap_start_tls($ds);
1123     }
1125     $r= ldap_bind($ds);
1126     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
1128     /* in case we don't get an entry, load a default picture */
1129     $this->set_picture ("./images/default.jpg");
1130     $this->jpegPhoto= "*removed*";
1132     /* fill data from LDAP */
1133     if ($sr) {
1134       $ei=ldap_first_entry($ds, $sr);
1135       if ($ei) {
1136         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
1137           $this->photoData= $info[0];
1138           $_SESSION['binary']= $this->photoData;
1139           $_SESSION['binarytype']= "image/jpeg";
1140           $this->jpegPhoto= "";
1141         }
1142       }
1143     }
1145     /* close conncetion */
1146     ldap_unbind($ds);
1147   }
1150   /* Load a certificate from LDAP, this is going to be simplified later on */
1151   function load_cert()
1152   {
1153     $ds= ldap_connect($this->config->current['SERVER']);
1154     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1155     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1156       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1157       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1158     }
1159     if(isset($this->config->current['TLS']) &&
1160         $this->config->current['TLS'] == "true"){
1162       ldap_start_tls($ds);
1163     }
1165     $r= ldap_bind($ds);
1166     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1168     if ($sr) {
1169       $ei= @ldap_first_entry($ds, $sr);
1170       
1171       if ($ei) {
1172         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1173           $this->userCertificate= "";
1174         } else {
1175           $this->userCertificate= $info[0];
1176         }
1177       }
1178     } else {
1179       $this->userCertificate= "";
1180     }
1182     ldap_unbind($ds);
1183   }
1186   /* Load picture from file to object */
1187   function set_picture($filename ="")
1188   {
1189     if (!is_file($filename) || $filename == ""){
1190       $filename= "./images/default.jpg";
1191       $this->jpegPhoto= "*removed*";
1192     }
1194     $fd = fopen ($filename, "rb");
1195     $this->photoData= fread ($fd, filesize ($filename));
1196     $_SESSION['binary']= $this->photoData;
1197     $_SESSION['binarytype']= "image/jpeg";
1198     $this->jpegPhoto= "";
1200     fclose ($fd);
1201   }
1204   /* Load certificate from file to object */
1205   function set_cert($cert, $filename)
1206   {
1207     $fd = fopen ($filename, "rb");
1208     if (filesize($filename)>0) {
1209       $this->$cert= fread ($fd, filesize ($filename));
1210       fclose ($fd);
1211       $this->is_modified= TRUE;
1212     } else {
1213       print_red(_("Could not open specified certificate!"));
1214     }
1215   }
1217   /* Adapt from given 'dn' */
1218   function adapt_from_template($dn)
1219   {
1220     plugin::adapt_from_template($dn);
1222     /* Get base */
1223     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1225     if ($this->config->current['GOVERNMENTMODE']){
1227       /* Walk through govattrs */
1228       foreach ($this->govattrs as $val){
1230         if (isset($this->attrs["$val"][0])){
1232           /* If attribute is set, replace dynamic parts: 
1233              %sn, %givenName and %uid. Fill these in our local variables. */
1234           $value= $this->attrs["$val"][0];
1236           foreach (array("sn", "givenName", "uid") as $repl){
1237             if (preg_match("/%$repl/i", $value)){
1238               $value= preg_replace ("/%$repl/i",
1239                   $this->parent->$repl, $value);
1240             }
1241           }
1242           $this->$val= $value;
1243         }
1244       }
1245     }
1247     /* Get back uid/sn/givenName */
1248     if ($this->parent != NULL){
1249       $this->uid= $this->parent->uid;
1250       $this->sn= $this->parent->sn;
1251       $this->givenName= $this->parent->givenName;
1252     }
1253   }
1255  
1256   /* This avoids that users move themselves out of their rights. 
1257    */
1258   function allowedBasesToMoveTo()
1259   {
1260     $allowed = array();
1261     $ret_all = false;
1262     if($this->uid == $_SESSION['ui']->username){
1263       $ldap= $this->config->get_ldap_link(); 
1264       $ldap->cd($this->config->current['BASE']); 
1265       $ldap->search("(&(objectClass=posixGroup)(memberUid=".$_SESSION['ui']->username."))",array("gosaSubtreeACL"));
1266        
1267       while($attrs = $ldap->fetch()){
1268     
1269         if(isset($attrs['gosaSubtreeACL'])){
1270         
1271           foreach($attrs['gosaSubtreeACL'] as $attr){
1272             if((preg_match("/:user#/",$attr))||(preg_match("/:all/",$attr))){
1273               $s =  preg_replace("/^.*".get_groups_ou().",/","",$attrs['dn']);
1275               foreach($this->config->idepartments as $key => $dep) {
1276                 if(preg_match("/".$s."/i",$key)){
1277                   $allowed[$key] = $dep;
1278                 }
1279               }
1280             }
1281           }
1282         }
1283       }
1284       if(count($allowed) == 0){
1285         foreach($this->config->idepartments as $key => $dep) {
1286           if($this->base==$key){
1287             $allowed[$key] = $dep;
1288           }
1289         }
1290       }  
1291   
1292       return($allowed);
1293       
1294     }else{
1295       return($this->config->idepartments);
1296     }
1297   } 
1300   function getCopyDialog()
1301   {
1302     $str = "";
1304     $_SESSION['binary'] = $this->photoData; 
1305     $_SESSION['binarytype']= "image/jpeg";
1307     /* Get random number for pictures */
1308     srand((double)microtime()*1000000); 
1309     $rand = rand(0, 10000);
1311     $smarty = get_smarty();
1313     $smarty->assign("passwordTodo","clear");
1315     if(isset($_POST['passwordTodo'])){
1316       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1317     }
1319     $smarty->assign("sn",       $this->sn);
1320     $smarty->assign("givenName",$this->givenName);
1321     $smarty->assign("uid",      $this->uid);
1322     $smarty->assign("rand",     $rand);
1323     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1326     $ret = array();
1327     $ret['string'] = $str;
1328     $ret['status'] = "";  
1329     return($ret);
1330   }
1332   function saveCopyDialog()
1333   {
1335     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1336       $this->set_picture($_FILES['picture_file']['tmp_name']);
1337     }
1339     /* Remove picture? */
1340     if (isset($_POST['picture_remove'])){
1341       $this->jpegPhoto= "*removed*";
1342       $this->set_picture ("./images/default.jpg");
1343       $this->is_modified= TRUE;
1344     }
1346     $attrs = array("uid","givenName","sn");
1347     foreach($attrs as $attr){
1348       if(isset($_POST[$attr])){
1349         $this->$attr = $_POST[$attr];
1350       }
1351     } 
1352   }
1355   function PrepareForCopyPaste($source)
1356   {
1357     plugin::PrepareForCopyPaste($source);
1359     /* Reset certificate information addepted from source user
1360         to avoid setting the same user certificate for the destination user. */
1361     $this->userPKCS12= "";
1362     $this->userSMIMECertificate= "";
1363     $this->userCertificate= "";
1364     $this->certificateSerialNumber= "";
1365     $this->old_certificateSerialNumber= "";
1366     $this->old_userPKCS12= "";
1367     $this->old_userSMIMECertificate= "";
1368     $this->old_userCertificate= "";
1369   }
1372 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1373 ?>