Code

Updated user ACL
[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         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
428           msg_dialog::display(_("Error"), _("Cannot upload file!"), ERROR_DIALOG);
429         }else{
430           /* Activate new picture */
431           $this->set_picture($_FILES['picture_file']['tmp_name']);
432         }
433       }
434       $this->picture_dialog= FALSE;
435       $this->dialog= FALSE;
436       $this->is_modified= TRUE;
437     }
440     /* Cancel picture */
441     if (isset($_POST['picture_edit_cancel'])){
443       /* Restore values */
444       $this->jpegPhoto= $this->old_jpegPhoto;
445       $this->photoData= $this->old_photoData;
447       /* Update picture */
448       session::set('binary',$this->photoData);
449       session::set('binarytype',"image/jpeg");
450       $this->picture_dialog= FALSE;
451       $this->dialog= FALSE;
452     }
454     /* Want certificate= */
455     if ((isset($_POST['edit_cert'])) && $this->acl_is_readable("Certificate")){
457       /* Save original values for later reconstruction */
458       foreach (array("certificateSerialNumber", "userCertificate",
459             "userSMIMECertificate", "userPKCS12") as $val){
461         $oval= "old_$val";
462         $this->$oval= $this->$val;
463       }
465       $this->cert_dialog= TRUE;
466       $this->dialog= TRUE;
467     }
470     /* Cancel certificate dialog */
471     if (isset($_POST['cert_edit_cancel'])){
473       /* Restore original values in case of 'cancel' */
474       foreach (array("certificateSerialNumber", "userCertificate",
475             "userSMIMECertificate", "userPKCS12") as $val){
477         $oval= "old_$val";
478         $this->$val= $this->$oval;
479       }
480       $this->cert_dialog= FALSE;
481       $this->dialog= FALSE;
482     }
485     /* Remove certificate? */
486     if($this->acl_is_writeable("Certificate")){
487       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
488         if (isset($_POST["remove_$val"])){
490           /* Reset specified cert*/
491           $this->$val= "";
492           $this->is_modified= TRUE;
493         }
494       }
495     }
497     /* Upload new cert and close dialog? */     
498     if($this->acl_is_writeable("Certificate")){
499       $fail =false;
500       if (isset($_POST['cert_edit_finish'])){
502         /* for all certificates do */
503         foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
504             as $val){
506           /* Check for clean upload */
507           if (array_key_exists($val."_file", $_FILES) &&
508               array_key_exists('name', $_FILES[$val."_file"]) &&
509               $_FILES[$val."_file"]['name'] != "" &&
510               is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
511             $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
512           }
513         }
515         /* Save serial number */
516         if (isset($_POST["certificateSerialNumber"]) &&
517             $_POST["certificateSerialNumber"] != ""){
519           if (!tests::is_id(get_post('certificateSerialNumber'))){
520             $fail = true;
521             msg_dialog::display(_("Error"), msgPool::invalid(_("Serial number"),$_POST["certificateSerialNumber"],"/[0-9]/"),ERROR_DIALOG);
523             foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
524               if ($this->$cert != ""){
525                 $smarty->assign("$cert"."_state", "true");
526               } else {
527                 $smarty->assign("$cert"."_state", "");
528               }
529             }
530           }
532           $this->certificateSerialNumber= get_post("certificateSerialNumber");
533           $this->is_modified= TRUE;
534         }
535         if(!$fail){
536           $this->cert_dialog= FALSE;
537           $this->dialog= FALSE;
538         }
539       }
540     }
541     /* Display picture dialog */
542     if ($this->picture_dialog){
543       pathNavigator::registerPlugin(_("User picture"));
544       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
545     }
547     /* Display cert dialog */
548     if ($this->cert_dialog){
549       pathNavigator::registerPlugin(_("Certificates"));
550       $smarty->assign("CertificateACL",$this->getacl("Certificate"));
551       $smarty->assign("Certificate_readable",$this->acl_is_readable("Certificate"));
552       $smarty->assign("certificateSerialNumber",$this->certificateSerialNumber);
554       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
555         if ($this->$cert != ""){
556           /* import certificate */
557           $certificate = new certificate;
558           $certificate->import($this->$cert);
559       
560           /* Read out data*/
561           $timeto   = $certificate->getvalidto_date();
562           $timefrom = $certificate->getvalidfrom_date();
563          
564           
565           /* Additional info if start end time is '0' */
566           $add_str_info = "";
567           if($timeto == 0 && $timefrom == 0){
568             $add_str_info = "<br>".bold(_("(Not supported certificate types are marked as invalid.)"));
569           }
571           $str = "<table \"\" border=0 summary='"._("Certificates")."'>
572                     <tr>
573                       <td>CN</td>
574                       <td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td>
575                     </tr>
576                   </table><br>".
578                   sprintf(_("Certificate is valid from %s to %s and is currently %s."),
579                         bold(date('d M Y',$timefrom)),
580                         bold(date('d M Y',$timeto)),
581                         $certificate->isvalid()?bold("<span style='color:green'>"._("valid")."</span>"):
582                                                 bold("<span style='color:red'>"._("invalid")."</span>")).$add_str_info;
584           $smarty->assign($cert."info",$str);
585           $smarty->assign($cert."_state","true");
586         } else {
587           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
588           $smarty->assign($cert."_state","");
589         }
590       }
591   
592       if($this->governmentmode){
593         $smarty->assign("honourIvbbAttributes", "true");
594       }else{
595         $smarty->assign("honourIvbbAttributes", "false");
596       }
597       $smarty->assign("governmentmode", $this->governmentmode);
598       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
599     }
601     /* Prepare password hashes */
602     if ($this->pw_storage == ""){
603       $this->pw_storage= $this->config->get_cfg_value("core","passwordDefaultHash");
604     }
606     $temp= passwordMethod::get_available_methods();
607     $is_configurable= FALSE;
608     $hashes = $temp['name'];
609     if(isset($temp[$this->pw_storage])){
610       $test= new $temp[$this->pw_storage]($this->config, $this->dn);
611       $is_configurable= $test->is_configurable();
612     }else{
613       new msg_dialog(_("Password method"),_("The selected password method is no longer available."),WARNING_DIALOG);
614     }
617     /* Create password methods array */
618     $pwd_methods = array();
619     foreach($hashes as $id => $name){
620       if(!empty($temp['desc'][$id])){
621         $pwd_methods[$name] = $name." (".$temp['desc'][$id].")";
622       }else{
623         $pwd_methods[$name] = $name;
624       }
625     }
626  
627     /* Load attributes and acl's */
628     $ui =get_userinfo();
629     foreach($this->attributes as $val){
630       $smarty->assign("$val", set_post($this->$val));
631       if(in_array($val,$this->multi_boxes)){
632         $smarty->assign("use_".$val,TRUE);
633       }else{
634         $smarty->assign("use_".$val,FALSE);
635       }
636     }
637     foreach(array("base","pw_storage","edit_picture") as $val){
638       if(in_array($val,$this->multi_boxes)){
639         $smarty->assign("use_".$val,TRUE);
640       }else{
641         $smarty->assign("use_".$val,FALSE);
642       }
643     }
645     /* Set acls */
646     $tmp = $this->plinfo();
647     foreach($tmp['plProvidedAcls'] as $val => $translation){
648       $smarty->assign("$val"."ACL", $this->getacl($val));
649     }
651     // Special ACL for gosaLoginRestrictions - 
652     // In case of multiple edit, we need a readonly ACL for the list. 
653     $smarty->assign('gosaLoginRestriction_ONLY_R_ACL', preg_replace("/[^r]/i","", $this->getacl($val)));
655     $smarty->assign("pwmode", set_post($pwd_methods));
656     $smarty->assign("pwmode_select", set_post($this->pw_storage));
657     $smarty->assign("pw_configurable", $is_configurable);
658     $smarty->assign("passwordStorageACL", $this->getacl("userPassword"));
659     $smarty->assign("CertificatesACL",  $this->getacl("Certificate"));
660     $smarty->assign("userPictureACL",   $this->getacl("userPicture"));
661     $smarty->assign("userPicture_is_readable",   $this->acl_is_readable("userPicture"));
663     /* Create base acls */
664     $smarty->assign("base", $this->baseSelector->render());
666     /* Save government mode attributes */
667     if($this->governmentmode){
668       $smarty->assign("governmentmode", "true");
669       $ivbbmodes= array("nein", "", "ivbv", "testa", "ivbv,testa", "internet",
670                         "internet,ivbv", "internet,testa", "internet,ivbv,testa");
671       $smarty->assign("ivbbmodes", $ivbbmodes);
672       foreach ($this->govattrs as $val){
673         $smarty->assign("$val", set_post($this->$val));
674         $smarty->assign("$val"."ACL", $this->getacl($val));
675       }
676     } else {
677       $smarty->assign("governmentmode", "false");
678     }
680     /* Special mode for uid */
681     $uidACL= $this->getacl("uid");
682     if (isset ($this->dn)){
683       if ($this->dn != "new"){
684         $uidACL= preg_replace("/w/","",$uidACL);
685       }
686     }  else {
687       $uidACL= preg_replace("/w/","",$uidACL);
688     }
689     
690     $smarty->assign("uidACL", $uidACL);
691     $smarty->assign("is_template", $this->is_template);
692     $smarty->assign("use_dob", $this->use_dob);
694     if (isset($this->parent)){
695       if (isset($this->parent->by_object['phoneAccount']) &&
696           $this->parent->by_object['phoneAccount']->is_account){
697         $smarty->assign("has_phoneaccount", "true");
698       } else {
699         $smarty->assign("has_phoneaccount", "false");
700       }
701     } else {
702       $smarty->assign("has_phoneaccount", "false");
703     }
704     $smarty->assign("multiple_support" , $this->multiple_support_active);
705     $smarty->assign("manager_name", set_post($this->manager_name));
706     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
707   }
710   /* remove object from parent */
711   function remove_from_parent()
712   {
713     /* Only remove valid accounts */
714     if(!$this->initially_was_account) return;
716     /* Remove password extension */
717     $temp= passwordMethod::get_available_methods();
719     /* Remove password method from user account */
720     if(isset($temp[$this->pw_storage]) && class_available($temp[$this->pw_storage])){
721       $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
722       $this->pwObject->remove_from_parent();
723     }
725     /* Remove user */
726     $ldap= $this->config->get_ldap_link();
727     $ldap->rmdir ($this->dn);
728     if (!$ldap->success()){
729       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
730     }
731   
732     new log("remove","users/".get_class($this),$this->dn,$this->attributes,$ldap->get_error());
733   
734     /* Delete references to groups */
735     $ldap->cd ($this->config->current['BASE']);
736     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
737     while ($ldap->fetch()){
738       $g= new group($this->config, $ldap->getDN());
739       $g->removeUser($this->uid);
740       $g->save ();
741     }
743     /* Delete references to object groups */
744     $ldap->cd ($this->config->current['BASE']);
745     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
746     while ($ldap->fetch()){
747       $og= new ogroup($this->config, $ldap->getDN());
748       unset($og->member[$this->dn]);
749       $og->save ();
750     }
752     // Update 'manager' attributes from gosaDepartment and inetOrgPerson
753     $filter = "(&(objectClass=inetOrgPerson)(manager=".LDAP::prepare4filter($this->dn)."))";
754     $ocs = $ldap->get_objectclasses();
755     if(isset($ocs['gosaDepartment']['MAY']) && in_array('manager', $ocs['gosaDepartment']['MAY'])){
756       $filter = "(|".$filter."(&(objectClass=gosaDepartment)(manager=".LDAP::prepare4filter($this->dn).")))";
757     }
758     $leaf_deps=  get_list($filter,array("all"),$this->config->current['BASE'],
759         array("manager","dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
760     foreach($leaf_deps as $entry){
761       $update = array('manager' => array());
762       $ldap->cd($entry['dn']);
763       $ldap->modify($update);
764       if(!$ldap->success()){
765         trigger_error(sprintf("Failed to update manager for '%s', error was '%s'", $entry['dn'], $ldap->get_error()));
766       }
767     }
769     /* Delete references to roles */
770     $ldap->cd ($this->config->current['BASE']);
771     $ldap->search ("(&(objectClass=organizationalRole)(roleOccupant=".LDAP::prepare4filter($this->dn)."))", array("cn"));
772     while ($ldap->fetch()){
773       $role= new roleGeneric($this->config, $ldap->getDN());
774       $key = array_search($this->dn,$role->roleOccupant);
775       if($key !== FALSE){
776         unset($role->roleOccupant[$key]);
777         $role->roleOccupant= array_values($role->roleOccupant);
778         $role->save ();
779       }
780     }
782     /* If needed, let the password method do some cleanup */
783     $tmp = new passwordMethod($this->config, $this->dn);
784     $available = $tmp->get_available_methods();
785     if (in_array_ics($this->pw_storage, $available['name'])){
786       $test= new $available[$this->pw_storage]($this->config);
787       $test->attrs= $this->attrs;
788       $test->dn= $this->dn;
789       $test->remove_from_parent();
790     }
792     /* Remove ACL dependencies too */
793     acl::remove_acl_for($this->dn);
795     /* Optionally execute a command after we're done */
796     $this->handle_post_events("remove",array("uid" => $this->uid));
797   }
800   /* Save data to object */
801   function save_object()
802   {
803     if(isset($_POST['generic']) || isset($_POST['multiple_user_posted'])){
805       /* Make a backup of the current selected base */
806       $base_tmp = $this->base;
808       /* Parents save function */
809       plugin::save_object ();
811       /* Refresh base */
812       if ($this->acl_is_moveable($this->base)){
813         if (!$this->baseSelector->update()) {
814           msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
815         }
816         if ($this->base != $this->baseSelector->getBase()) {
817           $this->base= $this->baseSelector->getBase();
818           $this->is_modified= TRUE;
819         }
820       }
821       
822       /* Sync lists */
823       $this->gosaLoginRestrictionWidget->save_object();
824       if ($this->gosaLoginRestrictionWidget->isModified()) {
825         $this->gosaLoginRestriction= array_values($this->gosaLoginRestrictionWidget->getMaintainedData());
826       }
828       /* Save government mode attributes */
829       if ($this->governmentmode){
830         foreach ($this->govattrs as $val){
831           if ($this->acl_is_writeable($val)){
832             $data= get_post($val);
833             if ($data != $this->$val){
834               $this->is_modified= TRUE;
835             }
836             $this->$val= $data;
837           }
838         }
839       }
841       /* In template mode, the uid is autogenerated... */
842       if ($this->is_template){
843         $this->uid= strtolower($this->sn);
844         $this->givenName= $this->sn;
845       }
847       /* Get pw_storage mode */
848       if (isset($_POST['pw_storage'])){
849         foreach(array("pw_storage") as $val){
850           if(isset($_POST[$val])){
851             $data= get_post($val);
852             if ($data != $this->$val){
853               $this->is_modified= TRUE;
854             }
855             $this->$val= $data;
856           }
857         }
858       }
860       if($this->pw_storage != $this->last_pw_storage && isset($_POST['pw_storage'])){
861         if ($this->acl_is_writeable("userPassword")){
862           $temp= passwordMethod::get_available_methods();
863           if (!is_object($this->pwObject) || !($this->pwObject instanceOf $temp[$this->pw_storage])){
864             foreach($temp as $id => $data){
865               if(isset($data['name']) && $data['name'] == $this->pw_storage && $data['is_configurable']){
866                 $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
867                 break;
868               }
869             }
870           }
871         }
872       }
874       /* Save current cn
875        */
876       $this->cn = $this->givenName." ".$this->sn;
877     }
878   }
880   function rebind($ldap, $referral)
881   {
882     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
883     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
884       $this->error = "Success";
885       $this->hascon=true;
886       $this->reconnect= true;
887       return (0);
888     } else {
889       $this->error = "Could not bind to " . $credentials['ADMIN'];
890       return NULL;
891     }
892   }
894   
895   /* Save data to LDAP, depending on is_account we save or delete */
896   function save()
897   {
898     global $lang;
900     /* Only force save of changes .... 
901        If this attributes aren't changed, avoid saving.
902      */
903   
904     if($this->gender=="0") $this->gender ="";
905     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
907     /* First use parents methods to do some basic fillup in $this->attrs */
908     plugin::save ();
910     if ($this->dateOfBirth != ""){
911       if(!is_array($this->attrs['dateOfBirth'])) {
912         #TODO: use $lang to convert date
913         list($day, $month, $year)= explode(".", $this->dateOfBirth);
914         $this->attrs['dateOfBirth'] = sprintf("%04d-%02d-%02d", $year, $month, $day);
915       }
916     }
918     /* Remove additional objectClasses */
919     $tmp= array();
920     foreach ($this->attrs['objectClass'] as $key => $set){
921       $found= false;
922       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
923         if (preg_match ("/^$set$/i", $val)){
924           $found= true;
925           break;
926         }
927       }
928       if (!$found){
929         $tmp[]= $set;
930       }
931     }
933     /* Replace the objectClass array. This is done because of the
934        separation into government and normal mode. */
935     $this->attrs['objectClass']= $tmp;
937     /* Add objectClasss for template mode? */
938     if ($this->is_template){
939       $this->attrs['objectClass'][]= "gosaUserTemplate";
940     }
942     /* Hard coded government mode? */
943     if ($this->governmentmode){
944       $this->attrs['objectClass'][]= "ivbbentry";
946       /* Copy standard attributes */
947       foreach ($this->govattrs as $val){
948         if ($this->$val != ""){
949           $this->attrs["$val"]= $this->$val;
950         } elseif (!$this->is_new) {
951           $this->attrs["$val"]= array();
952         }
953       }
955       /* Remove attribute if set to "nein" */
956       if ($this->publicVisible == "nein"){
957         $this->attrs['publicVisible']= array();
958         if($this->is_new){
959           unset($this->attrs['publicVisible']);
960         }else{
961           $this->attrs['publicVisible']=array();
962         }
964       }
966     }
968     /* Special handling for attribute userCertificate needed */
969     if ($this->userCertificate != ""){
970       $this->attrs["userCertificate;binary"]= $this->userCertificate;
971       $remove_userCertificate= false;
972     } else {
973       $remove_userCertificate= true;
974     }
976     /* Special handling for dateOfBirth value */
977     if ($this->dateOfBirth == ""){
978       if ($this->is_new) {
979         unset($this->attrs["dateOfBirth"]);
980       } else {
981         $this->attrs["dateOfBirth"]= array();
982       }
983     }
984     if (!$this->gender){
985       if ($this->is_new) {
986         unset($this->attrs["gender"]);
987       } else {
988         $this->attrs["gender"]= array();
989       }
990     }
991     if (!$this->preferredLanguage){
992       if ($this->is_new) {
993         unset($this->attrs["preferredLanguage"]);
994       } else {
995         $this->attrs["preferredLanguage"]= array();
996       }
997     }
999     /* Special handling for attribute jpegPhote needed, scale image via
1000        image magick to 147x200 pixels and inject resulting data. */
1001     if ($this->jpegPhoto == "*removed*"){
1002     
1003       /* Reset attribute to avoid writing *removed* as value */    
1004       $this->attrs["jpegPhoto"] = array();
1006     } else {
1008       /* Fallback if there's no image magick inside PHP */
1009       if (!function_exists("imagick_blob2image")){
1010         /* Get temporary file name for conversation */
1011         $fname = tempnam (TEMP_DIR, "GOsa");
1012   
1013         /* Open file and write out photoData */
1014         $fp = fopen ($fname, "w");
1015         fwrite ($fp, $this->photoData);
1016         fclose ($fp);
1018         /* Build conversation query. Filename is generated automatically, so
1019            we do not need any special security checks. Exec command and save
1020            output. For PHP safe mode, you'll need a configuration which respects
1021            image magick as executable... */
1022         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
1023         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
1024             $query, "Execute");
1025   
1026         /* Read data written by convert */
1027         $output= "";
1028         $sh= popen($query, 'r');
1029         while (!feof($sh)){
1030           $output.= fread($sh, 4096);
1031         }
1032         pclose($sh);
1034         unlink($fname);
1036         /* Save attribute */
1037         $this->attrs["jpegPhoto"] = $output;
1039       } else {
1041         /* Load the new uploaded Photo */
1042         if(!$handle  =  imagick_blob2image($this->photoData))  {
1043           new log("debug","users/".get_class($this),$this->dn,array(),"Could not access uploaded image");
1044         }
1046         /* Resizing image to 147x200 and blur */
1047         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
1048           new log("debug","users/".get_class($this),$this->dn,array(),"Could not resize uploaded image");
1049         }
1051         /* Converting image to JPEG */
1052         if(!imagick_convert($handle,"JPEG")) {
1053           new log("debug","users/".get_class($this),$this->dn,array(),"Could not convert uploaded image to jepg");
1054         }
1056         /* Creating binary Code for the Image */
1057         if(!$dump = imagick_image2blob($handle)){
1058           new log("debug","users/".get_class($this),$this->dn,array(),"Could not create new user image");
1059         }
1061         /* Sending Image */
1062         $output=  $dump;
1064         /* Save attribute */
1065         $this->attrs["jpegPhoto"] = $output;
1066       }
1068     }
1070     /* This only gets called when user is renaming himself */
1071     $ldap= $this->config->get_ldap_link();
1072     if ($this->dn != $this->new_dn){
1074       /* Write entry on new 'dn' */
1075       $this->update_acls($this->dn,$this->new_dn);
1076       $this->move($this->dn, $this->new_dn);
1078       /* Happen to use the new one */
1079       change_ui_dn($this->dn, $this->new_dn);
1080       $this->dn= $this->new_dn;
1081     }
1084     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
1085        new entries. So do a check first... */
1086     $ldap->cat ($this->dn, array('dn'));
1087     if ($ldap->fetch()){
1088       $mode= "modify";
1089     } else {
1090       $mode= "add";
1091       $ldap->cd($this->config->current['BASE']);
1092       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
1093     }
1095     /* Set password to some junk stuff in case of templates */
1096     if ($this->is_template){
1097       $temp= passwordMethod::get_available_methods();
1098       foreach($temp as $id => $data){
1099         if(isset($data['name']) && $data['name'] == $this->pw_storage){
1100           $tmp = new  $temp[$this->pw_storage]($this->config,$this->dn);
1101           $tmp->set_hash($this->pw_storage);
1102           $this->attrs['userPassword'] = $tmp->create_template_hash($this->attrs);
1103           break;
1104         }
1105       }
1106     }
1108     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
1109         $this->attributes, "Save via $mode");
1111     /* Finally write data with selected 'mode' */
1112     $this->cleanup();
1114     /* Update current locale settings, if we have edited ourselves */
1115     $ui = session::get('ui');
1116     if(isset($this->attrs['preferredLanguage']) && $this->dn == $ui->dn){
1117       $ui->language = $this->preferredLanguage;
1118       session::set('ui',$ui);
1119       session::set('Last_init_lang',"update");
1120     }
1122     $ldap->cd ($this->dn);
1123     $ldap->$mode ($this->attrs);
1124     if (!$ldap->success()){
1125       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
1126       return (1);
1127     }
1129     /* Remove ACL dependencies too */
1130     if($this->dn != $this->orig_dn && $this->orig_dn != "new"){
1131       $tmp = new acl($this->config,$this->parent,$this->dn);
1132       $tmp->update_acl_membership($this->orig_dn,$this->dn);
1133     }
1135     if($mode == "modify"){
1136       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1137     }else{
1138       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1139     }
1141     /* Remove cert? 
1142        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
1143        to work around myself. */
1144     if ($remove_userCertificate == true && !$this->is_new && $this->had_userCertificate){
1146       /* Reset array, assemble new, this should be reworked */
1147       $this->attrs= array();
1148       $this->attrs['userCertificate;binary']= array();
1150       /* Prepare connection */
1151       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
1152         die ("Could not connect to LDAP server");
1153       }
1154       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1155       if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("core","ldapFollowReferrals") == "true") {
1156         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1157         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1158       }
1159       if($this->config->get_cfg_value("core","ldapTLS") == "true"){
1160         ldap_start_tls($ds);
1161       }
1162       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
1163               $this->config->current['PASSWORD']))) {
1164         die ("Could not bind to LDAP");
1165       }
1167       /* Modify using attrs */
1168       ldap_mod_del($ds,$this->dn,$this->attrs);
1169       ldap_close($ds);
1170     }
1172     /* If needed, let the password method do some cleanup */
1173     if ($this->pw_storage != $this->last_pw_storage){
1174       $tmp = new passwordMethod($this->config, $this->dn);
1175       $available = $tmp->get_available_methods();
1176       if (in_array_ics($this->last_pw_storage, $available['name'])){
1177         $test= new $available[$this->last_pw_storage]($this->config,$this->dn);
1178         $test->attrs= $this->attrs;
1179         $test->remove_from_parent();
1180       }
1181     }
1183     /* Maybe the current password method want's to do some changes... */
1184     if (is_object($this->pwObject)){
1185       $this->pwObject->save($this->dn);
1186     }
1188     /* Optionally execute a command after we're done */
1189     if ($mode == "add"){
1190       $this->handle_post_events("add", array("uid" => $this->uid));
1191     } elseif ($this->is_modified){
1192       $this->handle_post_events("modify", array("uid" => $this->uid));
1193     }
1195     return (0);
1196   }
1199   function create_initial_rdn($pattern)
1200   {
1201     // Only generate single RDNs
1202     if (preg_match('/\+/', $pattern)){
1203       msg_dialog::display(_("Error"), _("Cannot build RDN: no + allowed to build sub RDN!"), ERROR_DIALOG);
1204       return "";
1205     }
1207     // Extract attribute
1208     $attribute= preg_replace('/=.*$/', '', $pattern);
1209     if (!in_array_ics($attribute, $this->attributes)) {
1210       msg_dialog::display(_("Error"), _("Cannot build RDN: attribute is not defined!"), ERROR_DIALOG);
1211       return "";
1212     }
1214     // Sort attributes for length
1215     $attrl= array();
1216     foreach ($this->attributes as $attr) {
1217       $attrl[$attr]= strlen($attr);
1218     }
1219     arsort($attrl);
1220     
1221     // Walk thru sorted attributes and replace them in pattern
1222     foreach ($attrl as $attr => $dummy) {
1223       if (!is_array($this->$attr)){
1224         $pattern= preg_replace("/%$attr/", $this->$attr, $pattern);
1225       } else {
1226         // Array elements cannot be used for ID generation
1227         if (preg_match("/%$attr/", $pattern)) {
1228           msg_dialog::display(_("Error"), _("Cannot build RDN: invalid attribute parameters!"), ERROR_DIALOG);
1229           break;
1230         }
1231       }
1232     }
1234     // Internally assign value
1235     $this->$attribute= preg_replace('/^[^=]+=/', '', $pattern);
1237     return $pattern;
1238   }
1240   
1241   function update_new_dn()
1242   {
1243     // Alternative way to handle DN
1244     $pattern= $this->config->get_cfg_value("user","accountRDN");
1245     if ($pattern != "") {
1246       $rdn= $this->create_initial_rdn($pattern);
1247       $attribute= preg_replace('/=.*$/', '', $rdn);
1248       $value= preg_replace('/^[^=]+=$/', '', $rdn);
1250       /* Don't touch dn, if $attribute hasn't changed */
1251       if (isset($this->saved_attributes[$attribute]) && $this->saved_attributes[$attribute] == $this->$attribute &&
1252             $this->orig_base == $this->base ){
1253         $this->new_dn= $this->dn;
1254       } else {
1255         $this->new_dn= $this->create_unique_dn2($rdn, get_people_ou().$this->base);
1256       }
1258     // Original way to handle DN
1259     } else {
1261       $pt= "";
1262       if($this->config->get_cfg_value("core","personalTitleInDN") == "true"){
1263         if(!empty($this->personalTitle)){
1264           $pt = $this->personalTitle." ";
1265         }
1266       }
1268       $this->cn= $pt.$this->givenName." ".$this->sn;
1270       /* Permissions for that base? */
1271       if ($this->config->get_cfg_value("core","accountPrimaryAttribute") == "uid"){
1272         $this->new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
1273       } else {
1274         /* Don't touch dn, if cn hasn't changed */
1275         if (isset($this->saved_attributes['cn']) && $this->saved_attributes['cn'] == $this->cn &&
1276             $this->orig_base == $this->base ){
1277           $this->new_dn= $this->dn;
1278         } else {
1279           $this->new_dn= $this->create_unique_dn('cn', get_people_ou().$this->base);
1280         }
1281       }
1282     }
1283   }
1284   
1286   /* Check formular input */
1287   function check()
1288   {
1289     /* Call common method to give check the hook */
1290     $message= plugin::check();
1292     /* Configurable password methods should be configured initially. 
1293      */ 
1294     if($this->last_pw_storage != $this->pw_storage){
1295       $temp= passwordMethod::get_available_methods();
1296       foreach($temp['name'] as $id => $name){
1297         if($name == $this->pw_storage){
1298           if($temp['is_configurable'][$id] && !$this->pwObject instanceof $temp[$name] ){
1299             $message[] = _("The selected password method requires initial configuration!");
1300           }
1301           break;
1302         }
1303       }
1304     }
1306     $this->update_new_dn();
1308     /* Set the new acl base */
1309     if($this->dn == "new") {
1310       $this->set_acl_base($this->base);
1311     }
1313     /* Check if we are allowed to create/move this user */
1314     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
1315       $message[]= msgPool::permCreate();
1316     }elseif($this->orig_dn != "new" && $this->new_dn != $this->orig_dn){
1318         /* Check if the objects dn has changed while the base was left unchanged. 
1319          * In this case we've to check move permissions for the object itself.
1320          * 
1321          * If the base has changed then we've to check the permission for the destination
1322          *  base.
1323          */
1324         if($this->orig_base == $this->base && !$this->acl_is_moveable($this->dn)){
1325             $message[]= msgPool::permMove();
1326         }elseif($this->orig_base != $this->base && !$this->acl_is_moveable($this->base)){
1327             $message[]= msgPool::permMove();
1328         }
1329     }
1331     /* UID already used? */
1332     $ldap= $this->config->get_ldap_link();
1333     $ldap->cd($this->config->current['BASE']);
1334     $ldap->search("(uid=$this->uid)", array("uid"));
1335     $ldap->fetch();
1336     if ($ldap->count() != 0 && $this->dn == 'new'){
1337       $message[]= msgPool::duplicated(_("Login"));
1338     }
1340     /* In template mode, the uid and givenName are autogenerated... */
1341     if ($this->sn == ""){
1342       $message[]= msgPool::required(_("Name"));
1343     }
1345     // Check if a wrong base was supplied
1346     if(!$this->baseSelector->checkLastBaseUpdate()){
1347       $message[]= msgPool::check_base();;
1348     }
1350     if (!$this->is_template){
1351       if ($this->givenName == ""){
1352         $message[]= msgPool::required(_("Given name"));
1353       }
1354       if ($this->uid == ""){
1355         $message[]= msgPool::required(_("Login"));
1356       }
1357       if ($this->config->get_cfg_value("core","accountPrimaryAttribute") != "uid"){
1358         $ldap->cat($this->new_dn);
1359         if ($ldap->count() != 0 && $this->dn != $this->new_dn && $this->dn == 'new'){
1360           $message[]= msgPool::duplicated(_("Name"));
1361         }
1362       }
1363     }
1365     /* Check for valid input */
1366     if ($this->is_modified && !tests::is_uid($this->uid)){
1368       if (strict_uid_mode()){
1369         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/");
1370       } else {
1371         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/i");
1372       }
1373     }
1374     if (!tests::is_url($this->labeledURI)){
1375       $message[]= msgPool::invalid(_("Homepage"), "", "", "http://www.your-domain.com/yourname");
1376     }
1378     /* Check phone numbers */
1379     if (!tests::is_phone_nr($this->telephoneNumber)){
1380       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1381     }
1382     if (!tests::is_phone_nr($this->facsimileTelephoneNumber)){
1383       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1384     }
1385     if (!tests::is_phone_nr($this->mobile)){
1386       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1387     }
1388     if (!tests::is_phone_nr($this->pager)){
1389       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1390     }
1392     /* Check dates */
1393     if (!tests::is_date($this->dateOfBirth)){
1394       $message[]= msgPool::invalid(_("Date of birth"), $this->dateOfBirth,"" ,"23.02.2009");
1395     }
1397     /* Check for reserved characers */
1398     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName)){
1399       $message[]= msgPool::invalid(_("Given name"), $this->givenName, '/[^,+"?\'()=<>;\\\\]/');
1400     }
1401     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn)){
1402       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1403     }
1405     return $message;
1406   }
1409   /* Indicate whether a password change is needed or not */
1410   function password_change_needed()
1411   {
1412     if($this->multiple_support_active){
1413       return(FALSE);
1414     }else{
1416       if(in_array("pw_storage",$this->multi_boxes)){
1417         return(TRUE);
1418       }
1419       return($this->pw_storage != $this->last_pw_storage && !$this->is_template);
1420     }
1421   }
1424   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1425   function load_picture()
1426   {
1427     $ldap = $this->config->get_ldap_link();
1428     $ldap->cd ($this->dn);
1429     $data = $ldap->get_attribute($this->dn,"jpegPhoto");
1431     if((!$data) || ($data == "*removed*")){ 
1433       /* In case we don't get an entry, load a default picture */
1434       $this->set_picture ();
1435       $this->jpegPhoto= "*removed*";
1436     }else{
1438       /* Set picture */
1439       $this->photoData= $data;
1440       session::set('binary',$this->photoData);
1441       session::set('binarytype',"image/jpeg");
1442       $this->jpegPhoto= "";
1443     }
1444   }
1447   /* Load a certificate from LDAP, this is going to be simplified later on */
1448   function load_cert()
1449   {
1450     $ds= ldap_connect($this->config->current['SERVER']);
1451     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1452     if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("core","ldapFollowReferrals") == "true"){
1453       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1454       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1455     }
1456     if ($this->config->get_cfg_value("core","ldapTLS") == "true"){
1457       ldap_start_tls($ds);
1458     }
1460     $r= ldap_bind($ds);
1461     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1463     if ($sr) {
1464       $ei= @ldap_first_entry($ds, $sr);
1465       
1466       if ($ei) {
1467         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1468           $this->userCertificate= "";
1469         } else {
1470           $this->userCertificate= $info[0];
1471         }
1472       }
1473     } else {
1474       $this->userCertificate= "";
1475     }
1477     ldap_unbind($ds);
1478   }
1481   /* Load picture from file to object */
1482   function set_picture($filename ="")
1483   {
1484     if (!is_file($filename) || $filename =="" ){
1485       $filename= "./plugins/users/images/default.jpg";
1486       $this->jpegPhoto= "*removed*";
1487     }
1489     $fd = fopen ($filename, "rb");
1490     $this->photoData= fread ($fd, filesize ($filename));
1491     session::set('binary',$this->photoData);
1492     session::set('binarytype',"image/jpeg");
1493     $this->jpegPhoto= "";
1495     fclose ($fd);
1496   }
1499   /* Load certificate from file to object */
1500   function set_cert($cert, $filename)
1501   {
1502     if(!$this->acl_is_writeable("Certificate")) return;
1503     $fd = fopen ($filename, "rb");
1504     if (filesize($filename)>0) {
1505       $this->$cert= fread ($fd, filesize ($filename));
1506       fclose ($fd);
1507       $this->is_modified= TRUE;
1508     } else {
1509       msg_dialog::display(_("Error"), _("Cannot open certificate!"), ERROR_DIALOG);
1510     }
1511   }
1513   /* Adapt from given 'dn' */
1514   function adapt_from_template($dn, $skip= array())
1515   {
1516     plugin::adapt_from_template($dn, $skip);
1518     /* Get password method from template 
1519      */
1520     $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
1521     if(is_object($tmp)){
1522       if($tmp->is_configurable()){
1523         $tmp->adapt_from_template($dn);
1524         $this->pwObject = &$tmp;
1525       }
1526       $this->pw_storage= $tmp->get_hash();
1527     }
1529     /* Get base */
1530     $this->base= preg_replace('/^[^,]+,'.preg_quote(get_people_ou(), '/').'/i', '', $dn);
1532     if($this->governmentmode){
1534       /* Walk through govattrs */
1535       foreach ($this->govattrs as $val){
1537         if (in_array($val, $skip)){
1538           continue;
1539         }
1541         if (isset($this->attrs["$val"][0])){
1543           /* If attribute is set, replace dynamic parts: 
1544              %sn, %givenName and %uid. Fill these in our local variables. */
1545           $value= $this->attrs["$val"][0];
1547           foreach (array("sn", "givenName", "uid") as $repl){
1548             if (preg_match("/%$repl/i", $value)){
1549               $value= preg_replace ("/%$repl/i",
1550                   $this->parent->$repl, $value);
1551             }
1552           }
1553           $this->$val= $value;
1554         }
1555       }
1556     }
1558     /* Get back uid/sn/givenName - only write if nothing's skipped */
1559     if ($this->parent !== NULL && count($skip) == 0){
1560       $this->uid= $this->parent->uid;
1561       $this->sn= $this->parent->sn;
1562       $this->givenName= $this->parent->givenName;
1563     }
1565     /* Generate dateOfBirth entry */
1566     if (isset ($this->attrs['dateOfBirth'])){
1567       /* This entry is ISO 8601 conform */
1568       list($year, $month, $day)= explode("-", $this->attrs['dateOfBirth'][0], 3);
1569     
1570       #TODO: use $lang to convert date
1571       $this->dateOfBirth= "$day.$month.$year";
1572     } else {
1573       $this->dateOfBirth= "";
1574     }
1575   }
1577  
1578   /* This avoids that users move themselves out of their rights. 
1579    */
1580   function allowedBasesToMoveTo()
1581   {
1582     /* Get bases */
1583     $bases  = $this->get_allowed_bases();
1584     return($bases);
1585   } 
1588   function getCopyDialog()
1589   {
1590     $str = "";
1592     session::set('binary',$this->photoData); 
1593     session::set('binarytype',"image/jpeg");
1595     /* Get random number for pictures */
1596     srand((double)microtime()*1000000); 
1597     $rand = rand(0, 10000);
1599     $smarty = get_smarty();
1601     $smarty->assign("passwordTodo","clear");
1603     if(isset($_POST['passwordTodo'])){
1604       $smarty->assign("passwordTodo",set_post(get_post('passwordTodo')));
1605     }
1607     $smarty->assign("sn",       set_post($this->sn));
1608     $smarty->assign("givenName",set_post($this->givenName));
1609     $smarty->assign("uid",      set_post($this->uid));
1610     $smarty->assign("rand",     $rand);
1611     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1614     $ret = array();
1615     $ret['string'] = $str;
1616     $ret['status'] = "";  
1617     return($ret);
1618   }
1620   function saveCopyDialog()
1621   {
1622     /* Set_acl_base */
1623     $this->set_acl_base($this->base);
1625     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1626       $this->set_picture($_FILES['picture_file']['tmp_name']);
1627     }
1629     /* Remove picture? */
1630     if (isset($_POST['picture_remove'])){
1631       $this->jpegPhoto= "*removed*";
1632       $this->set_picture ("./plugins/users/images/default.jpg");
1633       $this->is_modified= TRUE;
1634     }
1636     $attrs = array("uid","givenName","sn");
1637     foreach($attrs as $attr){
1638       if(isset($_POST[$attr])){
1639         $this->$attr = get_post($attr);
1640       }
1641     } 
1642   }
1645   function PrepareForCopyPaste($source)
1646   {
1647     plugin::PrepareForCopyPaste($source);
1649     /* Reset certificate information addepted from source user
1650        to avoid setting the same user certificate for the destination user. */
1651     $this->userPKCS12= "";
1652     $this->userSMIMECertificate= "";
1653     $this->userCertificate= "";
1654     $this->certificateSerialNumber= "";
1655     $this->old_certificateSerialNumber= "";
1656     $this->old_userPKCS12= "";
1657     $this->old_userSMIMECertificate= "";
1658     $this->old_userCertificate= "";
1660     /* Generate dateOfBirth entry */
1661     if (isset ($source['dateOfBirth'])){
1662         list($year, $month, $day)= explode("-", $source['dateOfBirth'][0], 3);
1663         $this->dateOfBirth= "$day.$month.$year";
1664     } else {
1665         $this->dateOfBirth= "";
1666     }
1668     // Try to load the user picture
1669     $tmp_dn = $this->dn;
1670     $this->dn = $source['dn'];
1671     $this->load_picture();
1672     $this->dn = $tmp_dn;
1673   }
1676   static function plInfo()
1677   {
1678   
1679     $govattrs= array(
1680         "gouvernmentOrganizationalUnit"             =>  _("Unit"), 
1681         "houseIdentifier"                           =>  _("House identifier"), 
1682         "vocation"                                  =>  _("Vocation"),
1683         "ivbbLastDeliveryCollective"                =>  _("Last delivery"), 
1684         "gouvernmentOrganizationalPersonLocality"   =>  _("Person locality"),
1685         "gouvernmentOrganizationalUnitDescription"  =>  _("Unit description"),
1686         "gouvernmentOrganizationalUnitSubjectArea"  =>  _("Subject area"),
1687         "functionalTitle"                           =>  _("Functional title"),
1688         "certificateSerialNumber"                   =>  _("Certificate serial number"),
1689         "publicVisible"                             =>  _("Public visible"),
1690         "street"                                    =>  _("Street"),
1691         "role"                                      =>  _("Role"),
1692         "postalCode"                                =>  _("Postal code"));
1694     $ret = array(
1695         "plShortName" => _("Generic"),
1696         "plDescription" => _("Generic user settings"),
1697         "plSelfModify"  => TRUE,
1698         "plDepends"     => array(),
1699         "plPriority"    => 1,
1700         "plSection"     => array("personal" => _("My account")),
1701         "plCategory"    => array("users" => array("description" => _("Users"),
1702                                                   "objectClass" => "gosaAccount")),
1704         "plRequirements"=> array(
1705             'ldapSchema' => array(
1706                 'gosaAccount' => '>=2.7',
1707                 'gosaUserTemplate' => '>=2.7'
1708                 ),
1709             'onFailureDisablePlugin' => array(get_class(),'userManagement', 'user')
1710             ),
1712         "plProperties" => array(
1713             array(
1714                 "name"          => "accountRDN",
1715                 "type"          => "string",
1716                 "default"       => "",
1717                 "description"   => sprintf(
1718                     _("The 'accountRDN' option tells GOsa to use a placeholder pattern for generating account RDNs. A pattern can include attribute names prefaced by a %% and normal text: %s. This will generate a RDN consisting of cn=.... filled with surname and given name of the edited account. This option disables the use of accountPrimaryAttribute and personalTitleInDn."), "accountRDN=\"cn=%sn %givenName\""),
1719                 "check"         => "gosaProperty::isString",
1720                 "migrate"       => "",
1721                 "group"         => "plugin",
1722                 "mandatory"     => FALSE
1723                 )
1725             ),
1726         "plProvidedAcls" => array(
1728           "sn"                => _("Surname"),
1729           "givenName"         => _("Given name"),
1730           "uid"               => _("Login"),
1732           "gosaUserDefinedFilter"  => _("Allow definition of custom filters"),
1734           "personalTitle"     => _("Personal title"),
1735           "academicTitle"     => _("Academic title"),
1737           "dateOfBirth"       => _("Date of birth"),
1738           "gender"            => _("Sex"),
1739           "preferredLanguage" => _("Preferred language"),
1740           "base"              => _("Base"), 
1742           "userPicture"       => _("User picture"),
1744           "gosaLoginRestriction" => _("Login restrictions"),         
1746           "o"                 => _("Organization"),
1747           "ou"                => _("Department"),
1748           "departmentNumber"  => _("Department number"),
1749           "manager"           => _("Manager"),
1750           "employeeNumber"    => _("Employee number"),
1751           "employeeType"      => _("Employee type"),
1753           "roomNumber"        => _("Room number"),
1754           "telephoneNumber"   => _("Telephone number"),
1755           "pager"             => _("Pager number"),
1756           "mobile"            => _("Mobile number"),
1757           "facsimileTelephoneNumber"     => _("Fax number"),
1759           "st"                => _("State"),
1760           "l"                 => _("Location"),
1761           "postalAddress"     => _("Postal address"),
1763           "homePostalAddress" => _("Home postal address"),
1764           "homePhone"         => _("Home phone number"),
1765           "labeledURI"        => _("Homepage"),
1766           "userPassword"      => _("User password method"), 
1767           "Certificate"       => _("User certificates"))
1769         );
1771 #   /* Append government attributes if required */
1772 #   global $config;
1773 #   if($config->get_cfg_value("core","honourIvbbAttributes") == "true"){
1774 #     foreach($govattrs as $attr => $desc){
1775 #       $ret["plProvidedAcls"][$attr] = $desc;
1776 #     }
1777 #   }
1778     return($ret);
1779   }
1781   function get_multi_edit_values()
1782   {
1783     $ret = plugin::get_multi_edit_values();
1784     if(in_array("pw_storage",$this->multi_boxes)){
1785       $ret['pw_storage'] = $this->pw_storage;
1786     }
1787     if(in_array("edit_picture",$this->multi_boxes)){
1788       $ret['jpegPhoto'] = $this->jpegPhoto;
1789       $ret['photoData'] = $this->photoData;
1790       $ret['old_jpegPhoto'] = $this->old_jpegPhoto;
1791       $ret['old_photoData'] = $this->old_photoData;
1792     }
1793     if(isset($ret['dateOfBirth'])){
1794       unset($ret['dateOfBirth']);
1795     }
1796     if(isset($ret['cn'])){
1797       unset($ret['cn']);
1798     }
1799     $ret['is_modified'] = $this->is_modified;
1800     if(in_array("base",$this->multi_boxes)){
1801       $ret['orig_base']="Changed_by_Multi_Plug";
1802       $ret['base']=$this->base;
1803     }
1805     $ret['gosaLoginRestriction'] = $this->gosaLoginRestriction;
1806     $ret['gosaLoginRestriction_some'] = $this->gosaLoginRestriction_some;
1808     return($ret); 
1809   }
1812   function multiple_save_object()
1813   {
1815     if(!isset($_POST['user_mulitple_edit'])) return;
1817     plugin::multiple_save_object();
1819     /* Get pw_storage mode */
1820     if (isset($_POST['pw_storage'])){
1821       foreach(array("pw_storage") as $val){
1822         if(isset($_POST[$val])){
1823           $data= get_post($val);
1824           if ($data != $this->$val){
1825             $this->is_modified= TRUE;
1826           }
1827           $this->$val= $data;
1828         }
1829       }
1830     }
1831   
1832     /* Refresh base */
1833     if ($this->acl_is_moveable($this->base)){
1834       if (!$this->baseSelector->update()) {
1835         msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
1836       }
1837       if ($this->base != $this->baseSelector->getBase()) {
1838         $this->base= $this->baseSelector->getBase();
1839       }
1840     }
1842     if(isset($_POST['user_mulitple_edit'])){
1843       foreach(array("base","pw_storage","edit_picture") as $val){
1844         if(isset($_POST["use_".$val])){
1845           $this->multi_boxes[] = $val;
1846         }
1847       }
1848     }
1850     /* Sync lists */
1851     $this->gosaLoginRestrictionWidget->save_object();
1852     if ($this->gosaLoginRestrictionWidget->isModified()) {
1853       $this->gosaLoginRestriction= array_values($this->gosaLoginRestrictionWidget->getMaintainedData());
1854     }
1855   }
1857   
1858   function multiple_check()
1859   {
1860     /* Call check() to set new_dn correctly ... */
1861     $message = plugin::multiple_check();
1863     /* Set the new acl base */
1864     if($this->dn == "new") {
1865       $this->set_acl_base($this->base);
1866     }
1867     if (!tests::is_url($this->labeledURI) && in_array("labeledURI",$this->multi_boxes)){
1868       $message[]= msgPool::invalid(_("Homepage"));
1869     }
1870     if (!tests::is_phone_nr($this->telephoneNumber) && in_array("telephoneNumber",$this->multi_boxes)){
1871       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1872     }
1873     if (!tests::is_phone_nr($this->facsimileTelephoneNumber) &&  in_array("facsimileTelephoneNumber",$this->multi_boxes)){
1874       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1875     }
1876     if (!tests::is_phone_nr($this->mobile) && in_array("mobile",$this->multi_boxes)){
1877       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1878     }
1879     if (!tests::is_phone_nr($this->pager) && in_array("pager",$this->multi_boxes)){
1880       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1881     }
1882     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName) && in_array("givenName",$this->multi_boxes)){
1883       $message[]= msgPool::invalid(_("Given name"), $this->giveName, '/[^,+"?\'()=<>;\\\\]/');
1884     }
1885     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn) && in_array("sn",$this->multi_boxes)){
1886       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1887     }
1888     return($message);
1889   }
1893   function multiple_execute()
1894   {
1895     return($this->execute());
1896   }
1899   /*! \brief  Prepares the plugin to be used for multiple edit
1900    *          Update plugin attributes with given array of attribtues.
1901    *  \param  array   Array with attributes that must be updated.
1902    */
1903   function init_multiple_support($attrs,$all)
1904   {
1905     plugin::init_multiple_support($attrs,$all);
1907     // Get login restrictions
1908     if(isset($attrs['gosaLoginRestriction'])){
1909       $this->gosaLoginRestriction  =array();
1910       for($i =0;$i < $attrs['gosaLoginRestriction']['count']; $i++){
1911         $this->gosaLoginRestriction[] = $attrs['gosaLoginRestriction'][$i];
1912       }
1913     }
1915     // Detect the managers name
1916     $this->manager_name = "";
1917     $ldap = $this->config->get_ldap_link();
1918     if(!empty($this->manager)){
1919       $ldap->cat($this->manager, array('cn'));
1920       if($ldap->count()){
1921         $attrs = $ldap->fetch();
1922         $this->manager_name = $attrs['cn'][0];
1923       }else{
1924         $this->manager_name = "("._("unknown")."!): ".$this->manager;
1925       }
1926     }
1928     // Detect login restriction not used in all user objects.
1929     $this->gosaLoginRestriction_some = array();
1930     if(isset($all['gosaLoginRestriction'])){
1931       for($i=0;$i<$all['gosaLoginRestriction']['count'];$i++){
1932         $this->gosaLoginRestriction_some[] = $all['gosaLoginRestriction'][$i];
1933       }
1934     }
1937     // Reinit the login restriction list.
1938     $data = $this->convertLoginRestriction();
1939     if(count($data)){
1940       $this->gosaLoginRestrictionWidget->setListData($data['data'], $data['displayData']);
1941     }
1942   }
1945   function set_multi_edit_values($attrs)
1946   {
1947     $lR = array();
1949     // Update loginRestrictions, keep my settings while ip is optional
1950     foreach($attrs['gosaLoginRestriction_some'] as $ip){
1951       if(in_array($ip, $this->gosaLoginRestriction) && in_array($ip, $attrs['gosaLoginRestriction'])){
1952         $lR[] = $ip;
1953       }
1954     }
1956     // Add enforced loginRestrictions 
1957     foreach($attrs['gosaLoginRestriction'] as $ip){
1958       $lR[] = $ip;
1959     }
1961     $lR = array_values(array_unique($lR));
1962     $this->is_modified |=  array_differs($this->gosaLoginRestriction, $lR);
1963     plugin::set_multi_edit_values($attrs);
1964     $this->gosaLoginRestriction = $lR;
1965   }
1968   function convertLoginRestriction()
1969   {
1970     $all = array_unique(array_merge($this->gosaLoginRestriction,$this->gosaLoginRestriction_some));
1971     $data = array();
1972     foreach($all as $ip){
1973       $data['data'][] = $ip;
1974       if(!in_array($ip, $this->gosaLoginRestriction)){
1975         $data['displayData'][] = array('mode' => LIST_MARKED , 'data' => array($ip.' ('._("Entries differ").')'));
1976       }else{
1977         $data['displayData'][] = array('mode' => 0 , 'data' => array($ip));
1978       }
1979     }   
1980     return($data);
1981   }
1984 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1985 ?>