Code

Fix role removal
[gosa.git] / gosa-core / plugins / personal / generic / class_user.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 /*!
24   \brief   user plugin
25   \author  Cajus Pollmeier <pollmeier@gonicus.de>
26   \version 2.00
27   \date    24.07.2003
29   This class provides the functionality to read and write all attributes
30   relevant for person, organizationalPerson, inetOrgPerson and gosaAccount
31   from/to the LDAP. It does syntax checking and displays the formulars required.
32  */
34 class user extends plugin
35 {
36   /* Definitions */
37   var $plHeadline= "Generic";
38   var $plDescription= "Edit organizational user settings";
40   /* Plugin specific values */
41   var $base= "";
42   var $orig_base= "";
43   var $cn= "";
44   var $new_dn= "";
45   var $personalTitle= "";
46   var $academicTitle= "";
47   var $homePostalAddress= "";
48   var $homePhone= "";
49   var $labeledURI= "";
50   var $o= "";
51   var $ou= "";
52   var $departmentNumber= "";
53   var $gosaLoginRestriction= array();
54   var $employeeNumber= "";
55   var $employeeType= "";
56   var $roomNumber= "";
57   var $telephoneNumber= "";
58   var $facsimileTelephoneNumber= "";
59   var $mobile= "";
60   var $pager= "";
61   var $l= "";
62   var $st= "";
63   var $postalAddress= "";
64   var $dateOfBirth;
65   var $use_dob= "0";
66   var $gender="0";
67   var $preferredLanguage="0";
69   var $jpegPhoto= "*removed*";
70   var $photoData= "";
71   var $old_jpegPhoto= "";
72   var $old_photoData= "";
73   var $cert_dialog= FALSE;
74   var $picture_dialog= FALSE;
75   var $pwObject= NULL;
77   var $userPKCS12= "";
78   var $userSMIMECertificate= "";
79   var $userCertificate= "";
80   var $certificateSerialNumber= "";
81   var $old_certificateSerialNumber= "";
82   var $old_userPKCS12= "";
83   var $old_userSMIMECertificate= "";
84   var $old_userCertificate= "";
86   var $gouvernmentOrganizationalUnit= "";
87   var $houseIdentifier= "";
88   var $street= "";
89   var $postalCode= "";
90   var $vocation= "";
91   var $ivbbLastDeliveryCollective= "";
92   var $gouvernmentOrganizationalPersonLocality= "";
93   var $gouvernmentOrganizationalUnitDescription= "";
94   var $gouvernmentOrganizationalUnitSubjectArea= "";
95   var $functionalTitle= "";
96   var $role= "";
97   var $publicVisible= "";
99   var $orig_dn;
100   var $dialog;
102   /* variables to trigger password changes */
103   var $pw_storage= "md5";
104   var $last_pw_storage= "unset";
105   var $had_userCertificate= FALSE;
107   var $view_logged = FALSE;
109   /* attribute list for save action */
110   var $attributes= array("sn", "givenName", "uid", "personalTitle", "academicTitle",
111       "homePostalAddress", "homePhone", "labeledURI", "ou", "o", "dateOfBirth", "gender","preferredLanguage",
112       "departmentNumber", "employeeNumber", "employeeType", "l", "st","jpegPhoto",
113       "roomNumber", "telephoneNumber", "mobile", "pager", "cn", "userPKCS12",
114       "postalAddress", "facsimileTelephoneNumber", "userSMIMECertificate", "gosaLoginRestriction");
116   var $objectclasses= array("top", "person", "organizationalPerson", "inetOrgPerson",
117       "gosaAccount");
119   /* attributes that are part of the government mode */
120   var $govattrs= array("gouvernmentOrganizationalUnit", "houseIdentifier", "vocation",
121       "ivbbLastDeliveryCollective", "gouvernmentOrganizationalPersonLocality",
122       "gouvernmentOrganizationalUnitDescription","gouvernmentOrganizationalUnitSubjectArea",
123       "functionalTitle", "certificateSerialNumber", "publicVisible", "street", "role",
124       "postalCode");
126   var $multiple_support = TRUE;
128   var $governmentmode = FALSE;
130   /* constructor, if 'dn' is set, the node loads the given
131      'dn' from LDAP */
132   function user (&$config, $dn= NULL)
133   {
134     global $lang;
136     $this->config= $config;
137     /* Configuration is fine, allways */
138     if($this->config->get_cfg_value("honourIvbbAttributes") == "true"){
139       $this->governmentmode = TRUE;
140       $this->attributes=array_merge($this->attributes,$this->govattrs);
141     }
143     /* Load base attributes */
144     plugin::plugin ($config, $dn);
146     $this->orig_dn  = $this->dn;
147     $this->new_dn   = $dn;
149     if ($this->governmentmode){
150       /* Fix public visible attribute if unset */
151       if (!isset($this->attrs['publicVisible'])){
152         $this->publicVisible == "nein";
153       }
154     }
156     /* Load government mode attributes */
157     if ($this->governmentmode){
158       /* Copy all attributs */
159       foreach ($this->govattrs as $val){
160         if (isset($this->attrs["$val"][0])){
161           $this->$val= $this->attrs["$val"][0];
162         }
163       }
164     }
166     /* Create me for new accounts */
167     if ($dn == "new"){
168       $this->is_account= TRUE;
169     }
171     /* Make hash default to md5 if not set in config */
172     $hash= $this->config->get_cfg_value("passwordDefaultHash", "crypt/md5");
174     /* Load data from LDAP? */
175     if ($dn !== NULL){
177       /* Do base conversation */
178       if ($this->dn == "new"){
179         $ui= get_userinfo();
180         $this->base= dn2base(session::global_is_set("CurrentMainBase")?"cn=dummy,".session::global_get("CurrentMainBase"):$ui->dn);
181       } else {
182         $this->base= dn2base($dn);
183       }
185       /* get password storage type */
186       if (isset ($this->attrs['userPassword'][0])){
187         /* Initialize local array */
188         $matches= array();
189         if (preg_match ("/^{[^}]+}/", $this->attrs['userPassword'][0])){
190           $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
191           if(is_object($tmp)){
192             $this->pw_storage= $tmp->get_hash(); 
193           }
195         } else {
196           if ($this->attrs['userPassword'][0] != ""){
197             $this->pw_storage= "clear";
198           } else {
199             $this->pw_storage= $hash;
200           }
201         }
202       } else {
203         /* Preset with vaule from configuration */
204         $this->pw_storage= $hash;
205       }
207       /* Load extra attributes: certificate and picture */
208       $this->load_cert();
209       $this->load_picture();
210       if ($this->userCertificate != ""){
211         $this->had_userCertificate= TRUE;
212       }
213     }
215     /* Reset password storage indicator, used by password_change_needed() */
216     if ($dn == "new"){
217       $this->last_pw_storage= "unset";
218     } else {
219       $this->last_pw_storage= $this->pw_storage;
220     }
222     /* Generate dateOfBirth entry */
223     if (isset ($this->attrs['dateOfBirth'])){
224       /* This entry is ISO 8601 conform */
225       list($year, $month, $day)= split("-", $this->attrs['dateOfBirth'][0], 3);
226     
227       #TODO: use $lang to convert date
228       $this->dateOfBirth= "$day.$month.$year";
229     } else {
230       $this->dateOfBirth= "";
231     }
233     /* Put gender attribute to upper case */
234     if (isset ($this->attrs['gender'])){
235       $this->gender= strtoupper($this->attrs['gender'][0]);
236     }
238     // Get login restrictions
239     if(isset($this->attrs['gosaLoginRestriction'])){
240       $this->gosaLoginRestriction  =array();
241       for($i =0;$i < $this->attrs['gosaLoginRestriction']['count']; $i++){
242         $this->gosaLoginRestriction[] = $this->attrs['gosaLoginRestriction'][$i];
243       }
244     }
245  
246     $this->orig_base = $this->base;
247   }
250   /* execute generates the html output for this node */
251   function execute()
252   {
253     /* Call parent execute */
254     plugin::execute();
256     /* Handle add/delete for restriction mode */
257     if (isset($_POST['add_res']) && isset($_POST['res'])) {
258       $val= validate($_POST['res']);
259       if (preg_match('/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/', $val) ||
260           preg_match('/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\/([0-9]+)$/', $val) ||
261           preg_match('/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\/([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$/', $val)) {
262         $this->gosaLoginRestriction[]= $val;
263       } else {
264         msg_dialog::display(_("Error"), _("Please add a single IP address or a network/netmask combination!"), ERROR_DIALOG);
265       }
266     }
267     if (isset($_POST['del_res']) && isset($_POST['restrictions'])) {
268       $res= $_POST['restrictions'];
269       if (!is_array($res)){
270         $res= array($res);
271       }
272       foreach ($res as $restriction) {
273         if (in_array($restriction, $this->gosaLoginRestriction)) {
274           $this->gosaLoginRestriction= array_remove_entries(array($restriction), $this->gosaLoginRestriction);
275         }
276       }
277     }
279     /* Log view */
280     if($this->is_account && !$this->view_logged){
281       $this->view_logged = TRUE;
282       new log("view","users/".get_class($this),$this->dn);
283     }
285     $smarty= get_smarty();
286     $smarty->assign("usePrototype", "true");
288     /* Assign sex */
289     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
290     $smarty->assign("gender_list", $sex);
291     $language= array_merge(array(0 => "&nbsp;") ,get_languages(TRUE));
292     $smarty->assign("preferredLanguage_list", $language);
294     /* Get random number for pictures */
295     srand((double)microtime()*1000000); 
296     $smarty->assign("rand", rand(0, 10000));
299     /* Do we represent a valid gosaAccount? */
300     if (!$this->is_account){
301       $str = "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
302         msgPool::noValidExtension("GOsa")."</b>";
303       return($str);
304     }
306     /* Base select dialog */
307     $once = true;
308     foreach($_POST as $name => $value){
309       if(preg_match("/^chooseBase/",$name) && $once && $this->acl_is_writeable("base")){
310         $once = false;
311         $this->dialog = new baseSelectDialog($this->config,$this,$this->allowedBasesToMoveTo());
312         $this->dialog->setCurrentBase($this->base);
313       }
314     }
316     /* Password configure dialog handling */
317     if(is_object($this->pwObject) && $this->pwObject->display){
318       $output= $this->pwObject->configure();
319       if ($output != ""){
320         $this->dialog= TRUE;
321         return $output;
322       }
323       $this->dialog= false;
324     }
326     /* Dialog handling */
327     if(is_object($this->dialog)){
328       /* Must be called before save_object */
329       $this->dialog->save_object();
330    
331       if($this->dialog->isClosed()){
332         $this->dialog = false;
333       }elseif($this->dialog->isSelected()){
335         /* check if selected base is allowed to move to / create a new object */
336         $tmp = $this->get_allowed_bases();
337         if(isset($tmp[$this->dialog->isSelected()])){
338           $this->base = $this->dialog->isSelected();
339         }
340         $this->dialog= false;
341       }else{
342         return($this->dialog->execute());
343       }
344     }
346     /* Want password method editing? */
347     if ($this->acl_is_writeable("userPassword")){
348       if (isset($_POST['edit_pw_method'])){
349         if (!is_object($this->pwObject) || $this->pw_storage != $this->pwObject->get_hash_name()){
350           $temp= passwordMethod::get_available_methods();
351           $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
352         }
353         $this->pwObject->display = TRUE;
354         $this->dialog= TRUE;
355         return ($this->pwObject->configure());
356       }
357     }
359     /* Want picture edit dialog? */
360     if($this->acl_is_writeable("userPicture")) {
361       if (isset($_POST['edit_picture'])){
362         /* Save values for later recovery, in case some presses
363            the cancel button. */
364         $this->old_jpegPhoto= $this->jpegPhoto;
365         $this->old_photoData= $this->photoData;
366         $this->picture_dialog= TRUE;
367         $this->dialog= TRUE;
368       }
369     }
371     /* Remove picture? */
372     if($this->acl_is_writeable("userPicture",(!is_object($this->parent) && !session::is_set('edit'))) ){
373       if (isset($_POST['picture_remove'])){
374         $this->set_picture ();
375         $this->jpegPhoto= "*removed*";
376         $this->is_modified= TRUE;
377         return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
378       }
379     }
381     /* Save picture */
382     if (isset($_POST['picture_edit_finish'])){
384       /* Check for clean upload */
385       if ($_FILES['picture_file']['name'] != ""){
386         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
387           msg_dialog::display(_("Error"), _("Cannot upload file!"), ERROR_DIALOG);
388         }else{
389           /* Activate new picture */
390           $this->set_picture($_FILES['picture_file']['tmp_name']);
391         }
392       }
393       $this->picture_dialog= FALSE;
394       $this->dialog= FALSE;
395       $this->is_modified= TRUE;
396     }
399     /* Cancel picture */
400     if (isset($_POST['picture_edit_cancel'])){
402       /* Restore values */
403       $this->jpegPhoto= $this->old_jpegPhoto;
404       $this->photoData= $this->old_photoData;
406       /* Update picture */
407       session::set('binary',$this->photoData);
408       session::set('binarytype',"image/jpeg");
409       $this->picture_dialog= FALSE;
410       $this->dialog= FALSE;
411     }
413     /* Want certificate= */
414     if ((isset($_POST['edit_cert'])) && $this->acl_is_readable("Certificate")){
416       /* Save original values for later reconstruction */
417       foreach (array("certificateSerialNumber", "userCertificate",
418             "userSMIMECertificate", "userPKCS12") as $val){
420         $oval= "old_$val";
421         $this->$oval= $this->$val;
422       }
424       $this->cert_dialog= TRUE;
425       $this->dialog= TRUE;
426     }
429     /* Cancel certificate dialog */
430     if (isset($_POST['cert_edit_cancel'])){
432       /* Restore original values in case of 'cancel' */
433       foreach (array("certificateSerialNumber", "userCertificate",
434             "userSMIMECertificate", "userPKCS12") as $val){
436         $oval= "old_$val";
437         $this->$val= $this->$oval;
438       }
439       $this->cert_dialog= FALSE;
440       $this->dialog= FALSE;
441     }
444     /* Remove certificate? */
445     if($this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))){ 
446       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
447         if (isset($_POST["remove_$val"])){
449           /* Reset specified cert*/
450           $this->$val= "";
451           $this->is_modified= TRUE;
452         }
453       }
454     }
456     /* Upload new cert and close dialog? */     
457     if($this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))){ 
459       $fail =false;
461       if (isset($_POST['cert_edit_finish'])){
463         /* for all certificates do */
464         foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
465             as $val){
467           /* Check for clean upload */
468           if (array_key_exists($val."_file", $_FILES) &&
469               array_key_exists('name', $_FILES[$val."_file"]) &&
470               $_FILES[$val."_file"]['name'] != "" &&
471               is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
472             $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
473           }
474         }
476         /* Save serial number */
477         if (isset($_POST["certificateSerialNumber"]) &&
478             $_POST["certificateSerialNumber"] != ""){
480           if (!tests::is_id($_POST["certificateSerialNumber"])){
481             $fail = true;
482             msg_dialog::display(_("Error"), msgPool::invalid(_("Serial number"),$_POST["certificateSerialNumber"],"/[0-9]/"),ERROR_DIALOG);
484             foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
485               if ($this->$cert != ""){
486                 $smarty->assign("$cert"."_state", "true");
487               } else {
488                 $smarty->assign("$cert"."_state", "");
489               }
490             }
491           }
493           $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
494           $this->is_modified= TRUE;
495         }
496         if(!$fail){
497           $this->cert_dialog= FALSE;
498           $this->dialog= FALSE;
499         }
500       }
501     }
502     /* Display picture dialog */
503     if ($this->picture_dialog){
504       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
505     }
507     /* Display cert dialog */
508     if ($this->cert_dialog){
509       $smarty->assign("CertificateACL",$this->getacl("Certificate",(!is_object($this->parent) && !session::is_set('edit'))));
510       $smarty->assign("Certificate_readable",$this->acl_is_readable("Certificate"));
511       $smarty->assign("certificateSerialNumber",$this->certificateSerialNumber);
513       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
514         if ($this->$cert != ""){
515           /* import certificate */
516           $certificate = new certificate;
517           $certificate->import($this->$cert);
518       
519           /* Read out data*/
520           $timeto   = $certificate->getvalidto_date();
521           $timefrom = $certificate->getvalidfrom_date();
522          
523           
524           /* Additional info if start end time is '0' */
525           $add_str_info = "";
526           if($timeto == 0 && $timefrom == 0){
527             $add_str_info = "<br><i>"._("(Some types of certificates are currently not supported and may be displayed as 'invalid'.)")."</i>";
528           }
530           $str = "<table summary=\"\" border=0>
531                     <tr>
532                       <td style='vertical-align:top'>CN</td>
533                       <td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td>
534                     </tr>
535                   </table><br>".
537                   sprintf(_("Certificate is valid from %s to %s and is currently %s."),
538                         "<b>".date('d M Y',$timefrom)."</b>",
539                         "<b>".date('d M Y',$timeto)."</b>",
540                         $certificate->isvalid()?"<b><font style='color:green'>"._("valid")."</font></b>":
541                                                 "<b><font style='color:red'>"._("invalid")."</font></b>").$add_str_info;
543           $smarty->assign($cert."info",$str);
544           $smarty->assign($cert."_state","true");
545         } else {
546           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
547           $smarty->assign($cert."_state","");
548         }
549       }
550   
551       if($this->governmentmode){
552         $smarty->assign("honourIvbbAttributes", "true");
553       }else{
554         $smarty->assign("honourIvbbAttributes", "false");
555       }
556       $smarty->assign("governmentmode", $this->governmentmode);
557       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
558     }
560     /* Prepare password hashes */
561     if ($this->pw_storage == ""){
562       $this->pw_storage= $this->config->get_cfg_value("hash");
563     }
565     $temp= passwordMethod::get_available_methods();
566     $is_configurable= FALSE;
567     $hashes = $temp['name'];
568     if(isset($temp[$this->pw_storage])){
569       $test= new $temp[$this->pw_storage]($this->config);
570       $is_configurable= $test->is_configurable();
571     }else{
572       new msg_dialog(_("Password method"),_("The selected password method is no longer available."),WARNING_DIALOG);
573     }
576     /* Create password methods array */
577     $pwd_methods = array();
578     foreach($hashes as $id => $name){
579       if(!empty($temp['desc'][$id])){
580         $pwd_methods[$name] = $name." (".$temp['desc'][$id].")";
581       }else{
582         $pwd_methods[$name] = $name;
583       }
584     }
585  
586     /* Load attributes and acl's */
587     $ui =get_userinfo();
588     foreach($this->attributes as $val){
589       $smarty->assign("$val", $this->$val);
590       if(in_array($val,$this->multi_boxes)){
591         $smarty->assign("use_".$val,TRUE);
592       }else{
593         $smarty->assign("use_".$val,FALSE);
594       }
595     }
596     foreach(array("base","pw_storage","edit_picture") as $val){
597       if(in_array($val,$this->multi_boxes)){
598         $smarty->assign("use_".$val,TRUE);
599       }else{
600         $smarty->assign("use_".$val,FALSE);
601       }
602     }
604     /* Set acls */
605     $tmp = $this->plinfo();
606     foreach($tmp['plProvidedAcls'] as $val => $translation){
607       $smarty->assign("$val"."ACL", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit'))));
608     }
610     $smarty->assign("gosaLoginRestriction", $this->gosaLoginRestriction);
611     $smarty->assign("gosaLoginRestrictionACL", $this->getacl('gosaLoginRestriction', (!is_object($this->parent) && !session::is_set('edit'))));
612     $smarty->assign("pwmode", $pwd_methods);
613     $smarty->assign("pwmode_select", $this->pw_storage);
614     $smarty->assign("pw_configurable", $is_configurable);
615     $smarty->assign("passwordStorageACL", $this->getacl("userPassword",(!is_object($this->parent) && !session::is_set('edit'))));
616     $smarty->assign("base_select",      $this->base);
618     if(!session::is_set('edit')){
619       $smarty->assign("CertificatesACL","");
620     }else{
621       $smarty->assign("CertificatesACL",  $this->getacl("Certificate"));
622     }
623     
624     $smarty->assign("userPictureACL",   $this->getacl("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));
625     $smarty->assign("userPicture_is_readable",   $this->acl_is_readable("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));
627     /* Create base acls */
628     $tmp = @$this->allowedBasesToMoveTo();
629     $smarty->assign("bases", $tmp);
631     /* Save government mode attributes */
632     if($this->governmentmode){
633       $smarty->assign("governmentmode", "true");
634       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
635           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
636       $smarty->assign("ivbbmodes", $ivbbmodes);
637       foreach ($this->govattrs as $val){
638         $smarty->assign("$val", $this->$val);
639         $smarty->assign("$val"."ACL", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit'))));
640       }
641     } else {
642       $smarty->assign("governmentmode", "false");
643     }
645     /* Special mode for uid */
646     $uidACL= $this->getacl("uid",(!is_object($this->parent) && !session::is_set('edit')));
647     if (isset ($this->dn)){
648       if ($this->dn != "new"){
649         $uidACL= preg_replace("/w/","",$uidACL);
650       }
651     }  else {
652       $uidACL= preg_replace("/w/","",$uidACL);
653     }
654     
655     $smarty->assign("uidACL", $uidACL);
656     $smarty->assign("is_template", $this->is_template);
657     $smarty->assign("use_dob", $this->use_dob);
659     if (isset($this->parent)){
660       if (isset($this->parent->by_object['phoneAccount']) &&
661           $this->parent->by_object['phoneAccount']->is_account){
662         $smarty->assign("has_phoneaccount", "true");
663       } else {
664         $smarty->assign("has_phoneaccount", "false");
665       }
666     } else {
667       $smarty->assign("has_phoneaccount", "false");
668     }
669     $smarty->assign("multiple_support" , $this->multiple_support_active);
670     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
671   }
674   /* remove object from parent */
675   function remove_from_parent()
676   {
677     /* Only remove valid accounts */
678     if(!$this->initially_was_account) return;
680     /* Remove password extension */
681     $temp= passwordMethod::get_available_methods();
683     /* Remove password method from user account */
684     if(isset($temp[$this->pw_storage]) && class_available($temp[$this->pw_storage])){
685       $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
686       $this->pwObject->remove_from_parent();
687     }
689     /* Remove user */
690     $ldap= $this->config->get_ldap_link();
691     $ldap->rmdir ($this->dn);
692     if (!$ldap->success()){
693       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
694     }
695   
696     new log("remove","users/".get_class($this),$this->dn,$this->attributes,$ldap->get_error());
697   
698     /* Delete references to groups */
699     $ldap->cd ($this->config->current['BASE']);
700     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
701     while ($ldap->fetch()){
702       $g= new group($this->config, $ldap->getDN());
703       $g->removeUser($this->uid);
704       $g->save ();
705     }
707     /* Delete references to object groups */
708     $ldap->cd ($this->config->current['BASE']);
709     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
710     while ($ldap->fetch()){
711       $og= new ogroup($this->config, $ldap->getDN());
712       unset($og->member[$this->dn]);
713       $og->member= array_values($og->member);
714       $og->save ();
715     }
717     /* Delete references to roles */
718     $ldap->cd ($this->config->current['BASE']);
719     $ldap->search ("(&(objectClass=organizationalRole)(roleOccupant=".LDAP::prepare4filter($this->dn)."))", array("cn"));
720     while ($ldap->fetch()){
721       $role= new roleGeneric($this->config, $ldap->getDN());
722       $key = array_search($this->dn,$role->roleOccupant);
723       if($key !== FALSE){
724         unset($role->roleOccupant[$key]);
725         $role->roleOccupant= array_values($role->roleOccupant);
726         $role->save ();
727       }
728     }
730     /* If needed, let the password method do some cleanup */
731     $tmp = new passwordMethod($this->config);
732     $available = $tmp->get_available_methods();
733     if (in_array_ics($this->pw_storage, $available['name'])){
734       $test= new $available[$this->pw_storage]($this->config);
735       $test->attrs= $this->attrs;
736       $test->dn= $this->dn;
737       $test->remove_from_parent();
738     }
740     /* Remove ACL dependencies too */
741     acl::remove_acl_for($this->dn);
743     /* Optionally execute a command after we're done */
744     $this->handle_post_events("remove",array("uid" => $this->uid));
745   }
748   /* Save data to object */
749   function save_object()
750   {
751     if(isset($_POST['generic']) || isset($_POST['multiple_user_posted'])){
753       /* Make a backup of the current selected base */
754       $base_tmp = $this->base;
756       /* Parents save function */
757       plugin::save_object ();
759       /* Save government mode attributes */
760       if ($this->governmentmode){
761         foreach ($this->govattrs as $val){
762           if ($this->acl_is_writeable($val,(!is_object($this->parent) && !session::is_set('edit'))) && isset($_POST["$val"])){
763             $data= stripcslashes($_POST["$val"]);
764             if ($data != $this->$val){
765               $this->is_modified= TRUE;
766             }
767             $this->$val= $data;
768           }
769         }
770       }
772       /* In template mode, the uid is autogenerated... */
773       if ($this->is_template){
774         $this->uid= strtolower($this->sn);
775         $this->givenName= $this->sn;
776       }
778       /* Save base - its no no LDAP attribute */
779       if (isset($_POST['base'])){
780         $base= get_post('base');
781         if ($base != $this->base){
782           $tmp = $this->get_allowed_bases();
783           if(isset($tmp[$base])){
784             if ($base != $this->base){
785               $this->is_modified= TRUE;
786             }
787             $this->base= $base;
788           }else{
789             $this->base = $base_tmp;
790             msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
791           }
792         }
793       }
795       /* Get pw_storage mode */
796       if (isset($_POST['pw_storage'])){
797         foreach(array("pw_storage") as $val){
798           if(isset($_POST[$val])){
799             $data= validate($_POST[$val]);
800             if ($data != $this->$val){
801               $this->is_modified= TRUE;
802             }
803             $this->$val= $data;
804           }
805         }
806       }
808       if($this->pw_storage != $this->last_pw_storage && isset($_POST['pw_storage'])){
809         if ($this->acl_is_writeable("userPassword")){
810           $temp= passwordMethod::get_available_methods();
811           if (!is_object($this->pwObject) || !($this->pwObject instanceOf $temp[$this->pw_storage])){
812             foreach($temp as $id => $data){
813               if(isset($data['name']) && $data['name'] == $this->pw_storage && $data['is_configurable']){
814                 $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
815                 break;
816               }
817             }
818           }
819         }
820       }
822       /* Save current cn
823        */
824       $this->cn = $this->givenName." ".$this->sn;
825     }
826   }
828   function rebind($ldap, $referral)
829   {
830     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
831     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
832       $this->error = "Success";
833       $this->hascon=true;
834       $this->reconnect= true;
835       return (0);
836     } else {
837       $this->error = "Could not bind to " . $credentials['ADMIN'];
838       return NULL;
839     }
840   }
842   
843   /* Save data to LDAP, depending on is_account we save or delete */
844   function save()
845   {
846     global $lang;
848     /* Only force save of changes .... 
849        If this attributes aren't changed, avoid saving.
850      */
851   
852     if($this->gender=="0") $this->gender ="";
853     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
855     /* First use parents methods to do some basic fillup in $this->attrs */
856     plugin::save ();
858     if ($this->dateOfBirth != ""){
859       if(!is_array($this->attrs['dateOfBirth'])) {
860         #TODO: use $lang to convert date
861         list($day, $month, $year)= split("\.", $this->dateOfBirth);
862         $this->attrs['dateOfBirth'] = sprintf("%04d-%02d-%02d", $year, $month, $day);
863       }
864     }
866     /* Remove additional objectClasses */
867     $tmp= array();
868     foreach ($this->attrs['objectClass'] as $key => $set){
869       $found= false;
870       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
871         if (preg_match ("/^$set$/i", $val)){
872           $found= true;
873           break;
874         }
875       }
876       if (!$found){
877         $tmp[]= $set;
878       }
879     }
881     /* Replace the objectClass array. This is done because of the
882        separation into government and normal mode. */
883     $this->attrs['objectClass']= $tmp;
885     /* Add objectClasss for template mode? */
886     if ($this->is_template){
887       $this->attrs['objectClass'][]= "gosaUserTemplate";
888     }
890     /* Hard coded government mode? */
891     if ($this->governmentmode){
892       $this->attrs['objectClass'][]= "ivbbentry";
894       /* Copy standard attributes */
895       foreach ($this->govattrs as $val){
896         if ($this->$val != ""){
897           $this->attrs["$val"]= $this->$val;
898         } elseif (!$this->is_new) {
899           $this->attrs["$val"]= array();
900         }
901       }
903       /* Remove attribute if set to "nein" */
904       if ($this->publicVisible == "nein"){
905         $this->attrs['publicVisible']= array();
906         if($this->is_new){
907           unset($this->attrs['publicVisible']);
908         }else{
909           $this->attrs['publicVisible']=array();
910         }
912       }
914     }
916     /* Special handling for attribute userCertificate needed */
917     if ($this->userCertificate != ""){
918       $this->attrs["userCertificate;binary"]= $this->userCertificate;
919       $remove_userCertificate= false;
920     } else {
921       $remove_userCertificate= true;
922     }
924     /* Special handling for dateOfBirth value */
925     if ($this->dateOfBirth == ""){
926       if ($this->is_new) {
927         unset($this->attrs["dateOfBirth"]);
928       } else {
929         $this->attrs["dateOfBirth"]= array();
930       }
931     }
932     if (!$this->gender){
933       if ($this->is_new) {
934         unset($this->attrs["gender"]);
935       } else {
936         $this->attrs["gender"]= array();
937       }
938     }
939     if (!$this->preferredLanguage){
940       if ($this->is_new) {
941         unset($this->attrs["preferredLanguage"]);
942       } else {
943         $this->attrs["preferredLanguage"]= array();
944       }
945     }
947     /* Special handling for attribute jpegPhote needed, scale image via
948        image magick to 147x200 pixels and inject resulting data. */
949     if ($this->jpegPhoto == "*removed*"){
950     
951       /* Reset attribute to avoid writing *removed* as value */    
952       $this->attrs["jpegPhoto"] = array();
954     } else {
956       /* Fallback if there's no image magick inside PHP */
957       if (!function_exists("imagick_blob2image")){
958         /* Get temporary file name for conversation */
959         $fname = tempnam (TEMP_DIR, "GOsa");
960   
961         /* Open file and write out photoData */
962         $fp = fopen ($fname, "w");
963         fwrite ($fp, $this->photoData);
964         fclose ($fp);
966         /* Build conversation query. Filename is generated automatically, so
967            we do not need any special security checks. Exec command and save
968            output. For PHP safe mode, you'll need a configuration which respects
969            image magick as executable... */
970         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
971         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
972             $query, "Execute");
973   
974         /* Read data written by convert */
975         $output= "";
976         $sh= popen($query, 'r');
977         while (!feof($sh)){
978           $output.= fread($sh, 4096);
979         }
980         pclose($sh);
982         unlink($fname);
984         /* Save attribute */
985         $this->attrs["jpegPhoto"] = $output;
987       } else {
989         /* Load the new uploaded Photo */
990         if(!$handle  =  imagick_blob2image($this->photoData))  {
991           new log("debug","users/".get_class($this),$this->dn,array(),"Could not access uploaded image");
992         }
994         /* Resizing image to 147x200 and blur */
995         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
996           new log("debug","users/".get_class($this),$this->dn,array(),"Could not resize uploaded image");
997         }
999         /* Converting image to JPEG */
1000         if(!imagick_convert($handle,"JPEG")) {
1001           new log("debug","users/".get_class($this),$this->dn,array(),"Could not convert uploaded image to jepg");
1002         }
1004         /* Creating binary Code for the Image */
1005         if(!$dump = imagick_image2blob($handle)){
1006           new log("debug","users/".get_class($this),$this->dn,array(),"Could not create new user image");
1007         }
1009         /* Sending Image */
1010         $output=  $dump;
1012         /* Save attribute */
1013         $this->attrs["jpegPhoto"] = $output;
1014       }
1016     }
1018     /* This only gets called when user is renaming himself */
1019     $ldap= $this->config->get_ldap_link();
1020     if ($this->dn != $this->new_dn){
1022       /* Write entry on new 'dn' */
1023       $this->update_acls($this->dn,$this->new_dn);
1024       $this->move($this->dn, $this->new_dn);
1026       /* Happen to use the new one */
1027       change_ui_dn($this->dn, $this->new_dn);
1028       $this->dn= $this->new_dn;
1029     }
1032     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
1033        new entries. So do a check first... */
1034     $ldap->cat ($this->dn, array('dn'));
1035     if ($ldap->fetch()){
1036       $mode= "modify";
1037     } else {
1038       $mode= "add";
1039       $ldap->cd($this->config->current['BASE']);
1040       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
1041     }
1043     /* Set password to some junk stuff in case of templates */
1044     if ($this->is_template){
1045       $temp= passwordMethod::get_available_methods();
1046       foreach($temp as $id => $data){
1047         if(isset($data['name']) && $data['name'] == $this->pw_storage){
1048           $tmp = new  $temp[$this->pw_storage]($this->config,$this->dn);
1049           $tmp->set_hash($this->pw_storage);
1050           $this->attrs['userPassword'] = $tmp->create_template_hash($this->attrs);
1051           break;
1052         }
1053       }
1054     }
1056     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
1057         $this->attributes, "Save via $mode");
1059     /* Finally write data with selected 'mode' */
1060     $this->cleanup();
1062     /* Update current locale settings, if we have edited ourselves */
1063     $ui = session::get('ui');
1064     if(isset($this->attrs['preferredLanguage']) && $this->dn == $ui->dn){
1065       $ui->language = $this->preferredLanguage;
1066       session::set('ui',$ui);
1067       session::set('Last_init_lang',"update");
1068     }
1070     $ldap->cd ($this->dn);
1071     $ldap->$mode ($this->attrs);
1072     if (!$ldap->success()){
1073       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
1074       return (1);
1075     }
1077     /* Remove ACL dependencies too */
1078     if($this->dn != $this->orig_dn && $this->orig_dn != "new"){
1079       $tmp = new acl($this->config,$this->parent,$this->dn);
1080       $tmp->update_acl_membership($this->orig_dn,$this->dn);
1081     }
1083     if($mode == "modify"){
1084       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1085     }else{
1086       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1087     }
1089     /* Remove cert? 
1090        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
1091        to work around myself. */
1092     if ($remove_userCertificate == true && !$this->is_new && $this->had_userCertificate){
1094       /* Reset array, assemble new, this should be reworked */
1095       $this->attrs= array();
1096       $this->attrs['userCertificate;binary']= array();
1098       /* Prepare connection */
1099       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
1100         die ("Could not connect to LDAP server");
1101       }
1102       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1103       if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true") {
1104         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1105         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1106       }
1107       if($this->config->get_cfg_value("ldapTLS") == "true"){
1108         ldap_start_tls($ds);
1109       }
1110       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
1111               $this->config->current['PASSWORD']))) {
1112         die ("Could not bind to LDAP");
1113       }
1115       /* Modify using attrs */
1116       ldap_mod_del($ds,$this->dn,$this->attrs);
1117       ldap_close($ds);
1118     }
1120     /* If needed, let the password method do some cleanup */
1121     if ($this->pw_storage != $this->last_pw_storage){
1122       $tmp = new passwordMethod($this->config);
1123       $available = $tmp->get_available_methods();
1124       if (in_array_ics($this->last_pw_storage, $available['name'])){
1125         $test= new $available[$this->last_pw_storage]($this->config,$this->dn);
1126         $test->attrs= $this->attrs;
1127         $test->remove_from_parent();
1128       }
1129     }
1131     /* Maybe the current password method want's to do some changes... */
1132     if (is_object($this->pwObject)){
1133       $this->pwObject->save($this->dn);
1134     }
1136     /* Optionally execute a command after we're done */
1137     if ($mode == "add"){
1138       $this->handle_post_events("add", array("uid" => $this->uid));
1139     } elseif ($this->is_modified){
1140       $this->handle_post_events("modify", array("uid" => $this->uid));
1141     }
1143     return (0);
1144   }
1147   function create_initial_rdn($pattern)
1148   {
1149     // Only generate single RDNs
1150     if (preg_match('/\+/', $pattern)){
1151       msg_dialog::display(_("Error"), _("Cannot build RDN: no + allowed to build sub RDN!"), ERROR_DIALOG);
1152       return "";
1153     }
1155     // Extract attribute
1156     $attribute= preg_replace('/=.*$/', '', $pattern);
1157     if (!in_array_ics($attribute, $this->attributes)) {
1158       msg_dialog::display(_("Error"), _("Cannot build RDN: attribute is not defined!"), ERROR_DIALOG);
1159       return "";
1160     }
1162     // Sort attributes for length
1163     $attrl= array();
1164     foreach ($this->attributes as $attr) {
1165       $attrl[$attr]= strlen($attr);
1166     }
1167     arsort($attrl);
1168     
1169     // Walk thru sorted attributes and replace them in pattern
1170     foreach ($attrl as $attr => $dummy) {
1171       if (!is_array($this->$attr)){
1172         $pattern= preg_replace("/%$attr/", $this->$attr, $pattern);
1173       } else {
1174         // Array elements cannot be used for ID generation
1175         if (preg_match("/%$attr/", $pattern)) {
1176           msg_dialog::display(_("Error"), _("Cannot build RDN: invalid attribute parameters!"), ERROR_DIALOG);
1177           break;
1178         }
1179       }
1180     }
1182     // Internally assign value
1183     $this->$attribute= preg_replace('/^[^=]+=/', '', $pattern);
1185     return $pattern;
1186   }
1188   
1189   function update_new_dn()
1190   {
1191     // Alternative way to handle DN
1192     $pattern= $this->config->get_cfg_value("accountRDN");
1193     if ($pattern != "") {
1194       $rdn= $this->create_initial_rdn($pattern);
1195       $attribute= preg_replace('/=.*$/', '', $rdn);
1196       $value= preg_replace('/^[^=]+=$/', '', $rdn);
1198       /* Don't touch dn, if $attribute hasn't changed */
1199       if (isset($this->saved_attributes[$attribute]) && $this->saved_attributes[$attribute] == $this->$attribute &&
1200             $this->orig_base == $this->base ){
1201         $this->new_dn= $this->dn;
1202       } else {
1203         $this->new_dn= $this->create_unique_dn2($rdn, get_people_ou().$this->base);
1204       }
1206     // Original way to handle DN
1207     } else {
1209       $pt= "";
1210       if($this->config->get_cfg_value("personalTitleInDN") == "true"){
1211         if(!empty($this->personalTitle)){
1212           $pt = $this->personalTitle." ";
1213         }
1214       }
1216       $this->cn= $pt.$this->givenName." ".$this->sn;
1218       /* Permissions for that base? */
1219       if ($this->config->get_cfg_value("accountPrimaryAttribute") == "uid"){
1220         $this->new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
1221       } else {
1222         /* Don't touch dn, if cn hasn't changed */
1223         if (isset($this->saved_attributes['cn']) && $this->saved_attributes['cn'] == $this->cn &&
1224             $this->orig_base == $this->base ){
1225           $this->new_dn= $this->dn;
1226         } else {
1227           $this->new_dn= $this->create_unique_dn('cn', get_people_ou().$this->base);
1228         }
1229       }
1230     }
1231   }
1232   
1234   /* Check formular input */
1235   function check()
1236   {
1237     /* Call common method to give check the hook */
1238     $message= plugin::check();
1240     /* Configurable password methods should be configured initially. 
1241      */ 
1242     if($this->last_pw_storage != $this->pw_storage){
1243       $temp= passwordMethod::get_available_methods();
1244       foreach($temp['name'] as $id => $name){
1245         if($name == $this->pw_storage){
1246           if($temp['is_configurable'][$id] && !$this->pwObject instanceof $temp[$name] ){
1247             $message[] = _("The selected password method requires initial configuration!");
1248           }
1249           break;
1250         }
1251       }
1252     }
1254     $this->update_new_dn();
1256     /* Set the new acl base */
1257     if($this->dn == "new") {
1258       $this->set_acl_base($this->base);
1259     }
1261     /* Check if we are allowed to create/move this user */
1262     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
1263       $message[]= msgPool::permCreate();
1264     }elseif($this->orig_dn != "new" && $this->new_dn != $this->orig_dn && !$this->acl_is_moveable($this->base)){
1265       $message[]= msgPool::permMove();
1266     }
1268     /* UID already used? */
1269     $ldap= $this->config->get_ldap_link();
1270     $ldap->cd($this->config->current['BASE']);
1271     $ldap->search("(uid=$this->uid)", array("uid"));
1272     $ldap->fetch();
1273     if ($ldap->count() != 0 && $this->dn == 'new'){
1274       $message[]= msgPool::duplicated(_("Login"));
1275     }
1277     /* In template mode, the uid and givenName are autogenerated... */
1278     if ($this->sn == ""){
1279       $message[]= msgPool::required(_("Name"));
1280     }
1282     if (!$this->is_template){
1283       if ($this->givenName == ""){
1284         $message[]= msgPool::required(_("Given name"));
1285       }
1286       if ($this->uid == ""){
1287         $message[]= msgPool::required(_("Login"));
1288       }
1289       if ($this->config->get_cfg_value("accountPrimaryAttribute") != "uid"){
1290         $ldap->cat($this->new_dn);
1291         if ($ldap->count() != 0 && $this->dn != $this->new_dn && $this->dn == 'new'){
1292           $message[]= msgPool::duplicated(_("Name"));
1293         }
1294       }
1295     }
1297     /* Check for valid input */
1298     if ($this->is_modified && !tests::is_uid($this->uid)){
1300       if (strict_uid_mode()){
1301         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/");
1302       } else {
1303         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/i");
1304       }
1305     }
1306     if (!tests::is_url($this->labeledURI)){
1307       $message[]= msgPool::invalid(_("Homepage"), "", "", "http://www.your-domain.com/yourname");
1308     }
1310     /* Check phone numbers */
1311     if (!tests::is_phone_nr($this->telephoneNumber)){
1312       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1313     }
1314     if (!tests::is_phone_nr($this->facsimileTelephoneNumber)){
1315       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1316     }
1317     if (!tests::is_phone_nr($this->mobile)){
1318       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1319     }
1320     if (!tests::is_phone_nr($this->pager)){
1321       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1322     }
1324     /* Check dates */
1325     if (!tests::is_date($this->dateOfBirth)){
1326       $message[]= msgPool::invalid(_("Date of birth"), $this->dateOfBirth,"" ,"23.02.2009");
1327     }
1329     /* Check for reserved characers */
1330     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName)){
1331       $message[]= msgPool::invalid(_("Given name"), $this->givenName, '/[^,+"?\'()=<>;\\\\]/');
1332     }
1333     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn)){
1334       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1335     }
1337     return $message;
1338   }
1341   /* Indicate whether a password change is needed or not */
1342   function password_change_needed()
1343   {
1344     if(in_array("pw_storage",$this->multi_boxes)){
1345       return(TRUE);
1346     }
1347     return($this->pw_storage != $this->last_pw_storage && !$this->is_template);
1348   }
1351   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1352   function load_picture()
1353   {
1354     $ldap = $this->config->get_ldap_link();
1355     $ldap->cd ($this->dn);
1356     $data = $ldap->get_attribute($this->dn,"jpegPhoto");
1358     if((!$data) || ($data == "*removed*")){ 
1360       /* In case we don't get an entry, load a default picture */
1361       $this->set_picture ();
1362       $this->jpegPhoto= "*removed*";
1363     }else{
1365       /* Set picture */
1366       $this->photoData= $data;
1367       session::set('binary',$this->photoData);
1368       session::set('binarytype',"image/jpeg");
1369       $this->jpegPhoto= "";
1370     }
1371   }
1374   /* Load a certificate from LDAP, this is going to be simplified later on */
1375   function load_cert()
1376   {
1377     $ds= ldap_connect($this->config->current['SERVER']);
1378     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1379     if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true"){
1380       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1381       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1382     }
1383     if ($this->config->get_cfg_value("ldapTLS") == "true"){
1384       ldap_start_tls($ds);
1385     }
1387     $r= ldap_bind($ds);
1388     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1390     if ($sr) {
1391       $ei= @ldap_first_entry($ds, $sr);
1392       
1393       if ($ei) {
1394         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1395           $this->userCertificate= "";
1396         } else {
1397           $this->userCertificate= $info[0];
1398         }
1399       }
1400     } else {
1401       $this->userCertificate= "";
1402     }
1404     ldap_unbind($ds);
1405   }
1408   /* Load picture from file to object */
1409   function set_picture($filename ="")
1410   {
1411     if (!is_file($filename) || $filename =="" ){
1412       $filename= "./plugins/users/images/default.jpg";
1413       $this->jpegPhoto= "*removed*";
1414     }
1416     $fd = fopen ($filename, "rb");
1417     $this->photoData= fread ($fd, filesize ($filename));
1418     session::set('binary',$this->photoData);
1419     session::set('binarytype',"image/jpeg");
1420     $this->jpegPhoto= "";
1422     fclose ($fd);
1423   }
1426   /* Load certificate from file to object */
1427   function set_cert($cert, $filename)
1428   {
1429     if(!$this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))) return;
1430     $fd = fopen ($filename, "rb");
1431     if (filesize($filename)>0) {
1432       $this->$cert= fread ($fd, filesize ($filename));
1433       fclose ($fd);
1434       $this->is_modified= TRUE;
1435     } else {
1436       msg_dialog::display(_("Error"), _("Cannot open certificate!"), ERROR_DIALOG);
1437     }
1438   }
1440   /* Adapt from given 'dn' */
1441   function adapt_from_template($dn, $skip= array())
1442   {
1443     plugin::adapt_from_template($dn, $skip);
1445     /* Get password method from template 
1446      */
1447     $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
1448     if(is_object($tmp)){
1449       if($tmp->is_configurable()){
1450         $tmp->adapt_from_template($dn);
1451         $this->pwObject = &$tmp;
1452       }
1453       $this->pw_storage= $tmp->get_hash();
1454     }
1456     /* Get base */
1457     $this->base= preg_replace('/^[^,]+,'.preg_quote(get_people_ou(), '/').'/i', '', $dn);
1459     if($this->governmentmode){
1461       /* Walk through govattrs */
1462       foreach ($this->govattrs as $val){
1464         if (in_array($val, $skip)){
1465           continue;
1466         }
1468         if (isset($this->attrs["$val"][0])){
1470           /* If attribute is set, replace dynamic parts: 
1471              %sn, %givenName and %uid. Fill these in our local variables. */
1472           $value= $this->attrs["$val"][0];
1474           foreach (array("sn", "givenName", "uid") as $repl){
1475             if (preg_match("/%$repl/i", $value)){
1476               $value= preg_replace ("/%$repl/i",
1477                   $this->parent->$repl, $value);
1478             }
1479           }
1480           $this->$val= $value;
1481         }
1482       }
1483     }
1485     /* Get back uid/sn/givenName - only write if nothing's skipped */
1486     if ($this->parent !== NULL && count($skip) == 0){
1487       $this->uid= $this->parent->uid;
1488       $this->sn= $this->parent->sn;
1489       $this->givenName= $this->parent->givenName;
1490     }
1491   }
1493  
1494   /* This avoids that users move themselves out of their rights. 
1495    */
1496   function allowedBasesToMoveTo()
1497   {
1498     /* Get bases */
1499     $bases  = $this->get_allowed_bases();
1500     return($bases);
1501   } 
1504   function getCopyDialog()
1505   {
1506     $str = "";
1508     session::set('binary',$this->photoData); 
1509     session::set('binarytype',"image/jpeg");
1511     /* Get random number for pictures */
1512     srand((double)microtime()*1000000); 
1513     $rand = rand(0, 10000);
1515     $smarty = get_smarty();
1517     $smarty->assign("passwordTodo","clear");
1519     if(isset($_POST['passwordTodo'])){
1520       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1521     }
1523     $smarty->assign("sn",       $this->sn);
1524     $smarty->assign("givenName",$this->givenName);
1525     $smarty->assign("uid",      $this->uid);
1526     $smarty->assign("rand",     $rand);
1527     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1530     $ret = array();
1531     $ret['string'] = $str;
1532     $ret['status'] = "";  
1533     return($ret);
1534   }
1536   function saveCopyDialog()
1537   {
1538     /* Set_acl_base */
1539     $this->set_acl_base($this->base);
1541     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1542       $this->set_picture($_FILES['picture_file']['tmp_name']);
1543     }
1545     /* Remove picture? */
1546     if (isset($_POST['picture_remove'])){
1547       $this->jpegPhoto= "*removed*";
1548       $this->set_picture ("./plugins/users/images/default.jpg");
1549       $this->is_modified= TRUE;
1550     }
1552     $attrs = array("uid","givenName","sn");
1553     foreach($attrs as $attr){
1554       if(isset($_POST[$attr])){
1555         $this->$attr = $_POST[$attr];
1556       }
1557     } 
1558   }
1561   function PrepareForCopyPaste($source)
1562   {
1563     plugin::PrepareForCopyPaste($source);
1565     /* Reset certificate information addepted from source user
1566        to avoid setting the same user certificate for the destination user. */
1567     $this->userPKCS12= "";
1568     $this->userSMIMECertificate= "";
1569     $this->userCertificate= "";
1570     $this->certificateSerialNumber= "";
1571     $this->old_certificateSerialNumber= "";
1572     $this->old_userPKCS12= "";
1573     $this->old_userSMIMECertificate= "";
1574     $this->old_userCertificate= "";
1575   }
1578   static function plInfo()
1579   {
1580   
1581     $govattrs= array(
1582         "gouvernmentOrganizationalUnit"             =>  _("Unit"), 
1583         "houseIdentifier"                           =>  _("House identifier"), 
1584         "vocation"                                  =>  _("Vocation"),
1585         "ivbbLastDeliveryCollective"                =>  _("Last delivery"), 
1586         "gouvernmentOrganizationalPersonLocality"   =>  _("Person locality"),
1587         "gouvernmentOrganizationalUnitDescription"  =>  _("Unit description"),
1588         "gouvernmentOrganizationalUnitSubjectArea"  =>  _("Subject area"),
1589         "functionalTitle"                           =>  _("Functional title"),
1590         "certificateSerialNumber"                   =>  _("Certificate serial number"),
1591         "publicVisible"                             =>  _("Public visible"),
1592         "street"                                    =>  _("Street"),
1593         "role"                                      =>  _("Role"),
1594         "postalCode"                                =>  _("Postal code"));
1596     $ret = array(
1597         "plShortName" => _("Generic"),
1598         "plDescription" => _("Generic user settings"),
1599         "plSelfModify"  => TRUE,
1600         "plDepends"     => array(),
1601         "plPriority"    => 1,
1602         "plSection"     => array("personal" => _("My account")),
1603         "plCategory"    => array("users" => array("description" => _("Users"),
1604                                                   "objectClass" => "gosaAccount")),
1606         "plProvidedAcls" => array(
1608           "sn"                => _("Surname"),
1609           "givenName"         => _("Given name"),
1610           "uid"               => _("User identification"),
1611           "personalTitle"     => _("Personal title"),
1612           "academicTitle"     => _("Academic title"),
1614           "dateOfBirth"       => _("Date of birth"),
1615           "gender"            => _("Sex"),
1616           "preferredLanguage" => _("Preferred language"),
1617           "base"              => _("Base"), 
1619           "userPicture"       => _("User picture"),
1621           "o"                 => _("Organization"),
1622           "ou"                => _("Department"),
1623           "departmentNumber"  => _("Department number"),
1624           "employeeNumber"    => _("Employee number"),
1625           "employeeType"      => _("Employee type"),
1627           "roomNumber"        => _("Room number"),
1628           "telephoneNumber"   => _("Telefon number"),
1629           "pager"             => _("Pager number"),
1630           "mobile"            => _("Mobile number"),
1631           "facsimileTelephoneNumber"     => _("Fax number"),
1633           "st"                => _("State"),
1634           "l"                 => _("Location"),
1635           "postalAddress"     => _("Postal address"),
1637           "homePostalAddress" => _("Home postal address"),
1638           "homePhone"         => _("Home phone number"),
1639           "labeledURI"        => _("Homepage"),
1640           "userPassword"      => _("User password method"), 
1641           "Certificate"       => _("User certificates"))
1643         );
1645     /* Append government attributes if required */
1646     global $config;
1647     if($config->get_cfg_value("honourIvbbAttributes") == "true"){
1648       foreach($govattrs as $attr => $desc){
1649         $ret["plProvidedAcls"][$attr] = $desc;
1650       }
1651     }
1652     return($ret);
1653   }
1655   function get_multi_edit_values()
1656   {
1657     $ret = plugin::get_multi_edit_values();
1658     if(in_array("pw_storage",$this->multi_boxes)){
1659       $ret['pw_storage'] = $this->pw_storage;
1660     }
1661     if(in_array("edit_picture",$this->multi_boxes)){
1662       $ret['jpegPhoto'] = $this->jpegPhoto;
1663       $ret['photoData'] = $this->photoData;
1664       $ret['old_jpegPhoto'] = $this->old_jpegPhoto;
1665       $ret['old_photoData'] = $this->old_photoData;
1666     }
1667     if(isset($ret['dateOfBirth'])){
1668       unset($ret['dateOfBirth']);
1669     }
1670     if(isset($ret['cn'])){
1671       unset($ret['cn']);
1672     }
1673     $ret['is_modified'] = $this->is_modified;
1674     if(in_array("base",$this->multi_boxes)){
1675       $ret['orig_base']="Changed_by_Multi_Plug";
1676       $ret['base']=$this->base;
1677     }
1678     return($ret); 
1679   }
1682   function multiple_save_object()
1683   {
1684     plugin::multiple_save_object();
1686     /* Get pw_storage mode */
1687     if (isset($_POST['pw_storage'])){
1688       foreach(array("pw_storage") as $val){
1689         if(isset($_POST[$val])){
1690           $data= validate(get_post($val));
1691           if ($data != $this->$val){
1692             $this->is_modified= TRUE;
1693           }
1694           $this->$val= $data;
1695         }
1696       }
1697     }
1698     if(isset($_POST['base'])){
1699       $this->base = get_post('base');
1700     }
1702     if(isset($_POST['user_mulitple_edit'])){
1703       foreach(array("base","pw_storage","edit_picture") as $val){
1704         if(isset($_POST["use_".$val])){
1705           $this->multi_boxes[] = $val;
1706         }
1707       }
1708     }
1709   }
1711   
1712   function multiple_check()
1713   {
1714     /* Call check() to set new_dn correctly ... */
1715     $message = plugin::multiple_check();
1717     /* Set the new acl base */
1718     if($this->dn == "new") {
1719       $this->set_acl_base($this->base);
1720     }
1721     if (!tests::is_url($this->labeledURI) && in_array("labeledURI",$this->multi_boxes)){
1722       $message[]= msgPool::invalid(_("Homepage"));
1723     }
1724     if (!tests::is_phone_nr($this->telephoneNumber) && in_array("telephoneNumber",$this->multi_boxes)){
1725       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1726     }
1727     if (!tests::is_phone_nr($this->facsimileTelephoneNumber) &&  in_array("facsimileTelephoneNumber",$this->multi_boxes)){
1728       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1729     }
1730     if (!tests::is_phone_nr($this->mobile) && in_array("mobile",$this->multi_boxes)){
1731       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1732     }
1733     if (!tests::is_phone_nr($this->pager) && in_array("pager",$this->multi_boxes)){
1734       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1735     }
1736     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName) && in_array("givenName",$this->multi_boxes)){
1737       $message[]= msgPool::invalid(_("Given name"), $this->giveName, '/[^,+"?\'()=<>;\\\\]/');
1738     }
1739     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn) && in_array("sn",$this->multi_boxes)){
1740       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1741     }
1742     return($message);
1743   }
1747   function multiple_execute()
1748   {
1749     return($this->execute());
1750   }
1755 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1756 ?>