Code

Only allow edit remove on certificates if user has write access
[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 (isset($_POST['edit_picture'])){
305       /* Save values for later recovery, in case some presses
306          the cancel button. */
307       $this->old_jpegPhoto= $this->jpegPhoto;
308       $this->old_photoData= $this->photoData;
309       $this->picture_dialog= TRUE;
310       $this->dialog= TRUE;
311     }
313     /* Remove picture? */
314     if (isset($_POST['picture_remove'])){
315       $this->jpegPhoto= "*removed*";
316       $this->set_picture ("./images/default.jpg");
317       $this->is_modified= TRUE;
319       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
320     }
322     /* Save picture */
323     if (isset($_POST['picture_edit_finish'])){
325       /* Check for clean upload */
326       if ($_FILES['picture_file']['name'] != ""){
327         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
328           print_red(_("The specified file has not been uploaded via HTTP POST! Aborted."));
329           exit;
330         }
332         /* Activate new picture */
333         $this->set_picture($_FILES['picture_file']['tmp_name']);
334       }
335       $this->picture_dialog= FALSE;
336       $this->dialog= FALSE;
337       $this->is_modified= TRUE;
338     }
341     /* Cancel picture */
342     if (isset($_POST['picture_edit_cancel'])){
344       /* Restore values */
345       $this->jpegPhoto= $this->old_jpegPhoto;
346       $this->photoData= $this->old_photoData;
348       /* Update picture */
349       $_SESSION['binary']= $this->photoData;
350       $_SESSION['binarytype']= "image/jpeg";
351       $this->picture_dialog= FALSE;
352       $this->dialog= FALSE;
353     }
355     /* Toggle dateOfBirth information */
356     if (isset($_POST['set_dob'])){
357       $this->use_dob= ($this->use_dob == "0")?"1":"0";
358     }
361     /* Want certificate= */
362     if ((isset($_POST['edit_cert'])) && $this->acl_is_readable("Certificate")){
364       /* Save original values for later reconstruction */
365       foreach (array("certificateSerialNumber", "userCertificate",
366             "userSMIMECertificate", "userPKCS12") as $val){
368         $oval= "old_$val";
369         $this->$oval= $this->$val;
370       }
372       $this->cert_dialog= TRUE;
373       $this->dialog= TRUE;
374     }
377     /* Cancel certificate dialog */
378     if (isset($_POST['cert_edit_cancel'])){
380       /* Restore original values in case of 'cancel' */
381       foreach (array("certificateSerialNumber", "userCertificate",
382             "userSMIMECertificate", "userPKCS12") as $val){
384         $oval= "old_$val";
385         $this->$val= $this->$oval;
386       }
387       $this->cert_dialog= FALSE;
388       $this->dialog= FALSE;
389     }
392     /* Remove certificate? */
393     if($this->acl_is_writeable("Certificate")){ 
394       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
395         if (isset($_POST["remove_$val"])){
397           /* Reset specified cert*/
398           $this->$val= "";
399           $this->is_modified= TRUE;
400         }
401       }
402     }
404     /* Upload new cert and close dialog? */     
405     if($this->acl_is_writeable("Certificate")){ 
406       if (isset($_POST['cert_edit_finish'])){
408         /* for all certificates do */
409         foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
410             as $val){
412           /* Check for clean upload */
413           if (array_key_exists($val."_file", $_FILES) &&
414               array_key_exists('name', $_FILES[$val."_file"]) &&
415               $_FILES[$val."_file"]['name'] != "" &&
416               is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
417             $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
418           }
419         }
421         /* Save serial number */
422         if (isset($_POST["certificateSerialNumber"]) &&
423             $_POST["certificateSerialNumber"] != ""){
425           if (!is_id($_POST["certificateSerialNumber"])){
426             print_red (_("Please enter a valid serial number"));
428             foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
429               if ($this->$cert != ""){
430                 $smarty->assign("$cert"."_state", "true");
431               } else {
432                 $smarty->assign("$cert"."_state", "");
433               }
434             }
435             return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
436           }
438           $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
439           $this->is_modified= TRUE;
440         }
442         $this->cert_dialog= FALSE;
443         $this->dialog= FALSE;
444       }
445     }
446     /* Display picture dialog */
447     if ($this->picture_dialog){
448       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
449     }
451     /* Display cert dialog */
452     if ($this->cert_dialog){
453       $smarty->assign("CertificateACL",$this->getacl("Certificate"));
454       $smarty->assign("Certificate_readable",$this->acl_is_readable("Certificate"));
456       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
457         if ($this->$cert != ""){
458           /* import certificate */
459           $certificate = new certificate;
460           $certificate->import($this->$cert);
461       
462           /* Read out data*/
463           $timeto   = $certificate->getvalidto_date();
464           $timefrom = $certificate->getvalidfrom_date();
465           $str = "<table summary=\"\" border=0><tr><td style='vertical-align:top'>CN</td><td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td></tr></table><br>".
466                   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>");
467           $smarty->assign($cert."info",$str);
468           $smarty->assign($cert."_state","true");
469         } else {
470           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
471           $smarty->assign($cert."_state","");
472         }
473       }
474       $smarty->assign("governmentmode", "false");
475       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
476     }
478     /* Prepare password hashes */
479     if ($this->pw_storage == ""){
480       $this->pw_storage= $this->config->current['HASH'];
481     }
483     $temp   = @passwordMethod::get_available_methods();
484     $hashes = $temp['name'];
485     
486     /* Load attributes and acl's */
487     $ui =get_userinfo();
488     foreach($this->attributes as $val){
489       $smarty->assign("$val", $this->$val);
490       $smarty->assign("$val"."ACL", $this->getacl($val));
491     }
493     $smarty->assign("pwmode", $hashes);
494     $smarty->assign("pwmode_select", $this->pw_storage);
495     $smarty->assign("passwordStorageACL", $this->getacl("userPassword"));
496     $smarty->assign("base_select",      $this->base);
497     $smarty->assign("CertificatesACL",  $this->getacl("Certificate"));
498     $smarty->assign("userPictureACL",   $this->getacl("userPicture"));
500     /* Create base acls */
501     $baseACL = $this->getacl("base");
502     if(!$this->acl_is_moveable()) {
503       $baseACL = preg_replace("/w/","",$baseACL);
504     }
505     $smarty->assign("baseACL",          $baseACL);
507     /* Show us the edit screen */
508     @$smarty->assign("bases", $this->allowedBasesToMoveTo());
509 #  $smarty->assign("bases", $this->config->idepartments);
512     /* Save government mode attributes */
513     if (isset($this->config->current['GOVERNMENTMODE']) &&
514         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
515       $smarty->assign("governmentmode", "true");
516       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
517           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
518       $smarty->assign("ivbbmodes", $ivbbmodes);
519       foreach ($this->govattrs as $val){
520         $smarty->assign("$val", $this->$val);
521         $smarty->assign("$val"."ACL", $this->getacl($val));
522       }
523     } else {
524       $smarty->assign("governmentmode", "false");
525     }
527     /* Special mode for uid */
528     $uidACL= $this->getacl("uid");
529     if (isset ($this->dn)){
530       if ($this->dn != "new"){
531         $uidACL= preg_replace("/w/","",$uidACL);
532       }
533     }  else {
534       $uidACL= preg_replace("/w/","",$uidACL);
535     }
536     
537     $smarty->assign("uidACL", $uidACL);
538     $smarty->assign("is_template", $this->is_template);
539     $smarty->assign("use_dob", $this->use_dob);
541     if (isset($this->parent)){
542       if (isset($this->parent->by_object['phoneAccount']) &&
543           $this->parent->by_object['phoneAccount']->is_account){
544         $smarty->assign("has_phoneaccount", "true");
545       } else {
546         $smarty->assign("has_phoneaccount", "false");
547       }
548     } else {
549       $smarty->assign("has_phoneaccount", "false");
550     }
551     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
552   }
555   /* remove object from parent */
556   function remove_from_parent()
557   {
558     $ldap= $this->config->get_ldap_link();
559     $ldap->rmdir ($this->dn);
560     show_ldap_error($ldap->get_error(), sprintf(_("Removing of user/generic account with dn '%s' failed."),$this->dn));
562     /* Delete references to groups */
563     $ldap->cd ($this->config->current['BASE']);
564     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
565     while ($ldap->fetch()){
566       $g= new group($this->config, $ldap->getDN());
567       $g->removeUser($this->uid);
568       $g->save ();
569     }
571     /* Delete references to object groups */
572     $ldap->cd ($this->config->current['BASE']);
573     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
574     while ($ldap->fetch()){
575       $og= new ogroup($this->config, $ldap->getDN());
576       unset($og->member[$this->dn]);
577       $og->save ();
578     }
580     /* Optionally execute a command after we're done */
581     $this->handle_post_events("remove");
582   }
585   /* Save data to object */
586   function save_object()
587   {
588     if (isset($_POST['generic'])){
590       /* Parents save function */
591       plugin::save_object ();
593       /* Save government mode attributes */
594       if ($this->config->current['GOVERNMENTMODE']){
595         foreach ($this->govattrs as $val){
596           if ($this->acl_is_writable($val) && isset ($_POST["$val"])){
597             $data= stripcslashes($_POST["$val"]);
598             if ($data != $this->$val){
599               $this->is_modified= TRUE;
600             }
601             $this->$val= $data;
602           }
603         }
604       }
606       /* In template mode, the uid is autogenerated... */
607       if ($this->is_template){
608         $this->uid= strtolower($this->sn);
609         $this->givenName= $this->sn;
610       }
612       /* Save base and pw_storage, since these are no LDAP attributes */
613       if (isset($_POST['base'])){
614         foreach(array("base", "pw_storage") as $val){
615           if(isset($_POST[$val])){
616             $data= validate($_POST[$val]);
617             if ($data != $this->$val){
618               $this->is_modified= TRUE;
619             }
620             $this->$val= $data;
621           }
622         }
623       }
624     }
625   }
627   function rebind($ldap, $referral)
628   {
629     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
630     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
631       $this->error = "Success";
632       $this->hascon=true;
633       $this->reconnect= true;
634       return (0);
635     } else {
636       $this->error = "Could not bind to " . $credentials['ADMIN'];
637       return NULL;
638     }
639   }
641   /* Save data to LDAP, depending on is_account we save or delete */
642   function save()
643   {
644     /* Only force save of changes .... 
645        If this attributes aren't changed, avoid saving.
646      */
647     if ($this->use_dob == "1"){
648       $this->dateOfBirth= date("Y-m-d", $this->dateOfBirth);
649     }
650     if($this->gender=="0") $this->gender ="";
651     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
652     
653  
654     /* First use parents methods to do some basic fillup in $this->attrs */
655     plugin::save ();
657     /* Remove additional objectClasses */
658     $tmp= array();
659     foreach ($this->attrs['objectClass'] as $key => $set){
660       $found= false;
661       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
662         if (preg_match ("/^$set$/i", $val)){
663           $found= true;
664           break;
665         }
666       }
667       if (!$found){
668         $tmp[]= $set;
669       }
670     }
672     /* Replace the objectClass array. This is done because of the
673        separation into government and normal mode. */
674     $this->attrs['objectClass']= $tmp;
676     /* Add objectClasss for template mode? */
677     if ($this->is_template){
678       $this->attrs['objectClass'][]= "gosaUserTemplate";
679     }
681     /* Hard coded government mode? */
682     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
683       $this->attrs['objectClass'][]= "ivbbentry";
685       /* Copy standard attributes */
686       foreach ($this->govattrs as $val){
687         if ($this->$val != ""){
688           $this->attrs["$val"]= $this->$val;
689         } elseif (!$this->new) {
690           $this->attrs["$val"]= array();
691         }
692       }
694       /* Remove attribute if set to "nein" */
695       if ($this->publicVisible == "nein"){
696         $this->attrs['publicVisible']= array();
697         if($this->new){
698           unset($this->attrs['publicVisible']);
699         }else{
700           $this->attrs['publicVisible']=array();
701         }
703       }
705     }
707     /* Special handling for attribute userCertificate needed */
708     if ($this->userCertificate != ""){
709       $this->attrs["userCertificate;binary"]= $this->userCertificate;
710       $remove_userCertificate= false;
711     } else {
712       $remove_userCertificate= true;
713     }
715     /* Special handling for dateOfBirth value */
716     if ($this->use_dob != "1"){
717       if ($this->new) {
718         unset($this->attrs["dateOfBirth"]);
719       } else {
720         $this->attrs["dateOfBirth"]= array();
721       }
722     }
723     if (!$this->gender){
724       if ($this->new) {
725         unset($this->attrs["gender"]);
726       } else {
727         $this->attrs["gender"]= array();
728       }
729     }
730     if (!$this->preferredLanguage){
731       if ($this->new) {
732         unset($this->attrs["preferredLanguage"]);
733       } else {
734         $this->attrs["preferredLanguage"]= array();
735       }
736     }
738     /* Special handling for attribute jpegPhote needed, scale image via
739        image magick to 147x200 pixels and inject resulting data. */
740     if ($this->jpegPhoto != "*removed*"){
742       /* Fallback if there's no image magick inside PHP */
743       if (!function_exists("imagick_blob2image")){
744         /* Get temporary file name for conversation */
745         $fname = tempnam ("/tmp", "GOsa");
747         /* Open file and write out photoData */
748         $fp = fopen ($fname, "w");
749         fwrite ($fp, $this->photoData);
750         fclose ($fp);
752         /* Build conversation query. Filename is generated automatically, so
753            we do not need any special security checks. Exec command and save
754            output. For PHP safe mode, you'll need a configuration which respects
755            image magick as executable... */
756         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
757         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
758             $query, "Execute");
760         /* Read data written by convert */
761         $output= "";
762         $sh= popen($query, 'r');
763         while (!feof($sh)){
764           $output.= fread($sh, 4096);
765         }
766         pclose($sh);
768         unlink($fname);
770         /* Save attribute */
771         $this->attrs["jpegPhoto"] = $output;
773       } else {
775         /* Load the new uploaded Photo */
776         if(!$handle  =  imagick_blob2image($this->photoData))  {
777           gosa_log("Can't Load image");
778         }
780         /* Resizing image to 147x200 and blur */
781         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
782           gosa_log("imagick_resize failed");
783         }
785         /* Converting image to JPEG */
786         if(!imagick_convert($handle,"JPEG")) {
787           gosa_log("Can't Convert to JPEG");
788         }
790         /* Creating binary Code for the Image */
791         if(!$dump = imagick_image2blob($handle)){
792           gosa_log("Can't create blob for image");
793         }
795         /* Sending Image */
796         $output=  $dump;
798         /* Save attribute */
799         $this->attrs["jpegPhoto"] = $output;
800       }
802     } elseif(!$this->new) {
803       $this->attrs["jpegPhoto"] = array();
804     }
806     /* Build new dn */
807     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
808       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
809     } else {
810       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
811     }
813     /* This only gets called when user is renaming himself */
814     $ldap= $this->config->get_ldap_link();
815     if ($this->dn != $new_dn){
817       /* Write entry on new 'dn' */
818       $this->move($this->dn, $new_dn);
820       /* Happen to use the new one */
821       change_ui_dn($this->dn, $new_dn);
822       $this->dn= $new_dn;
823     }
826     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
827        new entries. So do a check first... */
828     $ldap->cat ($this->dn, array('dn'));
829     if ($ldap->fetch()){
830       $mode= "modify";
831     } else {
832       $mode= "add";
833       $ldap->cd($this->config->current['BASE']);
834       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
835     }
837     /* Set password to some junk stuff in case of templates */
838     if ($this->is_template){
839       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
840     }
842     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
843         $this->attributes, "Save via $mode");
845     /* Finally write data with selected 'mode' */
846     $this->cleanup();
847     $ldap->cd ($this->dn);
848     $ldap->$mode ($this->attrs);
849     if (show_ldap_error($ldap->get_error(), sprintf(_("Saving of user/generic account with dn '%s' failed."),$this->dn))){
850       return (1);
851     }
853     /* Remove cert? 
854        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
855        to work around myself. */
856     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
858       /* Reset array, assemble new, this should be reworked */
859       $this->attrs= array();
860       $this->attrs['userCertificate;binary']= array();
862       /* Prepare connection */
863       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
864         die ("Could not connect to LDAP server");
865       }
866       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
867       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
868         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
869         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
870       }
871       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
872         ldap_start_tls($ds);
873       }
874       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
875               $this->config->current['PASSWORD']))) {
876         die ("Could not bind to LDAP");
877       }
879       /* Modify using attrs */
880       ldap_mod_del($ds,$this->dn,$this->attrs);
881       ldap_close($ds);
882     }
884     /* Kerberos server defined? */
885     if (isset($this->config->data['SERVERS']['KERBEROS'])){
886       $cfg= $this->config->data['SERVERS']['KERBEROS'];
887     }
888     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
890       /* Connect to the admin interface */
891       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
892           $cfg['ADMIN'], $cfg['PASSWORD']);
894       /* Errors? */             
895       if ($handle === FALSE){
896         print_red (_("Kerberos database communication failed"));
897         return (2);
898       }
900       /* Build user principal, get list of existsing principals */
901       $principal= $this->uid."@".$cfg['REALM'];
902       $principals = kadm5_get_principals($handle);
904       /* User exists in database? */
905       if (in_array($principal, $principals)){
907         /* Ok. User exists. Remove him/her when pw_storage has
908            changed to be NOT kerberos. */
909         if ($this->pw_storage != "kerberos"){
910           $ret= kadm5_delete_principal ( $handle, $principal);
912           if ($ret === FALSE){
913             print_red (_("Can't remove user from kerberos database."));
914           }
915         }
917       } else {
919         /* User doesn't exists, create it when pw_storage is kerberos. */
920         if ($this->pw_storage == "kerberos"){
921           $ret= kadm5_create_principal ( $handle, $principal);
923           if ($ret === FALSE){
924             print_red (_("Can't add user to kerberos database."));
925           }
926         }
928       }
930       /* Free kerberos admin handle */
931       kadm5_destroy($handle);
932     }
934     /* Optionally execute a command after we're done */
935     if ($mode == "add"){
936       $this->handle_post_events("add");
937     } elseif ($this->is_modified){
938       $this->handle_post_events("modify");
939     }
941     /* Fix tagging if needed */
942     $this->handle_object_tagging();
944     return (0);
945   }
948   /* Check formular input */
949   function check()
950   {
951     /* Call common method to give check the hook */
952     $message= plugin::check();
954     /* Assemble cn */
955     $this->cn= $this->givenName." ".$this->sn;
957     /* Permissions for that base? */
958     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
959       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
960     } else {
961       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
962     }
964     if ($this->dn == "new" &&  !$this->acl_is_createable()){
965       $message[]= _("You have no permissions to create a user on this 'Base'.");
966     } elseif ($this->dn != $new_dn && $this->dn != "new"){
967       if (!$this->acl_is_writable($this->dn, "user","create")){
968         $message[]= _("You have no permissions to move a user from the original 'Base'.");
969       }
970     }
972     /* must: sn, givenName, uid */
973     if ($this->sn == "" && ($this->acl_is_writable($this->dn, "user","sn") || ($this->new))){
974       $message[]= _("The required field 'Name' is not set.");
975     }
977     /* UID already used? */
978     $ldap= $this->config->get_ldap_link();
979     $ldap->cd($this->config->current['BASE']);
980     $ldap->search("(uid=$this->uid)", array("uid"));
981     $ldap->fetch();
982     if ($ldap->count() != 0 && $this->dn == 'new'){
983       $message[]= _("There's already a person with this 'Login' in the database.");
984     }
986     /* In template mode, the uid and givenName are autogenerated... */
987     if (!$this->is_template){
988       if ($this->givenName == "" && $this->acl_is_writable("givenName")){
989         $message[]= _("The required field 'Given name' is not set.");
990       }
991       if ($this->uid == "" && $this->acl_is_writable("uid")){
992         $message[]= _("The required field 'Login' is not set.");
993       }
994       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
995         $ldap->cd($this->config->current['BASE']);
996         $ldap->search("(cn=".$this->cn.")", array("uid"));
997         $ldap->fetch();
998         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
999           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
1000         }
1001       }
1002     }
1004     /* Check for valid input */
1005     if ($this->is_modified && !is_uid($this->uid)){
1006       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
1007     }
1008     if (!is_url($this->labeledURI)){
1009       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
1010     }
1011     if (preg_match ("/[\\\\]/", $this->sn)){
1012       $message[]= _("The field 'Name' contains invalid characters.");
1013     }
1014     if (preg_match ("/[\\\\]/", $this->givenName)){
1015       $message[]= _("The field 'Given name' contains invalid characters.");
1016     }
1018     /* Check phone numbers */
1019     if (!is_phone_nr($this->telephoneNumber)){
1020       $message[]= _("The field 'Phone' contains an invalid phone number.");
1021     }
1022     if (!is_phone_nr($this->facsimileTelephoneNumber)){
1023       $message[]= _("The field 'Fax' contains an invalid phone number.");
1024     }
1025     if (!is_phone_nr($this->mobile)){
1026       $message[]= _("The field 'Mobile' contains an invalid phone number.");
1027     }
1028     if (!is_phone_nr($this->pager)){
1029       $message[]= _("The field 'Pager' contains an invalid phone number.");
1030     }
1032     /* Check for reserved characers */
1033     if (preg_match ('/[,+"?\'()=<>;]/', $this->givenName)){
1034       $message[]= _("The field 'Given name' contains invalid characters.");
1035     }
1036     if (preg_match ('/[,+"?\'()=<>;]/', $this->sn)){
1037       $message[]= _("The field 'Name' contains invalid characters.");
1038     }
1040   return $message;
1041   }
1044   /* Indicate whether a password change is needed or not */
1045   function password_change_needed()
1046   {
1047     return ($this->pw_storage != $this->last_pw_storage);
1048   }
1051   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1052   function load_picture()
1053   {
1054     /* make connection and read jpegPhoto */
1055     $ds= ldap_connect($this->config->current['SERVER']);
1056     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1057     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1058       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1059       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1060     }
1062     if(isset($this->config->current['TLS']) &&
1063         $this->config->current['TLS'] == "true"){
1065       ldap_start_tls($ds);
1066     }
1068     $r= ldap_bind($ds);
1069     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
1071     /* in case we don't get an entry, load a default picture */
1072     $this->set_picture ("./images/default.jpg");
1073     $this->jpegPhoto= "*removed*";
1075     /* fill data from LDAP */
1076     if ($sr) {
1077       $ei=ldap_first_entry($ds, $sr);
1078       if ($ei) {
1079         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
1080           $this->photoData= $info[0];
1081           $_SESSION['binary']= $this->photoData;
1082           $_SESSION['binarytype']= "image/jpeg";
1083           $this->jpegPhoto= "";
1084         }
1085       }
1086     }
1088     /* close conncetion */
1089     ldap_unbind($ds);
1090   }
1093   /* Load a certificate from LDAP, this is going to be simplified later on */
1094   function load_cert()
1095   {
1096     $ds= ldap_connect($this->config->current['SERVER']);
1097     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1098     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1099       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1100       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1101     }
1102     if(isset($this->config->current['TLS']) &&
1103         $this->config->current['TLS'] == "true"){
1105       ldap_start_tls($ds);
1106     }
1108     $r= ldap_bind($ds);
1109     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1111     if ($sr) {
1112       $ei= @ldap_first_entry($ds, $sr);
1113       
1114       if ($ei) {
1115         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1116           $this->userCertificate= "";
1117         } else {
1118           $this->userCertificate= $info[0];
1119         }
1120       }
1121     } else {
1122       $this->userCertificate= "";
1123     }
1125     ldap_unbind($ds);
1126   }
1129   /* Load picture from file to object */
1130   function set_picture($filename)
1131   {
1132     if (!is_file($filename)){
1133       $filename= "./images/default.jpg";
1134       $this->jpegPhoto= "*removed*";
1135     }
1137     $fd = fopen ($filename, "rb");
1138     $this->photoData= fread ($fd, filesize ($filename));
1139     $_SESSION['binary']= $this->photoData;
1140     $_SESSION['binarytype']= "image/jpeg";
1141     $this->jpegPhoto= "";
1143     fclose ($fd);
1144   }
1147   /* Load certificate from file to object */
1148   function set_cert($cert, $filename)
1149   {
1150     if(!$thsi->acl_is_writeable("Certificate")) return;
1151     $fd = fopen ($filename, "rb");
1152     if (filesize($filename)>0) {
1153       $this->$cert= fread ($fd, filesize ($filename));
1154       fclose ($fd);
1155       $this->is_modified= TRUE;
1156     } else {
1157       print_red(_("Could not open specified certificate!"));
1158     }
1159   }
1161   /* Adapt from given 'dn' */
1162   function adapt_from_template($dn)
1163   {
1164     plugin::adapt_from_template($dn);
1166     /* Get base */
1167     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1169     if ($this->config->current['GOVERNMENTMODE']){
1171       /* Walk through govattrs */
1172       foreach ($this->govattrs as $val){
1174         if (isset($this->attrs["$val"][0])){
1176           /* If attribute is set, replace dynamic parts: 
1177              %sn, %givenName and %uid. Fill these in our local variables. */
1178           $value= $this->attrs["$val"][0];
1180           foreach (array("sn", "givenName", "uid") as $repl){
1181             if (preg_match("/%$repl/i", $value)){
1182               $value= preg_replace ("/%$repl/i",
1183                   $this->parent->$repl, $value);
1184             }
1185           }
1186           $this->$val= $value;
1187         }
1188       }
1189     }
1191     /* Get back uid/sn/givenName */
1192     if ($this->parent != NULL){
1193       $this->uid= $this->parent->uid;
1194       $this->sn= $this->parent->sn;
1195       $this->givenName= $this->parent->givenName;
1196     }
1197   }
1199  
1200   /* This avoids that users move themselves out of their rights. 
1201    */
1202   function allowedBasesToMoveTo()
1203   {
1204     $allowed = array();
1205     $ret_all = false;
1206     if($this->uid == $_SESSION['ui']->username){
1207       $ldap= $this->config->get_ldap_link(); 
1208       $ldap->cd($this->config->current['BASE']); 
1209       $ldap->search("(&(objectClass=posixGroup)(memberUid=".$_SESSION['ui']->username."))",array("gosaSubtreeACL"));
1210        
1211       while($attrs = $ldap->fetch()){
1212     
1213         if(isset($attrs['gosaSubtreeACL'])){
1214         
1215           foreach($attrs['gosaSubtreeACL'] as $attr){
1216             if((preg_match("/:user#/",$attr))||(preg_match("/:all/",$attr))){
1217               $s =  preg_replace("/^.*ou=groups,/","",$attrs['dn']);
1219               foreach($this->config->idepartments as $key => $dep) {
1220                 if(preg_match("/".$s."/i",$key)){
1221                   $allowed[$key] = $dep;
1222                 }
1223               }
1224             }
1225           }
1226         }
1227       }
1228       if(count($allowed) == 0){
1229         foreach($this->config->idepartments as $key => $dep) {
1230           if($this->base==$key){
1231             $allowed[$key] = $dep;
1232           }
1233         }
1234       }  
1235   
1236       return($allowed);
1237       
1238     }else{
1239       return($this->config->idepartments);
1240     }
1241   } 
1244   function getCopyDialog()
1245   {
1246     $str = "";
1248     $_SESSION['binary'] = $this->photoData; 
1249     $_SESSION['binarytype']= "image/jpeg";
1251     /* Get random number for pictures */
1252     srand((double)microtime()*1000000); 
1253     $rand = rand(0, 10000);
1255     $smarty = get_smarty();
1257     $smarty->assign("passwordTodo","clear");
1259     if(isset($_POST['passwordTodo'])){
1260       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1261     }
1263     $smarty->assign("sn",       $this->sn);
1264     $smarty->assign("givenName",$this->givenName);
1265     $smarty->assign("uid",      $this->uid);
1266     $smarty->assign("rand",     $rand);
1267     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1270     $ret = array();
1271     $ret['string'] = $str;
1272     $ret['status'] = "";  
1273     return($ret);
1274   }
1276   function saveCopyDialog()
1277   {
1279     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1280       $this->set_picture($_FILES['picture_file']['tmp_name']);
1281     }
1283     /* Remove picture? */
1284     if (isset($_POST['picture_remove'])){
1285       $this->jpegPhoto= "*removed*";
1286       $this->set_picture ("./images/default.jpg");
1287       $this->is_modified= TRUE;
1288     }
1290     $attrs = array("uid","givenName","sn");
1291     foreach($attrs as $attr){
1292       if(isset($_POST[$attr])){
1293         $this->$attr = $_POST[$attr];
1294       }
1295     } 
1296   }
1299   function plInfo()
1300   {
1301   
1302     $govattrs= array(
1303         "gouvernmentOrganizationalUnit"             =>  _("Unit"), 
1304         "houseIdentifier"                           =>  _("House identifier"), 
1305         "vocation"                                  =>  _("Vocation"),
1306         "ivbbLastDeliveryCollective"                =>  _("Last delivery"), 
1307         "gouvernmentOrganizationalPersonLocality"   =>  _("Person locality"),
1308         "gouvernmentOrganizationalUnitDescription"  =>  _("Unit description"),
1309         "gouvernmentOrganizationalUnitSubjectArea"  =>  _("Subject area"),
1310         "functionalTitle"                           =>  _("Functional title"),
1311         "certificateSerialNumber"                   =>  _(""),
1312         "publicVisible"                             =>  _("Public visible"),
1313         "street"                                    =>  _("Street"),
1314         "role"                                      =>  _("Role"),
1315         "postalCode"                                =>  _("Postal code"));
1317     $ret = array(
1318         "plShortName" => _("Generic"),
1319         "plDescription" => _("Generic user settings"),
1320         "plSelfModify"  => TRUE,
1321         "plDepends"     => array(),
1322         "plPriority"    => 0,
1323         "plSection"     => array("personal" => _("My account")),
1324         "plCategory"    => array("users" => array("description" => _("Users"),
1325                                                   "objectClass" => "gosaAccount")),
1327         "plProvidedAcls" => array(
1328           "base"              => _("Base"), 
1329           "userPassword"      => _("User password"), 
1330           "sn"                => _("Surename"),
1331           "givenName"         => _("Given name"),
1332           "uid"               => _("User identification"),
1333           "personalTitle"     => _("Personal title"),
1334           "academicTitle"     => _("Academic title"),
1335           "homePostalAddress" => _("Home postal address"),
1336           "homePhone"         => _("Home phone number"),
1337           "labeledURI"        => _("Homepage"),
1338           "o"                 => _("Organization"),
1339           "ou"                => _("Department"),
1340           "dateOfBirth"       => _("Date of birth"),
1341           "gender"            => _("Gender"),
1342           "preferredLanguage" => _("Preferred language"),
1343           "departmentNumber"  => _("Department number"),
1344           "employeeNumber"    => _("Employee number"),
1345           "employeeType"      => _("Employee type"),
1346           "l"                 => _("Location"),
1347           "st"                => _("State"),
1348           "userPicture"       => _("User picture"),
1349           "roomNumber"        => _("Room number"),
1350           "telephoneNumber"   => _("Telefon number"),
1351           "mobile"            => _("Mobile number"),
1352           "pager"             => _("Pager number"),
1353           "Certificate"        => _("User certificates"),
1355           "postalAddress"                => _("Postal address"),
1356           "facsimileTelephoneNumber"     => _("Fax number"))
1357         );
1359     /* Append government attributes if required */
1360       global $config;
1361     if (isset($config->current['GOVERNMENTMODE']) &&  preg_match('/true/i', $config->current['GOVERNMENTMODE'])){
1362       foreach($govattrs as $attr => $desc){
1363         $ret["plProvidedAcls"][$attr] = $desc;
1364       }
1365     }
1367     return($ret);
1368   }
1371 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1372 ?>