Code

e7c13fefd0ac3d6397a473ce29f20c7cc69f7b71
[gosa.git] / plugins / personal / generic / class_user.inc
1 <?php
2 /*!
3   \brief   user plugin
4   \author  Cajus Pollmeier <pollmeier@gonicus.de>
5   \version 2.00
6   \date    24.07.2003
8   This class provides the functionality to read and write all attributes
9   relevant for person, organizationalPerson, inetOrgPerson and gosaAccount
10   from/to the LDAP. It does syntax checking and displays the formulars required.
11  */
13 class user extends plugin
14 {
15   /* Definitions */
16   var $plHeadline= "Generic";
17   var $plDescription= "This does something";
19   /* CLI vars */
20   var $cli_summary= "Handling of GOsa's user base object";
21   var $cli_description= "Some longer text\nfor help";
22   var $cli_parameters= array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
24   /* Plugin specific values */
25   var $base= "";
26   var $cn= "";
27   var $personalTitle= "";
28   var $academicTitle= "";
29   var $homePostalAddress= "";
30   var $homePhone= "";
31   var $labeledURI= "";
32   var $o= "";
33   var $ou= "";
34   var $departmentNumber= "";
35   var $employeeNumber= "";
36   var $employeeType= "";
37   var $roomNumber= "";
38   var $telephoneNumber= "";
39   var $facsimileTelephoneNumber= "";
40   var $mobile= "";
41   var $pager= "";
42   var $l= "";
43   var $st= "";
44   var $postalAddress= "";
45   var $dateOfBirth;
46   var $use_dob= "0";
47   var $gender="0";
48   var $preferredLanguage="0";
50   var $jpegPhoto= "*removed*";
51   var $photoData= "";
52   var $old_jpegPhoto= "";
53   var $old_photoData= "";
54   var $cert_dialog= FALSE;
55   var $picture_dialog= FALSE;
57   var $userPKCS12= "";
58   var $userSMIMECertificate= "";
59   var $userCertificate= "";
60   var $certificateSerialNumber= "";
61   var $old_certificateSerialNumber= "";
62   var $old_userPKCS12= "";
63   var $old_userSMIMECertificate= "";
64   var $old_userCertificate= "";
66   var $gouvernmentOrganizationalUnit= "";
67   var $houseIdentifier= "";
68   var $street= "";
69   var $postalCode= "";
70   var $vocation= "";
71   var $ivbbLastDeliveryCollective= "";
72   var $gouvernmentOrganizationalPersonLocality= "";
73   var $gouvernmentOrganizationalUnitDescription= "";
74   var $gouvernmentOrganizationalUnitSubjectArea= "";
75   var $functionalTitle= "";
76   var $role= "";
77   var $publicVisible= "";
79   var $dialog;
81   /* variables to trigger password changes */
82   var $pw_storage= "crypt";
83   var $last_pw_storage= "unset";
84   var $had_userCertificate= FALSE;
86   /* attribute list for save action */
87   var $attributes= array("sn", "givenName", "uid", "personalTitle", "academicTitle",
88       "homePostalAddress", "homePhone", "labeledURI", "o", "ou", "dateOfBirth", "gender","preferredLanguage",
89       "departmentNumber", "employeeNumber", "employeeType", "l", "st","jpegPhoto",
90       "roomNumber", "telephoneNumber", "mobile", "pager", "cn", "userPKCS12",
91       "postalAddress", "facsimileTelephoneNumber", "userSMIMECertificate");
93   var $objectclasses= array("top", "person", "organizationalPerson", "inetOrgPerson",
94       "gosaAccount");
96   /* attributes that are part of the government mode */
97   var $govattrs= array("gouvernmentOrganizationalUnit", "houseIdentifier", "vocation",
98       "ivbbLastDeliveryCollective", "gouvernmentOrganizationalPersonLocality",
99       "gouvernmentOrganizationalUnitDescription","gouvernmentOrganizationalUnitSubjectArea",
100       "functionalTitle", "certificateSerialNumber", "publicVisible", "street", "role",
101       "postalCode");
104   /* constructor, if 'dn' is set, the node loads the given
105      'dn' from LDAP */
106   function user ($config, $dn= NULL)
107   {
108     $this->config= $config;
109     /* Configuration is fine, allways */
110     if ($this->config->current['GOVERNMENTMODE']){
111       $this->attributes=array_merge($this->attributes,$this->govattrs);
112     }
114     /* Load base attributes */
115     plugin::plugin ($config, $dn);
117     if ($this->config->current['GOVERNMENTMODE']){
118       /* Fix public visible attribute if unset */
119       if (!isset($this->attrs['publicVisible'])){
120         $this->publicVisible == "nein";
121       }
122     }
124     /* Load government mode attributes */
125     if ($this->config->current['GOVERNMENTMODE']){
126       /* Copy all attributs */
127       foreach ($this->govattrs as $val){
128         if (isset($this->attrs["$val"][0])){
129           $this->$val= $this->attrs["$val"][0];
130         }
131       }
132     }
134     /* Create me for new accounts */
135     if ($dn == "new"){
136       $this->is_account= TRUE;
137     }
139     /* Make hash default to md5 if not set in config */
140     if (!isset($this->config->current['HASH'])){
141       $hash= "md5";
142     } else {
143       $hash= $this->config->current['HASH'];
144     }
146     /* Load data from LDAP? */
147     if ($dn != NULL){
149       /* Do base conversation */
150       if ($this->dn == "new"){
151         $ui= get_userinfo();
152         $this->base= dn2base($ui->dn);
153       } else {
154         $this->base= dn2base($dn);
155       }
157       /* get password storage type */
158       if (isset ($this->attrs['userPassword'][0])){
159         /* Initialize local array */
160         $matches= array();
161         if (preg_match ("/^{([^}]+)}(.+)/", $this->attrs['userPassword'][0], $matches)){
162           $this->pw_storage= strtolower($matches[1]);
163         } else {
164           if ($this->attrs['userPassword'][0] != ""){
165             $this->pw_storage= "clear";
166           } else {
167             $this->pw_storage= $hash;
168           }
169         }
170       } else {
171         /* Preset with vaule from configuration */
172         $this->pw_storage= $hash;
173       }
175       /* Load extra attributes: certificate and picture */
176       $this->load_picture();
177       $this->load_cert();
178       if ($this->userCertificate != ""){
179         $this->had_userCertificate= TRUE;
180       }
181     }
183     /* Reset password storage indicator, used by password_change_needed() */
184     if ($dn == "new"){
185       $this->last_pw_storage= "unset";
186     } else {
187       $this->last_pw_storage= $this->pw_storage;
188     }
190     /* Generate dateOfBirth entry */
191     if (isset ($this->attrs['dateOfBirth'])){
192       /* This entry is ISO 8601 conform */
193       list($year, $month, $day)= split("-", $this->attrs['dateOfBirth'][0], 3);
194     
195       $this->dateOfBirth=array( 'mon'=> $month,"mday"=> $day,"year"=> $year);
196       $this->use_dob= "1";
197     } else {
198       $this->use_dob= "0";
199     }
201     /* Put gender attribute to upper case */
202     if (isset ($this->attrs['gender'])){
203       $this->gender= strtoupper($this->attrs['gender'][0]);
204     }
205   }
208   /* execute generates the html output for this node */
209   function execute()
210   {
211     /* Call parent execute */
212     plugin::execute();
214     $smarty= get_smarty();
216     /* Fill calendar */
217     if ($this->dateOfBirth == "0"){
218       $date= getdate();
219     } else {
220       if(is_array($this->dateOfBirth)){
221         $date = $this->dateOfBirth;
222       }else{
223         $date = getdate($this->dateOfBirth);
224       } 
225     }
227     $days= array();
228     for($d= 1; $d<32; $d++){
229       $days[$d]= $d;
230     }
231     $years= array();
233     if(($date['year']-100)<1901){
234       $start = 1901;
235     }else{
236       $start = $date['year']-100;
237     }
239     $end = $start +100;
240     
241     for($y= $start; $y<=$end; $y++){
242       $years[]= $y;
243     }
244     $years['-']= "-&nbsp;";
245     $months= array(_("January"), _("February"), _("March"), _("April"),
246         _("May"), _("June"), _("July"), _("August"), _("September"),
247         _("October"), _("November"), _("December"), '-' => '-&nbsp;');
248     $smarty->assign("day", $date["mday"]);
249     $smarty->assign("days", $days);
250     $smarty->assign("months", $months);
251     $smarty->assign("month", $date["mon"]-1);
252     $smarty->assign("years", $years);
253     $smarty->assign("year", $date["year"]);
255     /* Assign sex */
256     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
257     $smarty->assign("gender_list", $sex);
259     /* Assign prefered langage */
260     $language= array(0 => "&nbsp;", "fr_FR" => ("fr_FR"), "en_EN" => ("en_EN"), 
261                                     "de_DE" => ("de_DE"), "it_IT" => ("it_IT"), 
262                                     "nl_NL" => ("nl_NL"), "ru_RU" => ("ru_RU"));
263     $smarty->assign("preferredLanguage_list", $language);
265     /* Get random number for pictures */
266     srand((double)microtime()*1000000); 
267     $smarty->assign("rand", rand(0, 10000));
269     /* Do we represent a valid gosaAccount? */
270     if (!$this->is_account){
271       echo "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
272         _("This account has no valid GOsa extensions.")."</b>";
273       return;
274     }
276     /* Base select dialog */
277     $once = true;
278     foreach($_POST as $name => $value){
279       if(preg_match("/^chooseBase/",$name) && $once){
280         $once = false;
281         $this->dialog = new baseSelectDialog($this->config,$this->allowedBasesToMoveTo());
282         $this->dialog->setCurrentBase($this->base);
283       }
284     }
286     /* Dialog handling */
287     if(is_object($this->dialog)){
288       /* Must be called before save_object */
289       $this->dialog->save_object();
290    
291       if($this->dialog->isClosed()){
292         $this->dialog = false;
293       }elseif($this->dialog->isSelected()){
294         $this->base = $this->dialog->isSelected();
295         $this->dialog= false;
296       }else{
297         return($this->dialog->execute());
298       }
299     }
301     /* Want picture edit dialog? */
302     if (isset($_POST['edit_picture'])){
303       /* Save values for later recovery, in case some presses
304          the cancel button. */
305       $this->old_jpegPhoto= $this->jpegPhoto;
306       $this->old_photoData= $this->photoData;
307       $this->picture_dialog= TRUE;
308       $this->dialog= TRUE;
309     }
311     /* Remove picture? */
312     if (isset($_POST['picture_remove'])){
313       $this->set_picture ();
314       $this->jpegPhoto= "*removed*";
315       $this->is_modified= TRUE;
317       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
318     }
320     /* Save picture */
321     if (isset($_POST['picture_edit_finish'])){
323       /* Check for clean upload */
324       if ($_FILES['picture_file']['name'] != ""){
325         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
326           print_red(_("The specified file has not been uploaded via HTTP POST! Aborted."));
327           exit;
328         }
330         /* Activate new picture */
331         $this->set_picture($_FILES['picture_file']['tmp_name']);
332       }
333       $this->picture_dialog= FALSE;
334       $this->dialog= FALSE;
335       $this->is_modified= TRUE;
336     }
339     /* Cancel picture */
340     if (isset($_POST['picture_edit_cancel'])){
342       /* Restore values */
343       $this->jpegPhoto= $this->old_jpegPhoto;
344       $this->photoData= $this->old_photoData;
346       /* Update picture */
347       $_SESSION['binary']= $this->photoData;
348       $_SESSION['binarytype']= "image/jpeg";
349       $this->picture_dialog= FALSE;
350       $this->dialog= FALSE;
351     }
353     /* Toggle dateOfBirth information */
354     if (isset($_POST['set_dob'])){
355       $this->use_dob= ($this->use_dob == "0")?"1":"0";
356     }
359     /* Want certificate= */
360     if (isset($_POST['edit_cert'])){
362       /* Save original values for later reconstruction */
363       foreach (array("certificateSerialNumber", "userCertificate",
364             "userSMIMECertificate", "userPKCS12") as $val){
366         $oval= "old_$val";
367         $this->$oval= $this->$val;
368       }
370       $this->cert_dialog= TRUE;
371       $this->dialog= TRUE;
372     }
375     /* Cancel certificate dialog */
376     if (isset($_POST['cert_edit_cancel'])){
378       /* Restore original values in case of 'cancel' */
379       foreach (array("certificateSerialNumber", "userCertificate",
380             "userSMIMECertificate", "userPKCS12") as $val){
382         $oval= "old_$val";
383         $this->$val= $this->$oval;
384       }
385       $this->cert_dialog= FALSE;
386       $this->dialog= FALSE;
387     }
390     /* Remove certificate? */
391     foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
392       if (isset($_POST["remove_$val"])){
394         /* Reset specified cert*/
395         $this->$val= "";
396         $this->is_modified= TRUE;
397       }
398     }
401     /* Upload new cert and close dialog? */     
402     if (isset($_POST['cert_edit_finish'])){
404       /* for all certificates do */
405       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
406           as $val){
408         /* Check for clean upload */
409         if (array_key_exists($val."_file", $_FILES) &&
410             array_key_exists('name', $_FILES[$val."_file"]) &&
411             $_FILES[$val."_file"]['name'] != "" &&
412             is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
413           $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
414         }
415       }
417       /* Save serial number */
418       if (isset($_POST["certificateSerialNumber"]) &&
419           $_POST["certificateSerialNumber"] != ""){
421         if (!is_id($_POST["certificateSerialNumber"])){
422           print_red (_("Please enter a valid serial number"));
424           foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
425             if ($this->$cert != ""){
426               $smarty->assign("$cert"."_state", "true");
427             } else {
428               $smarty->assign("$cert"."_state", "");
429             }
430           }
431           return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
432         }
434         $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
435         $this->is_modified= TRUE;
436       }
438       $this->cert_dialog= FALSE;
439       $this->dialog= FALSE;
440     }
442     /* Display picture dialog */
443     if ($this->picture_dialog){
444       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
445     }
447     /* Display cert dialog */
448     if ($this->cert_dialog){
449       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
450         if ($this->$cert != ""){
451           /* import certificate */
452           $certificate = new certificate;
453           $certificate->import($this->$cert);
454       
455           /* Read out data*/
456           $timeto   = $certificate->getvalidto_date();
457           $timefrom = $certificate->getvalidfrom_date();
459           /* Additional info if start end time is '0' */
460           $add_str_info = "";
461           if($timeto == 0 && $timefrom == 0){
462             $add_str_info = "<br><i>"._("(Some types of certificates are currently not supported and may be displayed as 'invalid'.)")."</i>";
463           }
465           $str = "<table summary=\"\" border=0>
466                     <tr>
467                       <td style='vertical-align:top'>CN</td>
468                       <td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td>
469                     </tr>
470                   </table><br>".
471                   
472                   sprintf(_("Certificate is valid from %s to %s and is currently %s."), 
473                         "<b>".date('d M Y',$timefrom)."</b>",
474                         "<b>".date('d M Y',$timeto)."</b>", 
475                         $certificate->isvalid()?"<b><font style='color:green'>"._("valid")."</font></b>": 
476                                                 "<b><font style='color:red'>"._("invalid")."</font></b>").$add_str_info;
477           $smarty->assign($cert."info",$str);
478           $smarty->assign($cert."_state","true");
479         } else {
480           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
481           $smarty->assign($cert."_state","");
482         }
483       }
484       $smarty->assign("governmentmode", "false");
485       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
486     }
488     /* Show us the edit screen */
489     @$smarty->assign("bases", $this->allowedBasesToMoveTo());
490 #  $smarty->assign("bases", $this->config->idepartments);
491     $smarty->assign("base_select",      $this->base);
492     $smarty->assign("selectmode",       chkacl($this->acl, "create"));
493     $smarty->assign("certificatesACL",  chkacl($this->acl, "certificates"));
494     $smarty->assign("jpegPhotoACL",     chkacl($this->acl, "jpegPhoto"));
496     /* Prepare password hashes */
497     if ($this->pw_storage == ""){
498       $this->pw_storage= $this->config->current['HASH'];
499     }
501     $temp   = @passwordMethod::get_available_methods();
502     $hashes = $temp['name'];
503     
504     $smarty->assign("pwmode", $hashes);
505     $smarty->assign("pwmode_select", $this->pw_storage);
506     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
508     /* Load attributes and acl's */
509     foreach($this->attributes as $val){
510       $smarty->assign("$val", $this->$val);
511       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
512     }
514     /* Save government mode attributes */
515     if (isset($this->config->current['GOVERNMENTMODE']) &&
516         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
517       $smarty->assign("governmentmode", "true");
518       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
519           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
520       $smarty->assign("ivbbmodes", $ivbbmodes);
521       foreach ($this->govattrs as $val){
522         $smarty->assign("$val", $this->$val);
523         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
524       }
525     } else {
526       $smarty->assign("governmentmode", "false");
527     }
529     /* Special mode for uid */
530     $uidACL= "";
531     if (isset ($this->dn)){
532       if ($this->dn != "new"){
533         $uidACL="readonly";
534       }
535     }  else {
536       $uidACL= "readonly";
537     }
538     $uidACL.= " ".chkacl($this->acl, "uid");
539     
540     $smarty->assign("uidACL", $uidACL);
541     $smarty->assign("is_template", $this->is_template);
542     $smarty->assign("use_dob", $this->use_dob);
544     if (isset($this->parent)){
545       if (isset($this->parent->by_object['phoneAccount']) &&
546           $this->parent->by_object['phoneAccount']->is_account){
547         $smarty->assign("has_phoneaccount", "true");
548       } else {
549         $smarty->assign("has_phoneaccount", "false");
550       }
551     } else {
552       $smarty->assign("has_phoneaccount", "false");
553     }
554     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
555   }
558   /* remove object from parent */
559   function remove_from_parent()
560   {
561     $ldap= $this->config->get_ldap_link();
562     $ldap->rmdir ($this->dn);
563     show_ldap_error($ldap->get_error(), _("Removing generic user account failed"));
565     /* Delete references to groups */
566     $ldap->cd ($this->config->current['BASE']);
567     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
568     while ($ldap->fetch()){
569       $g= new group($this->config, $ldap->getDN());
570       $g->removeUser($this->uid);
571       $g->save ();
572     }
574     /* Delete references to object groups */
575     $ldap->cd ($this->config->current['BASE']);
576     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
577     while ($ldap->fetch()){
578       $og= new ogroup($this->config, $ldap->getDN());
579       unset($og->member[$this->dn]);
580       $og->save ();
581     }
583     /* Kerberos server defined? */
584     if (isset($this->config->data['SERVERS']['KERBEROS'])){
585       $cfg= $this->config->data['SERVERS']['KERBEROS'];
586     }
587     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
589       /* Connect to the admin interface */
590       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
591           $cfg['ADMIN'], $cfg['PASSWORD']);
593       /* Errors? */             
594       if ($handle === FALSE){
595         print_red (_("Kerberos database communication failed"));
596         return (2);
597       }
599       /* Build user principal, get list of existsing principals */
600       $principal= $this->uid."@".$cfg['REALM'];
601       $principals = kadm5_get_principals($handle);
603       /* User exists in database? */
604       if (in_array($principal, $principals)){
606         /* Ok. User exists. Remove him/her */
607           $ret= kadm5_delete_principal ( $handle, $principal);
608           if ($ret === FALSE){
609             print_red (_("Can't remove user from kerberos database."));
610           }
611       }
613       /* Free kerberos admin handle */
614       kadm5_destroy($handle);
615     }
618     /* Optionally execute a command after we're done */
619     $this->handle_post_events("remove",array("uid" => $this->uid));
620   }
623   /* Save data to object */
624   function save_object()
625   {
626     if (isset($_POST['generic'])){
628       /* Parents save function */
629       plugin::save_object ();
631       /* Save government mode attributes */
632       if ($this->config->current['GOVERNMENTMODE']){
633         foreach ($this->govattrs as $val){
634           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
635             $data= stripcslashes($_POST["$val"]);
636             if ($data != $this->$val){
637               $this->is_modified= TRUE;
638             }
639             $this->$val= $data;
640           }
641         }
642       }
644       /* In template mode, the uid is autogenerated... */
645       if ($this->is_template){
646         $this->uid= strtolower($this->sn);
647         $this->givenName= $this->sn;
648       }
650       /* Save base and pw_storage, since these are no LDAP attributes */
651       if (isset($_POST['base'])){
652         foreach(array("base", "pw_storage") as $val){
653           if(isset($_POST[$val])){
654             $data= validate($_POST[$val]);
655             if ($data != $this->$val){
656               $this->is_modified= TRUE;
657             }
658             $this->$val= $data;
659           }
660         }
661       }
662     }
663   }
665   function rebind($ldap, $referral)
666   {
667     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
668     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
669       $this->error = "Success";
670       $this->hascon=true;
671       $this->reconnect= true;
672       return (0);
673     } else {
674       $this->error = "Could not bind to " . $credentials['ADMIN'];
675       return NULL;
676     }
677   }
679   /* Save data to LDAP, depending on is_account we save or delete */
680   function save()
681   {
682     /* Only force save of changes .... 
683        If this attributes aren't changed, avoid saving.
684      */
685     if($this->gender=="0") $this->gender ="";
686     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
687     
688  
689     /* First use parents methods to do some basic fillup in $this->attrs */
690     plugin::save ();
692     if ($this->use_dob == "1"){
693       /* 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. */
694       if(!is_array($this->attrs['dateOfBirth'])) {
695         $this->attrs['dateOfBirth']= date("Y-m-d", $this->attrs['dateOfBirth']);
696       }
697     }
698     /* Remove additional objectClasses */
699     $tmp= array();
700     foreach ($this->attrs['objectClass'] as $key => $set){
701       $found= false;
702       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
703         if (preg_match ("/^$set$/i", $val)){
704           $found= true;
705           break;
706         }
707       }
708       if (!$found){
709         $tmp[]= $set;
710       }
711     }
713     /* Replace the objectClass array. This is done because of the
714        separation into government and normal mode. */
715     $this->attrs['objectClass']= $tmp;
717     /* Add objectClasss for template mode? */
718     if ($this->is_template){
719       $this->attrs['objectClass'][]= "gosaUserTemplate";
720     }
722     /* Hard coded government mode? */
723     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
724       $this->attrs['objectClass'][]= "ivbbentry";
726       /* Copy standard attributes */
727       foreach ($this->govattrs as $val){
728         if ($this->$val != ""){
729           $this->attrs["$val"]= $this->$val;
730         } elseif (!$this->new) {
731           $this->attrs["$val"]= array();
732         }
733       }
735       /* Remove attribute if set to "nein" */
736       if ($this->publicVisible == "nein"){
737         $this->attrs['publicVisible']= array();
738         if($this->new){
739           unset($this->attrs['publicVisible']);
740         }else{
741           $this->attrs['publicVisible']=array();
742         }
744       }
746     }
748     /* Special handling for attribute userCertificate needed */
749     if ($this->userCertificate != ""){
750       $this->attrs["userCertificate;binary"]= $this->userCertificate;
751       $remove_userCertificate= false;
752     } else {
753       $remove_userCertificate= true;
754     }
756     /* Special handling for dateOfBirth value */
757     if ($this->use_dob != "1"){
758       if ($this->new) {
759         unset($this->attrs["dateOfBirth"]);
760       } else {
761         $this->attrs["dateOfBirth"]= array();
762       }
763     }
764     if (!$this->gender){
765       if ($this->new) {
766         unset($this->attrs["gender"]);
767       } else {
768         $this->attrs["gender"]= array();
769       }
770     }
771     if (!$this->preferredLanguage){
772       if ($this->new) {
773         unset($this->attrs["preferredLanguage"]);
774       } else {
775         $this->attrs["preferredLanguage"]= array();
776       }
777     }
779     /* Special handling for attribute jpegPhote needed, scale image via
780        image magick to 147x200 pixels and inject resulting data. */
781     if ($this->jpegPhoto != "*removed*"){
783       /* Fallback if there's no image magick inside PHP */
784       if (!function_exists("imagick_blob2image")){
785         /* Get temporary file name for conversation */
786         $fname = tempnam ("/tmp", "GOsa");
788         /* Open file and write out photoData */
789         $fp = fopen ($fname, "w");
790         fwrite ($fp, $this->photoData);
791         fclose ($fp);
793         /* Build conversation query. Filename is generated automatically, so
794            we do not need any special security checks. Exec command and save
795            output. For PHP safe mode, you'll need a configuration which respects
796            image magick as executable... */
797         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
798         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
799             $query, "Execute");
801         /* Read data written by convert */
802         $output= "";
803         $sh= popen($query, 'r');
804         while (!feof($sh)){
805           $output.= fread($sh, 4096);
806         }
807         pclose($sh);
809         unlink($fname);
811         /* Save attribute */
812         $this->attrs["jpegPhoto"] = $output;
814       } else {
816         /* Load the new uploaded Photo */
817         if(!$handle  =  imagick_blob2image($this->photoData))  {
818           gosa_log("Can't Load image");
819         }
821         /* Resizing image to 147x200 and blur */
822         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
823           gosa_log("imagick_resize failed");
824         }
826         /* Converting image to JPEG */
827         if(!imagick_convert($handle,"JPEG")) {
828           gosa_log("Can't Convert to JPEG");
829         }
831         /* Creating binary Code for the Image */
832         if(!$dump = imagick_image2blob($handle)){
833           gosa_log("Can't create blob for image");
834         }
836         /* Sending Image */
837         $output=  $dump;
839         /* Save attribute */
840         $this->attrs["jpegPhoto"] = $output;
841       }
843     } else{
844       $this->attrs["jpegPhoto"] = array();
845     }
847     /* Build new dn */
848     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
849       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
850     } else {
851       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
852     }
854     /* This only gets called when user is renaming himself */
855     $ldap= $this->config->get_ldap_link();
856     if ($this->dn != $new_dn){
858       /* Write entry on new 'dn' */
859       $this->move($this->dn, $new_dn);
861       /* Happen to use the new one */
862       change_ui_dn($this->dn, $new_dn);
863       $this->dn= $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. */
961         if ($this->pw_storage == "kerberos"){
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     $this->cn= $this->givenName." ".$this->sn;
998     /* Permissions for that base? */
999     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
1000       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
1001     } else {
1002       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
1003     }
1005     $ui= get_userinfo();
1006     $acl= get_permissions ($new_dn, $ui->subtreeACL);
1007     $acl= get_module_permission($acl, "user", $new_dn);
1008     if ($this->dn == "new" && chkacl($acl, "create") != ""){
1009       $message[]= _("You have no permissions to create a user on this 'Base'.");
1010     } elseif ($this->dn != $new_dn && $this->dn != "new"){
1011       $acl= get_permissions ($this->dn, $ui->subtreeACL);
1012       $acl= get_module_permission($acl, "user", $this->dn);
1013       if (chkacl($acl, "create") != ""){
1014         $message[]= _("You have no permissions to move a user from the original 'Base'.");
1015       }
1016     }
1018     /* must: sn, givenName, uid */
1019     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
1020       $message[]= _("The required field 'Name' is not set.");
1021     }
1023     /* UID already used? */
1024     $ldap= $this->config->get_ldap_link();
1025     $ldap->cd($this->config->current['BASE']);
1026     $ldap->search("(uid=$this->uid)", array("uid"));
1027     $ldap->fetch();
1028     if ($ldap->count() != 0 && $this->dn == 'new'){
1029       $message[]= _("There's already a person with this 'Login' in the database.");
1030     }
1032     /* In template mode, the uid and givenName are autogenerated... */
1033     if (!$this->is_template){
1034       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
1035         $message[]= _("The required field 'Given name' is not set.");
1036       }
1037       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
1038         $message[]= _("The required field 'Login' is not set.");
1039       }
1040       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
1041         $ldap->cd($this->config->current['BASE']);
1042         $ldap->search("(cn=".$this->cn.")", array("uid"));
1043         $ldap->fetch();
1044         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
1045           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
1046         }
1047       }
1048     }
1050     /* Check for valid input */
1051     if ($this->is_modified && !is_uid($this->uid)){
1052       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
1053     }
1054     if (!is_url($this->labeledURI)){
1055       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
1056     }
1057     if (preg_match ("/[\\\\]/", $this->sn)){
1058       $message[]= _("The field 'Name' contains invalid characters.");
1059     }
1060     if (preg_match ("/[\\\\]/", $this->givenName)){
1061       $message[]= _("The field 'Given name' contains invalid characters.");
1062     }
1064     /* Check phone numbers */
1065     if (!is_phone_nr($this->telephoneNumber)){
1066       $message[]= _("The field 'Phone' contains an invalid phone number.");
1067     }
1068     if (!is_phone_nr($this->facsimileTelephoneNumber)){
1069       $message[]= _("The field 'Fax' contains an invalid phone number.");
1070     }
1071     if (!is_phone_nr($this->mobile)){
1072       $message[]= _("The field 'Mobile' contains an invalid phone number.");
1073     }
1074     if (!is_phone_nr($this->pager)){
1075       $message[]= _("The field 'Pager' contains an invalid phone number.");
1076     }
1078     /* Check for reserved characers */
1079     if (preg_match ('/[,+"?\'()=<>;]/', $this->givenName)){
1080       $message[]= _("The field 'Given name' contains invalid characters.");
1081     }
1082     if (preg_match ('/[,+"?\'()=<>;]/', $this->sn)){
1083       $message[]= _("The field 'Name' contains invalid characters.");
1084     }
1086   return $message;
1087   }
1090   /* Indicate whether a password change is needed or not */
1091   function password_change_needed()
1092   {
1093     return ($this->pw_storage != $this->last_pw_storage);
1094   }
1097   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1098   function load_picture()
1099   {
1100     /* make connection and read jpegPhoto */
1101     $ds= ldap_connect($this->config->current['SERVER']);
1102     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1103     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1104       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1105       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1106     }
1108     if(isset($this->config->current['TLS']) &&
1109         $this->config->current['TLS'] == "true"){
1111       ldap_start_tls($ds);
1112     }
1114     $r= ldap_bind($ds);
1115     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
1117     /* in case we don't get an entry, load a default picture */
1118     $this->set_picture ("./images/default.jpg");
1119     $this->jpegPhoto= "*removed*";
1121     /* fill data from LDAP */
1122     if ($sr) {
1123       $ei=ldap_first_entry($ds, $sr);
1124       if ($ei) {
1125         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
1126           $this->photoData= $info[0];
1127           $_SESSION['binary']= $this->photoData;
1128           $_SESSION['binarytype']= "image/jpeg";
1129           $this->jpegPhoto= "";
1130         }
1131       }
1132     }
1134     /* close conncetion */
1135     ldap_unbind($ds);
1136   }
1139   /* Load a certificate from LDAP, this is going to be simplified later on */
1140   function load_cert()
1141   {
1142     $ds= ldap_connect($this->config->current['SERVER']);
1143     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1144     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1145       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1146       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1147     }
1148     if(isset($this->config->current['TLS']) &&
1149         $this->config->current['TLS'] == "true"){
1151       ldap_start_tls($ds);
1152     }
1154     $r= ldap_bind($ds);
1155     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1157     if ($sr) {
1158       $ei= @ldap_first_entry($ds, $sr);
1159       
1160       if ($ei) {
1161         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1162           $this->userCertificate= "";
1163         } else {
1164           $this->userCertificate= $info[0];
1165         }
1166       }
1167     } else {
1168       $this->userCertificate= "";
1169     }
1171     ldap_unbind($ds);
1172   }
1175   /* Load picture from file to object */
1176   function set_picture($filename ="")
1177   {
1178     if (!is_file($filename) || $filename == ""){
1179       $filename= "./images/default.jpg";
1180       $this->jpegPhoto= "*removed*";
1181     }
1183     $fd = fopen ($filename, "rb");
1184     $this->photoData= fread ($fd, filesize ($filename));
1185     $_SESSION['binary']= $this->photoData;
1186     $_SESSION['binarytype']= "image/jpeg";
1187     $this->jpegPhoto= "";
1189     fclose ($fd);
1190   }
1193   /* Load certificate from file to object */
1194   function set_cert($cert, $filename)
1195   {
1196     $fd = fopen ($filename, "rb");
1197     if (filesize($filename)>0) {
1198       $this->$cert= fread ($fd, filesize ($filename));
1199       fclose ($fd);
1200       $this->is_modified= TRUE;
1201     } else {
1202       print_red(_("Could not open specified certificate!"));
1203     }
1204   }
1206   /* Adapt from given 'dn' */
1207   function adapt_from_template($dn)
1208   {
1209     plugin::adapt_from_template($dn);
1211     /* Get base */
1212     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1214     if ($this->config->current['GOVERNMENTMODE']){
1216       /* Walk through govattrs */
1217       foreach ($this->govattrs as $val){
1219         if (isset($this->attrs["$val"][0])){
1221           /* If attribute is set, replace dynamic parts: 
1222              %sn, %givenName and %uid. Fill these in our local variables. */
1223           $value= $this->attrs["$val"][0];
1225           foreach (array("sn", "givenName", "uid") as $repl){
1226             if (preg_match("/%$repl/i", $value)){
1227               $value= preg_replace ("/%$repl/i",
1228                   $this->parent->$repl, $value);
1229             }
1230           }
1231           $this->$val= $value;
1232         }
1233       }
1234     }
1236     /* Get back uid/sn/givenName */
1237     if ($this->parent != NULL){
1238       $this->uid= $this->parent->uid;
1239       $this->sn= $this->parent->sn;
1240       $this->givenName= $this->parent->givenName;
1241     }
1242   }
1244  
1245   /* This avoids that users move themselves out of their rights. 
1246    */
1247   function allowedBasesToMoveTo()
1248   {
1249     $allowed = array();
1250     $ret_all = false;
1251     if($this->uid == $_SESSION['ui']->username){
1252       $ldap= $this->config->get_ldap_link(); 
1253       $ldap->cd($this->config->current['BASE']); 
1254       $ldap->search("(&(objectClass=posixGroup)(memberUid=".$_SESSION['ui']->username."))",array("gosaSubtreeACL"));
1255        
1256       while($attrs = $ldap->fetch()){
1257     
1258         if(isset($attrs['gosaSubtreeACL'])){
1259         
1260           foreach($attrs['gosaSubtreeACL'] as $attr){
1261             if((preg_match("/:user#/",$attr))||(preg_match("/:all/",$attr))){
1262               $s =  preg_replace("/^.*".get_groups_ou().",/","",$attrs['dn']);
1264               foreach($this->config->idepartments as $key => $dep) {
1265                 if(preg_match("/".$s."/i",$key)){
1266                   $allowed[$key] = $dep;
1267                 }
1268               }
1269             }
1270           }
1271         }
1272       }
1273       if(count($allowed) == 0){
1274         foreach($this->config->idepartments as $key => $dep) {
1275           if($this->base==$key){
1276             $allowed[$key] = $dep;
1277           }
1278         }
1279       }  
1280   
1281       return($allowed);
1282       
1283     }else{
1284       return($this->config->idepartments);
1285     }
1286   } 
1289   function getCopyDialog()
1290   {
1291     $str = "";
1293     $_SESSION['binary'] = $this->photoData; 
1294     $_SESSION['binarytype']= "image/jpeg";
1296     /* Get random number for pictures */
1297     srand((double)microtime()*1000000); 
1298     $rand = rand(0, 10000);
1300     $smarty = get_smarty();
1302     $smarty->assign("passwordTodo","clear");
1304     if(isset($_POST['passwordTodo'])){
1305       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1306     }
1308     $smarty->assign("sn",       $this->sn);
1309     $smarty->assign("givenName",$this->givenName);
1310     $smarty->assign("uid",      $this->uid);
1311     $smarty->assign("rand",     $rand);
1312     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1315     $ret = array();
1316     $ret['string'] = $str;
1317     $ret['status'] = "";  
1318     return($ret);
1319   }
1321   function saveCopyDialog()
1322   {
1324     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1325       $this->set_picture($_FILES['picture_file']['tmp_name']);
1326     }
1328     /* Remove picture? */
1329     if (isset($_POST['picture_remove'])){
1330       $this->jpegPhoto= "*removed*";
1331       $this->set_picture ("./images/default.jpg");
1332       $this->is_modified= TRUE;
1333     }
1335     $attrs = array("uid","givenName","sn");
1336     foreach($attrs as $attr){
1337       if(isset($_POST[$attr])){
1338         $this->$attr = $_POST[$attr];
1339       }
1340     } 
1341   }
1344   function PrepareForCopyPaste($source)
1345   {
1346     plugin::PrepareForCopyPaste($source);
1348     /* Reset certificate information addepted from source user
1349         to avoid setting the same user certificate for the destination user. */
1350     $this->userPKCS12= "";
1351     $this->userSMIMECertificate= "";
1352     $this->userCertificate= "";
1353     $this->certificateSerialNumber= "";
1354     $this->old_certificateSerialNumber= "";
1355     $this->old_userPKCS12= "";
1356     $this->old_userSMIMECertificate= "";
1357     $this->old_userCertificate= "";
1358   }
1361 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1362 ?>