Code

png - jpg
[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",
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       echo $this->base;
159       /* get password storage type */
160       if (isset ($this->attrs['userPassword'][0])){
161         /* Initialize local array */
162         $matches= array();
163         if (preg_match ("/^{([^}]+)}(.+)/", $this->attrs['userPassword'][0], $matches)){
164           $this->pw_storage= strtolower($matches[1]);
165         } else {
166           if ($this->attrs['userPassword'][0] != ""){
167             $this->pw_storage= "clear";
168           } else {
169             $this->pw_storage= $hash;
170           }
171         }
172       } else {
173         /* Preset with vaule from configuration */
174         $this->pw_storage= $hash;
175       }
177       /* Load extra attributes: certificate and picture */
178       $this->load_picture();
179       $this->load_cert();
180       if ($this->userCertificate != ""){
181         $this->had_userCertificate= TRUE;
182       }
183     }
185     /* Reset password storage indicator, used by password_change_needed() */
186     if ($dn == "new"){
187       $this->last_pw_storage= "unset";
188     } else {
189       $this->last_pw_storage= $this->pw_storage;
190     }
192     /* Generate dateOfBirth entry */
193     if (isset ($this->attrs['dateOfBirth'])){
194       /* This entry is ISO 8601 conform */
195       list($year, $month, $day)= split("-", $this->attrs['dateOfBirth'][0], 3);
196     
197       $this->dateOfBirth=array( 'mon'=> $month,"mday"=> $day,"year"=> $year);
198       $this->use_dob= "1";
199     } else {
200       $this->use_dob= "0";
201     }
203     /* Put gender attribute to upper case */
204     if (isset ($this->attrs['gender'])){
205       $this->gender= strtoupper($this->attrs['gender'][0]);
206     }
207   }
210   /* execute generates the html output for this node */
211   function execute()
212   {
213     /* Call parent execute */
214     plugin::execute();
216     $smarty= get_smarty();
218     /* Fill calendar */
219     if ($this->dateOfBirth == "0"){
220       $date= getdate();
221     } else {
222       if(is_array($this->dateOfBirth)){
223         $date = $this->dateOfBirth;
224       }else{
225         $date = getdate($this->dateOfBirth);
226       } 
227     }
229     $days= array();
230     for($d= 1; $d<32; $d++){
231       $days[$d]= $d;
232     }
233     $years= array();
235     if(($date['year']-100)<1901){
236       $start = 1901;
237     }else{
238       $start = $date['year']-100;
239     }
241     $end = $start +100;
242     
243     for($y= $start; $y<=$end; $y++){
244       $years[]= $y;
245     }
246     $years['-']= "-&nbsp;";
247     $months= array(_("January"), _("February"), _("March"), _("April"),
248         _("May"), _("June"), _("July"), _("August"), _("September"),
249         _("October"), _("November"), _("December"), '-' => '-&nbsp;');
250     $smarty->assign("day", $date["mday"]);
251     $smarty->assign("days", $days);
252     $smarty->assign("months", $months);
253     $smarty->assign("month", $date["mon"]-1);
254     $smarty->assign("years", $years);
255     $smarty->assign("year", $date["year"]);
257     /* Assign sex */
258     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
259     $smarty->assign("gender_list", $sex);
261     /* Assign prefered langage */
262     $language= array(0 => "&nbsp;", "fr_FR" => ("fr_FR"), "en_EN" => ("en_EN"), 
263                                     "de_DE" => ("de_DE"), "it_IT" => ("it_IT"), 
264                                     "nl_NL" => ("nl_NL"), "ru_RU" => ("ru_RU"));
265     $smarty->assign("preferredLanguage_list", $language);
267     /* Get random number for pictures */
268     srand((double)microtime()*1000000); 
269     $smarty->assign("rand", rand(0, 10000));
271     /* Do we represent a valid gosaAccount? */
272     if (!$this->is_account){
273       echo "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
274         _("This account has no valid GOsa extensions.")."</b>";
275       return;
276     }
278     /* Base select dialog */
279     $once = true;
280     foreach($_POST as $name => $value){
281       if(preg_match("/^chooseBase/",$name) && $once){
282         $once = false;
283         $this->dialog = new baseSelectDialog($this->config,$this,$this->allowedBasesToMoveTo());
284         $this->dialog->setCurrentBase($this->base);
285       }
286     }
288     /* Dialog handling */
289     if(is_object($this->dialog)){
290       /* Must be called before save_object */
291       $this->dialog->save_object();
292    
293       if($this->dialog->isClosed()){
294         $this->dialog = false;
295       }elseif($this->dialog->isSelected()){
296         $this->base = $this->dialog->isSelected();
297         $this->dialog= false;
298       }else{
299         return($this->dialog->execute());
300       }
301     }
303     /* Want picture edit dialog? */
304     if($this->acl_is_readable("userPicture")) {
305       if (isset($_POST['edit_picture'])){
306         /* Save values for later recovery, in case some presses
307            the cancel button. */
308         $this->old_jpegPhoto= $this->jpegPhoto;
309         $this->old_photoData= $this->photoData;
310         $this->picture_dialog= TRUE;
311         $this->dialog= TRUE;
312       }
313     }
315     /* Remove picture? */
316     if($this->acl_is_writeable("userPicture")) {
317       if (isset($_POST['picture_remove'])){
318         $this->jpegPhoto= "*removed*";
319         $this->set_picture ("./images/default.jpg");
320         $this->is_modified= TRUE;
322         return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
323       }
324     }
326     /* Save picture */
327     if (isset($_POST['picture_edit_finish'])){
329       /* Check for clean upload */
330       if ($_FILES['picture_file']['name'] != ""){
331         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
332           print_red(_("The specified file has not been uploaded via HTTP POST! Aborted."));
333           exit;
334         }
336         /* Activate new picture */
337         $this->set_picture($_FILES['picture_file']['tmp_name']);
338       }
339       $this->picture_dialog= FALSE;
340       $this->dialog= FALSE;
341       $this->is_modified= TRUE;
342     }
345     /* Cancel picture */
346     if (isset($_POST['picture_edit_cancel'])){
348       /* Restore values */
349       $this->jpegPhoto= $this->old_jpegPhoto;
350       $this->photoData= $this->old_photoData;
352       /* Update picture */
353       $_SESSION['binary']= $this->photoData;
354       $_SESSION['binarytype']= "image/jpeg";
355       $this->picture_dialog= FALSE;
356       $this->dialog= FALSE;
357     }
359     /* Toggle dateOfBirth information */
360     if (isset($_POST['set_dob'])){
361       $this->use_dob= ($this->use_dob == "0")?"1":"0";
362     }
365     /* Want certificate= */
366     if ((isset($_POST['edit_cert'])) && $this->acl_is_readable("Certificate")){
368       /* Save original values for later reconstruction */
369       foreach (array("certificateSerialNumber", "userCertificate",
370             "userSMIMECertificate", "userPKCS12") as $val){
372         $oval= "old_$val";
373         $this->$oval= $this->$val;
374       }
376       $this->cert_dialog= TRUE;
377       $this->dialog= TRUE;
378     }
381     /* Cancel certificate dialog */
382     if (isset($_POST['cert_edit_cancel'])){
384       /* Restore original values in case of 'cancel' */
385       foreach (array("certificateSerialNumber", "userCertificate",
386             "userSMIMECertificate", "userPKCS12") as $val){
388         $oval= "old_$val";
389         $this->$val= $this->$oval;
390       }
391       $this->cert_dialog= FALSE;
392       $this->dialog= FALSE;
393     }
396     /* Remove certificate? */
397     if($this->acl_is_writeable("Certificate")){ 
398       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
399         if (isset($_POST["remove_$val"])){
401           /* Reset specified cert*/
402           $this->$val= "";
403           $this->is_modified= TRUE;
404         }
405       }
406     }
408     /* Upload new cert and close dialog? */     
409     if($this->acl_is_writeable("Certificate")){ 
410       if (isset($_POST['cert_edit_finish'])){
412         /* for all certificates do */
413         foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
414             as $val){
416           /* Check for clean upload */
417           if (array_key_exists($val."_file", $_FILES) &&
418               array_key_exists('name', $_FILES[$val."_file"]) &&
419               $_FILES[$val."_file"]['name'] != "" &&
420               is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
421             $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
422           }
423         }
425         /* Save serial number */
426         if (isset($_POST["certificateSerialNumber"]) &&
427             $_POST["certificateSerialNumber"] != ""){
429           if (!is_id($_POST["certificateSerialNumber"])){
430             print_red (_("Please enter a valid serial number"));
432             foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
433               if ($this->$cert != ""){
434                 $smarty->assign("$cert"."_state", "true");
435               } else {
436                 $smarty->assign("$cert"."_state", "");
437               }
438             }
439             return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
440           }
442           $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
443           $this->is_modified= TRUE;
444         }
446         $this->cert_dialog= FALSE;
447         $this->dialog= FALSE;
448       }
449     }
450     /* Display picture dialog */
451     if ($this->picture_dialog){
452       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
453     }
455     /* Display cert dialog */
456     if ($this->cert_dialog){
457       $smarty->assign("CertificateACL",$this->getacl("Certificate"));
458       $smarty->assign("Certificate_readable",$this->acl_is_readable("Certificate"));
460       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
461         if ($this->$cert != ""){
462           /* import certificate */
463           $certificate = new certificate;
464           $certificate->import($this->$cert);
465       
466           /* Read out data*/
467           $timeto   = $certificate->getvalidto_date();
468           $timefrom = $certificate->getvalidfrom_date();
469           $str = "<table summary=\"\" border=0><tr><td style='vertical-align:top'>CN</td><td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td></tr></table><br>".
470                   sprintf(_("Certificate is valid from %s to %s and is currently %s."), "<b>".date('d M Y',$timefrom)."</b>","<b>".date('d M Y',$timeto)."</b>", $certificate->isvalid()?"<b><font style='color:green'>"._("valid")."</font></b>":"<b><font style='color:red'>"._("invalid")."</font></b>");
471           $smarty->assign($cert."info",$str);
472           $smarty->assign($cert."_state","true");
473         } else {
474           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
475           $smarty->assign($cert."_state","");
476         }
477       }
478       $smarty->assign("governmentmode", "false");
479       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
480     }
482     /* Prepare password hashes */
483     if ($this->pw_storage == ""){
484       $this->pw_storage= $this->config->current['HASH'];
485     }
487     $temp   = @passwordMethod::get_available_methods();
488     $hashes = $temp['name'];
489     
490     /* Load attributes and acl's */
491     $ui =get_userinfo();
492     foreach($this->attributes as $val){
493       $smarty->assign("$val", $this->$val);
494       $smarty->assign("$val"."ACL", $this->getacl($val));
495     }
497     $smarty->assign("pwmode", $hashes);
498     $smarty->assign("pwmode_select", $this->pw_storage);
499     $smarty->assign("passwordStorageACL", $this->getacl("userPassword"));
500     $smarty->assign("base_select",      $this->base);
501     $smarty->assign("CertificatesACL",  $this->getacl("Certificate"));
502     $smarty->assign("userPictureACL",   $this->getacl("userPicture"));
503     $smarty->assign("userPicture_is_readable",   $this->acl_is_readable("userPicture"));
505     /* Create base acls */
506     $baseACL = $this->getacl("base");
507     if(!$this->acl_is_moveable()) {
508       $baseACL = preg_replace("/w/","",$baseACL);
509     }
510     $smarty->assign("baseACL",          $baseACL);
512     /* Show us the edit screen */
513     @$smarty->assign("bases", $this->allowedBasesToMoveTo());
514 #  $smarty->assign("bases", $this->config->idepartments);
517     /* Save government mode attributes */
518     if (isset($this->config->current['GOVERNMENTMODE']) &&
519         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
520       $smarty->assign("governmentmode", "true");
521       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
522           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
523       $smarty->assign("ivbbmodes", $ivbbmodes);
524       foreach ($this->govattrs as $val){
525         $smarty->assign("$val", $this->$val);
526         $smarty->assign("$val"."ACL", $this->getacl($val));
527       }
528     } else {
529       $smarty->assign("governmentmode", "false");
530     }
532     /* Special mode for uid */
533     $uidACL= $this->getacl("uid");
534     if (isset ($this->dn)){
535       if ($this->dn != "new"){
536         $uidACL= preg_replace("/w/","",$uidACL);
537       }
538     }  else {
539       $uidACL= preg_replace("/w/","",$uidACL);
540     }
541     
542     $smarty->assign("uidACL", $uidACL);
543     $smarty->assign("is_template", $this->is_template);
544     $smarty->assign("use_dob", $this->use_dob);
546     if (isset($this->parent)){
547       if (isset($this->parent->by_object['phoneAccount']) &&
548           $this->parent->by_object['phoneAccount']->is_account){
549         $smarty->assign("has_phoneaccount", "true");
550       } else {
551         $smarty->assign("has_phoneaccount", "false");
552       }
553     } else {
554       $smarty->assign("has_phoneaccount", "false");
555     }
556     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
557   }
560   /* remove object from parent */
561   function remove_from_parent()
562   {
563     $ldap= $this->config->get_ldap_link();
564     $ldap->rmdir ($this->dn);
565     show_ldap_error($ldap->get_error(), sprintf(_("Removing of user/generic account with dn '%s' failed."),$this->dn));
567     /* Delete references to groups */
568     $ldap->cd ($this->config->current['BASE']);
569     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
570     while ($ldap->fetch()){
571       $g= new group($this->config, $ldap->getDN());
572       $g->removeUser($this->uid);
573       $g->save ();
574     }
576     /* Delete references to object groups */
577     $ldap->cd ($this->config->current['BASE']);
578     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
579     while ($ldap->fetch()){
580       $og= new ogroup($this->config, $ldap->getDN());
581       unset($og->member[$this->dn]);
582       $og->save ();
583     }
585     /* Optionally execute a command after we're done */
586     $this->handle_post_events("remove");
587   }
590   /* Save data to object */
591   function save_object()
592   {
593     if (isset($_POST['generic'])){
595       /* Parents save function */
596       plugin::save_object ();
598       /* Save government mode attributes */
599       if ($this->config->current['GOVERNMENTMODE']){
600         foreach ($this->govattrs as $val){
601           if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
602             $data= stripcslashes($_POST["$val"]);
603             if ($data != $this->$val){
604               $this->is_modified= TRUE;
605             }
606             $this->$val= $data;
607           }
608         }
609       }
611       /* In template mode, the uid is autogenerated... */
612       if ($this->is_template){
613         $this->uid= strtolower($this->sn);
614         $this->givenName= $this->sn;
615       }
617       /* Save base and pw_storage, since these are no LDAP attributes */
618       if (isset($_POST['base'])){
619         foreach(array("base", "pw_storage") as $val){
620           if(isset($_POST[$val])){
621             $data= validate($_POST[$val]);
622             if ($data != $this->$val){
623               $this->is_modified= TRUE;
624             }
625             $this->$val= $data;
626           }
627         }
628       }
629     }
630   }
632   function rebind($ldap, $referral)
633   {
634     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
635     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
636       $this->error = "Success";
637       $this->hascon=true;
638       $this->reconnect= true;
639       return (0);
640     } else {
641       $this->error = "Could not bind to " . $credentials['ADMIN'];
642       return NULL;
643     }
644   }
646   /* Save data to LDAP, depending on is_account we save or delete */
647   function save()
648   {
649     /* Only force save of changes .... 
650        If this attributes aren't changed, avoid saving.
651      */
652     if ($this->use_dob == "1"){
653       $this->dateOfBirth= date("Y-m-d", $this->dateOfBirth);
654     }
655     if($this->gender=="0") $this->gender ="";
656     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
657     
658  
659     /* First use parents methods to do some basic fillup in $this->attrs */
660     plugin::save ();
662     /* Remove additional objectClasses */
663     $tmp= array();
664     foreach ($this->attrs['objectClass'] as $key => $set){
665       $found= false;
666       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
667         if (preg_match ("/^$set$/i", $val)){
668           $found= true;
669           break;
670         }
671       }
672       if (!$found){
673         $tmp[]= $set;
674       }
675     }
677     /* Replace the objectClass array. This is done because of the
678        separation into government and normal mode. */
679     $this->attrs['objectClass']= $tmp;
681     /* Add objectClasss for template mode? */
682     if ($this->is_template){
683       $this->attrs['objectClass'][]= "gosaUserTemplate";
684     }
686     /* Hard coded government mode? */
687     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
688       $this->attrs['objectClass'][]= "ivbbentry";
690       /* Copy standard attributes */
691       foreach ($this->govattrs as $val){
692         if ($this->$val != ""){
693           $this->attrs["$val"]= $this->$val;
694         } elseif (!$this->new) {
695           $this->attrs["$val"]= array();
696         }
697       }
699       /* Remove attribute if set to "nein" */
700       if ($this->publicVisible == "nein"){
701         $this->attrs['publicVisible']= array();
702         if($this->new){
703           unset($this->attrs['publicVisible']);
704         }else{
705           $this->attrs['publicVisible']=array();
706         }
708       }
710     }
712     /* Special handling for attribute userCertificate needed */
713     if ($this->userCertificate != ""){
714       $this->attrs["userCertificate;binary"]= $this->userCertificate;
715       $remove_userCertificate= false;
716     } else {
717       $remove_userCertificate= true;
718     }
720     /* Special handling for dateOfBirth value */
721     if ($this->use_dob != "1"){
722       if ($this->new) {
723         unset($this->attrs["dateOfBirth"]);
724       } else {
725         $this->attrs["dateOfBirth"]= array();
726       }
727     }
728     if (!$this->gender){
729       if ($this->new) {
730         unset($this->attrs["gender"]);
731       } else {
732         $this->attrs["gender"]= array();
733       }
734     }
735     if (!$this->preferredLanguage){
736       if ($this->new) {
737         unset($this->attrs["preferredLanguage"]);
738       } else {
739         $this->attrs["preferredLanguage"]= array();
740       }
741     }
743     /* Special handling for attribute jpegPhote needed, scale image via
744        image magick to 147x200 pixels and inject resulting data. */
745     if ($this->jpegPhoto != "*removed*"){
747       /* Fallback if there's no image magick inside PHP */
748       if (!function_exists("imagick_blob2image")){
749         /* Get temporary file name for conversation */
750         $fname = tempnam ("/tmp", "GOsa");
752         /* Open file and write out photoData */
753         $fp = fopen ($fname, "w");
754         fwrite ($fp, $this->photoData);
755         fclose ($fp);
757         /* Build conversation query. Filename is generated automatically, so
758            we do not need any special security checks. Exec command and save
759            output. For PHP safe mode, you'll need a configuration which respects
760            image magick as executable... */
761         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
762         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
763             $query, "Execute");
765         /* Read data written by convert */
766         $output= "";
767         $sh= popen($query, 'r');
768         while (!feof($sh)){
769           $output.= fread($sh, 4096);
770         }
771         pclose($sh);
773         unlink($fname);
775         /* Save attribute */
776         $this->attrs["jpegPhoto"] = $output;
778       } else {
780         /* Load the new uploaded Photo */
781         if(!$handle  =  imagick_blob2image($this->photoData))  {
782           gosa_log("Can't Load image");
783         }
785         /* Resizing image to 147x200 and blur */
786         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
787           gosa_log("imagick_resize failed");
788         }
790         /* Converting image to JPEG */
791         if(!imagick_convert($handle,"JPEG")) {
792           gosa_log("Can't Convert to JPEG");
793         }
795         /* Creating binary Code for the Image */
796         if(!$dump = imagick_image2blob($handle)){
797           gosa_log("Can't create blob for image");
798         }
800         /* Sending Image */
801         $output=  $dump;
803         /* Save attribute */
804         $this->attrs["jpegPhoto"] = $output;
805       }
807     } elseif(!$this->new) {
808       $this->attrs["jpegPhoto"] = array();
809     }
811     /* Build new dn */
812     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
813       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
814     } else {
815       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
816     }
818     /* This only gets called when user is renaming himself */
819     $ldap= $this->config->get_ldap_link();
820     if ($this->dn != $new_dn){
822       /* Write entry on new 'dn' */
823       $this->move($this->dn, $new_dn);
825       /* Happen to use the new one */
826       change_ui_dn($this->dn, $new_dn);
827       $this->dn= $new_dn;
828     }
831     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
832        new entries. So do a check first... */
833     $ldap->cat ($this->dn, array('dn'));
834     if ($ldap->fetch()){
835       $mode= "modify";
836     } else {
837       $mode= "add";
838       $ldap->cd($this->config->current['BASE']);
839       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
840     }
842     /* Set password to some junk stuff in case of templates */
843     if ($this->is_template){
844       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
845     }
847     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
848         $this->attributes, "Save via $mode");
850     /* Finally write data with selected 'mode' */
851     $this->cleanup();
852     $ldap->cd ($this->dn);
853     $ldap->$mode ($this->attrs);
854     if (show_ldap_error($ldap->get_error(), sprintf(_("Saving of user/generic account with dn '%s' failed."),$this->dn))){
855       return (1);
856     }
858     /* Remove cert? 
859        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
860        to work around myself. */
861     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
863       /* Reset array, assemble new, this should be reworked */
864       $this->attrs= array();
865       $this->attrs['userCertificate;binary']= array();
867       /* Prepare connection */
868       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
869         die ("Could not connect to LDAP server");
870       }
871       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
872       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
873         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
874         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
875       }
876       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
877         ldap_start_tls($ds);
878       }
879       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
880               $this->config->current['PASSWORD']))) {
881         die ("Could not bind to LDAP");
882       }
884       /* Modify using attrs */
885       ldap_mod_del($ds,$this->dn,$this->attrs);
886       ldap_close($ds);
887     }
889     /* Kerberos server defined? */
890     if (isset($this->config->data['SERVERS']['KERBEROS'])){
891       $cfg= $this->config->data['SERVERS']['KERBEROS'];
892     }
893     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
895       /* Connect to the admin interface */
896       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
897           $cfg['ADMIN'], $cfg['PASSWORD']);
899       /* Errors? */             
900       if ($handle === FALSE){
901         print_red (_("Kerberos database communication failed"));
902         return (2);
903       }
905       /* Build user principal, get list of existsing principals */
906       $principal= $this->uid."@".$cfg['REALM'];
907       $principals = kadm5_get_principals($handle);
909       /* User exists in database? */
910       if (in_array($principal, $principals)){
912         /* Ok. User exists. Remove him/her when pw_storage has
913            changed to be NOT kerberos. */
914         if ($this->pw_storage != "kerberos"){
915           $ret= kadm5_delete_principal ( $handle, $principal);
917           if ($ret === FALSE){
918             print_red (_("Can't remove user from kerberos database."));
919           }
920         }
922       } else {
924         /* User doesn't exists, create it when pw_storage is kerberos. */
925         if ($this->pw_storage == "kerberos"){
926           $ret= kadm5_create_principal ( $handle, $principal);
928           if ($ret === FALSE){
929             print_red (_("Can't add user to kerberos database."));
930           }
931         }
933       }
935       /* Free kerberos admin handle */
936       kadm5_destroy($handle);
937     }
939     /* Optionally execute a command after we're done */
940     if ($mode == "add"){
941       $this->handle_post_events("add");
942     } elseif ($this->is_modified){
943       $this->handle_post_events("modify");
944     }
946     /* Fix tagging if needed */
947     $this->handle_object_tagging();
949     return (0);
950   }
953   /* Check formular input */
954   function check()
955   {
956     /* Call common method to give check the hook */
957     $message= plugin::check();
959     /* Assemble cn */
960     $this->cn= $this->givenName." ".$this->sn;
962     /* Permissions for that base? */
963     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
964       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
965     } else {
966       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
967     }
969     if ($this->dn == "new" &&  !$this->acl_is_createable()){
970       $message[]= _("You have no permissions to create a user on this 'Base'.");
971     } elseif ($this->dn != $new_dn && $this->dn != "new"){
972       if (!$this->acl_is_writeable($this->dn, "user","create")){
973         $message[]= _("You have no permissions to move a user from the original 'Base'.");
974       }
975     }
977     /* must: sn, givenName, uid */
978     if ($this->sn == "" && ($this->acl_is_writeable($this->dn, "user","sn") || ($this->new))){
979       $message[]= _("The required field 'Name' is not set.");
980     }
982     /* UID already used? */
983     $ldap= $this->config->get_ldap_link();
984     $ldap->cd($this->config->current['BASE']);
985     $ldap->search("(uid=$this->uid)", array("uid"));
986     $ldap->fetch();
987     if ($ldap->count() != 0 && $this->dn == 'new'){
988       $message[]= _("There's already a person with this 'Login' in the database.");
989     }
991     /* In template mode, the uid and givenName are autogenerated... */
992     if (!$this->is_template){
993       if ($this->givenName == "" && $this->acl_is_writeable("givenName")){
994         $message[]= _("The required field 'Given name' is not set.");
995       }
996       if ($this->uid == "" && $this->acl_is_writeable("uid")){
997         $message[]= _("The required field 'Login' is not set.");
998       }
999       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
1000         $ldap->cd($this->config->current['BASE']);
1001         $ldap->search("(cn=".$this->cn.")", array("uid"));
1002         $ldap->fetch();
1003         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
1004           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
1005         }
1006       }
1007     }
1009     /* Check for valid input */
1010     if ($this->is_modified && !is_uid($this->uid)){
1011       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
1012     }
1013     if (!is_url($this->labeledURI)){
1014       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
1015     }
1016     if (preg_match ("/[\\\\]/", $this->sn)){
1017       $message[]= _("The field 'Name' contains invalid characters.");
1018     }
1019     if (preg_match ("/[\\\\]/", $this->givenName)){
1020       $message[]= _("The field 'Given name' contains invalid characters.");
1021     }
1023     /* Check phone numbers */
1024     if (!is_phone_nr($this->telephoneNumber)){
1025       $message[]= _("The field 'Phone' contains an invalid phone number.");
1026     }
1027     if (!is_phone_nr($this->facsimileTelephoneNumber)){
1028       $message[]= _("The field 'Fax' contains an invalid phone number.");
1029     }
1030     if (!is_phone_nr($this->mobile)){
1031       $message[]= _("The field 'Mobile' contains an invalid phone number.");
1032     }
1033     if (!is_phone_nr($this->pager)){
1034       $message[]= _("The field 'Pager' contains an invalid phone number.");
1035     }
1037     /* Check for reserved characers */
1038     if (preg_match ('/[,+"?\'()=<>;]/', $this->givenName)){
1039       $message[]= _("The field 'Given name' contains invalid characters.");
1040     }
1041     if (preg_match ('/[,+"?\'()=<>;]/', $this->sn)){
1042       $message[]= _("The field 'Name' contains invalid characters.");
1043     }
1045   return $message;
1046   }
1049   /* Indicate whether a password change is needed or not */
1050   function password_change_needed()
1051   {
1052     return ($this->pw_storage != $this->last_pw_storage);
1053   }
1056   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1057   function load_picture()
1058   {
1059     /* make connection and read jpegPhoto */
1060     $ds= ldap_connect($this->config->current['SERVER']);
1061     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1062     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1063       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1064       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1065     }
1067     if(isset($this->config->current['TLS']) &&
1068         $this->config->current['TLS'] == "true"){
1070       ldap_start_tls($ds);
1071     }
1073     $r= ldap_bind($ds);
1074     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
1076     /* in case we don't get an entry, load a default picture */
1077     $this->set_picture ("./images/default.jpg");
1078     $this->jpegPhoto= "*removed*";
1080     /* fill data from LDAP */
1081     if ($sr) {
1082       $ei=ldap_first_entry($ds, $sr);
1083       if ($ei) {
1084         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
1085           $this->photoData= $info[0];
1086           $_SESSION['binary']= $this->photoData;
1087           $_SESSION['binarytype']= "image/jpeg";
1088           $this->jpegPhoto= "";
1089         }
1090       }
1091     }
1093     /* close conncetion */
1094     ldap_unbind($ds);
1095   }
1098   /* Load a certificate from LDAP, this is going to be simplified later on */
1099   function load_cert()
1100   {
1101     $ds= ldap_connect($this->config->current['SERVER']);
1102     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1103     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1104       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1105       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1106     }
1107     if(isset($this->config->current['TLS']) &&
1108         $this->config->current['TLS'] == "true"){
1110       ldap_start_tls($ds);
1111     }
1113     $r= ldap_bind($ds);
1114     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1116     if ($sr) {
1117       $ei= @ldap_first_entry($ds, $sr);
1118       
1119       if ($ei) {
1120         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1121           $this->userCertificate= "";
1122         } else {
1123           $this->userCertificate= $info[0];
1124         }
1125       }
1126     } else {
1127       $this->userCertificate= "";
1128     }
1130     ldap_unbind($ds);
1131   }
1134   /* Load picture from file to object */
1135   function set_picture($filename)
1136   {
1137     if($this->acl_is_writeable("userPicture")) {
1138       if (!is_file($filename)){
1139         $filename= "./images/default.jpg";
1140         $this->jpegPhoto= "*removed*";
1141       }
1143       $fd = fopen ($filename, "rb");
1144       $this->photoData= fread ($fd, filesize ($filename));
1145       $_SESSION['binary']= $this->photoData;
1146       $_SESSION['binarytype']= "image/jpeg";
1147       $this->jpegPhoto= "";
1149       fclose ($fd);
1150     }
1151   }
1154   /* Load certificate from file to object */
1155   function set_cert($cert, $filename)
1156   {
1157     if(!$thsi->acl_is_writeable("Certificate")) return;
1158     $fd = fopen ($filename, "rb");
1159     if (filesize($filename)>0) {
1160       $this->$cert= fread ($fd, filesize ($filename));
1161       fclose ($fd);
1162       $this->is_modified= TRUE;
1163     } else {
1164       print_red(_("Could not open specified certificate!"));
1165     }
1166   }
1168   /* Adapt from given 'dn' */
1169   function adapt_from_template($dn)
1170   {
1171     plugin::adapt_from_template($dn);
1173     /* Get base */
1174     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1176     if ($this->config->current['GOVERNMENTMODE']){
1178       /* Walk through govattrs */
1179       foreach ($this->govattrs as $val){
1181         if (isset($this->attrs["$val"][0])){
1183           /* If attribute is set, replace dynamic parts: 
1184              %sn, %givenName and %uid. Fill these in our local variables. */
1185           $value= $this->attrs["$val"][0];
1187           foreach (array("sn", "givenName", "uid") as $repl){
1188             if (preg_match("/%$repl/i", $value)){
1189               $value= preg_replace ("/%$repl/i",
1190                   $this->parent->$repl, $value);
1191             }
1192           }
1193           $this->$val= $value;
1194         }
1195       }
1196     }
1198     /* Get back uid/sn/givenName */
1199     if ($this->parent != NULL){
1200       $this->uid= $this->parent->uid;
1201       $this->sn= $this->parent->sn;
1202       $this->givenName= $this->parent->givenName;
1203     }
1204   }
1206  
1207   /* This avoids that users move themselves out of their rights. 
1208    */
1209   function allowedBasesToMoveTo()
1210   {
1211     $allowed = array();
1212     $ret_all = false;
1213     if($this->uid == $_SESSION['ui']->username){
1214       $ldap= $this->config->get_ldap_link(); 
1215       $ldap->cd($this->config->current['BASE']); 
1216       $ldap->search("(&(objectClass=posixGroup)(memberUid=".$_SESSION['ui']->username."))",array("gosaSubtreeACL"));
1217        
1218       while($attrs = $ldap->fetch()){
1219     
1220         if(isset($attrs['gosaSubtreeACL'])){
1221         
1222           foreach($attrs['gosaSubtreeACL'] as $attr){
1223             if((preg_match("/:user#/",$attr))||(preg_match("/:all/",$attr))){
1224               $s =  preg_replace("/^.*ou=groups,/","",$attrs['dn']);
1226               foreach($this->config->idepartments as $key => $dep) {
1227                 if(preg_match("/".$s."/i",$key)){
1228                   $allowed[$key] = $dep;
1229                 }
1230               }
1231             }
1232           }
1233         }
1234       }
1235       if(count($allowed) == 0){
1236         foreach($this->config->idepartments as $key => $dep) {
1237           if($this->base==$key){
1238             $allowed[$key] = $dep;
1239           }
1240         }
1241       }  
1242   
1243       return($allowed);
1244       
1245     }else{
1246       return($this->config->idepartments);
1247     }
1248   } 
1251   function getCopyDialog()
1252   {
1253     $str = "";
1255     $_SESSION['binary'] = $this->photoData; 
1256     $_SESSION['binarytype']= "image/jpeg";
1258     /* Get random number for pictures */
1259     srand((double)microtime()*1000000); 
1260     $rand = rand(0, 10000);
1262     $smarty = get_smarty();
1264     $smarty->assign("passwordTodo","clear");
1266     if(isset($_POST['passwordTodo'])){
1267       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1268     }
1270     $smarty->assign("sn",       $this->sn);
1271     $smarty->assign("givenName",$this->givenName);
1272     $smarty->assign("uid",      $this->uid);
1273     $smarty->assign("rand",     $rand);
1274     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1277     $ret = array();
1278     $ret['string'] = $str;
1279     $ret['status'] = "";  
1280     return($ret);
1281   }
1283   function saveCopyDialog()
1284   {
1286     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1287       $this->set_picture($_FILES['picture_file']['tmp_name']);
1288     }
1290     /* Remove picture? */
1291     if (isset($_POST['picture_remove'])){
1292       $this->jpegPhoto= "*removed*";
1293       $this->set_picture ("./images/default.jpg");
1294       $this->is_modified= TRUE;
1295     }
1297     $attrs = array("uid","givenName","sn");
1298     foreach($attrs as $attr){
1299       if(isset($_POST[$attr])){
1300         $this->$attr = $_POST[$attr];
1301       }
1302     } 
1303   }
1306   function plInfo()
1307   {
1308   
1309     $govattrs= array(
1310         "gouvernmentOrganizationalUnit"             =>  _("Unit"), 
1311         "houseIdentifier"                           =>  _("House identifier"), 
1312         "vocation"                                  =>  _("Vocation"),
1313         "ivbbLastDeliveryCollective"                =>  _("Last delivery"), 
1314         "gouvernmentOrganizationalPersonLocality"   =>  _("Person locality"),
1315         "gouvernmentOrganizationalUnitDescription"  =>  _("Unit description"),
1316         "gouvernmentOrganizationalUnitSubjectArea"  =>  _("Subject area"),
1317         "functionalTitle"                           =>  _("Functional title"),
1318         "certificateSerialNumber"                   =>  _(""),
1319         "publicVisible"                             =>  _("Public visible"),
1320         "street"                                    =>  _("Street"),
1321         "role"                                      =>  _("Role"),
1322         "postalCode"                                =>  _("Postal code"));
1324     $ret = array(
1325         "plShortName" => _("Generic"),
1326         "plDescription" => _("Generic user settings"),
1327         "plSelfModify"  => TRUE,
1328         "plDepends"     => array(),
1329         "plPriority"    => 0,
1330         "plSection"     => array("personal" => _("My account")),
1331         "plCategory"    => array("users" => array("description" => _("Users"),
1332                                                   "objectClass" => "gosaAccount")),
1334         "plProvidedAcls" => array(
1335           "base"              => _("Base"), 
1336           "userPassword"      => _("User password"), 
1337           "sn"                => _("Surename"),
1338           "givenName"         => _("Given name"),
1339           "uid"               => _("User identification"),
1340           "personalTitle"     => _("Personal title"),
1341           "academicTitle"     => _("Academic title"),
1342           "homePostalAddress" => _("Home postal address"),
1343           "homePhone"         => _("Home phone number"),
1344           "labeledURI"        => _("Homepage"),
1345           "o"                 => _("Organization"),
1346           "ou"                => _("Department"),
1347           "dateOfBirth"       => _("Date of birth"),
1348           "gender"            => _("Gender"),
1349           "preferredLanguage" => _("Preferred language"),
1350           "departmentNumber"  => _("Department number"),
1351           "employeeNumber"    => _("Employee number"),
1352           "employeeType"      => _("Employee type"),
1353           "l"                 => _("Location"),
1354           "st"                => _("State"),
1355           "userPicture"       => _("User picture"),
1356           "roomNumber"        => _("Room number"),
1357           "telephoneNumber"   => _("Telefon number"),
1358           "mobile"            => _("Mobile number"),
1359           "pager"             => _("Pager number"),
1360           "Certificate"        => _("User certificates"),
1362           "postalAddress"                => _("Postal address"),
1363           "facsimileTelephoneNumber"     => _("Fax number"))
1364         );
1366     /* Append government attributes if required */
1367       global $config;
1368     if (isset($config->current['GOVERNMENTMODE']) &&  preg_match('/true/i', $config->current['GOVERNMENTMODE'])){
1369       foreach($govattrs as $attr => $desc){
1370         $ret["plProvidedAcls"][$attr] = $desc;
1371       }
1372     }
1374     return($ret);
1375   }
1378 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1379 ?>