Code

e2c45e168778c7e01797ded55b12dc45097ec8ff
[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 $gosaLoginRestrictionWidget;
55   var $employeeNumber= "";
56   var $employeeType= "";
57   var $roomNumber= "";
58   var $telephoneNumber= "";
59   var $facsimileTelephoneNumber= "";
60   var $mobile= "";
61   var $pager= "";
62   var $l= "";
63   var $st= "";
64   var $postalAddress= "";
65   var $dateOfBirth;
66   var $use_dob= "0";
67   var $gender="0";
68   var $preferredLanguage="0";
69   var $baseSelector;
71   var $jpegPhoto= "*removed*";
72   var $photoData= "";
73   var $old_jpegPhoto= "";
74   var $old_photoData= "";
75   var $cert_dialog= FALSE;
76   var $picture_dialog= FALSE;
77   var $pwObject= NULL;
79   var $userPKCS12= "";
80   var $userSMIMECertificate= "";
81   var $userCertificate= "";
82   var $certificateSerialNumber= "";
83   var $old_certificateSerialNumber= "";
84   var $old_userPKCS12= "";
85   var $old_userSMIMECertificate= "";
86   var $old_userCertificate= "";
88   var $gouvernmentOrganizationalUnit= "";
89   var $houseIdentifier= "";
90   var $street= "";
91   var $postalCode= "";
92   var $vocation= "";
93   var $ivbbLastDeliveryCollective= "";
94   var $gouvernmentOrganizationalPersonLocality= "";
95   var $gouvernmentOrganizationalUnitDescription= "";
96   var $gouvernmentOrganizationalUnitSubjectArea= "";
97   var $functionalTitle= "";
98   var $role= "";
99   var $publicVisible= "";
101   var $orig_dn;
102   var $dialog;
104   /* variables to trigger password changes */
105   var $pw_storage= "md5";
106   var $last_pw_storage= "unset";
107   var $had_userCertificate= FALSE;
109   var $view_logged = FALSE;
111   var $manager = "";
112   var $manager_name = "";
115   /* attribute list for save action */
116   var $attributes= array("sn", "givenName", "uid", "personalTitle", "academicTitle",
117       "homePostalAddress", "homePhone", "labeledURI", "ou", "o", "dateOfBirth", "gender","preferredLanguage",
118       "departmentNumber", "employeeNumber", "employeeType", "l", "st","jpegPhoto",
119       "roomNumber", "telephoneNumber", "mobile", "pager", "cn", "userPKCS12",
120       "postalAddress", "facsimileTelephoneNumber", "userSMIMECertificate", "gosaLoginRestriction", "manager");
122   var $objectclasses= array("top", "person", "organizationalPerson", "inetOrgPerson",
123       "gosaAccount");
125   /* attributes that are part of the government mode */
126   var $govattrs= array("gouvernmentOrganizationalUnit", "houseIdentifier", "vocation",
127       "ivbbLastDeliveryCollective", "gouvernmentOrganizationalPersonLocality",
128       "gouvernmentOrganizationalUnitDescription","gouvernmentOrganizationalUnitSubjectArea",
129       "functionalTitle", "certificateSerialNumber", "publicVisible", "street", "role",
130       "postalCode");
132   var $multiple_support = TRUE;
134   var $governmentmode = FALSE;
136   /* constructor, if 'dn' is set, the node loads the given
137      'dn' from LDAP */
138   function user (&$config, $dn= NULL)
139   {
140     global $lang;
142     $this->config= $config;
143     /* Configuration is fine, allways */
144     if($this->config->get_cfg_value("core","honourIvbbAttributes") == "true"){
145       $this->governmentmode = TRUE;
146       $this->attributes=array_merge($this->attributes,$this->govattrs);
147     }
149     /* Load base attributes */
150     plugin::plugin ($config, $dn);
152     $this->orig_dn  = $this->dn;
153     $this->new_dn   = $dn;
155     if ($this->governmentmode){
156       /* Fix public visible attribute if unset */
157       if (!isset($this->attrs['publicVisible'])){
158         $this->publicVisible == "nein";
159       }
160     }
162     /* Load government mode attributes */
163     if ($this->governmentmode){
164       /* Copy all attributs */
165       foreach ($this->govattrs as $val){
166         if (isset($this->attrs["$val"][0])){
167           $this->$val= $this->attrs["$val"][0];
168         }
169       }
170     }
172     /* Create me for new accounts */
173     if ($dn == "new"){
174       $this->is_account= TRUE;
175     }
177     /* Make hash default to md5 if not set in config */
178     $hash= $this->config->get_cfg_value("core","passwordDefaultHash");
180     /* Load data from LDAP? */
181     if ($dn !== NULL){
183       /* Do base conversation */
184       if ($this->dn == "new"){
185         $ui= get_userinfo();
186         $this->base= dn2base(session::global_is_set("CurrentMainBase")?"cn=dummy,".session::global_get("CurrentMainBase"):$ui->dn);
187       } else {
188         $this->base= dn2base($dn);
189       }
191       /* get password storage type */
192       if (isset ($this->attrs['userPassword'][0])){
193         /* Initialize local array */
194         $matches= array();
195         if (preg_match ("/^{[^}]+}/", $this->attrs['userPassword'][0])){
196           $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
197           if(is_object($tmp)){
198             $this->pw_storage= $tmp->get_hash(); 
199           }
201         } else {
202           if ($this->attrs['userPassword'][0] != ""){
203             $this->pw_storage= "clear";
204           } else {
205             $this->pw_storage= $hash;
206           }
207         }
208       } else {
209         /* Preset with vaule from configuration */
210         $this->pw_storage= $hash;
211       }
213       /* Load extra attributes: certificate and picture */
214       $this->load_cert();
215       $this->load_picture();
216       if ($this->userCertificate != ""){
217         $this->had_userCertificate= TRUE;
218       }
219     }
221     /* Reset password storage indicator, used by password_change_needed() */
222     if ($dn == "new"){
223       $this->last_pw_storage= "unset";
224     } else {
225       $this->last_pw_storage= $this->pw_storage;
226     }
228     /* Generate dateOfBirth entry */
229     if (isset ($this->attrs['dateOfBirth'])){
230       /* This entry is ISO 8601 conform */
231       list($year, $month, $day)= explode("-", $this->attrs['dateOfBirth'][0], 3);
232     
233       #TODO: use $lang to convert date
234       $this->dateOfBirth= "$day.$month.$year";
235     } else {
236       $this->dateOfBirth= "";
237     }
239     /* Put gender attribute to upper case */
240     if (isset ($this->attrs['gender'])){
241       $this->gender= strtoupper($this->attrs['gender'][0]);
242     }
244     // Get login restrictions
245     if(isset($this->attrs['gosaLoginRestriction'])){
246       $this->gosaLoginRestriction  =array();
247       for($i =0;$i < $this->attrs['gosaLoginRestriction']['count']; $i++){
248         $this->gosaLoginRestriction[] = $this->attrs['gosaLoginRestriction'][$i];
249       }
250     }
251     $this->gosaLoginRestrictionWidget= new sortableListing($this->gosaLoginRestriction);
252     $this->gosaLoginRestrictionWidget->setDeleteable(true);
253     $this->gosaLoginRestrictionWidget->setColspecs(array('*'));
254     $this->gosaLoginRestrictionWidget->setWidth("100%");
255     $this->gosaLoginRestrictionWidget->setHeight("70px");
256  
257     $this->orig_base = $this->base;
258     $this->baseSelector= new baseSelector($this->allowedBasesToMoveTo(), $this->base);
259     $this->baseSelector->setSubmitButton(false);
260     $this->baseSelector->setHeight(300);
261     $this->baseSelector->update(true);
264     // Detect the managers name
265     $this->manager_name = "";
266     $ldap = $this->config->get_ldap_link();
267     if(!empty($this->manager)){
268       $ldap->cat($this->manager, array('cn'));
269       if($ldap->count()){
270         $attrs = $ldap->fetch();
271         $this->manager_name = $attrs['cn'][0];
272       }else{
273         $this->manager_name = "("._("unknown")."!): ".$this->manager;
274       }
275     }
276   }
279   /* execute generates the html output for this node */
280   function execute()
281   {
282     /* Call parent execute */
283     plugin::execute();
285     /* Set list ACL */
286     $this->gosaLoginRestrictionWidget->setAcl($this->getacl('gosaLoginRestriction'));
287     $this->gosaLoginRestrictionWidget->update();
289     /* Handle add/delete for restriction mode */
290     if (isset($_POST['add_res']) && isset($_POST['res'])) {
291       $val= get_post('res');
292       if (preg_match('/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/', $val) ||
293           preg_match('/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\/([0-9]+)$/', $val) ||
294           preg_match('/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\/([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$/', $val)) {
295         $this->gosaLoginRestrictionWidget->addEntry($val);
296       } else {
297         msg_dialog::display(_("Error"), _("Please add a single IP address or a network/net mask combination!"), ERROR_DIALOG);
298       }
299     }
301     /* Log view */
302     if($this->is_account && !$this->view_logged){
303       $this->view_logged = TRUE;
304       new log("view","users/".get_class($this),$this->dn);
305     }
307     // Clear manager attribute if requested
308     if(preg_match("/ removeManager/i", " ".implode(array_keys($_POST),' ')." ")){
309       $this->manager = "";
310       $this->manager_name = "";
311     }
313     // Allow to select a new inetOrgPersion:manager 
314     if(preg_match("/ editManager/i", " ".implode(array_keys($_POST),' ')." ")){
315       $this->dialog = new singleUserSelect($this->config, get_userinfo());
316     }
317     if($this->dialog && $this->dialog instanceOf singleUserSelect && count($this->dialog->detectPostActions())){
318       $users = $this->dialog->detectPostActions();
319       if(isset($users['action']) && $users['action'] =='userSelected' && isset($users['targets']) && count($users['targets'])){
320         $headpage = $this->dialog->getHeadpage();
321         $dn = $users['targets'][0];
322         $attrs = $headpage->getEntry($dn);
323         $this->manager = $dn;
324         $this->manager_name = $attrs['cn'][0];
325         $this->dialog = NULL;
326       }
327     }
328     if(isset($_POST['add_users_cancel'])){
329       $this->dialog = NULL;
330     }
331     if($this->dialog instanceOf singleUserSelect) return($this->dialog->execute()); 
334     $smarty= get_smarty();
336     $smarty->assign("gosaLoginRestrictionWidget", $this->gosaLoginRestrictionWidget->render());
338     /* Assign sex */
339     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
340     $smarty->assign("gender_list", $sex);
341     $language= array_merge(array(0 => "&nbsp;") ,get_languages(TRUE));
342     $smarty->assign("preferredLanguage_list", $language);
344     /* Get random number for pictures */
345     srand((double)microtime()*1000000); 
346     $smarty->assign("rand", rand(0, 10000));
349     /* Do we represent a valid gosaAccount? */
350     if (!$this->is_account){
351       $str = "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
352         msgPool::noValidExtension("GOsa")."</b>";
353       return($str);
354     }
356     /* Password configure dialog handling */
357     if(is_object($this->pwObject) && $this->pwObject->display){
358       $output= $this->pwObject->configure();
359       if ($output != ""){
360         $this->dialog= TRUE;
361         return $output;
362       }
363       $this->dialog= false;
364     }
366     /* Dialog handling */
367     if(is_object($this->dialog)){
368       /* Must be called before save_object */
369       $this->dialog->save_object();
370    
371       if($this->dialog->isClosed()){
372         $this->dialog = false;
373       }elseif($this->dialog->isSelected()){
375         /* check if selected base is allowed to move to / create a new object */
376         $tmp = $this->get_allowed_bases();
377         if(isset($tmp[$this->dialog->isSelected()])){
378           $this->base = $this->dialog->isSelected();
379         }
380         $this->dialog= false;
381       }else{
382         return($this->dialog->execute());
383       }
384     }
386     /* Want password method editing? */
387     if ($this->acl_is_writeable("userPassword")){
388       if (isset($_POST['edit_pw_method'])){
389         if (!is_object($this->pwObject) || $this->pw_storage != $this->pwObject->get_hash_name()){
390           $temp= passwordMethod::get_available_methods();
391           $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
392         }
393         $this->pwObject->display = TRUE;
394         $this->dialog= TRUE;
395         pathNavigator::registerPlugin(_("Password configuration"));
396         return ($this->pwObject->configure());
397       }
398     }
400     /* Want picture edit dialog? */
401     if($this->acl_is_writeable("userPicture")) {
402       if (isset($_POST['edit_picture'])){
403         /* Save values for later recovery, in case some presses
404            the cancel button. */
405         $this->old_jpegPhoto= $this->jpegPhoto;
406         $this->old_photoData= $this->photoData;
407         $this->picture_dialog= TRUE;
408         $this->dialog= TRUE;
409       }
410     }
412     /* Remove picture? */
413     if($this->acl_is_writeable("userPicture")){
414       if (isset($_POST['picture_remove'])){
415         $this->set_picture ();
416         $this->jpegPhoto= "*removed*";
417         $this->is_modified= TRUE;
418         return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
419       }
420     }
422     /* Save picture */
423     if (isset($_POST['picture_edit_finish'])){
425         /* Check for clean upload */
426         if ($_FILES['picture_file']['name'] != ""){
427             $filename = gosa_file_name($_FILES['picture_file']['tmp_name']);
428             if (!file_exists($filename)) {
429                 msg_dialog::display(_("Error"), _("Cannot upload file!"), ERROR_DIALOG);
430             }else{
431                 /* Activate new picture */
432                 $this->set_picture($filename);
433             }
434         }
435         $this->picture_dialog= FALSE;
436       $this->dialog= FALSE;
437       $this->is_modified= TRUE;
438     }
441     /* Cancel picture */
442     if (isset($_POST['picture_edit_cancel'])){
444       /* Restore values */
445       $this->jpegPhoto= $this->old_jpegPhoto;
446       $this->photoData= $this->old_photoData;
448       /* Update picture */
449       session::set('binary',$this->photoData);
450       session::set('binarytype',"image/jpeg");
451       $this->picture_dialog= FALSE;
452       $this->dialog= FALSE;
453     }
455     /* Want certificate= */
456     if ((isset($_POST['edit_cert'])) && $this->acl_is_readable("Certificate")){
458       /* Save original values for later reconstruction */
459       foreach (array("certificateSerialNumber", "userCertificate",
460             "userSMIMECertificate", "userPKCS12") as $val){
462         $oval= "old_$val";
463         $this->$oval= $this->$val;
464       }
466       $this->cert_dialog= TRUE;
467       $this->dialog= TRUE;
468     }
471     /* Cancel certificate dialog */
472     if (isset($_POST['cert_edit_cancel'])){
474       /* Restore original values in case of 'cancel' */
475       foreach (array("certificateSerialNumber", "userCertificate",
476             "userSMIMECertificate", "userPKCS12") as $val){
478         $oval= "old_$val";
479         $this->$val= $this->$oval;
480       }
481       $this->cert_dialog= FALSE;
482       $this->dialog= FALSE;
483     }
486     /* Remove certificate? */
487     if($this->acl_is_writeable("Certificate")){
488       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
489         if (isset($_POST["remove_$val"])){
491           /* Reset specified cert*/
492           $this->$val= "";
493           $this->is_modified= TRUE;
494         }
495       }
496     }
498     /* Upload new cert and close dialog? */     
499     if($this->acl_is_writeable("Certificate")){
500       $fail =false;
501       if (isset($_POST['cert_edit_finish'])){
503         /* for all certificates do */
504         foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
505             as $val){
507           /* Check for clean upload */
508           if (array_key_exists($val."_file", $_FILES) &&
509               array_key_exists('name', $_FILES[$val."_file"]) &&
510               $_FILES[$val."_file"]['name'] != "" &&
511               is_readable($_FILES[$val."_file"]['tmp_name'])) {
512             $this->set_cert("$val", gosa_file_name($_FILES[$val."_file"]['tmp_name']));
513           }
514         }
516         /* Save serial number */
517         if (isset($_POST["certificateSerialNumber"]) &&
518             $_POST["certificateSerialNumber"] != ""){
520           if (!tests::is_id(get_post('certificateSerialNumber'))){
521             $fail = true;
522             msg_dialog::display(_("Error"), msgPool::invalid(_("Serial number"),$_POST["certificateSerialNumber"],"/[0-9]/"),ERROR_DIALOG);
524             foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
525               if ($this->$cert != ""){
526                 $smarty->assign("$cert"."_state", "true");
527               } else {
528                 $smarty->assign("$cert"."_state", "");
529               }
530             }
531           }
533           $this->certificateSerialNumber= get_post("certificateSerialNumber");
534           $this->is_modified= TRUE;
535         }
536         if(!$fail){
537           $this->cert_dialog= FALSE;
538           $this->dialog= FALSE;
539         }
540       }
541     }
542     /* Display picture dialog */
543     if ($this->picture_dialog){
544       pathNavigator::registerPlugin(_("User picture"));
545       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
546     }
548     /* Display cert dialog */
549     if ($this->cert_dialog){
550       pathNavigator::registerPlugin(_("Certificates"));
551       $smarty->assign("CertificateACL",$this->getacl("Certificate"));
552       $smarty->assign("Certificate_readable",$this->acl_is_readable("Certificate"));
553       $smarty->assign("certificateSerialNumber",$this->certificateSerialNumber);
555       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
556         if ($this->$cert != ""){
557           /* import certificate */
558           $certificate = new certificate;
559           $certificate->import($this->$cert);
560       
561           /* Read out data*/
562           $timeto   = $certificate->getvalidto_date();
563           $timefrom = $certificate->getvalidfrom_date();
564          
565           
566           /* Additional info if start end time is '0' */
567           $add_str_info = "";
568           if($timeto == 0 && $timefrom == 0){
569             $add_str_info = "<br>".bold(_("(Not supported certificate types are marked as invalid.)"));
570           }
572           $str = "<table \"\" border=0 summary='"._("Certificates")."'>
573                     <tr>
574                       <td>CN</td>
575                       <td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td>
576                     </tr>
577                   </table><br>".
579                   sprintf(_("Certificate is valid from %s to %s and is currently %s."),
580                         bold(date('d M Y',$timefrom)),
581                         bold(date('d M Y',$timeto)),
582                         $certificate->isvalid()?bold("<span style='color:green'>"._("valid")."</span>"):
583                                                 bold("<span style='color:red'>"._("invalid")."</span>")).$add_str_info;
585           $smarty->assign($cert."info",$str);
586           $smarty->assign($cert."_state","true");
587         } else {
588           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
589           $smarty->assign($cert."_state","");
590         }
591       }
592   
593       if($this->governmentmode){
594         $smarty->assign("honourIvbbAttributes", "true");
595       }else{
596         $smarty->assign("honourIvbbAttributes", "false");
597       }
598       $smarty->assign("governmentmode", $this->governmentmode);
599       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
600     }
602     /* Prepare password hashes */
603     if ($this->pw_storage == ""){
604       $this->pw_storage= $this->config->get_cfg_value("core","passwordDefaultHash");
605     }
607     $temp= passwordMethod::get_available_methods();
608     $is_configurable= FALSE;
609     $hashes = $temp['name'];
610     if(isset($temp[$this->pw_storage])){
611       $test= new $temp[$this->pw_storage]($this->config, $this->dn);
612       $is_configurable= $test->is_configurable();
613     }else{
614       new msg_dialog(_("Password method"),_("The selected password method is no longer available."),WARNING_DIALOG);
615     }
618     /* Create password methods array */
619     $pwd_methods = array();
620     foreach($hashes as $id => $name){
621       if(!empty($temp['desc'][$id])){
622         $pwd_methods[$name] = $name." (".$temp['desc'][$id].")";
623       }else{
624         $pwd_methods[$name] = $name;
625       }
626     }
627  
628     /* Load attributes and acl's */
629     $ui =get_userinfo();
630     foreach($this->attributes as $val){
631       $smarty->assign("$val", set_post($this->$val));
632       if(in_array($val,$this->multi_boxes)){
633         $smarty->assign("use_".$val,TRUE);
634       }else{
635         $smarty->assign("use_".$val,FALSE);
636       }
637     }
638     foreach(array("base","pw_storage","edit_picture") as $val){
639       if(in_array($val,$this->multi_boxes)){
640         $smarty->assign("use_".$val,TRUE);
641       }else{
642         $smarty->assign("use_".$val,FALSE);
643       }
644     }
646     /* Set acls */
647     $tmp = $this->plinfo();
648     foreach($tmp['plProvidedAcls'] as $val => $translation){
649       $smarty->assign("$val"."ACL", $this->getacl($val));
650     }
652     // Special ACL for gosaLoginRestrictions - 
653     // In case of multiple edit, we need a readonly ACL for the list. 
654     $smarty->assign('gosaLoginRestriction_ONLY_R_ACL', preg_replace("/[^r]/i","", $this->getacl($val)));
656     $smarty->assign("pwmode", set_post($pwd_methods));
657     $smarty->assign("pwmode_select", set_post($this->pw_storage));
658     $smarty->assign("pw_configurable", $is_configurable);
659     $smarty->assign("passwordStorageACL", $this->getacl("userPassword"));
660     $smarty->assign("CertificatesACL",  $this->getacl("Certificate"));
661     $smarty->assign("userPictureACL",   $this->getacl("userPicture"));
662     $smarty->assign("userPicture_is_readable",   $this->acl_is_readable("userPicture"));
664     /* Create base acls */
665     $smarty->assign("base", $this->baseSelector->render());
667     /* Save government mode attributes */
668     if($this->governmentmode){
669       $smarty->assign("governmentmode", "true");
670       $ivbbmodes= array("nein", "", "ivbv", "testa", "ivbv,testa", "internet",
671                         "internet,ivbv", "internet,testa", "internet,ivbv,testa");
672       $smarty->assign("ivbbmodes", $ivbbmodes);
673       foreach ($this->govattrs as $val){
674         $smarty->assign("$val", set_post($this->$val));
675         $smarty->assign("$val"."ACL", $this->getacl($val));
676       }
677     } else {
678       $smarty->assign("governmentmode", "false");
679     }
681     /* Special mode for uid */
682     $uidACL= $this->getacl("uid");
683     if (isset ($this->dn)){
684       if ($this->dn != "new"){
685         $uidACL= preg_replace("/w/","",$uidACL);
686       }
687     }  else {
688       $uidACL= preg_replace("/w/","",$uidACL);
689     }
690     
691     $smarty->assign("uidACL", $uidACL);
692     $smarty->assign("is_template", $this->is_template);
693     $smarty->assign("use_dob", $this->use_dob);
695     if (isset($this->parent)){
696       if (isset($this->parent->by_object['phoneAccount']) &&
697           $this->parent->by_object['phoneAccount']->is_account){
698         $smarty->assign("has_phoneaccount", "true");
699       } else {
700         $smarty->assign("has_phoneaccount", "false");
701       }
702     } else {
703       $smarty->assign("has_phoneaccount", "false");
704     }
705     $smarty->assign("multiple_support" , $this->multiple_support_active);
706     $smarty->assign("manager_name", set_post($this->manager_name));
707     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
708   }
711   /* remove object from parent */
712   function remove_from_parent()
713   {
714     /* Only remove valid accounts */
715     if(!$this->initially_was_account) return;
717     /* Remove password extension */
718     $temp= passwordMethod::get_available_methods();
720     /* Remove password method from user account */
721     if(isset($temp[$this->pw_storage]) && class_available($temp[$this->pw_storage])){
722       $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
723       $this->pwObject->remove_from_parent();
724     }
726     /* Remove user */
727     $ldap= $this->config->get_ldap_link();
728     $ldap->rmdir ($this->dn);
729     if (!$ldap->success()){
730       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
731     }
732   
733     new log("remove","users/".get_class($this),$this->dn,$this->attributes,$ldap->get_error());
734   
735     /* Delete references to groups */
736     $ldap->cd ($this->config->current['BASE']);
737     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
738     while ($ldap->fetch()){
739       $g= new group($this->config, $ldap->getDN());
740       $g->removeUser($this->uid);
741       $g->save ();
742     }
744     /* Delete references to object groups */
745     $ldap->cd ($this->config->current['BASE']);
746     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
747     while ($ldap->fetch()){
748       $og= new ogroup($this->config, $ldap->getDN());
749       unset($og->member[$this->dn]);
750       $og->save ();
751     }
753     // Update 'manager' attributes from gosaDepartment and inetOrgPerson
754     $filter = "(&(objectClass=inetOrgPerson)(manager=".LDAP::prepare4filter($this->dn)."))";
755     $ocs = $ldap->get_objectclasses();
756     if(isset($ocs['gosaDepartment']['MAY']) && in_array('manager', $ocs['gosaDepartment']['MAY'])){
757       $filter = "(|".$filter."(&(objectClass=gosaDepartment)(manager=".LDAP::prepare4filter($this->dn).")))";
758     }
759     $leaf_deps=  get_list($filter,array("all"),$this->config->current['BASE'],
760         array("manager","dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
761     foreach($leaf_deps as $entry){
762       $update = array('manager' => array());
763       $ldap->cd($entry['dn']);
764       $ldap->modify($update);
765       if(!$ldap->success()){
766         trigger_error(sprintf("Failed to update manager for '%s', error was '%s'", $entry['dn'], $ldap->get_error()));
767       }
768     }
770     /* Delete references to roles */
771     $ldap->cd ($this->config->current['BASE']);
772     $ldap->search ("(&(objectClass=organizationalRole)(roleOccupant=".LDAP::prepare4filter($this->dn)."))", array("cn"));
773     while ($ldap->fetch()){
774       $role= new roleGeneric($this->config, $ldap->getDN());
775       $key = array_search($this->dn,$role->roleOccupant);
776       if($key !== FALSE){
777         unset($role->roleOccupant[$key]);
778         $role->roleOccupant= array_values($role->roleOccupant);
779         $role->save ();
780       }
781     }
783     /* If needed, let the password method do some cleanup */
784     $tmp = new passwordMethod($this->config, $this->dn);
785     $available = $tmp->get_available_methods();
786     if (in_array_ics($this->pw_storage, $available['name'])){
787       $test= new $available[$this->pw_storage]($this->config);
788       $test->attrs= $this->attrs;
789       $test->dn= $this->dn;
790       $test->remove_from_parent();
791     }
793     /* Remove ACL dependencies too */
794     acl::remove_acl_for($this->dn);
796     /* Optionally execute a command after we're done */
797     $this->handle_post_events("remove",array("uid" => $this->uid));
798   }
801   /* Save data to object */
802   function save_object()
803   {
804     if(isset($_POST['generic']) || isset($_POST['multiple_user_posted'])){
806       /* Make a backup of the current selected base */
807       $base_tmp = $this->base;
809       /* Parents save function */
810       plugin::save_object ();
812       /* Refresh base */
813       if ($this->acl_is_moveable($this->base) || 
814             ($this->dn == "new" && $this->acl_is_createable($this->base))){
815         if (!$this->baseSelector->update()) {
816           msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
817         }
818         if ($this->base != $this->baseSelector->getBase()) {
819           $this->base= $this->baseSelector->getBase();
820           $this->is_modified= TRUE;
821         }
822       }
823       
824       /* Sync lists */
825       $this->gosaLoginRestrictionWidget->save_object();
826       if ($this->gosaLoginRestrictionWidget->isModified()) {
827         $this->gosaLoginRestriction= array_values($this->gosaLoginRestrictionWidget->getMaintainedData());
828       }
830       /* Save government mode attributes */
831       if ($this->governmentmode){
832         foreach ($this->govattrs as $val){
833           if ($this->acl_is_writeable($val)){
834             $data= get_post($val);
835             if ($data != $this->$val){
836               $this->is_modified= TRUE;
837             }
838             $this->$val= $data;
839           }
840         }
841       }
843       /* In template mode, the uid is autogenerated... */
844       if ($this->is_template){
845         $this->uid= strtolower($this->sn);
846         $this->givenName= $this->sn;
847       }
849       /* Get pw_storage mode */
850       if (isset($_POST['pw_storage'])){
851         foreach(array("pw_storage") as $val){
852           if(isset($_POST[$val])){
853             $data= get_post($val);
854             if ($data != $this->$val){
855               $this->is_modified= TRUE;
856             }
857             $this->$val= $data;
858           }
859         }
860       }
862       if($this->pw_storage != $this->last_pw_storage && isset($_POST['pw_storage'])){
863         if ($this->acl_is_writeable("userPassword")){
864           $temp= passwordMethod::get_available_methods();
865           if (!is_object($this->pwObject) || !($this->pwObject instanceOf $temp[$this->pw_storage])){
866             foreach($temp as $id => $data){
867               if(isset($data['name']) && $data['name'] == $this->pw_storage && $data['is_configurable']){
868                 $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
869                 break;
870               }
871             }
872           }
873         }
874       }
876       /* Save current cn
877        */
878       $this->cn = $this->givenName." ".$this->sn;
879     }
880   }
882   function rebind($ldap, $referral)
883   {
884     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
885     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
886       $this->error = "Success";
887       $this->hascon=true;
888       $this->reconnect= true;
889       return (0);
890     } else {
891       $this->error = "Could not bind to " . $credentials['ADMIN'];
892       return NULL;
893     }
894   }
896   
897   /* Save data to LDAP, depending on is_account we save or delete */
898   function save()
899   {
900     global $lang;
902     /* Only force save of changes .... 
903        If this attributes aren't changed, avoid saving.
904      */
905   
906     if($this->gender=="0") $this->gender ="";
907     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
909     /* First use parents methods to do some basic fillup in $this->attrs */
910     plugin::save ();
912     if ($this->dateOfBirth != ""){
913       if(!is_array($this->attrs['dateOfBirth'])) {
914         #TODO: use $lang to convert date
915         list($day, $month, $year)= explode(".", $this->dateOfBirth);
916         $this->attrs['dateOfBirth'] = sprintf("%04d-%02d-%02d", $year, $month, $day);
917       }
918     }
920     /* Remove additional objectClasses */
921     $tmp= array();
922     foreach ($this->attrs['objectClass'] as $key => $set){
923       $found= false;
924       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
925         if (preg_match ("/^$set$/i", $val)){
926           $found= true;
927           break;
928         }
929       }
930       if (!$found){
931         $tmp[]= $set;
932       }
933     }
935     /* Replace the objectClass array. This is done because of the
936        separation into government and normal mode. */
937     $this->attrs['objectClass']= $tmp;
939     /* Add objectClasss for template mode? */
940     if ($this->is_template){
941       $this->attrs['objectClass'][]= "gosaUserTemplate";
942     }
944     /* Hard coded government mode? */
945     if ($this->governmentmode){
946       $this->attrs['objectClass'][]= "ivbbentry";
948       /* Copy standard attributes */
949       foreach ($this->govattrs as $val){
950         if ($this->$val != ""){
951           $this->attrs["$val"]= $this->$val;
952         } elseif (!$this->is_new) {
953           $this->attrs["$val"]= array();
954         }
955       }
957       /* Remove attribute if set to "nein" */
958       if ($this->publicVisible == "nein"){
959         $this->attrs['publicVisible']= array();
960         if($this->is_new){
961           unset($this->attrs['publicVisible']);
962         }else{
963           $this->attrs['publicVisible']=array();
964         }
966       }
968     }
970     /* Special handling for attribute userCertificate needed */
971     if ($this->userCertificate != ""){
972       $this->attrs["userCertificate;binary"]= $this->userCertificate;
973       $remove_userCertificate= false;
974     } else {
975       $remove_userCertificate= true;
976     }
978     /* Special handling for dateOfBirth value */
979     if ($this->dateOfBirth == ""){
980       if ($this->is_new) {
981         unset($this->attrs["dateOfBirth"]);
982       } else {
983         $this->attrs["dateOfBirth"]= array();
984       }
985     }
986     if (!$this->gender){
987       if ($this->is_new) {
988         unset($this->attrs["gender"]);
989       } else {
990         $this->attrs["gender"]= array();
991       }
992     }
993     if (!$this->preferredLanguage){
994       if ($this->is_new) {
995         unset($this->attrs["preferredLanguage"]);
996       } else {
997         $this->attrs["preferredLanguage"]= array();
998       }
999     }
1001     /* Special handling for attribute jpegPhote needed, scale image via
1002        image magick to 147x200 pixels and inject resulting data. */
1003     if ($this->jpegPhoto == "*removed*"){
1004     
1005       /* Reset attribute to avoid writing *removed* as value */    
1006       $this->attrs["jpegPhoto"] = array();
1008     } else {
1010         if(class_exists('Imagick')){
1012             $im = new Imagick();
1013             $im->readImageBlob($this->photoData);
1014             $im->setImageOpacity(1.0);
1015             $im->resizeImage(147,200,Imagick::FILTER_UNDEFINED,0.5,TRUE);
1016             $im->setCompressionQuality(90);
1017             $im->setImageFormat('jpeg'); 
1018             $this->attrs["jpegPhoto"] = $im->getImageBlob();
1020         }elseif (exec('convert')){
1021             /* Get temporary file name for conversation */
1022             $fname = tempnam (TEMP_DIR, "GOsa");
1024             /* Open file and write out photoData */
1025             $fp = fopen ($fname, "w");
1026             fwrite ($fp, $this->photoData);
1027             fclose ($fp);
1029             /* Build conversation query. Filename is generated automatically, so
1030                we do not need any special security checks. Exec command and save
1031                output. For PHP safe mode, you'll need a configuration which respects
1032                image magick as executable... */
1033             $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
1034             @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
1035                     $query, "Execute");
1037             /* Read data written by convert */
1038             $output= "";
1039             $sh= popen($query, 'r');
1040             while (!feof($sh)){
1041                 $output.= fread($sh, 4096);
1042             }
1043             pclose($sh);
1045             unlink($fname);
1047             /* Save attribute */
1048             $this->attrs["jpegPhoto"] = $output;
1049         }else{
1050             msg_dialog::display(_("Error"),
1051                     _("Cannot save user picture: GOsa requires the package 'imagemagick' or 'php5-imagick' to be installed!"),
1052                     ERROR_DIALOG);
1054         }
1055     }
1057     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
1058        new entries. So do a check first... */
1059     $ldap= $this->config->get_ldap_link();
1060     $ldap->cat ($this->dn, array('dn'));
1061     if ($ldap->fetch()){
1062       $mode= "modify";
1063     } else {
1064       $mode= "add";
1065       $ldap->cd($this->config->current['BASE']);
1066       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
1067     }
1069     /* Set password to some junk stuff in case of templates */
1070     if ($this->is_template){
1071       $temp= passwordMethod::get_available_methods();
1072       foreach($temp as $id => $data){
1073         if(isset($data['name']) && $data['name'] == $this->pw_storage){
1074           $tmp = new  $temp[$this->pw_storage]($this->config,$this->dn);
1075           $tmp->set_hash($this->pw_storage);
1076           $this->attrs['userPassword'] = $tmp->create_template_hash($this->attrs);
1077           break;
1078         }
1079       }
1080     }
1082     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
1083         $this->attributes, "Save via $mode");
1085     /* Finally write data with selected 'mode' */
1086     $this->cleanup();
1088     /* Update current locale settings, if we have edited ourselves */
1089     $ui = session::get('ui');
1090     if(isset($this->attrs['preferredLanguage']) && $this->dn == $ui->dn){
1091       $ui->language = $this->preferredLanguage;
1092       session::set('ui',$ui);
1093       session::set('Last_init_lang',"update");
1094     }
1096     $ldap->cd ($this->dn);
1097     $ldap->$mode ($this->attrs);
1098     if (!$ldap->success()){
1099       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
1100       return (1);
1101     }
1103     /* Remove ACL dependencies too */
1104     if($this->dn != $this->orig_dn && $this->orig_dn != "new"){
1105       $tmp = new acl($this->config,$this->parent,$this->dn);
1106       $tmp->update_acl_membership($this->orig_dn,$this->dn);
1107     }
1109     if($mode == "modify"){
1110       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1111     }else{
1112       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1113     }
1115     /* Remove cert? 
1116        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
1117        to work around myself. */
1118     if ($remove_userCertificate == true && !$this->is_new && $this->had_userCertificate){
1120       /* Reset array, assemble new, this should be reworked */
1121       $this->attrs= array();
1122       $this->attrs['userCertificate;binary']= array();
1124       /* Prepare connection */
1125       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
1126         die ("Could not connect to LDAP server");
1127       }
1128       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1129       if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("core","ldapFollowReferrals") == "true") {
1130         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1131         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1132       }
1133       if($this->config->get_cfg_value("core","ldapTLS") == "true"){
1134         ldap_start_tls($ds);
1135       }
1136       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
1137               $this->config->current['PASSWORD']))) {
1138         die ("Could not bind to LDAP");
1139       }
1141       /* Modify using attrs */
1142       ldap_mod_del($ds,$this->dn,$this->attrs);
1143       ldap_close($ds);
1144     }
1146     /* If needed, let the password method do some cleanup */
1147     if ($this->pw_storage != $this->last_pw_storage){
1148       $tmp = new passwordMethod($this->config, $this->dn);
1149       $available = $tmp->get_available_methods();
1150       if (in_array_ics($this->last_pw_storage, $available['name'])){
1151         $test= new $available[$this->last_pw_storage]($this->config,$this->dn);
1152         $test->attrs= $this->attrs;
1153         $test->remove_from_parent();
1154       }
1155     }
1157     /* Maybe the current password method want's to do some changes... */
1158     if (is_object($this->pwObject)){
1159       $this->pwObject->save($this->dn);
1160     }
1162     /* Optionally execute a command after we're done */
1163     if ($mode == "add"){
1164       $this->handle_post_events("add", array("uid" => $this->uid));
1165     } elseif ($this->is_modified){
1166       $this->handle_post_events("modify", array("uid" => $this->uid));
1167     }
1169     return (0);
1170   }
1173   function create_initial_rdn($pattern)
1174   {
1175     // Only generate single RDNs
1176     if (preg_match('/\+/', $pattern)){
1177       msg_dialog::display(_("Error"), _("Cannot build RDN: no + allowed to build sub RDN!"), ERROR_DIALOG);
1178       return "";
1179     }
1181     // Extract attribute
1182     $attribute= preg_replace('/=.*$/', '', $pattern);
1183     if (!in_array_ics($attribute, $this->attributes)) {
1184       msg_dialog::display(_("Error"), _("Cannot build RDN: attribute is not defined!"), ERROR_DIALOG);
1185       return "";
1186     }
1188     // Sort attributes for length
1189     $attrl= array();
1190     foreach ($this->attributes as $attr) {
1191       $attrl[$attr]= strlen($attr);
1192     }
1193     arsort($attrl);
1194     
1195     // Walk thru sorted attributes and replace them in pattern
1196     foreach ($attrl as $attr => $dummy) {
1197       if (!is_array($this->$attr)){
1198         $pattern= preg_replace("/%$attr/", $this->$attr, $pattern);
1199       } else {
1200         // Array elements cannot be used for ID generation
1201         if (preg_match("/%$attr/", $pattern)) {
1202           msg_dialog::display(_("Error"), _("Cannot build RDN: invalid attribute parameters!"), ERROR_DIALOG);
1203           break;
1204         }
1205       }
1206     }
1208     // Internally assign value
1209     $this->$attribute= preg_replace('/^[^=]+=/', '', $pattern);
1211     return $pattern;
1212   }
1214   
1215   function update_new_dn()
1216   {
1217     // Alternative way to handle DN
1218     $pattern= $this->config->get_cfg_value("user","accountRDN");
1219     if ($pattern != "") {
1220       $rdn= $this->create_initial_rdn($pattern);
1221       $attribute= preg_replace('/=.*$/', '', $rdn);
1222       $value= preg_replace('/^[^=]+=$/', '', $rdn);
1224       /* Don't touch dn, if $attribute hasn't changed */
1225       if (isset($this->saved_attributes[$attribute]) && $this->saved_attributes[$attribute] == $this->$attribute &&
1226             $this->orig_base == $this->base ){
1227         $this->new_dn= $this->dn;
1228       } else {
1229         $this->new_dn= $this->create_unique_dn2($rdn, get_people_ou().$this->base);
1230       }
1232     // Original way to handle DN
1233     } else {
1235       $pt= "";
1236       if($this->config->get_cfg_value("core","personalTitleInDN") == "true"){
1237         if(!empty($this->personalTitle)){
1238           $pt = $this->personalTitle." ";
1239         }
1240       }
1242       $this->cn= $pt.$this->givenName." ".$this->sn;
1244       /* Permissions for that base? */
1245       if ($this->config->get_cfg_value("core","accountPrimaryAttribute") == "uid"){
1246         $this->new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
1247       } else {
1248         /* Don't touch dn, if cn hasn't changed */
1249         if (isset($this->saved_attributes['cn']) && $this->saved_attributes['cn'] == $this->cn &&
1250             $this->orig_base == $this->base ){
1251           $this->new_dn= $this->dn;
1252         } else {
1253           $this->new_dn= $this->create_unique_dn('cn', get_people_ou().$this->base);
1254         }
1255       }
1256     }
1257   }
1258   
1260   /* Check formular input */
1261   function check()
1262   {
1263     /* Call common method to give check the hook */
1264     $message= plugin::check();
1266     /* Configurable password methods should be configured initially. 
1267      */ 
1268     if($this->last_pw_storage != $this->pw_storage){
1269       $temp= passwordMethod::get_available_methods();
1270       foreach($temp['name'] as $id => $name){
1271         if($name == $this->pw_storage){
1272           if($temp['is_configurable'][$id] && !$this->pwObject instanceof $temp[$name] ){
1273             $message[] = _("The selected password method requires initial configuration!");
1274           }
1275           break;
1276         }
1277       }
1278     }
1280     $this->update_new_dn();
1282     /* Set the new acl base */
1283     if($this->dn == "new") {
1284       $this->set_acl_base($this->base);
1285     }
1287     /* Check if we are allowed to create/move this user */
1288     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
1289       $message[]= msgPool::permCreate();
1290     }elseif($this->orig_dn != "new" && $this->new_dn != $this->orig_dn){
1292         /* Check if the objects dn has changed while the base was left unchanged. 
1293          * In this case we've to check move permissions for the object itself.
1294          * 
1295          * If the base has changed then we've to check the permission for the destination
1296          *  base.
1297          */
1298         if($this->orig_base == $this->base && !$this->acl_is_moveable($this->dn)){
1299             $message[]= msgPool::permMove();
1300         }elseif($this->orig_base != $this->base && !$this->acl_is_moveable($this->base)){
1301             $message[]= msgPool::permMove();
1302         }
1303     }
1305     /* UID already used? */
1306     $ldap= $this->config->get_ldap_link();
1307     $ldap->cd($this->config->current['BASE']);
1308     $ldap->search("(uid=$this->uid)", array("uid"));
1309     $ldap->fetch();
1310     if ($ldap->count() != 0 && $this->dn == 'new'){
1311       $message[]= msgPool::duplicated(_("Login"));
1312     }
1314     /* In template mode, the uid and givenName are autogenerated... */
1315     if ($this->sn == ""){
1316       $message[]= msgPool::required(_("Name"));
1317     }
1319     // Check if a wrong base was supplied
1320     if(!$this->baseSelector->checkLastBaseUpdate()){
1321       $message[]= msgPool::check_base();;
1322     }
1324     if (!$this->is_template){
1325       if ($this->givenName == ""){
1326         $message[]= msgPool::required(_("Given name"));
1327       }
1328       if ($this->uid == ""){
1329         $message[]= msgPool::required(_("Login"));
1330       }
1331       if ($this->config->get_cfg_value("core","accountPrimaryAttribute") != "uid"){
1332         $ldap->cat($this->new_dn);
1333         if ($ldap->count() != 0 && $this->dn != $this->new_dn && $this->dn == 'new'){
1334           $message[]= msgPool::duplicated(_("Name"));
1335         }
1336       }
1337     }
1339     /* Check for valid input */
1340     if ($this->is_modified && !tests::is_uid($this->uid)){
1342       if (strict_uid_mode()){
1343         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/");
1344       } else {
1345         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/i");
1346       }
1347     }
1348     if (!tests::is_url($this->labeledURI)){
1349       $message[]= msgPool::invalid(_("Homepage"), "", "", "http://www.your-domain.com/yourname");
1350     }
1352     /* Check phone numbers */
1353     if (!tests::is_phone_nr($this->telephoneNumber)){
1354       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1355     }
1356     if (!tests::is_phone_nr($this->facsimileTelephoneNumber)){
1357       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1358     }
1359     if (!tests::is_phone_nr($this->mobile)){
1360       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1361     }
1362     if (!tests::is_phone_nr($this->pager)){
1363       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1364     }
1366     /* Check dates */
1367     if (!tests::is_date($this->dateOfBirth)){
1368       $message[]= msgPool::invalid(_("Date of birth"), $this->dateOfBirth,"" ,"23.02.2009");
1369     }
1371     /* Check for reserved characers */
1372     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName)){
1373       $message[]= msgPool::invalid(_("Given name"), $this->givenName, '/[^,+"?\'()=<>;\\\\]/');
1374     }
1375     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn)){
1376       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1377     }
1379     return $message;
1380   }
1383   /* Indicate whether a password change is needed or not */
1384   function password_change_needed()
1385   {
1386     if($this->multiple_support_active){
1387       return(FALSE);
1388     }else{
1390       if(in_array("pw_storage",$this->multi_boxes)){
1391         return(TRUE);
1392       }
1393       return($this->pw_storage != $this->last_pw_storage && !$this->is_template);
1394     }
1395   }
1398   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1399   function load_picture()
1400   {
1401     $ldap = $this->config->get_ldap_link();
1402     $ldap->cd ($this->dn);
1403     $data = $ldap->get_attribute($this->dn,"jpegPhoto");
1405     if((!$data) || ($data == "*removed*")){ 
1407       /* In case we don't get an entry, load a default picture */
1408       $this->set_picture ();
1409       $this->jpegPhoto= "*removed*";
1410     }else{
1412       /* Set picture */
1413       $this->photoData= $data;
1414       session::set('binary',$this->photoData);
1415       session::set('binarytype',"image/jpeg");
1416       $this->jpegPhoto= "";
1417     }
1418   }
1421   /* Load a certificate from LDAP, this is going to be simplified later on */
1422   function load_cert()
1423   {
1424     $ds= ldap_connect($this->config->current['SERVER']);
1425     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1426     if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("core","ldapFollowReferrals") == "true"){
1427       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1428       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1429     }
1430     if ($this->config->get_cfg_value("core","ldapTLS") == "true"){
1431       ldap_start_tls($ds);
1432     }
1434     $r= ldap_bind($ds);
1435     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1437     if ($sr) {
1438       $ei= @ldap_first_entry($ds, $sr);
1439       
1440       if ($ei) {
1441         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1442           $this->userCertificate= "";
1443         } else {
1444           $this->userCertificate= $info[0];
1445         }
1446       }
1447     } else {
1448       $this->userCertificate= "";
1449     }
1451     ldap_unbind($ds);
1452   }
1455   /* Load picture from file to object */
1456   function set_picture($filename ="")
1457   {
1458     if (!is_file($filename) || $filename =="" ){
1459       $filename= "./plugins/users/images/default.jpg";
1460       $this->jpegPhoto= "*removed*";
1461     }
1463     $fd = fopen ($filename, "rb");
1464     $this->photoData= fread ($fd, filesize ($filename));
1465     session::set('binary',$this->photoData);
1466     session::set('binarytype',"image/jpeg");
1467     $this->jpegPhoto= "";
1469     fclose ($fd);
1470   }
1473   /* Load certificate from file to object */
1474   function set_cert($cert, $filename)
1475   {
1476     if(!$this->acl_is_writeable("Certificate")) return;
1477     $fd = fopen ($filename, "rb");
1478     if (filesize($filename)>0) {
1479       $this->$cert= fread ($fd, filesize ($filename));
1480       fclose ($fd);
1481       $this->is_modified= TRUE;
1482     } else {
1483       msg_dialog::display(_("Error"), _("Cannot open certificate!"), ERROR_DIALOG);
1484     }
1485   }
1487   /* Adapt from given 'dn' */
1488   function adapt_from_template($dn, $skip= array())
1489   {
1490     plugin::adapt_from_template($dn, $skip);
1492     /* Get password method from template 
1493      */
1494     $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
1495     if(is_object($tmp)){
1496       if($tmp->is_configurable()){
1497         $tmp->adapt_from_template($dn);
1498         $this->pwObject = &$tmp;
1499       }
1500       $this->pw_storage= $tmp->get_hash();
1501     }
1503     /* Get base */
1504     $this->base= preg_replace('/^[^,]+,'.preg_quote(get_people_ou(), '/').'/i', '', $dn);
1505     $this->baseSelector->setBase($this->base);
1507     if($this->governmentmode){
1509       /* Walk through govattrs */
1510       foreach ($this->govattrs as $val){
1512         if (in_array($val, $skip)){
1513           continue;
1514         }
1516         if (isset($this->attrs["$val"][0])){
1518           /* If attribute is set, replace dynamic parts: 
1519              %sn, %givenName and %uid. Fill these in our local variables. */
1520           $value= $this->attrs["$val"][0];
1522           foreach (array("sn", "givenName", "uid") as $repl){
1523             if (preg_match("/%$repl/i", $value)){
1524               $value= preg_replace ("/%$repl/i",
1525                   $this->parent->$repl, $value);
1526             }
1527           }
1528           $this->$val= $value;
1529         }
1530       }
1531     }
1533     /* Get back uid/sn/givenName - only write if nothing's skipped */
1534     if ($this->parent !== NULL && count($skip) == 0){
1535       $this->uid= $this->parent->uid;
1536       $this->sn= $this->parent->sn;
1537       $this->givenName= $this->parent->givenName;
1538     }
1540     /* Generate dateOfBirth entry */
1541     if (isset ($this->attrs['dateOfBirth'])){
1542       /* This entry is ISO 8601 conform */
1543       list($year, $month, $day)= explode("-", $this->attrs['dateOfBirth'][0], 3);
1544     
1545       #TODO: use $lang to convert date
1546       $this->dateOfBirth= "$day.$month.$year";
1547     } else {
1548       $this->dateOfBirth= "";
1549     }
1550   }
1552  
1553   /* This avoids that users move themselves out of their rights. 
1554    */
1555   function allowedBasesToMoveTo()
1556   {
1557     /* Get bases */
1558     $bases  = $this->get_allowed_bases();
1559     return($bases);
1560   } 
1563   function getCopyDialog()
1564   {
1565     $str = "";
1567     session::set('binary',$this->photoData); 
1568     session::set('binarytype',"image/jpeg");
1570     /* Get random number for pictures */
1571     srand((double)microtime()*1000000); 
1572     $rand = rand(0, 10000);
1574     $smarty = get_smarty();
1576     $smarty->assign("passwordTodo","clear");
1578     if(isset($_POST['passwordTodo'])){
1579       $smarty->assign("passwordTodo",set_post(get_post('passwordTodo')));
1580     }
1582     $smarty->assign("sn",       set_post($this->sn));
1583     $smarty->assign("givenName",set_post($this->givenName));
1584     $smarty->assign("uid",      set_post($this->uid));
1585     $smarty->assign("rand",     $rand);
1586     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1589     $ret = array();
1590     $ret['string'] = $str;
1591     $ret['status'] = "";  
1592     return($ret);
1593   }
1595   function saveCopyDialog()
1596   {
1597     /* Set_acl_base */
1598     $this->set_acl_base($this->base);
1600     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1601       $this->set_picture(gosa_file_name($_FILES['picture_file']['tmp_name']));
1602     }
1604     /* Remove picture? */
1605     if (isset($_POST['picture_remove'])){
1606       $this->jpegPhoto= "*removed*";
1607       $this->set_picture ("./plugins/users/images/default.jpg");
1608       $this->is_modified= TRUE;
1609     }
1611     $attrs = array("uid","givenName","sn");
1612     foreach($attrs as $attr){
1613       if(isset($_POST[$attr])){
1614         $this->$attr = get_post($attr);
1615       }
1616     } 
1617   }
1620   function PrepareForCopyPaste($source)
1621   {
1622     plugin::PrepareForCopyPaste($source);
1624     /* Reset certificate information addepted from source user
1625        to avoid setting the same user certificate for the destination user. */
1626     $this->userPKCS12= "";
1627     $this->userSMIMECertificate= "";
1628     $this->userCertificate= "";
1629     $this->certificateSerialNumber= "";
1630     $this->old_certificateSerialNumber= "";
1631     $this->old_userPKCS12= "";
1632     $this->old_userSMIMECertificate= "";
1633     $this->old_userCertificate= "";
1635     /* Generate dateOfBirth entry */
1636     if (isset ($source['dateOfBirth'])){
1637         list($year, $month, $day)= explode("-", $source['dateOfBirth'][0], 3);
1638         $this->dateOfBirth= "$day.$month.$year";
1639     } else {
1640         $this->dateOfBirth= "";
1641     }
1643     // Try to load the user picture
1644     $tmp_dn = $this->dn;
1645     $this->dn = $source['dn'];
1646     $this->load_picture();
1647     $this->dn = $tmp_dn;
1648   }
1651   static function plInfo()
1652   {
1653   
1654     $govattrs= array(
1655         "gouvernmentOrganizationalUnit"             =>  _("Unit"), 
1656         "houseIdentifier"                           =>  _("House identifier"), 
1657         "vocation"                                  =>  _("Vocation"),
1658         "ivbbLastDeliveryCollective"                =>  _("Last delivery"), 
1659         "gouvernmentOrganizationalPersonLocality"   =>  _("Person locality"),
1660         "gouvernmentOrganizationalUnitDescription"  =>  _("Unit description"),
1661         "gouvernmentOrganizationalUnitSubjectArea"  =>  _("Subject area"),
1662         "functionalTitle"                           =>  _("Functional title"),
1663         "certificateSerialNumber"                   =>  _("Certificate serial number"),
1664         "publicVisible"                             =>  _("Public visible"),
1665         "street"                                    =>  _("Street"),
1666         "role"                                      =>  _("Role"),
1667         "postalCode"                                =>  _("Postal code"));
1669     $ret = array(
1670         "plShortName" => _("Generic"),
1671         "plDescription" => _("Generic user settings"),
1672         "plSelfModify"  => TRUE,
1673         "plDepends"     => array(),
1674         "plPriority"    => 1,
1675         "plSection"     => array("personal" => _("My account")),
1676         "plCategory"    => array("users" => array("description" => _("Users"),
1677                                                   "objectClass" => "gosaAccount")),
1679         "plRequirements"=> array(
1680             'ldapSchema' => array(
1681                 'gosaAccount' => '>=2.7',
1682                 'gosaUserTemplate' => '>=2.7'
1683                 ),
1684             'onFailureDisablePlugin' => array(get_class(),'userManagement', 'user')
1685             ),
1687         "plProperties" => array(
1688             array(
1689                 "name"          => "accountRDN",
1690                 "type"          => "string",
1691                 "default"       => "",
1692                 "description"   =>  _("Pattern for the generation of user DNs. Please read the FAQ for details."),
1693                 "check"         => "gosaProperty::isString",
1694                 "migrate"       => "",
1695                 "group"         => "plugin",
1696                 "mandatory"     => FALSE
1697                 )
1699             ),
1700         "plProvidedAcls" => array(
1702           "sn"                => _("Surname"),
1703           "givenName"         => _("Given name"),
1704           "uid"               => _("Login"),
1706           "gosaUserDefinedFilter"  => _("Allow definition of custom filters"),
1708           "personalTitle"     => _("Personal title"),
1709           "academicTitle"     => _("Academic title"),
1711           "dateOfBirth"       => _("Date of birth"),
1712           "gender"            => _("Sex"),
1713           "preferredLanguage" => _("Preferred language"),
1714           "base"              => _("Base"), 
1716           "userPicture"       => _("User picture"),
1718           "gosaLoginRestriction" => _("Login restrictions"),         
1720           "o"                 => _("Organization"),
1721           "ou"                => _("Department"),
1722           "departmentNumber"  => _("Department number"),
1723           "manager"           => _("Manager"),
1724           "employeeNumber"    => _("Employee number"),
1725           "employeeType"      => _("Employee type"),
1727           "roomNumber"        => _("Room number"),
1728           "telephoneNumber"   => _("Telephone number"),
1729           "pager"             => _("Pager number"),
1730           "mobile"            => _("Mobile number"),
1731           "facsimileTelephoneNumber"     => _("Fax number"),
1733           "st"                => _("State"),
1734           "l"                 => _("Location"),
1735           "postalAddress"     => _("Postal address"),
1737           "homePostalAddress" => _("Home postal address"),
1738           "homePhone"         => _("Home phone number"),
1739           "labeledURI"        => _("Homepage"),
1740           "userPassword"      => _("User password method"), 
1741           "Certificate"       => _("User certificates"))
1743         );
1745 #   /* Append government attributes if required */
1746 #   global $config;
1747 #   if($config->get_cfg_value("core","honourIvbbAttributes") == "true"){
1748 #     foreach($govattrs as $attr => $desc){
1749 #       $ret["plProvidedAcls"][$attr] = $desc;
1750 #     }
1751 #   }
1752     return($ret);
1753   }
1755   function get_multi_edit_values()
1756   {
1757     $ret = plugin::get_multi_edit_values();
1758     if(in_array("pw_storage",$this->multi_boxes)){
1759       $ret['pw_storage'] = $this->pw_storage;
1760     }
1761     if(in_array("edit_picture",$this->multi_boxes)){
1762       $ret['jpegPhoto'] = $this->jpegPhoto;
1763       $ret['photoData'] = $this->photoData;
1764       $ret['old_jpegPhoto'] = $this->old_jpegPhoto;
1765       $ret['old_photoData'] = $this->old_photoData;
1766     }
1767     if(isset($ret['dateOfBirth'])){
1768       unset($ret['dateOfBirth']);
1769     }
1770     if(isset($ret['cn'])){
1771       unset($ret['cn']);
1772     }
1773     $ret['is_modified'] = $this->is_modified;
1774     if(in_array("base",$this->multi_boxes)){
1775       $ret['orig_base']="Changed_by_Multi_Plug";
1776       $ret['base']=$this->base;
1777     }
1779     $ret['gosaLoginRestriction'] = $this->gosaLoginRestriction;
1780     $ret['gosaLoginRestriction_some'] = $this->gosaLoginRestriction_some;
1782     return($ret); 
1783   }
1786   function multiple_save_object()
1787   {
1789     if(!isset($_POST['user_mulitple_edit'])) return;
1791     plugin::multiple_save_object();
1793     /* Get pw_storage mode */
1794     if (isset($_POST['pw_storage'])){
1795       foreach(array("pw_storage") as $val){
1796         if(isset($_POST[$val])){
1797           $data= get_post($val);
1798           if ($data != $this->$val){
1799             $this->is_modified= TRUE;
1800           }
1801           $this->$val= $data;
1802         }
1803       }
1804     }
1805   
1806     /* Refresh base */
1807     if ($this->acl_is_moveable($this->base)){
1808       if (!$this->baseSelector->update()) {
1809         msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
1810       }
1811       if ($this->base != $this->baseSelector->getBase()) {
1812         $this->base= $this->baseSelector->getBase();
1813       }
1814     }
1816     if(isset($_POST['user_mulitple_edit'])){
1817       foreach(array("base","pw_storage","edit_picture") as $val){
1818         if(isset($_POST["use_".$val])){
1819           $this->multi_boxes[] = $val;
1820         }
1821       }
1822     }
1824     /* Sync lists */
1825     $this->gosaLoginRestrictionWidget->save_object();
1826     if ($this->gosaLoginRestrictionWidget->isModified()) {
1827       $this->gosaLoginRestriction= array_values($this->gosaLoginRestrictionWidget->getMaintainedData());
1828     }
1829   }
1831   
1832   function multiple_check()
1833   {
1834     /* Call check() to set new_dn correctly ... */
1835     $message = plugin::multiple_check();
1837     /* Set the new acl base */
1838     if($this->dn == "new") {
1839       $this->set_acl_base($this->base);
1840     }
1841     if (!tests::is_url($this->labeledURI) && in_array("labeledURI",$this->multi_boxes)){
1842       $message[]= msgPool::invalid(_("Homepage"));
1843     }
1844     if (!tests::is_phone_nr($this->telephoneNumber) && in_array("telephoneNumber",$this->multi_boxes)){
1845       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1846     }
1847     if (!tests::is_phone_nr($this->facsimileTelephoneNumber) &&  in_array("facsimileTelephoneNumber",$this->multi_boxes)){
1848       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1849     }
1850     if (!tests::is_phone_nr($this->mobile) && in_array("mobile",$this->multi_boxes)){
1851       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1852     }
1853     if (!tests::is_phone_nr($this->pager) && in_array("pager",$this->multi_boxes)){
1854       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1855     }
1856     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName) && in_array("givenName",$this->multi_boxes)){
1857       $message[]= msgPool::invalid(_("Given name"), $this->giveName, '/[^,+"?\'()=<>;\\\\]/');
1858     }
1859     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn) && in_array("sn",$this->multi_boxes)){
1860       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1861     }
1862     return($message);
1863   }
1867   function multiple_execute()
1868   {
1869     return($this->execute());
1870   }
1873   /*! \brief  Prepares the plugin to be used for multiple edit
1874    *          Update plugin attributes with given array of attribtues.
1875    *  \param  array   Array with attributes that must be updated.
1876    */
1877   function init_multiple_support($attrs,$all)
1878   {
1879     plugin::init_multiple_support($attrs,$all);
1881     // Get login restrictions
1882     if(isset($attrs['gosaLoginRestriction'])){
1883       $this->gosaLoginRestriction  =array();
1884       for($i =0;$i < $attrs['gosaLoginRestriction']['count']; $i++){
1885         $this->gosaLoginRestriction[] = $attrs['gosaLoginRestriction'][$i];
1886       }
1887     }
1889     // Detect the managers name
1890     $this->manager_name = "";
1891     $ldap = $this->config->get_ldap_link();
1892     if(!empty($this->manager)){
1893       $ldap->cat($this->manager, array('cn'));
1894       if($ldap->count()){
1895         $attrs = $ldap->fetch();
1896         $this->manager_name = $attrs['cn'][0];
1897       }else{
1898         $this->manager_name = "("._("unknown")."!): ".$this->manager;
1899       }
1900     }
1902     // Detect login restriction not used in all user objects.
1903     $this->gosaLoginRestriction_some = array();
1904     if(isset($all['gosaLoginRestriction'])){
1905       for($i=0;$i<$all['gosaLoginRestriction']['count'];$i++){
1906         $this->gosaLoginRestriction_some[] = $all['gosaLoginRestriction'][$i];
1907       }
1908     }
1911     // Reinit the login restriction list.
1912     $data = $this->convertLoginRestriction();
1913     if(count($data)){
1914       $this->gosaLoginRestrictionWidget->setListData($data['data'], $data['displayData']);
1915     }
1916   }
1919   function set_multi_edit_values($attrs)
1920   {
1921     $lR = array();
1923     // Update loginRestrictions, keep my settings while ip is optional
1924     foreach($attrs['gosaLoginRestriction_some'] as $ip){
1925       if(in_array($ip, $this->gosaLoginRestriction) && in_array($ip, $attrs['gosaLoginRestriction'])){
1926         $lR[] = $ip;
1927       }
1928     }
1930     // Add enforced loginRestrictions 
1931     foreach($attrs['gosaLoginRestriction'] as $ip){
1932       $lR[] = $ip;
1933     }
1935     $lR = array_values(array_unique($lR));
1936     $this->is_modified |=  array_differs($this->gosaLoginRestriction, $lR);
1937     plugin::set_multi_edit_values($attrs);
1938     $this->gosaLoginRestriction = $lR;
1939   }
1942   function convertLoginRestriction()
1943   {
1944     $all = array_unique(array_merge($this->gosaLoginRestriction,$this->gosaLoginRestriction_some));
1945     $data = array();
1946     foreach($all as $ip){
1947       $data['data'][] = $ip;
1948       if(!in_array($ip, $this->gosaLoginRestriction)){
1949         $data['displayData'][] = array('mode' => LIST_MARKED , 'data' => array($ip.' ('._("Entries differ").')'));
1950       }else{
1951         $data['displayData'][] = array('mode' => 0 , 'data' => array($ip));
1952       }
1953     }   
1954     return($data);
1955   }
1958 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1959 ?>