Code

Small fix
[gosa.git] / plugins / personal / generic / class_user.inc
1 <?php
2 /*!
3   \brief   user plugin
4   \author  Cajus Pollmeier <pollmeier@gonicus.de>
5   \version 2.00
6   \date    24.07.2003
8   This class provides the functionality to read and write all attributes
9   relevant for person, organizationalPerson, inetOrgPerson and gosaAccount
10   from/to the LDAP. It does syntax checking and displays the formulars required.
11  */
13 class user extends plugin
14 {
15   /* Definitions */
16   var $plHeadline= "Generic";
17   var $plDescription= "This does something";
19   /* CLI vars */
20   var $cli_summary= "Handling of GOsa's user base object";
21   var $cli_description= "Some longer text\nfor help";
22   var $cli_parameters= array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
24   /* Plugin specific values */
25   var $base= "";
26   var $cn= "";
27   var $personalTitle= "";
28   var $academicTitle= "";
29   var $homePostalAddress= "";
30   var $homePhone= "";
31   var $labeledURI= "";
32   var $o= "";
33   var $ou= "";
34   var $departmentNumber= "";
35   var $employeeNumber= "";
36   var $employeeType= "";
37   var $roomNumber= "";
38   var $telephoneNumber= "";
39   var $facsimileTelephoneNumber= "";
40   var $mobile= "";
41   var $pager= "";
42   var $l= "";
43   var $st= "";
44   var $postalAddress= "";
45   var $dateOfBirth;
46   var $use_dob= "0";
47   var $gender="0";
48   var $preferredLanguage="0";
50   var $jpegPhoto= "*removed*";
51   var $photoData= "";
52   var $old_jpegPhoto= "";
53   var $old_photoData= "";
54   var $cert_dialog= FALSE;
55   var $picture_dialog= FALSE;
57   var $userPKCS12= "";
58   var $userSMIMECertificate= "";
59   var $userCertificate= "";
60   var $certificateSerialNumber= "";
61   var $old_certificateSerialNumber= "";
62   var $old_userPKCS12= "";
63   var $old_userSMIMECertificate= "";
64   var $old_userCertificate= "";
66   var $gouvernmentOrganizationalUnit= "";
67   var $houseIdentifier= "";
68   var $street= "";
69   var $postalCode= "";
70   var $vocation= "";
71   var $ivbbLastDeliveryCollective= "";
72   var $gouvernmentOrganizationalPersonLocality= "";
73   var $gouvernmentOrganizationalUnitDescription= "";
74   var $gouvernmentOrganizationalUnitSubjectArea= "";
75   var $functionalTitle= "";
76   var $role= "";
77   var $publicVisible= "";
79   var $dialog;
81   /* variables to trigger password changes */
82   var $pw_storage= "crypt";
83   var $last_pw_storage= "unset";
84   var $had_userCertificate= FALSE;
86   /* attribute list for save action */
87   var $attributes= array("sn", "givenName", "uid", "personalTitle", "academicTitle",
88       "homePostalAddress", "homePhone", "labeledURI", "o", "ou", "dateOfBirth", "gender","preferredLanguage",
89       "departmentNumber", "employeeNumber", "employeeType", "l", "st","jpegPhoto",
90       "roomNumber", "telephoneNumber", "mobile", "pager", "cn", "userPKCS12",
91       "postalAddress", "facsimileTelephoneNumber", "userSMIMECertificate");
93   var $objectclasses= array("top", "person", "organizationalPerson", "inetOrgPerson",
94       "gosaAccount");
96   /* attributes that are part of the government mode */
97   var $govattrs= array("gouvernmentOrganizationalUnit", "houseIdentifier", "vocation",
98       "ivbbLastDeliveryCollective", "gouvernmentOrganizationalPersonLocality",
99       "gouvernmentOrganizationalUnitDescription","gouvernmentOrganizationalUnitSubjectArea",
100       "functionalTitle", "certificateSerialNumber", "publicVisible", "street", "role",
101       "postalCode");
104   /* constructor, if 'dn' is set, the node loads the given
105      'dn' from LDAP */
106   function user ($config, $dn= NULL)
107   {
108     $this->config= $config;
109     /* Configuration is fine, allways */
110     if ($this->config->current['GOVERNMENTMODE']){
111       $this->attributes=array_merge($this->attributes,$this->govattrs);
112     }
114     /* Load base attributes */
115     plugin::plugin ($config, $dn);
117     if ($this->config->current['GOVERNMENTMODE']){
118       /* Fix public visible attribute if unset */
119       if (!isset($this->attrs['publicVisible'])){
120         $this->publicVisible == "nein";
121       }
122     }
124     /* Load government mode attributes */
125     if ($this->config->current['GOVERNMENTMODE']){
126       /* Copy all attributs */
127       foreach ($this->govattrs as $val){
128         if (isset($this->attrs["$val"][0])){
129           $this->$val= $this->attrs["$val"][0];
130         }
131       }
132     }
134     /* Create me for new accounts */
135     if ($dn == "new"){
136       $this->is_account= TRUE;
137     }
139     /* Make hash default to md5 if not set in config */
140     if (!isset($this->config->current['HASH'])){
141       $hash= "md5";
142     } else {
143       $hash= $this->config->current['HASH'];
144     }
146     /* Load data from LDAP? */
147     if ($dn != NULL){
149       /* Do base conversation */
150       if ($this->dn == "new"){
151         $ui= get_userinfo();
152         $this->base= dn2base($ui->dn);
153       } else {
154         $this->base= dn2base($dn);
155       }
157       /* get password storage type */
158       if (isset ($this->attrs['userPassword'][0])){
159         /* Initialize local array */
160         $matches= array();
161         if (preg_match ("/^{([^}]+)}(.+)/", $this->attrs['userPassword'][0], $matches)){
162           $this->pw_storage= strtolower($matches[1]);
163         } else {
164           if ($this->attrs['userPassword'][0] != ""){
165             $this->pw_storage= "clear";
166           } else {
167             $this->pw_storage= $hash;
168           }
169         }
170       } else {
171         /* Preset with vaule from configuration */
172         $this->pw_storage= $hash;
173       }
175       /* Load extra attributes: certificate and picture */
176       $this->load_picture();
177       $this->load_cert();
178       if ($this->userCertificate != ""){
179         $this->had_userCertificate= TRUE;
180       }
181     }
183     /* Reset password storage indicator, used by password_change_needed() */
184     if ($dn == "new"){
185       $this->last_pw_storage= "unset";
186     } else {
187       $this->last_pw_storage= $this->pw_storage;
188     }
190     /* Generate dateOfBirth entry */
191     if (isset ($this->attrs['dateOfBirth'])){
192       /* This entry is ISO 8601 conform */
193       list($year, $month, $day)= split("-", $this->attrs['dateOfBirth'][0], 3);
194     
195       $this->dateOfBirth=array( 'mon'=> $month,"mday"=> $day,"year"=> $year);
196       $this->use_dob= "1";
197     } else {
198       $this->use_dob= "0";
199     }
201     /* Put gender attribute to upper case */
202     if (isset ($this->attrs['gender'])){
203       $this->gender= strtoupper($this->attrs['gender'][0]);
204     }
205   }
208   /* execute generates the html output for this node */
209   function execute()
210   {
211     /* Call parent execute */
212     plugin::execute();
214     $smarty= get_smarty();
216     /* Fill calendar */
217     if ($this->dateOfBirth == "0"){
218       $date= getdate();
219     } else {
220       if(is_array($this->dateOfBirth)){
221         $date = $this->dateOfBirth;
222   
223         // Trigger on dates like 1985-04-01, getdate only understands timestamps
224       } else if (!empty($this->dateOfBirth) && !is_numeric($this->dateOfBirth)){
225         $date= getdate(strtotime($this->dateOfBirth));
227       } else {
228         $date = getdate($this->dateOfBirth);
229       } 
230     }
232     $days= array();
233     for($d= 1; $d<32; $d++){
234       $days[$d]= $d;
235     }
236     $years= array();
238     if(($date['year']-100)<1901){
239       $start = 1901;
240     }else{
241       $start = $date['year']-100;
242     }
244     $end = $start +100;
245     
246     for($y= $start; $y<=$end; $y++){
247       $years[]= $y;
248     }
249     $years['-']= "-&nbsp;";
250     $months= array(_("January"), _("February"), _("March"), _("April"),
251         _("May"), _("June"), _("July"), _("August"), _("September"),
252         _("October"), _("November"), _("December"), '-' => '-&nbsp;');
253     $smarty->assign("day", $date["mday"]);
254     $smarty->assign("days", $days);
255     $smarty->assign("months", $months);
256     $smarty->assign("month", $date["mon"]-1);
257     $smarty->assign("years", $years);
258     $smarty->assign("year", $date["year"]);
260     /* Assign sex */
261     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
262     $smarty->assign("gender_list", $sex);
264     /* Assign prefered langage */
265     $language= array(0 => "&nbsp;", "fr_FR" => ("fr_FR"), "en_EN" => ("en_EN"), 
266                                     "de_DE" => ("de_DE"), "it_IT" => ("it_IT"), 
267                                     "nl_NL" => ("nl_NL"), "ru_RU" => ("ru_RU"));
268     $smarty->assign("preferredLanguage_list", $language);
270     /* Get random number for pictures */
271     srand((double)microtime()*1000000); 
272     $smarty->assign("rand", rand(0, 10000));
274     /* Do we represent a valid gosaAccount? */
275     if (!$this->is_account){
276       echo "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
277         _("This account has no valid GOsa extensions.")."</b>";
278       return;
279     }
281     /* Base select dialog */
282     $once = true;
283     foreach($_POST as $name => $value){
284       if(preg_match("/^chooseBase/",$name) && $once){
285         $once = false;
286         $this->dialog = new baseSelectDialog($this->config,$this->allowedBasesToMoveTo());
287         $this->dialog->setCurrentBase($this->base);
288       }
289     }
291     /* Dialog handling */
292     if(is_object($this->dialog)){
293       /* Must be called before save_object */
294       $this->dialog->save_object();
295    
296       if($this->dialog->isClosed()){
297         $this->dialog = false;
298       }elseif($this->dialog->isSelected()){
299         $this->base = $this->dialog->isSelected();
300         $this->dialog= false;
301       }else{
302         return($this->dialog->execute());
303       }
304     }
306     /* Want picture edit dialog? */
307     if (isset($_POST['edit_picture'])){
308       /* Save values for later recovery, in case some presses
309          the cancel button. */
310       $this->old_jpegPhoto= $this->jpegPhoto;
311       $this->old_photoData= $this->photoData;
312       $this->picture_dialog= TRUE;
313       $this->dialog= TRUE;
314     }
316     /* Remove picture? */
317     if (isset($_POST['picture_remove'])){
318       $this->set_picture ();
319       $this->jpegPhoto= "*removed*";
320       $this->is_modified= TRUE;
322       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
323     }
325     /* Save picture */
326     if (isset($_POST['picture_edit_finish'])){
328       /* Check for clean upload */
329       if ($_FILES['picture_file']['name'] != ""){
330         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
331           print_red(_("The specified file has not been uploaded via HTTP POST! Aborted."));
332           exit;
333         }
335         /* Activate new picture */
336         $this->set_picture($_FILES['picture_file']['tmp_name']);
337       }
338       $this->picture_dialog= FALSE;
339       $this->dialog= FALSE;
340       $this->is_modified= TRUE;
341     }
344     /* Cancel picture */
345     if (isset($_POST['picture_edit_cancel'])){
347       /* Restore values */
348       $this->jpegPhoto= $this->old_jpegPhoto;
349       $this->photoData= $this->old_photoData;
351       /* Update picture */
352       $_SESSION['binary']= $this->photoData;
353       $_SESSION['binarytype']= "image/jpeg";
354       $this->picture_dialog= FALSE;
355       $this->dialog= FALSE;
356     }
358     /* Toggle dateOfBirth information */
359     if (isset($_POST['set_dob'])){
360       $this->use_dob= ($this->use_dob == "0")?"1":"0";
361     }
364     /* Want certificate= */
365     if (isset($_POST['edit_cert'])){
367       /* Save original values for later reconstruction */
368       foreach (array("certificateSerialNumber", "userCertificate",
369             "userSMIMECertificate", "userPKCS12") as $val){
371         $oval= "old_$val";
372         $this->$oval= $this->$val;
373       }
375       $this->cert_dialog= TRUE;
376       $this->dialog= TRUE;
377     }
380     /* Cancel certificate dialog */
381     if (isset($_POST['cert_edit_cancel'])){
383       /* Restore original values in case of 'cancel' */
384       foreach (array("certificateSerialNumber", "userCertificate",
385             "userSMIMECertificate", "userPKCS12") as $val){
387         $oval= "old_$val";
388         $this->$val= $this->$oval;
389       }
390       $this->cert_dialog= FALSE;
391       $this->dialog= FALSE;
392     }
395     /* Remove certificate? */
396     foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
397       if (isset($_POST["remove_$val"])){
399         /* Reset specified cert*/
400         $this->$val= "";
401         $this->is_modified= TRUE;
402       }
403     }
406     /* Upload new cert and close dialog? */     
407     if (isset($_POST['cert_edit_finish'])){
409       /* for all certificates do */
410       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
411           as $val){
413         /* Check for clean upload */
414         if (array_key_exists($val."_file", $_FILES) &&
415             array_key_exists('name', $_FILES[$val."_file"]) &&
416             $_FILES[$val."_file"]['name'] != "" &&
417             is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
418           $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
419         }
420       }
422       /* Save serial number */
423       if (isset($_POST["certificateSerialNumber"]) &&
424           $_POST["certificateSerialNumber"] != ""){
426         if (!is_id($_POST["certificateSerialNumber"])){
427           print_red (_("Please enter a valid serial number"));
429           foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
430             if ($this->$cert != ""){
431               $smarty->assign("$cert"."_state", "true");
432             } else {
433               $smarty->assign("$cert"."_state", "");
434             }
435           }
436           return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
437         }
439         $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
440         $this->is_modified= TRUE;
441       }
443       $this->cert_dialog= FALSE;
444       $this->dialog= FALSE;
445     }
447     /* Display picture dialog */
448     if ($this->picture_dialog){
449       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
450     }
452     /* Display cert dialog */
453     if ($this->cert_dialog){
454       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
455         if ($this->$cert != ""){
456           /* import certificate */
457           $certificate = new certificate;
458           $certificate->import($this->$cert);
459       
460           /* Read out data*/
461           $timeto   = $certificate->getvalidto_date();
462           $timefrom = $certificate->getvalidfrom_date();
464           /* Additional info if start end time is '0' */
465           $add_str_info = "";
466           if($timeto == 0 && $timefrom == 0){
467             $add_str_info = "<br><i>"._("(Some types of certificates are currently not supported and may be displayed as 'invalid'.)")."</i>";
468           }
470           $str = "<table summary=\"\" border=0>
471                     <tr>
472                       <td style='vertical-align:top'>CN</td>
473                       <td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td>
474                     </tr>
475                   </table><br>".
476                   
477                   sprintf(_("Certificate is valid from %s to %s and is currently %s."), 
478                         "<b>".date('d M Y',$timefrom)."</b>",
479                         "<b>".date('d M Y',$timeto)."</b>", 
480                         $certificate->isvalid()?"<b><font style='color:green'>"._("valid")."</font></b>": 
481                                                 "<b><font style='color:red'>"._("invalid")."</font></b>").$add_str_info;
482           $smarty->assign($cert."info",$str);
483           $smarty->assign($cert."_state","true");
484         } else {
485           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
486           $smarty->assign($cert."_state","");
487         }
488       }
489       $smarty->assign("governmentmode", "false");
490       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
491     }
493     /* Show us the edit screen */
494     @$smarty->assign("bases", $this->allowedBasesToMoveTo());
495 #  $smarty->assign("bases", $this->config->idepartments);
496     $smarty->assign("base_select",      $this->base);
497     $smarty->assign("selectmode",       chkacl($this->acl, "create"));
498     $smarty->assign("certificatesACL",  chkacl($this->acl, "certificates"));
499     $smarty->assign("jpegPhotoACL",     chkacl($this->acl, "jpegPhoto"));
501     /* Prepare password hashes */
502     if ($this->pw_storage == ""){
503       $this->pw_storage= $this->config->current['HASH'];
504     }
506     $temp   = @passwordMethod::get_available_methods();
507     $hashes = $temp['name'];
508     
509     $smarty->assign("pwmode", $hashes);
510     $smarty->assign("pwmode_select", $this->pw_storage);
511     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
513     /* Load attributes and acl's */
514     foreach($this->attributes as $val){
515       $smarty->assign("$val", $this->$val);
516       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
517     }
519     /* Save government mode attributes */
520     if (isset($this->config->current['GOVERNMENTMODE']) &&
521         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
522       $smarty->assign("governmentmode", "true");
523       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
524           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
525       $smarty->assign("ivbbmodes", $ivbbmodes);
526       foreach ($this->govattrs as $val){
527         $smarty->assign("$val", $this->$val);
528         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
529       }
530     } else {
531       $smarty->assign("governmentmode", "false");
532     }
534     /* Special mode for uid */
535     $uidACL= "";
536     if (isset ($this->dn)){
537       if ($this->dn != "new"){
538         $uidACL="readonly";
539       }
540     }  else {
541       $uidACL= "readonly";
542     }
543     $uidACL.= " ".chkacl($this->acl, "uid");
544     
545     $smarty->assign("uidACL", $uidACL);
546     $smarty->assign("is_template", $this->is_template);
547     $smarty->assign("use_dob", $this->use_dob);
549     if (isset($this->parent)){
550       if (isset($this->parent->by_object['phoneAccount']) &&
551           $this->parent->by_object['phoneAccount']->is_account){
552         $smarty->assign("has_phoneaccount", "true");
553       } else {
554         $smarty->assign("has_phoneaccount", "false");
555       }
556     } else {
557       $smarty->assign("has_phoneaccount", "false");
558     }
559     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
560   }
563   /* remove object from parent */
564   function remove_from_parent()
565   {
566     $ldap= $this->config->get_ldap_link();
567     $ldap->rmdir ($this->dn);
568     show_ldap_error($ldap->get_error(), _("Removing generic user account failed"));
570     /* Delete references to groups */
571     $ldap->cd ($this->config->current['BASE']);
572     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
573     while ($ldap->fetch()){
574       $g= new group($this->config, $ldap->getDN());
575       $g->removeUser($this->uid);
576       $g->save ();
577     }
579     /* Delete references to object groups */
580     $ldap->cd ($this->config->current['BASE']);
581     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
582     while ($ldap->fetch()){
583       $og= new ogroup($this->config, $ldap->getDN());
584       unset($og->member[$this->dn]);
585       $og->save ();
586     }
588     /* Kerberos server defined? */
589     if (isset($this->config->data['SERVERS']['KERBEROS'])){
590       $cfg= $this->config->data['SERVERS']['KERBEROS'];
591     }
592     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
594       /* Connect to the admin interface */
595       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
596           $cfg['ADMIN'], $cfg['PASSWORD']);
598       /* Errors? */             
599       if ($handle === FALSE){
600         print_red (_("Kerberos database communication failed"));
601         return (2);
602       }
604       /* Build user principal, get list of existsing principals */
605       $principal= $this->uid."@".$cfg['REALM'];
606       $principals = kadm5_get_principals($handle);
608       /* User exists in database? */
609       if (in_array($principal, $principals)){
611         /* Ok. User exists. Remove him/her */
612           $ret= kadm5_delete_principal ( $handle, $principal);
613           if ($ret === FALSE){
614             print_red (_("Can't remove user from kerberos database."));
615           }
616       }
618       /* Free kerberos admin handle */
619       kadm5_destroy($handle);
620     }
623     /* Optionally execute a command after we're done */
624     $this->handle_post_events("remove",array("uid" => $this->uid));
625   }
628   /* Save data to object */
629   function save_object()
630   {
631     if (isset($_POST['generic'])){
633       /* Parents save function */
634       plugin::save_object ();
636       /* Save government mode attributes */
637       if ($this->config->current['GOVERNMENTMODE']){
638         foreach ($this->govattrs as $val){
639           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
640             $data= stripcslashes($_POST["$val"]);
641             if ($data != $this->$val){
642               $this->is_modified= TRUE;
643             }
644             $this->$val= $data;
645           }
646         }
647       }
649       /* In template mode, the uid is autogenerated... */
650       if ($this->is_template){
651         $this->uid= strtolower($this->sn);
652         $this->givenName= $this->sn;
653       }
655       /* Save base and pw_storage, since these are no LDAP attributes */
656       if (isset($_POST['base'])){
657         foreach(array("base", "pw_storage") as $val){
658           if(isset($_POST[$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     /* Build new dn */
853     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
854       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
855     } else {
856       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
857     }
859     /* This only gets called when user is renaming himself */
860     $ldap= $this->config->get_ldap_link();
861     if ($this->dn != $new_dn){
863       /* Write entry on new 'dn' */
864       $this->move($this->dn, $new_dn);
866       /* Happen to use the new one */
867       change_ui_dn($this->dn, $new_dn);
868       $this->dn= $new_dn;
869     }
872     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
873        new entries. So do a check first... */
874     $ldap->cat ($this->dn, array('dn'));
875     if ($ldap->fetch()){
876       $mode= "modify";
877     } else {
878       $mode= "add";
879       $ldap->cd($this->config->current['BASE']);
880       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
881     }
883     /* Set password to some junk stuff in case of templates */
884     if ($this->is_template){
885       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
886     }
888     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
889         $this->attributes, "Save via $mode");
891     /* Finally write data with selected 'mode' */
892     $this->cleanup();
893     $ldap->cd ($this->dn);
894     $ldap->$mode ($this->attrs);
895     if (show_ldap_error($ldap->get_error(), _("Saving generic user account failed"))){
896       return (1);
897     }
899     /* Remove cert? 
900        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
901        to work around myself. */
902     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
904       /* Reset array, assemble new, this should be reworked */
905       $this->attrs= array();
906       $this->attrs['userCertificate;binary']= array();
908       /* Prepare connection */
909       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
910         die ("Could not connect to LDAP server");
911       }
912       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
913       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
914         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
915         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
916       }
917       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
918         ldap_start_tls($ds);
919       }
920       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
921               $this->config->current['PASSWORD']))) {
922         die ("Could not bind to LDAP");
923       }
925       /* Modify using attrs */
926       ldap_mod_del($ds,$this->dn,$this->attrs);
927       ldap_close($ds);
928     }
930     /* Kerberos server defined? */
931     if (isset($this->config->data['SERVERS']['KERBEROS'])){
932       $cfg= $this->config->data['SERVERS']['KERBEROS'];
933     }
934     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
936       /* Connect to the admin interface */
937       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
938           $cfg['ADMIN'], $cfg['PASSWORD']);
940       /* Errors? */             
941       if ($handle === FALSE){
942         print_red (_("Kerberos database communication failed"));
943         return (2);
944       }
946       /* Build user principal, get list of existsing principals */
947       $principal= $this->uid."@".$cfg['REALM'];
948       $principals = kadm5_get_principals($handle);
950       /* User exists in database? */
951       if (in_array($principal, $principals)){
953         /* Ok. User exists. Remove him/her when pw_storage has
954            changed to be NOT kerberos. */
955         if ($this->pw_storage != $this->config->current['KRBSASL']){
956           $ret= kadm5_delete_principal ( $handle, $principal);
958           if ($ret === FALSE){
959             print_red (_("Can't remove user from kerberos database."));
960           }
961         }
963       } else {
965         /* User doesn't exists, create it when pw_storage is kerberos or SASL. */
966         if ($this->pw_storage == "kerberos" || $this->pw_storage == "sasl" ){
967           $ret= kadm5_create_principal ( $handle, $principal);
969           if ($ret === FALSE){
970             print_red (_("Can't add user to kerberos database."));
971           }
972         }
974       }
976       /* Free kerberos admin handle */
977       kadm5_destroy($handle);
978     }
980     /* Optionally execute a command after we're done */
981     if ($mode == "add"){
982       $this->handle_post_events("add",array("uid" => $this->uid));
983     } elseif ($this->is_modified){
984       $this->handle_post_events("modify",array("uid" => $this->uid));
985     }
987     /* Fix tagging if needed */
988     $this->handle_object_tagging();
990     return (0);
991   }
994   /* Check formular input */
995   function check()
996   {
997     /* Call common method to give check the hook */
998     $message= plugin::check();
1000     /* Assemble cn */
1001     if ($this->personalTitle == ""){
1002       $pt= "";
1003     } else {
1004       $pt= $this->personalTitle." ";
1005     }
1006     $this->cn= $pt.$this->givenName." ".$this->sn;
1008     /* Permissions for that base? */
1009     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
1010       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
1011     } else {
1012       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
1013     }
1015     $ui= get_userinfo();
1016     $acl= get_permissions ($new_dn, $ui->subtreeACL);
1017     $acl= get_module_permission($acl, "user", $new_dn);
1018     if ($this->dn == "new" && chkacl($acl, "create") != ""){
1019       $message[]= _("You have no permissions to create a user on this 'Base'.");
1020     } elseif ($this->dn != $new_dn && $this->dn != "new"){
1021       $acl= get_permissions ($this->dn, $ui->subtreeACL);
1022       $acl= get_module_permission($acl, "user", $this->dn);
1023       if (chkacl($acl, "create") != ""){
1024         $message[]= _("You have no permissions to move a user from the original 'Base'.");
1025       }
1026     }
1028     /* must: sn, givenName, uid */
1029     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
1030       $message[]= _("The required field 'Name' is not set.");
1031     }
1033     /* UID already used? */
1034     $ldap= $this->config->get_ldap_link();
1035     $ldap->cd($this->config->current['BASE']);
1036     $ldap->search("(uid=$this->uid)", array("uid"));
1037     $ldap->fetch();
1038     if ($ldap->count() != 0 && $this->dn == 'new'){
1039       $message[]= _("There's already a person with this 'Login' in the database.");
1040     }
1042     /* In template mode, the uid and givenName are autogenerated... */
1043     if (!$this->is_template){
1044       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
1045         $message[]= _("The required field 'Given name' is not set.");
1046       }
1047       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
1048         $message[]= _("The required field 'Login' is not set.");
1049       }
1050       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
1051         $ldap->cd($this->config->current['BASE']);
1052         $ldap->search("(cn=".$this->cn.")", array("uid"));
1053         $ldap->fetch();
1054         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
1055           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
1056         }
1057       }
1058     }
1060     /* Check for valid input */
1061     if ($this->is_modified && !is_uid($this->uid)){
1062       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
1063     }
1064     if (!is_url($this->labeledURI)){
1065       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
1066     }
1067     if (preg_match ("/[\\\\]/", $this->sn)){
1068       $message[]= _("The field 'Name' contains invalid characters.");
1069     }
1070     if (preg_match ("/[\\\\]/", $this->givenName)){
1071       $message[]= _("The field 'Given name' contains invalid characters.");
1072     }
1074     /* Check phone numbers */
1075     if (!is_phone_nr($this->telephoneNumber)){
1076       $message[]= _("The field 'Phone' contains an invalid phone number.");
1077     }
1078     if (!is_phone_nr($this->facsimileTelephoneNumber)){
1079       $message[]= _("The field 'Fax' contains an invalid phone number.");
1080     }
1081     if (!is_phone_nr($this->mobile)){
1082       $message[]= _("The field 'Mobile' contains an invalid phone number.");
1083     }
1084     if (!is_phone_nr($this->pager)){
1085       $message[]= _("The field 'Pager' contains an invalid phone number.");
1086     }
1088     /* Check for reserved characers */
1089     if (preg_match ('/[,+"?\'()=<>;]/', $this->givenName)){
1090       $message[]= _("The field 'Given name' contains invalid characters.");
1091     }
1092     if (preg_match ('/[,+"?\'()=<>;]/', $this->sn)){
1093       $message[]= _("The field 'Name' contains invalid characters.");
1094     }
1096   return $message;
1097   }
1100   /* Indicate whether a password change is needed or not */
1101   function password_change_needed()
1102   {
1103     return ($this->pw_storage != $this->last_pw_storage);
1104   }
1107   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1108   function load_picture()
1109   {
1110     /* make connection and read jpegPhoto */
1111     $ds= ldap_connect($this->config->current['SERVER']);
1112     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1113     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1114       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1115       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1116     }
1118     if(isset($this->config->current['TLS']) &&
1119         $this->config->current['TLS'] == "true"){
1121       ldap_start_tls($ds);
1122     }
1124     $r= ldap_bind($ds);
1125     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
1127     /* in case we don't get an entry, load a default picture */
1128     $this->set_picture ("./images/default.jpg");
1129     $this->jpegPhoto= "*removed*";
1131     /* fill data from LDAP */
1132     if ($sr) {
1133       $ei=ldap_first_entry($ds, $sr);
1134       if ($ei) {
1135         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
1136           $this->photoData= $info[0];
1137           $_SESSION['binary']= $this->photoData;
1138           $_SESSION['binarytype']= "image/jpeg";
1139           $this->jpegPhoto= "";
1140         }
1141       }
1142     }
1144     /* close conncetion */
1145     ldap_unbind($ds);
1146   }
1149   /* Load a certificate from LDAP, this is going to be simplified later on */
1150   function load_cert()
1151   {
1152     $ds= ldap_connect($this->config->current['SERVER']);
1153     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1154     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1155       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1156       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1157     }
1158     if(isset($this->config->current['TLS']) &&
1159         $this->config->current['TLS'] == "true"){
1161       ldap_start_tls($ds);
1162     }
1164     $r= ldap_bind($ds);
1165     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1167     if ($sr) {
1168       $ei= @ldap_first_entry($ds, $sr);
1169       
1170       if ($ei) {
1171         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1172           $this->userCertificate= "";
1173         } else {
1174           $this->userCertificate= $info[0];
1175         }
1176       }
1177     } else {
1178       $this->userCertificate= "";
1179     }
1181     ldap_unbind($ds);
1182   }
1185   /* Load picture from file to object */
1186   function set_picture($filename ="")
1187   {
1188     if (!is_file($filename) || $filename == ""){
1189       $filename= "./images/default.jpg";
1190       $this->jpegPhoto= "*removed*";
1191     }
1193     $fd = fopen ($filename, "rb");
1194     $this->photoData= fread ($fd, filesize ($filename));
1195     $_SESSION['binary']= $this->photoData;
1196     $_SESSION['binarytype']= "image/jpeg";
1197     $this->jpegPhoto= "";
1199     fclose ($fd);
1200   }
1203   /* Load certificate from file to object */
1204   function set_cert($cert, $filename)
1205   {
1206     $fd = fopen ($filename, "rb");
1207     if (filesize($filename)>0) {
1208       $this->$cert= fread ($fd, filesize ($filename));
1209       fclose ($fd);
1210       $this->is_modified= TRUE;
1211     } else {
1212       print_red(_("Could not open specified certificate!"));
1213     }
1214   }
1216   /* Adapt from given 'dn' */
1217   function adapt_from_template($dn)
1218   {
1219     plugin::adapt_from_template($dn);
1221     /* Get base */
1222     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1224     if ($this->config->current['GOVERNMENTMODE']){
1226       /* Walk through govattrs */
1227       foreach ($this->govattrs as $val){
1229         if (isset($this->attrs["$val"][0])){
1231           /* If attribute is set, replace dynamic parts: 
1232              %sn, %givenName and %uid. Fill these in our local variables. */
1233           $value= $this->attrs["$val"][0];
1235           foreach (array("sn", "givenName", "uid") as $repl){
1236             if (preg_match("/%$repl/i", $value)){
1237               $value= preg_replace ("/%$repl/i",
1238                   $this->parent->$repl, $value);
1239             }
1240           }
1241           $this->$val= $value;
1242         }
1243       }
1244     }
1246     /* Get back uid/sn/givenName */
1247     if ($this->parent != NULL){
1248       $this->uid= $this->parent->uid;
1249       $this->sn= $this->parent->sn;
1250       $this->givenName= $this->parent->givenName;
1251     }
1252   }
1254  
1255   /* This avoids that users move themselves out of their rights. 
1256    */
1257   function allowedBasesToMoveTo()
1258   {
1259     $allowed = array();
1260     $ret_all = false;
1261     if($this->uid == $_SESSION['ui']->username){
1262       $ldap= $this->config->get_ldap_link(); 
1263       $ldap->cd($this->config->current['BASE']); 
1264       $ldap->search("(&(objectClass=posixGroup)(memberUid=".$_SESSION['ui']->username."))",array("gosaSubtreeACL"));
1265        
1266       while($attrs = $ldap->fetch()){
1267     
1268         if(isset($attrs['gosaSubtreeACL'])){
1269         
1270           foreach($attrs['gosaSubtreeACL'] as $attr){
1271             if((preg_match("/:user#/",$attr))||(preg_match("/:all/",$attr))){
1272               $s =  preg_replace("/^.*".get_groups_ou().",/","",$attrs['dn']);
1274               foreach($this->config->idepartments as $key => $dep) {
1275                 if(preg_match("/".$s."/i",$key)){
1276                   $allowed[$key] = $dep;
1277                 }
1278               }
1279             }
1280           }
1281         }
1282       }
1283       if(count($allowed) == 0){
1284         foreach($this->config->idepartments as $key => $dep) {
1285           if($this->base==$key){
1286             $allowed[$key] = $dep;
1287           }
1288         }
1289       }  
1290   
1291       return($allowed);
1292       
1293     }else{
1294       return($this->config->idepartments);
1295     }
1296   } 
1299   function getCopyDialog()
1300   {
1301     $str = "";
1303     $_SESSION['binary'] = $this->photoData; 
1304     $_SESSION['binarytype']= "image/jpeg";
1306     /* Get random number for pictures */
1307     srand((double)microtime()*1000000); 
1308     $rand = rand(0, 10000);
1310     $smarty = get_smarty();
1312     $smarty->assign("passwordTodo","clear");
1314     if(isset($_POST['passwordTodo'])){
1315       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1316     }
1318     $smarty->assign("sn",       $this->sn);
1319     $smarty->assign("givenName",$this->givenName);
1320     $smarty->assign("uid",      $this->uid);
1321     $smarty->assign("rand",     $rand);
1322     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1325     $ret = array();
1326     $ret['string'] = $str;
1327     $ret['status'] = "";  
1328     return($ret);
1329   }
1331   function saveCopyDialog()
1332   {
1334     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1335       $this->set_picture($_FILES['picture_file']['tmp_name']);
1336     }
1338     /* Remove picture? */
1339     if (isset($_POST['picture_remove'])){
1340       $this->jpegPhoto= "*removed*";
1341       $this->set_picture ("./images/default.jpg");
1342       $this->is_modified= TRUE;
1343     }
1345     $attrs = array("uid","givenName","sn");
1346     foreach($attrs as $attr){
1347       if(isset($_POST[$attr])){
1348         $this->$attr = $_POST[$attr];
1349       }
1350     } 
1351   }
1354   function PrepareForCopyPaste($source)
1355   {
1356     plugin::PrepareForCopyPaste($source);
1358     /* Reset certificate information addepted from source user
1359         to avoid setting the same user certificate for the destination user. */
1360     $this->userPKCS12= "";
1361     $this->userSMIMECertificate= "";
1362     $this->userCertificate= "";
1363     $this->certificateSerialNumber= "";
1364     $this->old_certificateSerialNumber= "";
1365     $this->old_userPKCS12= "";
1366     $this->old_userSMIMECertificate= "";
1367     $this->old_userCertificate= "";
1368   }
1371 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1372 ?>