Code

Skip saving user certificate in copy & paste
[gosa.git] / plugins / personal / generic / class_user.inc
1 <?php
2 /*!
3   \brief   user plugin
4   \author  Cajus Pollmeier <pollmeier@gonicus.de>
5   \version 2.00
6   \date    24.07.2003
8   This class provides the functionality to read and write all attributes
9   relevant for person, organizationalPerson, inetOrgPerson and gosaAccount
10   from/to the LDAP. It does syntax checking and displays the formulars required.
11  */
13 class user extends plugin
14 {
15   /* Definitions */
16   var $plHeadline= "Generic";
17   var $plDescription= "This does something";
19   /* CLI vars */
20   var $cli_summary= "Handling of GOsa's user base object";
21   var $cli_description= "Some longer text\nfor help";
22   var $cli_parameters= array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
24   /* Plugin specific values */
25   var $base= "";
26   var $cn= "";
27   var $personalTitle= "";
28   var $academicTitle= "";
29   var $homePostalAddress= "";
30   var $homePhone= "";
31   var $labeledURI= "";
32   var $o= "";
33   var $ou= "";
34   var $departmentNumber= "";
35   var $employeeNumber= "";
36   var $employeeType= "";
37   var $roomNumber= "";
38   var $telephoneNumber= "";
39   var $facsimileTelephoneNumber= "";
40   var $mobile= "";
41   var $pager= "";
42   var $l= "";
43   var $st= "";
44   var $postalAddress= "";
45   var $dateOfBirth;
46   var $use_dob= "0";
47   var $gender="0";
48   var $preferredLanguage="0";
50   var $jpegPhoto= "*removed*";
51   var $photoData= "";
52   var $old_jpegPhoto= "";
53   var $old_photoData= "";
54   var $cert_dialog= FALSE;
55   var $picture_dialog= FALSE;
57   var $userPKCS12= "";
58   var $userSMIMECertificate= "";
59   var $userCertificate= "";
60   var $certificateSerialNumber= "";
61   var $old_certificateSerialNumber= "";
62   var $old_userPKCS12= "";
63   var $old_userSMIMECertificate= "";
64   var $old_userCertificate= "";
66   var $gouvernmentOrganizationalUnit= "";
67   var $houseIdentifier= "";
68   var $street= "";
69   var $postalCode= "";
70   var $vocation= "";
71   var $ivbbLastDeliveryCollective= "";
72   var $gouvernmentOrganizationalPersonLocality= "";
73   var $gouvernmentOrganizationalUnitDescription= "";
74   var $gouvernmentOrganizationalUnitSubjectArea= "";
75   var $functionalTitle= "";
76   var $role= "";
77   var $publicVisible= "";
79   var $dialog;
81   /* variables to trigger password changes */
82   var $pw_storage= "crypt";
83   var $last_pw_storage= "unset";
84   var $had_userCertificate= FALSE;
86   /* attribute list for save action */
87   var $attributes= array("sn", "givenName", "uid", "personalTitle", "academicTitle",
88       "homePostalAddress", "homePhone", "labeledURI", "o", "ou", "dateOfBirth", "gender","preferredLanguage",
89       "departmentNumber", "employeeNumber", "employeeType", "l", "st","jpegPhoto",
90       "roomNumber", "telephoneNumber", "mobile", "pager", "cn", "userPKCS12",
91       "postalAddress", "facsimileTelephoneNumber", "userSMIMECertificate");
93   var $objectclasses= array("top", "person", "organizationalPerson", "inetOrgPerson",
94       "gosaAccount");
96   /* attributes that are part of the government mode */
97   var $govattrs= array("gouvernmentOrganizationalUnit", "houseIdentifier", "vocation",
98       "ivbbLastDeliveryCollective", "gouvernmentOrganizationalPersonLocality",
99       "gouvernmentOrganizationalUnitDescription","gouvernmentOrganizationalUnitSubjectArea",
100       "functionalTitle", "certificateSerialNumber", "publicVisible", "street", "role",
101       "postalCode");
104   /* constructor, if 'dn' is set, the node loads the given
105      'dn' from LDAP */
106   function user ($config, $dn= NULL)
107   {
108     $this->config= $config;
109     /* Configuration is fine, allways */
110     if ($this->config->current['GOVERNMENTMODE']){
111       $this->attributes=array_merge($this->attributes,$this->govattrs);
112     }
114     /* Load base attributes */
115     plugin::plugin ($config, $dn);
117     if ($this->config->current['GOVERNMENTMODE']){
118       /* Fix public visible attribute if unset */
119       if (!isset($this->attrs['publicVisible'])){
120         $this->publicVisible == "nein";
121       }
122     }
124     /* Load government mode attributes */
125     if ($this->config->current['GOVERNMENTMODE']){
126       /* Copy all attributs */
127       foreach ($this->govattrs as $val){
128         if (isset($this->attrs["$val"][0])){
129           $this->$val= $this->attrs["$val"][0];
130         }
131       }
132     }
134     /* Create me for new accounts */
135     if ($dn == "new"){
136       $this->is_account= TRUE;
137     }
139     /* Make hash default to md5 if not set in config */
140     if (!isset($this->config->current['HASH'])){
141       $hash= "md5";
142     } else {
143       $hash= $this->config->current['HASH'];
144     }
146     /* Load data from LDAP? */
147     if ($dn != NULL){
149       /* Do base conversation */
150       if ($this->dn == "new"){
151         $ui= get_userinfo();
152         $this->base= dn2base($ui->dn);
153       } else {
154         $this->base= dn2base($dn);
155       }
157       /* get password storage type */
158       if (isset ($this->attrs['userPassword'][0])){
159         /* Initialize local array */
160         $matches= array();
161         if (preg_match ("/^{([^}]+)}(.+)/", $this->attrs['userPassword'][0], $matches)){
162           $this->pw_storage= strtolower($matches[1]);
163         } else {
164           if ($this->attrs['userPassword'][0] != ""){
165             $this->pw_storage= "clear";
166           } else {
167             $this->pw_storage= $hash;
168           }
169         }
170       } else {
171         /* Preset with vaule from configuration */
172         $this->pw_storage= $hash;
173       }
175       /* Load extra attributes: certificate and picture */
176       $this->load_picture();
177       $this->load_cert();
178       if ($this->userCertificate != ""){
179         $this->had_userCertificate= TRUE;
180       }
181     }
183     /* Reset password storage indicator, used by password_change_needed() */
184     if ($dn == "new"){
185       $this->last_pw_storage= "unset";
186     } else {
187       $this->last_pw_storage= $this->pw_storage;
188     }
190     /* Generate dateOfBirth entry */
191     if (isset ($this->attrs['dateOfBirth'])){
192       /* This entry is ISO 8601 conform */
193       list($year, $month, $day)= split("-", $this->attrs['dateOfBirth'][0], 3);
194     
195       $this->dateOfBirth=array( 'mon'=> $month,"mday"=> $day,"year"=> $year);
196       $this->use_dob= "1";
197     } else {
198       $this->use_dob= "0";
199     }
201     /* Put gender attribute to upper case */
202     if (isset ($this->attrs['gender'])){
203       $this->gender= strtoupper($this->attrs['gender'][0]);
204     }
205   }
208   /* execute generates the html output for this node */
209   function execute()
210   {
211     /* Call parent execute */
212     plugin::execute();
214     $smarty= get_smarty();
216     /* Fill calendar */
217     if ($this->dateOfBirth == "0"){
218       $date= getdate();
219     } else {
220       if(is_array($this->dateOfBirth)){
221         $date = $this->dateOfBirth;
222       }else{
223         $date = getdate($this->dateOfBirth);
224       } 
225     }
227     $days= array();
228     for($d= 1; $d<32; $d++){
229       $days[$d]= $d;
230     }
231     $years= array();
233     if(($date['year']-100)<1901){
234       $start = 1901;
235     }else{
236       $start = $date['year']-100;
237     }
239     $end = $start +100;
240     
241     for($y= $start; $y<=$end; $y++){
242       $years[]= $y;
243     }
244     $years['-']= "-&nbsp;";
245     $months= array(_("January"), _("February"), _("March"), _("April"),
246         _("May"), _("June"), _("July"), _("August"), _("September"),
247         _("October"), _("November"), _("December"), '-' => '-&nbsp;');
248     $smarty->assign("day", $date["mday"]);
249     $smarty->assign("days", $days);
250     $smarty->assign("months", $months);
251     $smarty->assign("month", $date["mon"]-1);
252     $smarty->assign("years", $years);
253     $smarty->assign("year", $date["year"]);
255     /* Assign sex */
256     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
257     $smarty->assign("gender_list", $sex);
259     /* Assign prefered langage */
260     $language= array(0 => "&nbsp;", "fr_FR" => ("fr_FR"), "en_EN" => ("en_EN"), 
261                                     "de_DE" => ("de_DE"), "it_IT" => ("it_IT"), 
262                                     "nl_NL" => ("nl_NL"), "ru_RU" => ("ru_RU"));
263     $smarty->assign("preferredLanguage_list", $language);
265     /* Get random number for pictures */
266     srand((double)microtime()*1000000); 
267     $smarty->assign("rand", rand(0, 10000));
269     /* Do we represent a valid gosaAccount? */
270     if (!$this->is_account){
271       echo "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
272         _("This account has no valid GOsa extensions.")."</b>";
273       return;
274     }
276     /* Base select dialog */
277     $once = true;
278     foreach($_POST as $name => $value){
279       if(preg_match("/^chooseBase/",$name) && $once){
280         $once = false;
281         $this->dialog = new baseSelectDialog($this->config,$this->allowedBasesToMoveTo());
282         $this->dialog->setCurrentBase($this->base);
283       }
284     }
286     /* Dialog handling */
287     if(is_object($this->dialog)){
288       /* Must be called before save_object */
289       $this->dialog->save_object();
290    
291       if($this->dialog->isClosed()){
292         $this->dialog = false;
293       }elseif($this->dialog->isSelected()){
294         $this->base = $this->dialog->isSelected();
295         $this->dialog= false;
296       }else{
297         return($this->dialog->execute());
298       }
299     }
301     /* Want picture edit dialog? */
302     if (isset($_POST['edit_picture'])){
303       /* Save values for later recovery, in case some presses
304          the cancel button. */
305       $this->old_jpegPhoto= $this->jpegPhoto;
306       $this->old_photoData= $this->photoData;
307       $this->picture_dialog= TRUE;
308       $this->dialog= TRUE;
309     }
311     /* Remove picture? */
312     if (isset($_POST['picture_remove'])){
313       $this->set_picture ();
314       $this->jpegPhoto= "*removed*";
315       $this->is_modified= TRUE;
317       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
318     }
320     /* Save picture */
321     if (isset($_POST['picture_edit_finish'])){
323       /* Check for clean upload */
324       if ($_FILES['picture_file']['name'] != ""){
325         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
326           print_red(_("The specified file has not been uploaded via HTTP POST! Aborted."));
327           exit;
328         }
330         /* Activate new picture */
331         $this->set_picture($_FILES['picture_file']['tmp_name']);
332       }
333       $this->picture_dialog= FALSE;
334       $this->dialog= FALSE;
335       $this->is_modified= TRUE;
336     }
339     /* Cancel picture */
340     if (isset($_POST['picture_edit_cancel'])){
342       /* Restore values */
343       $this->jpegPhoto= $this->old_jpegPhoto;
344       $this->photoData= $this->old_photoData;
346       /* Update picture */
347       $_SESSION['binary']= $this->photoData;
348       $_SESSION['binarytype']= "image/jpeg";
349       $this->picture_dialog= FALSE;
350       $this->dialog= FALSE;
351     }
353     /* Toggle dateOfBirth information */
354     if (isset($_POST['set_dob'])){
355       $this->use_dob= ($this->use_dob == "0")?"1":"0";
356     }
359     /* Want certificate= */
360     if (isset($_POST['edit_cert'])){
362       /* Save original values for later reconstruction */
363       foreach (array("certificateSerialNumber", "userCertificate",
364             "userSMIMECertificate", "userPKCS12") as $val){
366         $oval= "old_$val";
367         $this->$oval= $this->$val;
368       }
370       $this->cert_dialog= TRUE;
371       $this->dialog= TRUE;
372     }
375     /* Cancel certificate dialog */
376     if (isset($_POST['cert_edit_cancel'])){
378       /* Restore original values in case of 'cancel' */
379       foreach (array("certificateSerialNumber", "userCertificate",
380             "userSMIMECertificate", "userPKCS12") as $val){
382         $oval= "old_$val";
383         $this->$val= $this->$oval;
384       }
385       $this->cert_dialog= FALSE;
386       $this->dialog= FALSE;
387     }
390     /* Remove certificate? */
391     foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
392       if (isset($_POST["remove_$val"])){
394         /* Reset specified cert*/
395         $this->$val= "";
396         $this->is_modified= TRUE;
397       }
398     }
401     /* Upload new cert and close dialog? */     
402     if (isset($_POST['cert_edit_finish'])){
404       /* for all certificates do */
405       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
406           as $val){
408         /* Check for clean upload */
409         if (array_key_exists($val."_file", $_FILES) &&
410             array_key_exists('name', $_FILES[$val."_file"]) &&
411             $_FILES[$val."_file"]['name'] != "" &&
412             is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
413           $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
414         }
415       }
417       /* Save serial number */
418       if (isset($_POST["certificateSerialNumber"]) &&
419           $_POST["certificateSerialNumber"] != ""){
421         if (!is_id($_POST["certificateSerialNumber"])){
422           print_red (_("Please enter a valid serial number"));
424           foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
425             if ($this->$cert != ""){
426               $smarty->assign("$cert"."_state", "true");
427             } else {
428               $smarty->assign("$cert"."_state", "");
429             }
430           }
431           return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
432         }
434         $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
435         $this->is_modified= TRUE;
436       }
438       $this->cert_dialog= FALSE;
439       $this->dialog= FALSE;
440     }
442     /* Display picture dialog */
443     if ($this->picture_dialog){
444       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
445     }
447     /* Display cert dialog */
448     if ($this->cert_dialog){
449       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
450         if ($this->$cert != ""){
451           /* import certificate */
452           $certificate = new certificate;
453           $certificate->import($this->$cert);
454       
455           /* Read out data*/
456           $timeto   = $certificate->getvalidto_date();
457           $timefrom = $certificate->getvalidfrom_date();
459           /* Additional info if start end time is '0' */
460           $add_str_info = "";
461           if($timeto == 0 && $timefrom == 0){
462             $add_str_info = "<br><i>"._("(Some types of certificates are currently not supported and may be displayed as 'invalid'.)")."</i>";
463           }
465           $str = "<table summary=\"\" border=0>
466                     <tr>
467                       <td style='vertical-align:top'>CN</td>
468                       <td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td>
469                     </tr>
470                   </table><br>".
471                   
472                   sprintf(_("Certificate is valid from %s to %s and is currently %s."), 
473                         "<b>".date('d M Y',$timefrom)."</b>",
474                         "<b>".date('d M Y',$timeto)."</b>", 
475                         $certificate->isvalid()?"<b><font style='color:green'>"._("valid")."</font></b>": 
476                                                 "<b><font style='color:red'>"._("invalid")."</font></b>").$add_str_info;
477           $smarty->assign($cert."info",$str);
478           $smarty->assign($cert."_state","true");
479         } else {
480           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
481           $smarty->assign($cert."_state","");
482         }
483       }
484       $smarty->assign("governmentmode", "false");
485       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
486     }
488     /* Show us the edit screen */
489     @$smarty->assign("bases", $this->allowedBasesToMoveTo());
490 #  $smarty->assign("bases", $this->config->idepartments);
491     $smarty->assign("base_select",      $this->base);
492     $smarty->assign("selectmode",       chkacl($this->acl, "create"));
493     $smarty->assign("certificatesACL",  chkacl($this->acl, "certificates"));
494     $smarty->assign("jpegPhotoACL",     chkacl($this->acl, "jpegPhoto"));
496     /* Prepare password hashes */
497     if ($this->pw_storage == ""){
498       $this->pw_storage= $this->config->current['HASH'];
499     }
501     $temp   = @passwordMethod::get_available_methods();
502     $hashes = $temp['name'];
503     
504     $smarty->assign("pwmode", $hashes);
505     $smarty->assign("pwmode_select", $this->pw_storage);
506     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
508     /* Load attributes and acl's */
509     foreach($this->attributes as $val){
510       $smarty->assign("$val", $this->$val);
511       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
512     }
514     /* Save government mode attributes */
515     if (isset($this->config->current['GOVERNMENTMODE']) &&
516         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
517       $smarty->assign("governmentmode", "true");
518       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
519           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
520       $smarty->assign("ivbbmodes", $ivbbmodes);
521       foreach ($this->govattrs as $val){
522         $smarty->assign("$val", $this->$val);
523         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
524       }
525     } else {
526       $smarty->assign("governmentmode", "false");
527     }
529     /* Special mode for uid */
530     $uidACL= "";
531     if (isset ($this->dn)){
532       if ($this->dn != "new"){
533         $uidACL="readonly";
534       }
535     }  else {
536       $uidACL= "readonly";
537     }
538     $uidACL.= " ".chkacl($this->acl, "uid");
539     
540     $smarty->assign("uidACL", $uidACL);
541     $smarty->assign("is_template", $this->is_template);
542     $smarty->assign("use_dob", $this->use_dob);
544     if (isset($this->parent)){
545       if (isset($this->parent->by_object['phoneAccount']) &&
546           $this->parent->by_object['phoneAccount']->is_account){
547         $smarty->assign("has_phoneaccount", "true");
548       } else {
549         $smarty->assign("has_phoneaccount", "false");
550       }
551     } else {
552       $smarty->assign("has_phoneaccount", "false");
553     }
554     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
555   }
558   /* remove object from parent */
559   function remove_from_parent()
560   {
561     $ldap= $this->config->get_ldap_link();
562     $ldap->rmdir ($this->dn);
563     show_ldap_error($ldap->get_error(), _("Removing generic user account failed"));
565     /* Delete references to groups */
566     $ldap->cd ($this->config->current['BASE']);
567     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
568     while ($ldap->fetch()){
569       $g= new group($this->config, $ldap->getDN());
570       $g->removeUser($this->uid);
571       $g->save ();
572     }
574     /* Delete references to object groups */
575     $ldap->cd ($this->config->current['BASE']);
576     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
577     while ($ldap->fetch()){
578       $og= new ogroup($this->config, $ldap->getDN());
579       unset($og->member[$this->dn]);
580       $og->save ();
581     }
583     /* Optionally execute a command after we're done */
584     $this->handle_post_events("remove",array("uid" => $this->uid));
585   }
588   /* Save data to object */
589   function save_object()
590   {
591     if (isset($_POST['generic'])){
593       /* Parents save function */
594       plugin::save_object ();
596       /* Save government mode attributes */
597       if ($this->config->current['GOVERNMENTMODE']){
598         foreach ($this->govattrs as $val){
599           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
600             $data= stripcslashes($_POST["$val"]);
601             if ($data != $this->$val){
602               $this->is_modified= TRUE;
603             }
604             $this->$val= $data;
605           }
606         }
607       }
609       /* In template mode, the uid is autogenerated... */
610       if ($this->is_template){
611         $this->uid= strtolower($this->sn);
612         $this->givenName= $this->sn;
613       }
615       /* Save base and pw_storage, since these are no LDAP attributes */
616       if (isset($_POST['base'])){
617         foreach(array("base", "pw_storage") as $val){
618           if(isset($_POST[$val])){
619             $data= validate($_POST[$val]);
620             if ($data != $this->$val){
621               $this->is_modified= TRUE;
622             }
623             $this->$val= $data;
624           }
625         }
626       }
627     }
628   }
630   function rebind($ldap, $referral)
631   {
632     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
633     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
634       $this->error = "Success";
635       $this->hascon=true;
636       $this->reconnect= true;
637       return (0);
638     } else {
639       $this->error = "Could not bind to " . $credentials['ADMIN'];
640       return NULL;
641     }
642   }
644   /* Save data to LDAP, depending on is_account we save or delete */
645   function save()
646   {
647     /* Only force save of changes .... 
648        If this attributes aren't changed, avoid saving.
649      */
650     if ($this->use_dob == "1"){
651       $this->dateOfBirth= date("Y-m-d", $this->dateOfBirth);
652     }
653     if($this->gender=="0") $this->gender ="";
654     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
655     
656  
657     /* First use parents methods to do some basic fillup in $this->attrs */
658     plugin::save ();
660     /* Remove additional objectClasses */
661     $tmp= array();
662     foreach ($this->attrs['objectClass'] as $key => $set){
663       $found= false;
664       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
665         if (preg_match ("/^$set$/i", $val)){
666           $found= true;
667           break;
668         }
669       }
670       if (!$found){
671         $tmp[]= $set;
672       }
673     }
675     /* Replace the objectClass array. This is done because of the
676        separation into government and normal mode. */
677     $this->attrs['objectClass']= $tmp;
679     /* Add objectClasss for template mode? */
680     if ($this->is_template){
681       $this->attrs['objectClass'][]= "gosaUserTemplate";
682     }
684     /* Hard coded government mode? */
685     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
686       $this->attrs['objectClass'][]= "ivbbentry";
688       /* Copy standard attributes */
689       foreach ($this->govattrs as $val){
690         if ($this->$val != ""){
691           $this->attrs["$val"]= $this->$val;
692         } elseif (!$this->new) {
693           $this->attrs["$val"]= array();
694         }
695       }
697       /* Remove attribute if set to "nein" */
698       if ($this->publicVisible == "nein"){
699         $this->attrs['publicVisible']= array();
700         if($this->new){
701           unset($this->attrs['publicVisible']);
702         }else{
703           $this->attrs['publicVisible']=array();
704         }
706       }
708     }
710     /* Special handling for attribute userCertificate needed */
711     if ($this->userCertificate != ""){
712       $this->attrs["userCertificate;binary"]= $this->userCertificate;
713       $remove_userCertificate= false;
714     } else {
715       $remove_userCertificate= true;
716     }
718     /* Special handling for dateOfBirth value */
719     if ($this->use_dob != "1"){
720       if ($this->new) {
721         unset($this->attrs["dateOfBirth"]);
722       } else {
723         $this->attrs["dateOfBirth"]= array();
724       }
725     }
726     if (!$this->gender){
727       if ($this->new) {
728         unset($this->attrs["gender"]);
729       } else {
730         $this->attrs["gender"]= array();
731       }
732     }
733     if (!$this->preferredLanguage){
734       if ($this->new) {
735         unset($this->attrs["preferredLanguage"]);
736       } else {
737         $this->attrs["preferredLanguage"]= array();
738       }
739     }
741     /* Special handling for attribute jpegPhote needed, scale image via
742        image magick to 147x200 pixels and inject resulting data. */
743     if ($this->jpegPhoto != "*removed*"){
745       /* Fallback if there's no image magick inside PHP */
746       if (!function_exists("imagick_blob2image")){
747         /* Get temporary file name for conversation */
748         $fname = tempnam ("/tmp", "GOsa");
750         /* Open file and write out photoData */
751         $fp = fopen ($fname, "w");
752         fwrite ($fp, $this->photoData);
753         fclose ($fp);
755         /* Build conversation query. Filename is generated automatically, so
756            we do not need any special security checks. Exec command and save
757            output. For PHP safe mode, you'll need a configuration which respects
758            image magick as executable... */
759         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
760         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
761             $query, "Execute");
763         /* Read data written by convert */
764         $output= "";
765         $sh= popen($query, 'r');
766         while (!feof($sh)){
767           $output.= fread($sh, 4096);
768         }
769         pclose($sh);
771         unlink($fname);
773         /* Save attribute */
774         $this->attrs["jpegPhoto"] = $output;
776       } else {
778         /* Load the new uploaded Photo */
779         if(!$handle  =  imagick_blob2image($this->photoData))  {
780           gosa_log("Can't Load image");
781         }
783         /* Resizing image to 147x200 and blur */
784         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
785           gosa_log("imagick_resize failed");
786         }
788         /* Converting image to JPEG */
789         if(!imagick_convert($handle,"JPEG")) {
790           gosa_log("Can't Convert to JPEG");
791         }
793         /* Creating binary Code for the Image */
794         if(!$dump = imagick_image2blob($handle)){
795           gosa_log("Can't create blob for image");
796         }
798         /* Sending Image */
799         $output=  $dump;
801         /* Save attribute */
802         $this->attrs["jpegPhoto"] = $output;
803       }
805     } else{
806       $this->attrs["jpegPhoto"] = array();
807     }
809     /* Build new dn */
810     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
811       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
812     } else {
813       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
814     }
816     /* This only gets called when user is renaming himself */
817     $ldap= $this->config->get_ldap_link();
818     if ($this->dn != $new_dn){
820       /* Write entry on new 'dn' */
821       $this->move($this->dn, $new_dn);
823       /* Happen to use the new one */
824       change_ui_dn($this->dn, $new_dn);
825       $this->dn= $new_dn;
826     }
829     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
830        new entries. So do a check first... */
831     $ldap->cat ($this->dn, array('dn'));
832     if ($ldap->fetch()){
833       $mode= "modify";
834     } else {
835       $mode= "add";
836       $ldap->cd($this->config->current['BASE']);
837       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
838     }
840     /* Set password to some junk stuff in case of templates */
841     if ($this->is_template){
842       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
843     }
845     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
846         $this->attributes, "Save via $mode");
848     /* Finally write data with selected 'mode' */
849     $this->cleanup();
850     $ldap->cd ($this->dn);
851     $ldap->$mode ($this->attrs);
852     if (show_ldap_error($ldap->get_error(), _("Saving generic user account failed"))){
853       return (1);
854     }
856     /* Remove cert? 
857        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
858        to work around myself. */
859     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
861       /* Reset array, assemble new, this should be reworked */
862       $this->attrs= array();
863       $this->attrs['userCertificate;binary']= array();
865       /* Prepare connection */
866       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
867         die ("Could not connect to LDAP server");
868       }
869       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
870       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
871         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
872         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
873       }
874       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
875         ldap_start_tls($ds);
876       }
877       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
878               $this->config->current['PASSWORD']))) {
879         die ("Could not bind to LDAP");
880       }
882       /* Modify using attrs */
883       ldap_mod_del($ds,$this->dn,$this->attrs);
884       ldap_close($ds);
885     }
887     /* Kerberos server defined? */
888     if (isset($this->config->data['SERVERS']['KERBEROS'])){
889       $cfg= $this->config->data['SERVERS']['KERBEROS'];
890     }
891     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
893       /* Connect to the admin interface */
894       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
895           $cfg['ADMIN'], $cfg['PASSWORD']);
897       /* Errors? */             
898       if ($handle === FALSE){
899         print_red (_("Kerberos database communication failed"));
900         return (2);
901       }
903       /* Build user principal, get list of existsing principals */
904       $principal= $this->uid."@".$cfg['REALM'];
905       $principals = kadm5_get_principals($handle);
907       /* User exists in database? */
908       if (in_array($principal, $principals)){
910         /* Ok. User exists. Remove him/her when pw_storage has
911            changed to be NOT kerberos. */
912         if ($this->pw_storage != "kerberos"){
913           $ret= kadm5_delete_principal ( $handle, $principal);
915           if ($ret === FALSE){
916             print_red (_("Can't remove user from kerberos database."));
917           }
918         }
920       } else {
922         /* User doesn't exists, create it when pw_storage is kerberos. */
923         if ($this->pw_storage == "kerberos"){
924           $ret= kadm5_create_principal ( $handle, $principal);
926           if ($ret === FALSE){
927             print_red (_("Can't add user to kerberos database."));
928           }
929         }
931       }
933       /* Free kerberos admin handle */
934       kadm5_destroy($handle);
935     }
937     /* Optionally execute a command after we're done */
938     if ($mode == "add"){
939       $this->handle_post_events("add",array("uid" => $this->uid));
940     } elseif ($this->is_modified){
941       $this->handle_post_events("modify",array("uid" => $this->uid));
942     }
944     /* Fix tagging if needed */
945     $this->handle_object_tagging();
947     return (0);
948   }
951   /* Check formular input */
952   function check()
953   {
954     /* Call common method to give check the hook */
955     $message= plugin::check();
957     /* Assemble cn */
958     $this->cn= $this->givenName." ".$this->sn;
960     /* Permissions for that base? */
961     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
962       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
963     } else {
964       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
965     }
967     $ui= get_userinfo();
968     $acl= get_permissions ($new_dn, $ui->subtreeACL);
969     $acl= get_module_permission($acl, "user", $new_dn);
970     if ($this->dn == "new" && chkacl($acl, "create") != ""){
971       $message[]= _("You have no permissions to create a user on this 'Base'.");
972     } elseif ($this->dn != $new_dn && $this->dn != "new"){
973       $acl= get_permissions ($this->dn, $ui->subtreeACL);
974       $acl= get_module_permission($acl, "user", $this->dn);
975       if (chkacl($acl, "create") != ""){
976         $message[]= _("You have no permissions to move a user from the original 'Base'.");
977       }
978     }
980     /* must: sn, givenName, uid */
981     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
982       $message[]= _("The required field 'Name' is not set.");
983     }
985     /* UID already used? */
986     $ldap= $this->config->get_ldap_link();
987     $ldap->cd($this->config->current['BASE']);
988     $ldap->search("(uid=$this->uid)", array("uid"));
989     $ldap->fetch();
990     if ($ldap->count() != 0 && $this->dn == 'new'){
991       $message[]= _("There's already a person with this 'Login' in the database.");
992     }
994     /* In template mode, the uid and givenName are autogenerated... */
995     if (!$this->is_template){
996       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
997         $message[]= _("The required field 'Given name' is not set.");
998       }
999       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
1000         $message[]= _("The required field 'Login' is not set.");
1001       }
1002       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
1003         $ldap->cd($this->config->current['BASE']);
1004         $ldap->search("(cn=".$this->cn.")", array("uid"));
1005         $ldap->fetch();
1006         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
1007           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
1008         }
1009       }
1010     }
1012     /* Check for valid input */
1013     if ($this->is_modified && !is_uid($this->uid)){
1014       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
1015     }
1016     if (!is_url($this->labeledURI)){
1017       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
1018     }
1019     if (preg_match ("/[\\\\]/", $this->sn)){
1020       $message[]= _("The field 'Name' contains invalid characters.");
1021     }
1022     if (preg_match ("/[\\\\]/", $this->givenName)){
1023       $message[]= _("The field 'Given name' contains invalid characters.");
1024     }
1026     /* Check phone numbers */
1027     if (!is_phone_nr($this->telephoneNumber)){
1028       $message[]= _("The field 'Phone' contains an invalid phone number.");
1029     }
1030     if (!is_phone_nr($this->facsimileTelephoneNumber)){
1031       $message[]= _("The field 'Fax' contains an invalid phone number.");
1032     }
1033     if (!is_phone_nr($this->mobile)){
1034       $message[]= _("The field 'Mobile' contains an invalid phone number.");
1035     }
1036     if (!is_phone_nr($this->pager)){
1037       $message[]= _("The field 'Pager' contains an invalid phone number.");
1038     }
1040     /* Check for reserved characers */
1041     if (preg_match ('/[,+"?\'()=<>;]/', $this->givenName)){
1042       $message[]= _("The field 'Given name' contains invalid characters.");
1043     }
1044     if (preg_match ('/[,+"?\'()=<>;]/', $this->sn)){
1045       $message[]= _("The field 'Name' contains invalid characters.");
1046     }
1048   return $message;
1049   }
1052   /* Indicate whether a password change is needed or not */
1053   function password_change_needed()
1054   {
1055     return ($this->pw_storage != $this->last_pw_storage);
1056   }
1059   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1060   function load_picture()
1061   {
1062     /* make connection and read jpegPhoto */
1063     $ds= ldap_connect($this->config->current['SERVER']);
1064     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1065     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1066       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1067       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1068     }
1070     if(isset($this->config->current['TLS']) &&
1071         $this->config->current['TLS'] == "true"){
1073       ldap_start_tls($ds);
1074     }
1076     $r= ldap_bind($ds);
1077     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
1079     /* in case we don't get an entry, load a default picture */
1080     $this->set_picture ("./images/default.jpg");
1081     $this->jpegPhoto= "*removed*";
1083     /* fill data from LDAP */
1084     if ($sr) {
1085       $ei=ldap_first_entry($ds, $sr);
1086       if ($ei) {
1087         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
1088           $this->photoData= $info[0];
1089           $_SESSION['binary']= $this->photoData;
1090           $_SESSION['binarytype']= "image/jpeg";
1091           $this->jpegPhoto= "";
1092         }
1093       }
1094     }
1096     /* close conncetion */
1097     ldap_unbind($ds);
1098   }
1101   /* Load a certificate from LDAP, this is going to be simplified later on */
1102   function load_cert()
1103   {
1104     $ds= ldap_connect($this->config->current['SERVER']);
1105     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1106     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1107       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1108       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1109     }
1110     if(isset($this->config->current['TLS']) &&
1111         $this->config->current['TLS'] == "true"){
1113       ldap_start_tls($ds);
1114     }
1116     $r= ldap_bind($ds);
1117     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1119     if ($sr) {
1120       $ei= @ldap_first_entry($ds, $sr);
1121       
1122       if ($ei) {
1123         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1124           $this->userCertificate= "";
1125         } else {
1126           $this->userCertificate= $info[0];
1127         }
1128       }
1129     } else {
1130       $this->userCertificate= "";
1131     }
1133     ldap_unbind($ds);
1134   }
1137   /* Load picture from file to object */
1138   function set_picture($filename ="")
1139   {
1140     if (!is_file($filename) || $filename == ""){
1141       $filename= "./images/default.jpg";
1142       $this->jpegPhoto= "*removed*";
1143     }
1145     $fd = fopen ($filename, "rb");
1146     $this->photoData= fread ($fd, filesize ($filename));
1147     $_SESSION['binary']= $this->photoData;
1148     $_SESSION['binarytype']= "image/jpeg";
1149     $this->jpegPhoto= "";
1151     fclose ($fd);
1152   }
1155   /* Load certificate from file to object */
1156   function set_cert($cert, $filename)
1157   {
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("/^.*".get_groups_ou().",/","",$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 PrepareForCopyPaste($source)
1307   {
1308     plugin::PrepareForCopyPaste($source);
1310     /* Reset certificate information addepted from source user
1311         to avoid setting the same user certificate for the destination user. */
1312     $this->userPKCS12= "";
1313     $this->userSMIMECertificate= "";
1314     $this->userCertificate= "";
1315     $this->certificateSerialNumber= "";
1316     $this->old_certificateSerialNumber= "";
1317     $this->old_userPKCS12= "";
1318     $this->old_userSMIMECertificate= "";
1319     $this->old_userCertificate= "";
1320   }
1323 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1324 ?>