Code

Removed - from year and month selection, fixed year calculation
[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();
232     $start  = date("Y") - 100;
233     $end    = $start +100;
234     
235     for($y= $start; $y<=$end; $y++){
236       $years[]= $y;
237     }
238     $months= array(_("January"), _("February"), _("March"), _("April"),
239         _("May"), _("June"), _("July"), _("August"), _("September"),
240         _("October"), _("November"), _("December"));
241     $smarty->assign("day", $date["mday"]);
242     $smarty->assign("days", $days);
243     $smarty->assign("months", $months);
244     $smarty->assign("month", $date["mon"]-1);
245     $smarty->assign("years", $years);
246     $smarty->assign("year", $date["year"]);
248     /* Assign sex */
249     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
250     $smarty->assign("gender_list", $sex);
252     /* Assign prefered langage */
253     $language= array(0 => "&nbsp;", "fr_FR" => ("fr_FR"), "en_EN" => ("en_EN"), 
254                                     "de_DE" => ("de_DE"), "it_IT" => ("it_IT"), 
255                                     "nl_NL" => ("nl_NL"), "ru_RU" => ("ru_RU"));
256     $smarty->assign("preferredLanguage_list", $language);
258     /* Get random number for pictures */
259     srand((double)microtime()*1000000); 
260     $smarty->assign("rand", rand(0, 10000));
262     /* Do we represent a valid gosaAccount? */
263     if (!$this->is_account){
264       echo "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
265         _("This account has no valid GOsa extensions.")."</b>";
266       return;
267     }
269     /* Base select dialog */
270     $once = true;
271     foreach($_POST as $name => $value){
272       if(preg_match("/^chooseBase/",$name) && $once){
273         $once = false;
274         $this->dialog = new baseSelectDialog($this->config,$this->allowedBasesToMoveTo());
275         $this->dialog->setCurrentBase($this->base);
276       }
277     }
279     /* Dialog handling */
280     if(is_object($this->dialog)){
281       /* Must be called before save_object */
282       $this->dialog->save_object();
283    
284       if($this->dialog->isClosed()){
285         $this->dialog = false;
286       }elseif($this->dialog->isSelected()){
287         $this->base = $this->dialog->isSelected();
288         $this->dialog= false;
289       }else{
290         return($this->dialog->execute());
291       }
292     }
294     /* Want picture edit dialog? */
295     if (isset($_POST['edit_picture'])){
296       /* Save values for later recovery, in case some presses
297          the cancel button. */
298       $this->old_jpegPhoto= $this->jpegPhoto;
299       $this->old_photoData= $this->photoData;
300       $this->picture_dialog= TRUE;
301       $this->dialog= TRUE;
302     }
304     /* Remove picture? */
305     if (isset($_POST['picture_remove'])){
306       $this->jpegPhoto= "*removed*";
307       $this->set_picture ("./images/default.jpg");
308       $this->is_modified= TRUE;
310       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
311     }
313     /* Save picture */
314     if (isset($_POST['picture_edit_finish'])){
316       /* Check for clean upload */
317       if ($_FILES['picture_file']['name'] != ""){
318         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
319           print_red(_("The specified file has not been uploaded via HTTP POST! Aborted."));
320           exit;
321         }
323         /* Activate new picture */
324         $this->set_picture($_FILES['picture_file']['tmp_name']);
325       }
326       $this->picture_dialog= FALSE;
327       $this->dialog= FALSE;
328       $this->is_modified= TRUE;
329     }
332     /* Cancel picture */
333     if (isset($_POST['picture_edit_cancel'])){
335       /* Restore values */
336       $this->jpegPhoto= $this->old_jpegPhoto;
337       $this->photoData= $this->old_photoData;
339       /* Update picture */
340       $_SESSION['binary']= $this->photoData;
341       $_SESSION['binarytype']= "image/jpeg";
342       $this->picture_dialog= FALSE;
343       $this->dialog= FALSE;
344     }
346     /* Toggle dateOfBirth information */
347     if (isset($_POST['set_dob'])){
348       $this->use_dob= ($this->use_dob == "0")?"1":"0";
349     }
352     /* Want certificate= */
353     if (isset($_POST['edit_cert'])){
355       /* Save original values for later reconstruction */
356       foreach (array("certificateSerialNumber", "userCertificate",
357             "userSMIMECertificate", "userPKCS12") as $val){
359         $oval= "old_$val";
360         $this->$oval= $this->$val;
361       }
363       $this->cert_dialog= TRUE;
364       $this->dialog= TRUE;
365     }
368     /* Cancel certificate dialog */
369     if (isset($_POST['cert_edit_cancel'])){
371       /* Restore original values in case of 'cancel' */
372       foreach (array("certificateSerialNumber", "userCertificate",
373             "userSMIMECertificate", "userPKCS12") as $val){
375         $oval= "old_$val";
376         $this->$val= $this->$oval;
377       }
378       $this->cert_dialog= FALSE;
379       $this->dialog= FALSE;
380     }
383     /* Remove certificate? */
384     foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
385       if (isset($_POST["remove_$val"])){
387         /* Reset specified cert*/
388         $this->$val= "";
389         $this->is_modified= TRUE;
390       }
391     }
394     /* Upload new cert and close dialog? */     
395     if (isset($_POST['cert_edit_finish'])){
397       /* for all certificates do */
398       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
399           as $val){
401         /* Check for clean upload */
402         if (array_key_exists($val."_file", $_FILES) &&
403             array_key_exists('name', $_FILES[$val."_file"]) &&
404             $_FILES[$val."_file"]['name'] != "" &&
405             is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
406           $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
407         }
408       }
410       /* Save serial number */
411       if (isset($_POST["certificateSerialNumber"]) &&
412           $_POST["certificateSerialNumber"] != ""){
414         if (!is_id($_POST["certificateSerialNumber"])){
415           print_red (_("Please enter a valid serial number"));
417           foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
418             if ($this->$cert != ""){
419               $smarty->assign("$cert"."_state", "true");
420             } else {
421               $smarty->assign("$cert"."_state", "");
422             }
423           }
424           return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
425         }
427         $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
428         $this->is_modified= TRUE;
429       }
431       $this->cert_dialog= FALSE;
432       $this->dialog= FALSE;
433     }
435     /* Display picture dialog */
436     if ($this->picture_dialog){
437       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
438     }
440     /* Display cert dialog */
441     if ($this->cert_dialog){
442       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
443         if ($this->$cert != ""){
444           /* import certificate */
445           $certificate = new certificate;
446           $certificate->import($this->$cert);
447       
448           /* Read out data*/
449           $timeto   = $certificate->getvalidto_date();
450           $timefrom = $certificate->getvalidfrom_date();
451           $str = "<table summary=\"\" border=0><tr><td style='vertical-align:top'>CN</td><td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td></tr></table><br>".
452                   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>");
453           $smarty->assign($cert."info",$str);
454           $smarty->assign($cert."_state","true");
455         } else {
456           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
457           $smarty->assign($cert."_state","");
458         }
459       }
460       $smarty->assign("governmentmode", "false");
461       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
462     }
464     /* Show us the edit screen */
465     @$smarty->assign("bases", $this->allowedBasesToMoveTo());
466 #  $smarty->assign("bases", $this->config->idepartments);
467     $smarty->assign("base_select",      $this->base);
468     $smarty->assign("selectmode",       chkacl($this->acl, "create"));
469     $smarty->assign("certificatesACL",  chkacl($this->acl, "certificates"));
470     $smarty->assign("jpegPhotoACL",     chkacl($this->acl, "jpegPhoto"));
472     /* Prepare password hashes */
473     if ($this->pw_storage == ""){
474       $this->pw_storage= $this->config->current['HASH'];
475     }
477     $temp   = passwordMethod::get_available_methods();
478     $hashes = $temp['name'];
479     
480     $smarty->assign("pwmode", $hashes);
481     $smarty->assign("pwmode_select", $this->pw_storage);
482     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
484     /* Load attributes and acl's */
485     foreach($this->attributes as $val){
486       $smarty->assign("$val", $this->$val);
487       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
488     }
490     /* Save government mode attributes */
491     if (isset($this->config->current['GOVERNMENTMODE']) &&
492         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
493       $smarty->assign("governmentmode", "true");
494       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
495           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
496       $smarty->assign("ivbbmodes", $ivbbmodes);
497       foreach ($this->govattrs as $val){
498         $smarty->assign("$val", $this->$val);
499         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
500       }
501     } else {
502       $smarty->assign("governmentmode", "false");
503     }
505     /* Special mode for uid */
506     $uidACL= "";
507     if (isset ($this->dn)){
508       if ($this->dn != "new"){
509         $uidACL="readonly";
510       }
511     }  else {
512       $uidACL= "readonly";
513     }
514     $uidACL.= " ".chkacl($this->acl, "uid");
515     
516     $smarty->assign("uidACL", $uidACL);
517     $smarty->assign("is_template", $this->is_template);
518     $smarty->assign("use_dob", $this->use_dob);
520     if (isset($this->parent)){
521       if (isset($this->parent->by_object['phoneAccount']) &&
522           $this->parent->by_object['phoneAccount']->is_account){
523         $smarty->assign("has_phoneaccount", "true");
524       } else {
525         $smarty->assign("has_phoneaccount", "false");
526       }
527     } else {
528       $smarty->assign("has_phoneaccount", "false");
529     }
530     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
531   }
534   /* remove object from parent */
535   function remove_from_parent()
536   {
537     $ldap= $this->config->get_ldap_link();
538     $ldap->rmdir ($this->dn);
539     show_ldap_error($ldap->get_error(), _("Removing generic user account failed"));
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, array('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(), _("Saving generic user account failed"))){
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     /* Fix tagging if needed */
921     $this->handle_object_tagging();
923     return (0);
924   }
927   /* Check formular input */
928   function check()
929   {
930     /* Call common method to give check the hook */
931     $message= plugin::check();
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   } 
1227   function getCopyDialog()
1228   {
1229     $str = "";
1231     $_SESSION['binary'] = $this->photoData; 
1232     $_SESSION['binarytype']= "image/jpeg";
1234     /* Get random number for pictures */
1235     srand((double)microtime()*1000000); 
1236     $rand = rand(0, 10000);
1238     $smarty = get_smarty();
1240     $smarty->assign("passwordTodo","clear");
1242     if(isset($_POST['passwordTodo'])){
1243       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1244     }
1246     $smarty->assign("sn",       $this->sn);
1247     $smarty->assign("givenName",$this->givenName);
1248     $smarty->assign("uid",      $this->uid);
1249     $smarty->assign("rand",     $rand);
1250     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1253     $ret = array();
1254     $ret['string'] = $str;
1255     $ret['status'] = "";  
1256     return($ret);
1257   }
1259   function saveCopyDialog()
1260   {
1262     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1263       $this->set_picture($_FILES['picture_file']['tmp_name']);
1264     }
1266     /* Remove picture? */
1267     if (isset($_POST['picture_remove'])){
1268       $this->jpegPhoto= "*removed*";
1269       $this->set_picture ("./images/default.jpg");
1270       $this->is_modified= TRUE;
1271     }
1273     $attrs = array("uid","givenName","sn");
1274     foreach($attrs as $attr){
1275       if(isset($_POST[$attr])){
1276         $this->$attr = $_POST[$attr];
1277       }
1278     } 
1279   }
1282 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1283 ?>