Code

Ensure that %ou is not interpreted as %o with leading char "u" in postcreate/modify...
[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 $cn= "";
22   var $personalTitle= "";
23   var $academicTitle= "";
24   var $homePostalAddress= "";
25   var $homePhone= "";
26   var $labeledURI= "";
27   var $o= "";
28   var $ou= "";
29   var $departmentNumber= "";
30   var $employeeNumber= "";
31   var $employeeType= "";
32   var $roomNumber= "";
33   var $telephoneNumber= "";
34   var $facsimileTelephoneNumber= "";
35   var $mobile= "";
36   var $pager= "";
37   var $l= "";
38   var $st= "";
39   var $postalAddress= "";
40   var $dateOfBirth;
41   var $use_dob= "0";
42   var $gender="0";
43   var $preferredLanguage="0";
45   var $jpegPhoto= "*removed*";
46   var $photoData= "";
47   var $old_jpegPhoto= "";
48   var $old_photoData= "";
49   var $cert_dialog= FALSE;
50   var $picture_dialog= FALSE;
52   var $userPKCS12= "";
53   var $userSMIMECertificate= "";
54   var $userCertificate= "";
55   var $certificateSerialNumber= "";
56   var $old_certificateSerialNumber= "";
57   var $old_userPKCS12= "";
58   var $old_userSMIMECertificate= "";
59   var $old_userCertificate= "";
61   var $gouvernmentOrganizationalUnit= "";
62   var $houseIdentifier= "";
63   var $street= "";
64   var $postalCode= "";
65   var $vocation= "";
66   var $ivbbLastDeliveryCollective= "";
67   var $gouvernmentOrganizationalPersonLocality= "";
68   var $gouvernmentOrganizationalUnitDescription= "";
69   var $gouvernmentOrganizationalUnitSubjectArea= "";
70   var $functionalTitle= "";
71   var $role= "";
72   var $publicVisible= "";
74   var $dialog;
76   /* variables to trigger password changes */
77   var $pw_storage= "crypt";
78   var $last_pw_storage= "unset";
79   var $had_userCertificate= FALSE;
81   /* attribute list for save action */
82   var $attributes= array("sn", "givenName", "uid", "personalTitle", "academicTitle",
83       "homePostalAddress", "homePhone", "labeledURI", "ou", "o", "dateOfBirth", "gender","preferredLanguage",
84       "departmentNumber", "employeeNumber", "employeeType", "l", "st","jpegPhoto",
85       "roomNumber", "telephoneNumber", "mobile", "pager", "cn", "userPKCS12",
86       "postalAddress", "facsimileTelephoneNumber", "userSMIMECertificate");
88   var $objectclasses= array("top", "person", "organizationalPerson", "inetOrgPerson",
89       "gosaAccount");
91   /* attributes that are part of the government mode */
92   var $govattrs= array("gouvernmentOrganizationalUnit", "houseIdentifier", "vocation",
93       "ivbbLastDeliveryCollective", "gouvernmentOrganizationalPersonLocality",
94       "gouvernmentOrganizationalUnitDescription","gouvernmentOrganizationalUnitSubjectArea",
95       "functionalTitle", "certificateSerialNumber", "publicVisible", "street", "role",
96       "postalCode");
99   /* constructor, if 'dn' is set, the node loads the given
100      'dn' from LDAP */
101   function user ($config, $dn= NULL)
102   {
103     $this->config= $config;
104     /* Configuration is fine, allways */
105     if ($this->config->current['GOVERNMENTMODE']){
106       $this->attributes=array_merge($this->attributes,$this->govattrs);
107     }
109     /* Load base attributes */
110     plugin::plugin ($config, $dn);
112     if ($this->config->current['GOVERNMENTMODE']){
113       /* Fix public visible attribute if unset */
114       if (!isset($this->attrs['publicVisible'])){
115         $this->publicVisible == "nein";
116       }
117     }
119     /* Load government mode attributes */
120     if ($this->config->current['GOVERNMENTMODE']){
121       /* Copy all attributs */
122       foreach ($this->govattrs as $val){
123         if (isset($this->attrs["$val"][0])){
124           $this->$val= $this->attrs["$val"][0];
125         }
126       }
127     }
129     /* Create me for new accounts */
130     if ($dn == "new"){
131       $this->is_account= TRUE;
132     }
134     /* Make hash default to md5 if not set in config */
135     if (!isset($this->config->current['HASH'])){
136       $hash= "md5";
137     } else {
138       $hash= $this->config->current['HASH'];
139     }
141     /* Load data from LDAP? */
142     if ($dn != NULL){
144       /* Do base conversation */
145       if ($this->dn == "new"){
146         $ui= get_userinfo();
147         $this->base= dn2base($ui->dn);
148       } else {
149         $this->base= dn2base($dn);
150       }
152       /* get password storage type */
153       if (isset ($this->attrs['userPassword'][0])){
154         /* Initialize local array */
155         $matches= array();
156         if (preg_match ("/^{([^}]+)}(.+)/", $this->attrs['userPassword'][0], $matches)){
157           $this->pw_storage= strtolower($matches[1]);
158         } else {
159           if ($this->attrs['userPassword'][0] != ""){
160             $this->pw_storage= "clear";
161           } else {
162             $this->pw_storage= $hash;
163           }
164         }
165       } else {
166         /* Preset with vaule from configuration */
167         $this->pw_storage= $hash;
168       }
170       /* Load extra attributes: certificate and picture */
171       $this->load_picture();
172       $this->load_cert();
173       if ($this->userCertificate != ""){
174         $this->had_userCertificate= TRUE;
175       }
176     }
178     /* Reset password storage indicator, used by password_change_needed() */
179     if ($dn == "new"){
180       $this->last_pw_storage= "unset";
181     } else {
182       $this->last_pw_storage= $this->pw_storage;
183     }
185     /* Generate dateOfBirth entry */
186     if (isset ($this->attrs['dateOfBirth'])){
187       /* This entry is ISO 8601 conform */
188       list($year, $month, $day)= split("-", $this->attrs['dateOfBirth'][0], 3);
189     
190       $this->dateOfBirth=array( 'mon'=> $month,"mday"=> $day,"year"=> $year);
191       $this->use_dob= "1";
192     } else {
193       $this->use_dob= "0";
194     }
196     /* Put gender attribute to upper case */
197     if (isset ($this->attrs['gender'])){
198       $this->gender= strtoupper($this->attrs['gender'][0]);
199     }
200   }
203   /* execute generates the html output for this node */
204   function execute()
205   {
206     /* Call parent execute */
207     plugin::execute();
209     $smarty= get_smarty();
211     /* Fill calendar */
212     if ($this->dateOfBirth == "0"){
213       $date= getdate();
214     } else {
215       if(is_array($this->dateOfBirth)){
216         $date = $this->dateOfBirth;
217   
218         // Trigger on dates like 1985-04-01, getdate only understands timestamps
219       } else if (!empty($this->dateOfBirth) && !is_numeric($this->dateOfBirth)){
220         $date= getdate(strtotime($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){
654           if(isset($_POST[$val]) && chkacl ($this->acl, "$val") == ""){
655             $data= validate($_POST[$val]);
656             if ($data != $this->$val){
657               $this->is_modified= TRUE;
658             }
659             $this->$val= $data;
660           }
661         }
662       }
663     }
664   }
666   function rebind($ldap, $referral)
667   {
668     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
669     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
670       $this->error = "Success";
671       $this->hascon=true;
672       $this->reconnect= true;
673       return (0);
674     } else {
675       $this->error = "Could not bind to " . $credentials['ADMIN'];
676       return NULL;
677     }
678   }
680   /* Save data to LDAP, depending on is_account we save or delete */
681   function save()
682   {
683     /* Only force save of changes .... 
684        If this attributes aren't changed, avoid saving.
685      */
686     if($this->gender=="0") $this->gender ="";
687     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
688     
689  
690     /* First use parents methods to do some basic fillup in $this->attrs */
691     plugin::save ();
693     if ($this->use_dob == "1"){
694       /* 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. */
695       if(!is_array($this->attrs['dateOfBirth'])) {
696         $this->attrs['dateOfBirth']= date("Y-m-d", $this->attrs['dateOfBirth']);
697       }
698     }
699     /* Remove additional objectClasses */
700     $tmp= array();
701     foreach ($this->attrs['objectClass'] as $key => $set){
702       $found= false;
703       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
704         if (preg_match ("/^$set$/i", $val)){
705           $found= true;
706           break;
707         }
708       }
709       if (!$found){
710         $tmp[]= $set;
711       }
712     }
714     /* Replace the objectClass array. This is done because of the
715        separation into government and normal mode. */
716     $this->attrs['objectClass']= $tmp;
718     /* Add objectClasss for template mode? */
719     if ($this->is_template){
720       $this->attrs['objectClass'][]= "gosaUserTemplate";
721     }
723     /* Hard coded government mode? */
724     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
725       $this->attrs['objectClass'][]= "ivbbentry";
727       /* Copy standard attributes */
728       foreach ($this->govattrs as $val){
729         if ($this->$val != ""){
730           $this->attrs["$val"]= $this->$val;
731         } elseif (!$this->new) {
732           $this->attrs["$val"]= array();
733         }
734       }
736       /* Remove attribute if set to "nein" */
737       if ($this->publicVisible == "nein"){
738         $this->attrs['publicVisible']= array();
739         if($this->new){
740           unset($this->attrs['publicVisible']);
741         }else{
742           $this->attrs['publicVisible']=array();
743         }
745       }
747     }
749     /* Special handling for attribute userCertificate needed */
750     if ($this->userCertificate != ""){
751       $this->attrs["userCertificate;binary"]= $this->userCertificate;
752       $remove_userCertificate= false;
753     } else {
754       $remove_userCertificate= true;
755     }
757     /* Special handling for dateOfBirth value */
758     if ($this->use_dob != "1"){
759       if ($this->new) {
760         unset($this->attrs["dateOfBirth"]);
761       } else {
762         $this->attrs["dateOfBirth"]= array();
763       }
764     }
765     if (!$this->gender){
766       if ($this->new) {
767         unset($this->attrs["gender"]);
768       } else {
769         $this->attrs["gender"]= array();
770       }
771     }
772     if (!$this->preferredLanguage){
773       if ($this->new) {
774         unset($this->attrs["preferredLanguage"]);
775       } else {
776         $this->attrs["preferredLanguage"]= array();
777       }
778     }
780     /* Special handling for attribute jpegPhote needed, scale image via
781        image magick to 147x200 pixels and inject resulting data. */
782     if ($this->jpegPhoto != "*removed*"){
784       /* Fallback if there's no image magick inside PHP */
785       if (!function_exists("imagick_blob2image")){
786         /* Get temporary file name for conversation */
787         $fname = tempnam ("/tmp", "GOsa");
789         /* Open file and write out photoData */
790         $fp = fopen ($fname, "w");
791         fwrite ($fp, $this->photoData);
792         fclose ($fp);
794         /* Build conversation query. Filename is generated automatically, so
795            we do not need any special security checks. Exec command and save
796            output. For PHP safe mode, you'll need a configuration which respects
797            image magick as executable... */
798         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
799         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
800             $query, "Execute");
802         /* Read data written by convert */
803         $output= "";
804         $sh= popen($query, 'r');
805         while (!feof($sh)){
806           $output.= fread($sh, 4096);
807         }
808         pclose($sh);
810         unlink($fname);
812         /* Save attribute */
813         $this->attrs["jpegPhoto"] = $output;
815       } else {
817         /* Load the new uploaded Photo */
818         if(!$handle  =  imagick_blob2image($this->photoData))  {
819           gosa_log("Can't Load image");
820         }
822         /* Resizing image to 147x200 and blur */
823         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
824           gosa_log("imagick_resize failed");
825         }
827         /* Converting image to JPEG */
828         if(!imagick_convert($handle,"JPEG")) {
829           gosa_log("Can't Convert to JPEG");
830         }
832         /* Creating binary Code for the Image */
833         if(!$dump = imagick_image2blob($handle)){
834           gosa_log("Can't create blob for image");
835         }
837         /* Sending Image */
838         $output=  $dump;
840         /* Save attribute */
841         $this->attrs["jpegPhoto"] = $output;
842       }
844     } else{
845       $this->attrs["jpegPhoto"] = array();
846     }
848     /* Build new dn */
849     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
850       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
851     } else {
852       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
853     }
855     /* This only gets called when user is renaming himself */
856     $ldap= $this->config->get_ldap_link();
857     if ($this->dn != $new_dn){
859       /* Write entry on new 'dn' */
860       $this->move($this->dn, $new_dn);
862       /* Happen to use the new one */
863       change_ui_dn($this->dn, $new_dn);
864       $this->dn= $new_dn;
865     }
868     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
869        new entries. So do a check first... */
870     $ldap->cat ($this->dn, array('dn'));
871     if ($ldap->fetch()){
872       $mode= "modify";
873     } else {
874       $mode= "add";
875       $ldap->cd($this->config->current['BASE']);
876       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
877     }
879     /* Set password to some junk stuff in case of templates */
880     if ($this->is_template){
881       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
882     }
884     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
885         $this->attributes, "Save via $mode");
887     /* Finally write data with selected 'mode' */
888     $this->cleanup();
889     $ldap->cd ($this->dn);
890     $ldap->$mode ($this->attrs);
891     if (show_ldap_error($ldap->get_error(), _("Saving generic user account failed"))){
892       return (1);
893     }
895     /* Remove cert? 
896        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
897        to work around myself. */
898     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
900       /* Reset array, assemble new, this should be reworked */
901       $this->attrs= array();
902       $this->attrs['userCertificate;binary']= array();
904       /* Prepare connection */
905       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
906         die ("Could not connect to LDAP server");
907       }
908       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
909       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
910         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
911         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
912       }
913       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
914         ldap_start_tls($ds);
915       }
916       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
917               $this->config->current['PASSWORD']))) {
918         die ("Could not bind to LDAP");
919       }
921       /* Modify using attrs */
922       ldap_mod_del($ds,$this->dn,$this->attrs);
923       ldap_close($ds);
924     }
926     /* Kerberos server defined? */
927     if (isset($this->config->data['SERVERS']['KERBEROS'])){
928       $cfg= $this->config->data['SERVERS']['KERBEROS'];
929     }
930     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
932       /* Connect to the admin interface */
933       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
934           $cfg['ADMIN'], $cfg['PASSWORD']);
936       /* Errors? */             
937       if ($handle === FALSE){
938         print_red (_("Kerberos database communication failed"));
939         return (2);
940       }
942       /* Build user principal, get list of existsing principals */
943       $principal= $this->uid."@".$cfg['REALM'];
944       $principals = kadm5_get_principals($handle);
946       /* User exists in database? */
947       if (in_array($principal, $principals)){
949         /* Ok. User exists. Remove him/her when pw_storage has
950            changed to be NOT kerberos. */
951         if ($this->pw_storage != $this->config->current['KRBSASL']){
952           $ret= kadm5_delete_principal ( $handle, $principal);
954           if ($ret === FALSE){
955             print_red (_("Can't remove user from kerberos database."));
956           }
957         }
959       } else {
961         /* User doesn't exists, create it when pw_storage is kerberos or SASL. */
962         if ($this->pw_storage == "kerberos" || $this->pw_storage == "sasl" ){
963           $ret= kadm5_create_principal ( $handle, $principal);
965           if ($ret === FALSE){
966             print_red (_("Can't add user to kerberos database."));
967           }
968         }
970       }
972       /* Free kerberos admin handle */
973       kadm5_destroy($handle);
974     }
976     /* Optionally execute a command after we're done */
977     if ($mode == "add"){
978       $this->handle_post_events("add",array("uid" => $this->uid));
979     } elseif ($this->is_modified){
980       $this->handle_post_events("modify",array("uid" => $this->uid));
981     }
983     /* Fix tagging if needed */
984     $this->handle_object_tagging();
986     return (0);
987   }
990   /* Check formular input */
991   function check()
992   {
993     /* Call common method to give check the hook */
994     $message= plugin::check();
996     /* Assemble cn */
997     $pt= "";
998     if(isset($this->config->current['INCLUDE_PERSONAL_TITLE']) && preg_match("/true/i",$this->config->current['INCLUDE_PERSONAL_TITLE'])){
999       if(!empty($this->personalTitle)){
1000         $pt = $this->personalTitle." ";
1001       }
1002     }
1003     
1004     $this->cn= $pt.$this->givenName." ".$this->sn;
1006     /* Permissions for that base? */
1007     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
1008       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
1009     } else {
1010       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
1011     }
1013     $ui= get_userinfo();
1014     $acl= get_permissions ($new_dn, $ui->subtreeACL);
1015     $acl= get_module_permission($acl, "user", $new_dn);
1016     if ($this->dn == "new" && chkacl($acl, "create") != ""){
1017       $message[]= _("You have no permissions to create a user on this 'Base'.");
1018     } elseif ($this->dn != $new_dn && $this->dn != "new"){
1019       $acl= get_permissions ($this->dn, $ui->subtreeACL);
1020       $acl= get_module_permission($acl, "user", $this->dn);
1021       if (chkacl($acl, "create") != ""){
1022         $message[]= _("You have no permissions to move a user from the original 'Base'.");
1023       }
1024     }
1026     /* must: sn, givenName, uid */
1027     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
1028       $message[]= _("The required field 'Name' is not set.");
1029     }
1031     /* UID already used? */
1032     $ldap= $this->config->get_ldap_link();
1033     $ldap->cd($this->config->current['BASE']);
1034     $ldap->search("(uid=$this->uid)", array("uid"));
1035     $ldap->fetch();
1036     if ($ldap->count() != 0 && $this->dn == 'new'){
1037       $message[]= _("There's already a person with this 'Login' in the database.");
1038     }
1040     /* In template mode, the uid and givenName are autogenerated... */
1041     if (!$this->is_template){
1042       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
1043         $message[]= _("The required field 'Given name' is not set.");
1044       }
1045       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
1046         $message[]= _("The required field 'Login' is not set.");
1047       }
1048       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
1049         $ldap->cd($this->config->current['BASE']);
1050         $ldap->search("(cn=".$this->cn.")", array("uid"));
1051         $ldap->fetch();
1052         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
1053           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
1054         }
1055       }
1056     }
1058     /* Check for valid input */
1059     if ($this->is_modified && !is_uid($this->uid)){
1060       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
1061     }
1062     if (!is_url($this->labeledURI)){
1063       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
1064     }
1065     if (preg_match ("/[\\\\]/", $this->sn)){
1066       $message[]= _("The field 'Name' contains invalid characters.");
1067     }
1068     if (preg_match ("/[\\\\]/", $this->givenName)){
1069       $message[]= _("The field 'Given name' contains invalid characters.");
1070     }
1072     /* Check phone numbers */
1073     if (!is_phone_nr($this->telephoneNumber)){
1074       $message[]= _("The field 'Phone' contains an invalid phone number.");
1075     }
1076     if (!is_phone_nr($this->facsimileTelephoneNumber)){
1077       $message[]= _("The field 'Fax' contains an invalid phone number.");
1078     }
1079     if (!is_phone_nr($this->mobile)){
1080       $message[]= _("The field 'Mobile' contains an invalid phone number.");
1081     }
1082     if (!is_phone_nr($this->pager)){
1083       $message[]= _("The field 'Pager' contains an invalid phone number.");
1084     }
1086     /* Check for reserved characers */
1087     if (preg_match ('/[,+"?\'()=<>;]/', $this->givenName)){
1088       $message[]= _("The field 'Given name' contains invalid characters.");
1089     }
1090     if (preg_match ('/[,+"?\'()=<>;]/', $this->sn)){
1091       $message[]= _("The field 'Name' contains invalid characters.");
1092     }
1094   return $message;
1095   }
1098   /* Indicate whether a password change is needed or not */
1099   function password_change_needed()
1100   {
1101     return ($this->pw_storage != $this->last_pw_storage);
1102   }
1105   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1106   function load_picture()
1107   {
1108     /* make connection and read jpegPhoto */
1109     $ds= ldap_connect($this->config->current['SERVER']);
1110     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1111     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1112       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1113       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1114     }
1116     if(isset($this->config->current['TLS']) &&
1117         $this->config->current['TLS'] == "true"){
1119       ldap_start_tls($ds);
1120     }
1122     $r= ldap_bind($ds);
1123     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
1125     /* in case we don't get an entry, load a default picture */
1126     $this->set_picture ("./images/default.jpg");
1127     $this->jpegPhoto= "*removed*";
1129     /* fill data from LDAP */
1130     if ($sr) {
1131       $ei=ldap_first_entry($ds, $sr);
1132       if ($ei) {
1133         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
1134           $this->photoData= $info[0];
1135           $_SESSION['binary']= $this->photoData;
1136           $_SESSION['binarytype']= "image/jpeg";
1137           $this->jpegPhoto= "";
1138         }
1139       }
1140     }
1142     /* close conncetion */
1143     ldap_unbind($ds);
1144   }
1147   /* Load a certificate from LDAP, this is going to be simplified later on */
1148   function load_cert()
1149   {
1150     $ds= ldap_connect($this->config->current['SERVER']);
1151     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1152     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1153       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1154       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1155     }
1156     if(isset($this->config->current['TLS']) &&
1157         $this->config->current['TLS'] == "true"){
1159       ldap_start_tls($ds);
1160     }
1162     $r= ldap_bind($ds);
1163     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1165     if ($sr) {
1166       $ei= @ldap_first_entry($ds, $sr);
1167       
1168       if ($ei) {
1169         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1170           $this->userCertificate= "";
1171         } else {
1172           $this->userCertificate= $info[0];
1173         }
1174       }
1175     } else {
1176       $this->userCertificate= "";
1177     }
1179     ldap_unbind($ds);
1180   }
1183   /* Load picture from file to object */
1184   function set_picture($filename ="")
1185   {
1186     if (!is_file($filename) || $filename == ""){
1187       $filename= "./images/default.jpg";
1188       $this->jpegPhoto= "*removed*";
1189     }
1191     $fd = fopen ($filename, "rb");
1192     $this->photoData= fread ($fd, filesize ($filename));
1193     $_SESSION['binary']= $this->photoData;
1194     $_SESSION['binarytype']= "image/jpeg";
1195     $this->jpegPhoto= "";
1197     fclose ($fd);
1198   }
1201   /* Load certificate from file to object */
1202   function set_cert($cert, $filename)
1203   {
1204     $fd = fopen ($filename, "rb");
1205     if (filesize($filename)>0) {
1206       $this->$cert= fread ($fd, filesize ($filename));
1207       fclose ($fd);
1208       $this->is_modified= TRUE;
1209     } else {
1210       print_red(_("Could not open specified certificate!"));
1211     }
1212   }
1214   /* Adapt from given 'dn' */
1215   function adapt_from_template($dn)
1216   {
1217     plugin::adapt_from_template($dn);
1219     /* Get base */
1220     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1222     if ($this->config->current['GOVERNMENTMODE']){
1224       /* Walk through govattrs */
1225       foreach ($this->govattrs as $val){
1227         if (isset($this->attrs["$val"][0])){
1229           /* If attribute is set, replace dynamic parts: 
1230              %sn, %givenName and %uid. Fill these in our local variables. */
1231           $value= $this->attrs["$val"][0];
1233           foreach (array("sn", "givenName", "uid") as $repl){
1234             if (preg_match("/%$repl/i", $value)){
1235               $value= preg_replace ("/%$repl/i",
1236                   $this->parent->$repl, $value);
1237             }
1238           }
1239           $this->$val= $value;
1240         }
1241       }
1242     }
1244     /* Get back uid/sn/givenName */
1245     if ($this->parent != NULL){
1246       $this->uid= $this->parent->uid;
1247       $this->sn= $this->parent->sn;
1248       $this->givenName= $this->parent->givenName;
1249     }
1250   }
1252  
1253   /* This avoids that users move themselves out of their rights. 
1254    */
1255   function allowedBasesToMoveTo()
1256   {
1257     $allowed = array();
1258     $ret_all = false;
1259     if($this->uid == $_SESSION['ui']->username){
1260       $ldap= $this->config->get_ldap_link(); 
1261       $ldap->cd($this->config->current['BASE']); 
1262       $ldap->search("(&(objectClass=posixGroup)(memberUid=".$_SESSION['ui']->username."))",array("gosaSubtreeACL"));
1263        
1264       while($attrs = $ldap->fetch()){
1265     
1266         if(isset($attrs['gosaSubtreeACL'])){
1267         
1268           foreach($attrs['gosaSubtreeACL'] as $attr){
1269             if((preg_match("/:user#/",$attr))||(preg_match("/:all/",$attr))){
1270               $s =  preg_replace("/^.*".get_groups_ou().",/","",$attrs['dn']);
1272               foreach($this->config->idepartments as $key => $dep) {
1273                 if(preg_match("/".$s."/i",$key)){
1274                   $allowed[$key] = $dep;
1275                 }
1276               }
1277             }
1278           }
1279         }
1280       }
1281       if(count($allowed) == 0){
1282         foreach($this->config->idepartments as $key => $dep) {
1283           if($this->base==$key){
1284             $allowed[$key] = $dep;
1285           }
1286         }
1287       }  
1288   
1289       return($allowed);
1290       
1291     }else{
1292       return($this->config->idepartments);
1293     }
1294   } 
1297   function getCopyDialog()
1298   {
1299     $str = "";
1301     $_SESSION['binary'] = $this->photoData; 
1302     $_SESSION['binarytype']= "image/jpeg";
1304     /* Get random number for pictures */
1305     srand((double)microtime()*1000000); 
1306     $rand = rand(0, 10000);
1308     $smarty = get_smarty();
1310     $smarty->assign("passwordTodo","clear");
1312     if(isset($_POST['passwordTodo'])){
1313       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1314     }
1316     $smarty->assign("sn",       $this->sn);
1317     $smarty->assign("givenName",$this->givenName);
1318     $smarty->assign("uid",      $this->uid);
1319     $smarty->assign("rand",     $rand);
1320     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1323     $ret = array();
1324     $ret['string'] = $str;
1325     $ret['status'] = "";  
1326     return($ret);
1327   }
1329   function saveCopyDialog()
1330   {
1332     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1333       $this->set_picture($_FILES['picture_file']['tmp_name']);
1334     }
1336     /* Remove picture? */
1337     if (isset($_POST['picture_remove'])){
1338       $this->jpegPhoto= "*removed*";
1339       $this->set_picture ("./images/default.jpg");
1340       $this->is_modified= TRUE;
1341     }
1343     $attrs = array("uid","givenName","sn");
1344     foreach($attrs as $attr){
1345       if(isset($_POST[$attr])){
1346         $this->$attr = $_POST[$attr];
1347       }
1348     } 
1349   }
1352   function PrepareForCopyPaste($source)
1353   {
1354     plugin::PrepareForCopyPaste($source);
1356     /* Reset certificate information addepted from source user
1357         to avoid setting the same user certificate for the destination user. */
1358     $this->userPKCS12= "";
1359     $this->userSMIMECertificate= "";
1360     $this->userCertificate= "";
1361     $this->certificateSerialNumber= "";
1362     $this->old_certificateSerialNumber= "";
1363     $this->old_userPKCS12= "";
1364     $this->old_userSMIMECertificate= "";
1365     $this->old_userCertificate= "";
1366   }
1369 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1370 ?>