Code

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