Code

Updated Base selection
[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       /* 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"), "de_DE" => ("de_DE"), "it_IT" => ("it_IT"), "nl_NL" => ("nl_NL"));
261     $smarty->assign("preferredLanguage_list", $language);
263     /* Get random number for pictures */
264     srand((double)microtime()*1000000); 
265     $smarty->assign("rand", rand(0, 10000));
267     /* Do we represent a valid gosaAccount? */
268     if (!$this->is_account){
269       echo "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
270         _("This account has no valid GOsa extensions.")."</b>";
271       return;
272     }
274     /* Base select dialog */
275     $once = true;
276     foreach($_POST as $name => $value){
277       if(preg_match("/^chooseBase/",$name) && $once){
278         $once = false;
279         $this->dialog = new baseSelectDialog($this->config,$this->allowedBasesToMoveTo());
280         $this->dialog->setCurrentBase($this->base);
281       }
282     }
284     /* Dialog handling */
285     if(is_object($this->dialog)){
286       /* Must be called before save_object */
287       $this->dialog->save_object();
288    
289       if($this->dialog->isClosed()){
290         $this->dialog = false;
291       }elseif($this->dialog->isSelected()){
292         $this->base = $this->dialog->isSelected();
293         $this->dialog= false;
294       }else{
295         return($this->dialog->execute());
296       }
297     }
299     /* Want picture edit dialog? */
300     if (isset($_POST['edit_picture'])){
301       /* Save values for later recovery, in case some presses
302          the cancel button. */
303       $this->old_jpegPhoto= $this->jpegPhoto;
304       $this->old_photoData= $this->photoData;
305       $this->picture_dialog= TRUE;
306       $this->dialog= TRUE;
307     }
309     /* Remove picture? */
310     if (isset($_POST['picture_remove'])){
311       $this->jpegPhoto= "*removed*";
312       $this->set_picture ("./images/default.jpg");
313       $this->is_modified= TRUE;
315       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
316     }
318     /* Save picture */
319     if (isset($_POST['picture_edit_finish'])){
321       /* Check for clean upload */
322       if ($_FILES['picture_file']['name'] != ""){
323         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
324           print_red(_("The specified file has not been uploaded via HTTP POST! Aborted."));
325           exit;
326         }
328         /* Activate new picture */
329         $this->set_picture($_FILES['picture_file']['tmp_name']);
330       }
331       $this->picture_dialog= FALSE;
332       $this->dialog= FALSE;
333       $this->is_modified= TRUE;
334     }
337     /* Cancel picture */
338     if (isset($_POST['picture_edit_cancel'])){
340       /* Restore values */
341       $this->jpegPhoto= $this->old_jpegPhoto;
342       $this->photoData= $this->old_photoData;
344       /* Update picture */
345       $_SESSION['binary']= $this->photoData;
346       $_SESSION['binarytype']= "image/jpeg";
347       $this->picture_dialog= FALSE;
348       $this->dialog= FALSE;
349     }
351     /* Toggle dateOfBirth information */
352     if (isset($_POST['set_dob'])){
353       $this->use_dob= ($this->use_dob == "0")?"1":"0";
354     }
357     /* Want certificate= */
358     if (isset($_POST['edit_cert'])){
360       /* Save original values for later reconstruction */
361       foreach (array("certificateSerialNumber", "userCertificate",
362             "userSMIMECertificate", "userPKCS12") as $val){
364         $oval= "old_$val";
365         $this->$oval= $this->$val;
366       }
368       $this->cert_dialog= TRUE;
369       $this->dialog= TRUE;
370     }
373     /* Cancel certificate dialog */
374     if (isset($_POST['cert_edit_cancel'])){
376       /* Restore original values in case of 'cancel' */
377       foreach (array("certificateSerialNumber", "userCertificate",
378             "userSMIMECertificate", "userPKCS12") as $val){
380         $oval= "old_$val";
381         $this->$val= $this->$oval;
382       }
383       $this->cert_dialog= FALSE;
384       $this->dialog= FALSE;
385     }
388     /* Remove certificate? */
389     foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
390       if (isset($_POST["remove_$val"])){
392         /* Reset specified cert*/
393         $this->$val= "";
394         $this->is_modified= TRUE;
395       }
396     }
399     /* Upload new cert and close dialog? */     
400     if (isset($_POST['cert_edit_finish'])){
402       /* for all certificates do */
403       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
404           as $val){
406         /* Check for clean upload */
407         if (array_key_exists($val."_file", $_FILES) &&
408             array_key_exists('name', $_FILES[$val."_file"]) &&
409             $_FILES[$val."_file"]['name'] != "" &&
410             is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
411           $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
412         }
413       }
415       /* Save serial number */
416       if (isset($_POST["certificateSerialNumber"]) &&
417           $_POST["certificateSerialNumber"] != ""){
419         if (!is_id($_POST["certificateSerialNumber"])){
420           print_red (_("Please enter a valid serial number"));
422           foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
423             if ($this->$cert != ""){
424               $smarty->assign("$cert"."_state", "true");
425             } else {
426               $smarty->assign("$cert"."_state", "");
427             }
428           }
429           return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
430         }
432         $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
433         $this->is_modified= TRUE;
434       }
436       $this->cert_dialog= FALSE;
437       $this->dialog= FALSE;
438     }
440     /* Display picture dialog */
441     if ($this->picture_dialog){
442       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
443     }
445     /* Display cert dialog */
446     if ($this->cert_dialog){
447       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
448         if ($this->$cert != ""){
449           /* import certificate */
450           $certificate = new certificate;
451           $certificate->import($this->$cert);
452       
453           /* Read out data*/
454           $timeto   = $certificate->getvalidto_date();
455           $timefrom = $certificate->getvalidfrom_date();
456           $str = "<table summary=\"\" border=0><tr><td style='vertical-align:top'>CN</td><td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td></tr></table><br>".
457                   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>");
458           $smarty->assign($cert."info",$str);
459           $smarty->assign($cert."_state","true");
460         } else {
461           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
462           $smarty->assign($cert."_state","");
463         }
464       }
465       $smarty->assign("governmentmode", "false");
466       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
467     }
469     /* Show us the edit screen */
470     @$smarty->assign("bases", $this->allowedBasesToMoveTo());
471 #  $smarty->assign("bases", $this->config->idepartments);
472     $smarty->assign("base_select",      $this->base);
473     $smarty->assign("selectmode",       chkacl($this->acl, "create"));
474     $smarty->assign("certificatesACL",  chkacl($this->acl, "certificates"));
475     $smarty->assign("jpegPhotoACL",     chkacl($this->acl, "jpegPhoto"));
477     /* Prepare password hashes */
478     if ($this->pw_storage == ""){
479       $this->pw_storage= $this->config->current['HASH'];
480     }
482     $temp   = passwordMethod::get_available_methods();
483     $hashes = $temp['name'];
484     
485     $smarty->assign("pwmode", $hashes);
486     $smarty->assign("pwmode_select", $this->pw_storage);
487     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
489     /* Load attributes and acl's */
490     foreach($this->attributes as $val){
491       $smarty->assign("$val", $this->$val);
492       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
493     }
495     /* Save government mode attributes */
496     if (isset($this->config->current['GOVERNMENTMODE']) &&
497         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
498       $smarty->assign("governmentmode", "true");
499       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
500           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
501       $smarty->assign("ivbbmodes", $ivbbmodes);
502       foreach ($this->govattrs as $val){
503         $smarty->assign("$val", $this->$val);
504         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
505       }
506     } else {
507       $smarty->assign("governmentmode", "false");
508     }
510     /* Special mode for uid */
511     $uidACL= "";
512     if (isset ($this->dn)){
513       if ($this->dn != "new"){
514         $uidACL="readonly";
515       }
516     }  else {
517       $uidACL= "readonly";
518     }
519     $uidACL.= " ".chkacl($this->acl, "uid");
520     
521     $smarty->assign("uidACL", $uidACL);
522     $smarty->assign("is_template", $this->is_template);
523     $smarty->assign("use_dob", $this->use_dob);
525     if (isset($this->parent)){
526       if (isset($this->parent->by_object['phoneAccount']) &&
527           $this->parent->by_object['phoneAccount']->is_account){
528         $smarty->assign("has_phoneaccount", "true");
529       } else {
530         $smarty->assign("has_phoneaccount", "false");
531       }
532     } else {
533       $smarty->assign("has_phoneaccount", "false");
534     }
535     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
536   }
539   /* remove object from parent */
540   function remove_from_parent()
541   {
542     $ldap= $this->config->get_ldap_link();
543     $ldap->rmdir ($this->dn);
545     /* Delete references to groups */
546     $ldap->cd ($this->config->current['BASE']);
547     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
548     while ($ldap->fetch()){
549       $g= new group($this->config, $ldap->getDN());
550       $g->removeUser($this->uid);
551       $g->save ();
552     }
554     /* Delete references to object groups */
555     $ldap->cd ($this->config->current['BASE']);
556     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
557     while ($ldap->fetch()){
558       $og= new ogroup($this->config, $ldap->getDN());
559       unset($og->member[$this->dn]);
560       $og->save ();
561     }
563     /* Optionally execute a command after we're done */
564     $this->handle_post_events("remove");
565   }
568   /* Save data to object */
569   function save_object()
570   {
571     if (isset($_POST['generic'])){
573       /* Parents save function */
574       plugin::save_object ();
576       /* Save government mode attributes */
577       if ($this->config->current['GOVERNMENTMODE']){
578         foreach ($this->govattrs as $val){
579           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
580             $data= stripcslashes($_POST["$val"]);
581             if ($data != $this->$val){
582               $this->is_modified= TRUE;
583             }
584             $this->$val= $data;
585           }
586         }
587       }
589       /* In template mode, the uid is autogenerated... */
590       if ($this->is_template){
591         $this->uid= strtolower($this->sn);
592         $this->givenName= $this->sn;
593       }
595       /* Save base and pw_storage, since these are no LDAP attributes */
596       if (isset($_POST['base'])){
597         foreach(array("base", "pw_storage") as $val){
598           if(isset($_POST[$val])){
599             $data= validate($_POST[$val]);
600             if ($data != $this->$val){
601               $this->is_modified= TRUE;
602             }
603             $this->$val= $data;
604           }
605         }
606       }
607     }
608   }
610   function rebind($ldap, $referral)
611   {
612     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
613     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
614       $this->error = "Success";
615       $this->hascon=true;
616       $this->reconnect= true;
617       return (0);
618     } else {
619       $this->error = "Could not bind to " . $credentials['ADMIN'];
620       return NULL;
621     }
622   }
624   /* Save data to LDAP, depending on is_account we save or delete */
625   function save()
626   {
627     /* Only force save of changes .... 
628        If this attributes aren't changed, avoid saving.
629      */
630     if ($this->use_dob == "1"){
631       $this->dateOfBirth= date("Y-m-d", $this->dateOfBirth);
632     }
633     if($this->gender=="0") $this->gender ="";
634     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
635     
636  
637     /* First use parents methods to do some basic fillup in $this->attrs */
638     plugin::save ();
640     /* Remove additional objectClasses */
641     $tmp= array();
642     foreach ($this->attrs['objectClass'] as $key => $set){
643       $found= false;
644       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
645         if (preg_match ("/^$set$/i", $val)){
646           $found= true;
647           break;
648         }
649       }
650       if (!$found){
651         $tmp[]= $set;
652       }
653     }
655     /* Replace the objectClass array. This is done because of the
656        separation into government and normal mode. */
657     $this->attrs['objectClass']= $tmp;
659     /* Add objectClasss for template mode? */
660     if ($this->is_template){
661       $this->attrs['objectClass'][]= "gosaUserTemplate";
662     }
664     /* Hard coded government mode? */
665     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
666       $this->attrs['objectClass'][]= "ivbbentry";
668       /* Copy standard attributes */
669       foreach ($this->govattrs as $val){
670         if ($this->$val != ""){
671           $this->attrs["$val"]= $this->$val;
672         } elseif (!$this->new) {
673           $this->attrs["$val"]= array();
674         }
675       }
677       /* Remove attribute if set to "nein" */
678       if ($this->publicVisible == "nein"){
679         $this->attrs['publicVisible']= array();
680         if($this->new){
681           unset($this->attrs['publicVisible']);
682         }else{
683           $this->attrs['publicVisible']=array();
684         }
686       }
688     }
690     /* Special handling for attribute userCertificate needed */
691     if ($this->userCertificate != ""){
692       $this->attrs["userCertificate;binary"]= $this->userCertificate;
693       $remove_userCertificate= false;
694     } else {
695       $remove_userCertificate= true;
696     }
698     /* Special handling for dateOfBirth value */
699     if ($this->use_dob != "1"){
700       if ($this->new) {
701         unset($this->attrs["dateOfBirth"]);
702       } else {
703         $this->attrs["dateOfBirth"]= array();
704       }
705     }
706     if (!$this->gender){
707       if ($this->new) {
708         unset($this->attrs["gender"]);
709       } else {
710         $this->attrs["gender"]= array();
711       }
712     }
713     if (!$this->preferredLanguage){
714       if ($this->new) {
715         unset($this->attrs["preferredLanguage"]);
716       } else {
717         $this->attrs["preferredLanguage"]= array();
718       }
719     }
721     /* Special handling for attribute jpegPhote needed, scale image via
722        image magick to 147x200 pixels and inject resulting data. */
723     if ($this->jpegPhoto != "*removed*"){
725       /* Fallback if there's no image magick inside PHP */
726       if (!function_exists("imagick_blob2image")){
727         /* Get temporary file name for conversation */
728         $fname = tempnam ("/tmp", "GOsa");
730         /* Open file and write out photoData */
731         $fp = fopen ($fname, "w");
732         fwrite ($fp, $this->photoData);
733         fclose ($fp);
735         /* Build conversation query. Filename is generated automatically, so
736            we do not need any special security checks. Exec command and save
737            output. For PHP safe mode, you'll need a configuration which respects
738            image magick as executable... */
739         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
740         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
741             $query, "Execute");
743         /* Read data written by convert */
744         $output= "";
745         $sh= popen($query, 'r');
746         while (!feof($sh)){
747           $output.= fread($sh, 4096);
748         }
749         pclose($sh);
751         unlink($fname);
753         /* Save attribute */
754         $this->attrs["jpegPhoto"] = $output;
756       } else {
758         /* Load the new uploaded Photo */
759         if(!$handle  =  imagick_blob2image($this->photoData))  {
760           gosa_log("Can't Load image");
761         }
763         /* Resizing image to 147x200 and blur */
764         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
765           gosa_log("imagick_resize failed");
766         }
768         /* Converting image to JPEG */
769         if(!imagick_convert($handle,"JPEG")) {
770           gosa_log("Can't Convert to JPEG");
771         }
773         /* Creating binary Code for the Image */
774         if(!$dump = imagick_image2blob($handle)){
775           gosa_log("Can't create blob for image");
776         }
778         /* Sending Image */
779         $output=  $dump;
781         /* Save attribute */
782         $this->attrs["jpegPhoto"] = $output;
783       }
785     } elseif(!$this->new) {
786       $this->attrs["jpegPhoto"] = array();
787     }
789     /* Build new dn */
790     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
791       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
792     } else {
793       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
794     }
796     /* This only gets called when user is renaming himself */
797     $ldap= $this->config->get_ldap_link();
798     if ($this->dn != $new_dn){
800       /* Write entry on new 'dn' */
801       $this->move($this->dn, $new_dn);
803       /* Happen to use the new one */
804       change_ui_dn($this->dn, $new_dn);
805       $this->dn= $new_dn;
806     }
809     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
810        new entries. So do a check first... */
811     $ldap->cat ($this->dn);
812     if ($ldap->fetch()){
813       $mode= "modify";
814     } else {
815       $mode= "add";
816       $ldap->cd($this->config->current['BASE']);
817       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
818     }
820     /* Set password to some junk stuff in case of templates */
821     if ($this->is_template){
822       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
823     }
825     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
826         $this->attributes, "Save via $mode");
828     /* Finally write data with selected 'mode' */
829     $this->cleanup();
830     $ldap->cd ($this->dn);
831     $ldap->$mode ($this->attrs);
832     if (show_ldap_error($ldap->get_error())){
833       return (1);
834     }
836     /* Remove cert? 
837        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
838        to work around myself. */
839     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
841       /* Reset array, assemble new, this should be reworked */
842       $this->attrs= array();
843       $this->attrs['userCertificate;binary']= array();
845       /* Prepare connection */
846       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
847         die ("Could not connect to LDAP server");
848       }
849       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
850       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
851         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
852         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
853       }
854       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
855         ldap_start_tls($ds);
856       }
857       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
858               $this->config->current['PASSWORD']))) {
859         die ("Could not bind to LDAP");
860       }
862       /* Modify using attrs */
863       ldap_mod_del($ds,$this->dn,$this->attrs);
864       ldap_close($ds);
865     }
867     /* Kerberos server defined? */
868     if (isset($this->config->data['SERVERS']['KERBEROS'])){
869       $cfg= $this->config->data['SERVERS']['KERBEROS'];
870     }
871     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
873       /* Connect to the admin interface */
874       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
875           $cfg['ADMIN'], $cfg['PASSWORD']);
877       /* Errors? */             
878       if ($handle === FALSE){
879         print_red (_("Kerberos database communication failed"));
880         return (2);
881       }
883       /* Build user principal, get list of existsing principals */
884       $principal= $this->uid."@".$cfg['REALM'];
885       $principals = kadm5_get_principals($handle);
887       /* User exists in database? */
888       if (in_array($principal, $principals)){
890         /* Ok. User exists. Remove him/her when pw_storage has
891            changed to be NOT kerberos. */
892         if ($this->pw_storage != "kerberos"){
893           $ret= kadm5_delete_principal ( $handle, $principal);
895           if ($ret === FALSE){
896             print_red (_("Can't remove user from kerberos database."));
897           }
898         }
900       } else {
902         /* User doesn't exists, create it when pw_storage is kerberos. */
903         if ($this->pw_storage == "kerberos"){
904           $ret= kadm5_create_principal ( $handle, $principal);
906           if ($ret === FALSE){
907             print_red (_("Can't add user to kerberos database."));
908           }
909         }
911       }
913       /* Free kerberos admin handle */
914       kadm5_destroy($handle);
915     }
917     /* Optionally execute a command after we're done */
918     if ($mode == "add"){
919       $this->handle_post_events("add");
920     } elseif ($this->is_modified){
921       $this->handle_post_events("modify");
922     }
924     return (0);
925   }
928   /* Check formular input */
929   function check()
930   {
931     $message= array();
933     /* Assemble cn */
934     $this->cn= $this->givenName." ".$this->sn;
936     /* Permissions for that base? */
937     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
938       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
939     } else {
940       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
941     }
943     $ui= get_userinfo();
944     $acl= get_permissions ($new_dn, $ui->subtreeACL);
945     $acl= get_module_permission($acl, "user", $new_dn);
946     if ($this->dn == "new" && chkacl($acl, "create") != ""){
947       $message[]= _("You have no permissions to create a user on this 'Base'.");
948     } elseif ($this->dn != $new_dn && $this->dn != "new"){
949       $acl= get_permissions ($this->dn, $ui->subtreeACL);
950       $acl= get_module_permission($acl, "user", $this->dn);
951       if (chkacl($acl, "create") != ""){
952         $message[]= _("You have no permissions to move a user from the original 'Base'.");
953       }
954     }
956     /* must: sn, givenName, uid */
957     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
958       $message[]= _("The required field 'Name' is not set.");
959     }
961     /* UID already used? */
962     $ldap= $this->config->get_ldap_link();
963     $ldap->cd($this->config->current['BASE']);
964     $ldap->search("(uid=$this->uid)", array("uid"));
965     $ldap->fetch();
966     if ($ldap->count() != 0 && $this->dn == 'new'){
967       $message[]= _("There's already a person with this 'Login' in the database.");
968     }
970     /* In template mode, the uid and givenName are autogenerated... */
971     if (!$this->is_template){
972       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
973         $message[]= _("The required field 'Given name' is not set.");
974       }
975       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
976         $message[]= _("The required field 'Login' is not set.");
977       }
978       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
979         $ldap->cd($this->config->current['BASE']);
980         $ldap->search("(cn=".$this->cn.")", array("uid"));
981         $ldap->fetch();
982         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
983           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
984         }
985       }
986     }
988     /* Check for valid input */
989     if ($this->is_modified && !is_uid($this->uid)){
990       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
991     }
992     if (!is_url($this->labeledURI)){
993       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
994     }
995     if (preg_match ("/[\\\\]/", $this->sn)){
996       $message[]= _("The field 'Name' contains invalid characters.");
997     }
998     if (preg_match ("/[\\\\]/", $this->givenName)){
999       $message[]= _("The field 'Given name' contains invalid characters.");
1000     }
1002     /* Check phone numbers */
1003     if (!is_phone_nr($this->telephoneNumber)){
1004       $message[]= _("The field 'Phone' contains an invalid phone number.");
1005     }
1006     if (!is_phone_nr($this->facsimileTelephoneNumber)){
1007       $message[]= _("The field 'Fax' contains an invalid phone number.");
1008     }
1009     if (!is_phone_nr($this->mobile)){
1010       $message[]= _("The field 'Mobile' contains an invalid phone number.");
1011     }
1012     if (!is_phone_nr($this->pager)){
1013       $message[]= _("The field 'Pager' contains an invalid phone number.");
1014     }
1016     /* Check for reserved characers */
1017     if (preg_match ('/[,+"?\'()=<>;]/', $this->givenName)){
1018       $message[]= _("The field 'Given name' contains invalid characters.");
1019     }
1020     if (preg_match ('/[,+"?\'()=<>;]/', $this->sn)){
1021       $message[]= _("The field 'Name' contains invalid characters.");
1022     }
1024   return $message;
1025   }
1028   /* Indicate whether a password change is needed or not */
1029   function password_change_needed()
1030   {
1031     return ($this->pw_storage != $this->last_pw_storage);
1032   }
1035   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1036   function load_picture()
1037   {
1038     /* make connection and read jpegPhoto */
1039     $ds= ldap_connect($this->config->current['SERVER']);
1040     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1041     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1042       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1043       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1044     }
1046     if(isset($this->config->current['TLS']) &&
1047         $this->config->current['TLS'] == "true"){
1049       ldap_start_tls($ds);
1050     }
1052     $r= ldap_bind($ds);
1053     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
1055     /* in case we don't get an entry, load a default picture */
1056     $this->set_picture ("./images/default.jpg");
1057     $this->jpegPhoto= "*removed*";
1059     /* fill data from LDAP */
1060     if ($sr) {
1061       $ei=ldap_first_entry($ds, $sr);
1062       if ($ei) {
1063         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
1064           $this->photoData= $info[0];
1065           $_SESSION['binary']= $this->photoData;
1066           $_SESSION['binarytype']= "image/jpeg";
1067           $this->jpegPhoto= "";
1068         }
1069       }
1070     }
1072     /* close conncetion */
1073     ldap_unbind($ds);
1074   }
1077   /* Load a certificate from LDAP, this is going to be simplified later on */
1078   function load_cert()
1079   {
1080     $ds= ldap_connect($this->config->current['SERVER']);
1081     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1082     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1083       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1084       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1085     }
1086     if(isset($this->config->current['TLS']) &&
1087         $this->config->current['TLS'] == "true"){
1089       ldap_start_tls($ds);
1090     }
1092     $r= ldap_bind($ds);
1093     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1095     if ($sr) {
1096       $ei= @ldap_first_entry($ds, $sr);
1097       
1098       if ($ei) {
1099         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1100           $this->userCertificate= "";
1101         } else {
1102           $this->userCertificate= $info[0];
1103         }
1104       }
1105     } else {
1106       $this->userCertificate= "";
1107     }
1109     ldap_unbind($ds);
1110   }
1113   /* Load picture from file to object */
1114   function set_picture($filename)
1115   {
1116     if (!is_file($filename)){
1117       $filename= "./images/default.jpg";
1118       $this->jpegPhoto= "*removed*";
1119     }
1121     $fd = fopen ($filename, "rb");
1122     $this->photoData= fread ($fd, filesize ($filename));
1123     $_SESSION['binary']= $this->photoData;
1124     $_SESSION['binarytype']= "image/jpeg";
1125     $this->jpegPhoto= "";
1127     fclose ($fd);
1128   }
1131   /* Load certificate from file to object */
1132   function set_cert($cert, $filename)
1133   {
1134     $fd = fopen ($filename, "rb");
1135     if (filesize($filename)>0) {
1136       $this->$cert= fread ($fd, filesize ($filename));
1137       fclose ($fd);
1138       $this->is_modified= TRUE;
1139     } else {
1140       print_red(_("Could not open specified certificate!"));
1141     }
1142   }
1144   /* Adapt from given 'dn' */
1145   function adapt_from_template($dn)
1146   {
1147     plugin::adapt_from_template($dn);
1149     /* Get base */
1150     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1152     if ($this->config->current['GOVERNMENTMODE']){
1154       /* Walk through govattrs */
1155       foreach ($this->govattrs as $val){
1157         if (isset($this->attrs["$val"][0])){
1159           /* If attribute is set, replace dynamic parts: 
1160              %sn, %givenName and %uid. Fill these in our local variables. */
1161           $value= $this->attrs["$val"][0];
1163           foreach (array("sn", "givenName", "uid") as $repl){
1164             if (preg_match("/%$repl/i", $value)){
1165               $value= preg_replace ("/%$repl/i",
1166                   $this->parent->$repl, $value);
1167             }
1168           }
1169           $this->$val= $value;
1170         }
1171       }
1172     }
1174     /* Get back uid/sn/givenName */
1175     if ($this->parent != NULL){
1176       $this->uid= $this->parent->uid;
1177       $this->sn= $this->parent->sn;
1178       $this->givenName= $this->parent->givenName;
1179     }
1180   }
1182  
1183   /* This avoids that users move themselves out of their rights. 
1184    */
1185   function allowedBasesToMoveTo()
1186   {
1187     $allowed = array();
1188     $ret_all = false;
1189     if($this->uid == $_SESSION['ui']->username){
1190       $ldap= $this->config->get_ldap_link(); 
1191       $ldap->cd($this->config->current['BASE']); 
1192       $ldap->search("(&(objectClass=posixGroup)(memberUid=".$_SESSION['ui']->username."))",array("gosaSubtreeACL"));
1193        
1194       while($attrs = $ldap->fetch()){
1195     
1196         if(isset($attrs['gosaSubtreeACL'])){
1197         
1198           foreach($attrs['gosaSubtreeACL'] as $attr){
1199             if((preg_match("/:user#/",$attr))||(preg_match("/:all/",$attr))){
1200               $s =  preg_replace("/^.*ou=groups,/","",$attrs['dn']);
1202               foreach($this->config->idepartments as $key => $dep) {
1203                 if(preg_match("/".$s."/i",$key)){
1204                   $allowed[$key] = $dep;
1205                 }
1206               }
1207             }
1208           }
1209         }
1210       }
1211       if(count($allowed) == 0){
1212         foreach($this->config->idepartments as $key => $dep) {
1213           if($this->base==$key){
1214             $allowed[$key] = $dep;
1215           }
1216         }
1217       }  
1218   
1219       return($allowed);
1220       
1221     }else{
1222       return($this->config->idepartments);
1223     }
1224   } 
1233 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1234 ?>