Code

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