Code

'Enabled multiple edit for the manager attribute
[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("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("passwordDefaultHash", "crypt/md5");
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', (!is_object($this->parent) && !session::is_set('edit'))));
287     $this->gosaLoginRestrictionWidget->update();
289     /* Handle add/delete for restriction mode */
290     if (isset($_POST['add_res']) && isset($_POST['res'])) {
291       $val= validate($_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/netmask 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 && count($this->dialog->detectPostActions())){
318       $users = $this->dialog->detectPostActions();
319       if(isset($users['targets']) && count($users['targets'])){
321         $headpage = $this->dialog->getHeadpage();
322         $dn = $users['targets'][0];
323         $attrs = $headpage->getEntry($dn);
324         $this->manager = $dn;
325         $this->manager_name = $attrs['cn'][0];
326         $this->dialog = NULL;
327       }
328     }
329     if(isset($_POST['add_users_cancel'])){
330       $this->dialog = NULL;
331     }
332     if($this->dialog) return($this->dialog->execute()); 
335     $smarty= get_smarty();
336     $smarty->assign("usePrototype", "true");
337     $smarty->assign("gosaLoginRestrictionWidget", $this->gosaLoginRestrictionWidget->render());
339     /* Assign sex */
340     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
341     $smarty->assign("gender_list", $sex);
342     $language= array_merge(array(0 => "&nbsp;") ,get_languages(TRUE));
343     $smarty->assign("preferredLanguage_list", $language);
345     /* Get random number for pictures */
346     srand((double)microtime()*1000000); 
347     $smarty->assign("rand", rand(0, 10000));
350     /* Do we represent a valid gosaAccount? */
351     if (!$this->is_account){
352       $str = "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
353         msgPool::noValidExtension("GOsa")."</b>";
354       return($str);
355     }
357     /* Password configure dialog handling */
358     if(is_object($this->pwObject) && $this->pwObject->display){
359       $output= $this->pwObject->configure();
360       if ($output != ""){
361         $this->dialog= TRUE;
362         return $output;
363       }
364       $this->dialog= false;
365     }
367     /* Dialog handling */
368     if(is_object($this->dialog)){
369       /* Must be called before save_object */
370       $this->dialog->save_object();
371    
372       if($this->dialog->isClosed()){
373         $this->dialog = false;
374       }elseif($this->dialog->isSelected()){
376         /* check if selected base is allowed to move to / create a new object */
377         $tmp = $this->get_allowed_bases();
378         if(isset($tmp[$this->dialog->isSelected()])){
379           $this->base = $this->dialog->isSelected();
380         }
381         $this->dialog= false;
382       }else{
383         return($this->dialog->execute());
384       }
385     }
387     /* Want password method editing? */
388     if ($this->acl_is_writeable("userPassword")){
389       if (isset($_POST['edit_pw_method'])){
390         if (!is_object($this->pwObject) || $this->pw_storage != $this->pwObject->get_hash_name()){
391           $temp= passwordMethod::get_available_methods();
392           $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
393         }
394         $this->pwObject->display = TRUE;
395         $this->dialog= TRUE;
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",(!is_object($this->parent) && !session::is_set('edit'))) ){
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",(!is_object($this->parent) && !session::is_set('edit')))){ 
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",(!is_object($this->parent) && !session::is_set('edit')))){ 
500       $fail =false;
502       if (isset($_POST['cert_edit_finish'])){
504         /* for all certificates do */
505         foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
506             as $val){
508           /* Check for clean upload */
509           if (array_key_exists($val."_file", $_FILES) &&
510               array_key_exists('name', $_FILES[$val."_file"]) &&
511               $_FILES[$val."_file"]['name'] != "" &&
512               is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
513             $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
514           }
515         }
517         /* Save serial number */
518         if (isset($_POST["certificateSerialNumber"]) &&
519             $_POST["certificateSerialNumber"] != ""){
521           if (!tests::is_id($_POST["certificateSerialNumber"])){
522             $fail = true;
523             msg_dialog::display(_("Error"), msgPool::invalid(_("Serial number"),$_POST["certificateSerialNumber"],"/[0-9]/"),ERROR_DIALOG);
525             foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
526               if ($this->$cert != ""){
527                 $smarty->assign("$cert"."_state", "true");
528               } else {
529                 $smarty->assign("$cert"."_state", "");
530               }
531             }
532           }
534           $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
535           $this->is_modified= TRUE;
536         }
537         if(!$fail){
538           $this->cert_dialog= FALSE;
539           $this->dialog= FALSE;
540         }
541       }
542     }
543     /* Display picture dialog */
544     if ($this->picture_dialog){
545       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
546     }
548     /* Display cert dialog */
549     if ($this->cert_dialog){
550       $smarty->assign("CertificateACL",$this->getacl("Certificate",(!is_object($this->parent) && !session::is_set('edit'))));
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><i>"._("(Some types of certificates are currently not supported and may be displayed as 'invalid'.)")."</i>";
569           }
571           $str = "<table summary=\"\" border=0>
572                     <tr>
573                       <td style='vertical-align:top'>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                         "<b>".date('d M Y',$timefrom)."</b>",
580                         "<b>".date('d M Y',$timeto)."</b>",
581                         $certificate->isvalid()?"<b><font style='color:green'>"._("valid")."</font></b>":
582                                                 "<b><font style='color:red'>"._("invalid")."</font></b>").$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("hash");
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);
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", $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,(!is_object($this->parent) && !session::is_set('edit'))));
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', 
654       preg_replace("/[^r]/i","", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit')))));
656     $smarty->assign("pwmode", $pwd_methods);
657     $smarty->assign("pwmode_select", $this->pw_storage);
658     $smarty->assign("pw_configurable", $is_configurable);
659     $smarty->assign("passwordStorageACL", $this->getacl("userPassword",(!is_object($this->parent) && !session::is_set('edit'))));
661     if(!session::is_set('edit')){
662       $smarty->assign("CertificatesACL","");
663     }else{
664       $smarty->assign("CertificatesACL",  $this->getacl("Certificate"));
665     }
666     
667     $smarty->assign("userPictureACL",   $this->getacl("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));
668     $smarty->assign("userPicture_is_readable",   $this->acl_is_readable("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));
670     /* Create base acls */
671     $smarty->assign("base", $this->baseSelector->render());
673     /* Save government mode attributes */
674     if($this->governmentmode){
675       $smarty->assign("governmentmode", "true");
676       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
677           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
678       $smarty->assign("ivbbmodes", $ivbbmodes);
679       foreach ($this->govattrs as $val){
680         $smarty->assign("$val", $this->$val);
681         $smarty->assign("$val"."ACL", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit'))));
682       }
683     } else {
684       $smarty->assign("governmentmode", "false");
685     }
687     /* Special mode for uid */
688     $uidACL= $this->getacl("uid",(!is_object($this->parent) && !session::is_set('edit')));
689     if (isset ($this->dn)){
690       if ($this->dn != "new"){
691         $uidACL= preg_replace("/w/","",$uidACL);
692       }
693     }  else {
694       $uidACL= preg_replace("/w/","",$uidACL);
695     }
696     
697     $smarty->assign("uidACL", $uidACL);
698     $smarty->assign("is_template", $this->is_template);
699     $smarty->assign("use_dob", $this->use_dob);
701     if (isset($this->parent)){
702       if (isset($this->parent->by_object['phoneAccount']) &&
703           $this->parent->by_object['phoneAccount']->is_account){
704         $smarty->assign("has_phoneaccount", "true");
705       } else {
706         $smarty->assign("has_phoneaccount", "false");
707       }
708     } else {
709       $smarty->assign("has_phoneaccount", "false");
710     }
711     $smarty->assign("multiple_support" , $this->multiple_support_active);
712     $smarty->assign("manager_name",$this->manager_name);
713     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
714   }
717   /* remove object from parent */
718   function remove_from_parent()
719   {
720     /* Only remove valid accounts */
721     if(!$this->initially_was_account) return;
723     /* Remove password extension */
724     $temp= passwordMethod::get_available_methods();
726     /* Remove password method from user account */
727     if(isset($temp[$this->pw_storage]) && class_available($temp[$this->pw_storage])){
728       $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
729       $this->pwObject->remove_from_parent();
730     }
732     /* Remove user */
733     $ldap= $this->config->get_ldap_link();
734     $ldap->rmdir ($this->dn);
735     if (!$ldap->success()){
736       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
737     }
738   
739     new log("remove","users/".get_class($this),$this->dn,$this->attributes,$ldap->get_error());
740   
741     /* Delete references to groups */
742     $ldap->cd ($this->config->current['BASE']);
743     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
744     while ($ldap->fetch()){
745       $g= new group($this->config, $ldap->getDN());
746       $g->removeUser($this->uid);
747       $g->save ();
748     }
750     /* Delete references to object groups */
751     $ldap->cd ($this->config->current['BASE']);
752     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
753     while ($ldap->fetch()){
754       $og= new ogroup($this->config, $ldap->getDN());
755       unset($og->member[$this->dn]);
756       $og->member= array_values($og->member);
757       $og->save ();
758     }
760     /* Delete references to roles */
761     $ldap->cd ($this->config->current['BASE']);
762     $ldap->search ("(&(objectClass=organizationalRole)(roleOccupant=".LDAP::prepare4filter($this->dn)."))", array("cn"));
763     while ($ldap->fetch()){
764       $role= new roleGeneric($this->config, $ldap->getDN());
765       $key = array_search($this->dn,$role->roleOccupant);
766       if($key !== FALSE){
767         unset($role->roleOccupant[$key]);
768         $role->roleOccupant= array_values($role->roleOccupant);
769         $role->save ();
770       }
771     }
773     /* If needed, let the password method do some cleanup */
774     $tmp = new passwordMethod($this->config);
775     $available = $tmp->get_available_methods();
776     if (in_array_ics($this->pw_storage, $available['name'])){
777       $test= new $available[$this->pw_storage]($this->config);
778       $test->attrs= $this->attrs;
779       $test->dn= $this->dn;
780       $test->remove_from_parent();
781     }
783     /* Remove ACL dependencies too */
784     acl::remove_acl_for($this->dn);
786     /* Optionally execute a command after we're done */
787     $this->handle_post_events("remove",array("uid" => $this->uid));
788   }
791   /* Save data to object */
792   function save_object()
793   {
794     if(isset($_POST['generic']) || isset($_POST['multiple_user_posted'])){
796       /* Make a backup of the current selected base */
797       $base_tmp = $this->base;
799       /* Parents save function */
800       plugin::save_object ();
802       /* Refresh base */
803       if ($this->acl_is_moveable($this->base)){
804         if (!$this->baseSelector->update()) {
805           msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
806         }
807         if ($this->base != $this->baseSelector->getBase()) {
808           $this->base= $this->baseSelector->getBase();
809           $this->is_modified= TRUE;
810         }
811       }
812       
813       /* Sync lists */
814       $this->gosaLoginRestrictionWidget->save_object();
815       if ($this->gosaLoginRestrictionWidget->isModified()) {
816         $this->gosaLoginRestriction= array_values($this->gosaLoginRestrictionWidget->getMaintainedData());
817       }
819       /* Save government mode attributes */
820       if ($this->governmentmode){
821         foreach ($this->govattrs as $val){
822           if ($this->acl_is_writeable($val,(!is_object($this->parent) && !session::is_set('edit'))) && isset($_POST["$val"])){
823             $data= stripcslashes($_POST["$val"]);
824             if ($data != $this->$val){
825               $this->is_modified= TRUE;
826             }
827             $this->$val= $data;
828           }
829         }
830       }
832       /* In template mode, the uid is autogenerated... */
833       if ($this->is_template){
834         $this->uid= strtolower($this->sn);
835         $this->givenName= $this->sn;
836       }
838       /* Get pw_storage mode */
839       if (isset($_POST['pw_storage'])){
840         foreach(array("pw_storage") as $val){
841           if(isset($_POST[$val])){
842             $data= validate($_POST[$val]);
843             if ($data != $this->$val){
844               $this->is_modified= TRUE;
845             }
846             $this->$val= $data;
847           }
848         }
849       }
851       if($this->pw_storage != $this->last_pw_storage && isset($_POST['pw_storage'])){
852         if ($this->acl_is_writeable("userPassword")){
853           $temp= passwordMethod::get_available_methods();
854           if (!is_object($this->pwObject) || !($this->pwObject instanceOf $temp[$this->pw_storage])){
855             foreach($temp as $id => $data){
856               if(isset($data['name']) && $data['name'] == $this->pw_storage && $data['is_configurable']){
857                 $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
858                 break;
859               }
860             }
861           }
862         }
863       }
865       /* Save current cn
866        */
867       $this->cn = $this->givenName." ".$this->sn;
868     }
869   }
871   function rebind($ldap, $referral)
872   {
873     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
874     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
875       $this->error = "Success";
876       $this->hascon=true;
877       $this->reconnect= true;
878       return (0);
879     } else {
880       $this->error = "Could not bind to " . $credentials['ADMIN'];
881       return NULL;
882     }
883   }
885   
886   /* Save data to LDAP, depending on is_account we save or delete */
887   function save()
888   {
889     global $lang;
891     /* Only force save of changes .... 
892        If this attributes aren't changed, avoid saving.
893      */
894   
895     if($this->gender=="0") $this->gender ="";
896     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
898     /* First use parents methods to do some basic fillup in $this->attrs */
899     plugin::save ();
901     if ($this->dateOfBirth != ""){
902       if(!is_array($this->attrs['dateOfBirth'])) {
903         #TODO: use $lang to convert date
904         list($day, $month, $year)= explode(".", $this->dateOfBirth);
905         $this->attrs['dateOfBirth'] = sprintf("%04d-%02d-%02d", $year, $month, $day);
906       }
907     }
909     /* Remove additional objectClasses */
910     $tmp= array();
911     foreach ($this->attrs['objectClass'] as $key => $set){
912       $found= false;
913       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
914         if (preg_match ("/^$set$/i", $val)){
915           $found= true;
916           break;
917         }
918       }
919       if (!$found){
920         $tmp[]= $set;
921       }
922     }
924     /* Replace the objectClass array. This is done because of the
925        separation into government and normal mode. */
926     $this->attrs['objectClass']= $tmp;
928     /* Add objectClasss for template mode? */
929     if ($this->is_template){
930       $this->attrs['objectClass'][]= "gosaUserTemplate";
931     }
933     /* Hard coded government mode? */
934     if ($this->governmentmode){
935       $this->attrs['objectClass'][]= "ivbbentry";
937       /* Copy standard attributes */
938       foreach ($this->govattrs as $val){
939         if ($this->$val != ""){
940           $this->attrs["$val"]= $this->$val;
941         } elseif (!$this->is_new) {
942           $this->attrs["$val"]= array();
943         }
944       }
946       /* Remove attribute if set to "nein" */
947       if ($this->publicVisible == "nein"){
948         $this->attrs['publicVisible']= array();
949         if($this->is_new){
950           unset($this->attrs['publicVisible']);
951         }else{
952           $this->attrs['publicVisible']=array();
953         }
955       }
957     }
959     /* Special handling for attribute userCertificate needed */
960     if ($this->userCertificate != ""){
961       $this->attrs["userCertificate;binary"]= $this->userCertificate;
962       $remove_userCertificate= false;
963     } else {
964       $remove_userCertificate= true;
965     }
967     /* Special handling for dateOfBirth value */
968     if ($this->dateOfBirth == ""){
969       if ($this->is_new) {
970         unset($this->attrs["dateOfBirth"]);
971       } else {
972         $this->attrs["dateOfBirth"]= array();
973       }
974     }
975     if (!$this->gender){
976       if ($this->is_new) {
977         unset($this->attrs["gender"]);
978       } else {
979         $this->attrs["gender"]= array();
980       }
981     }
982     if (!$this->preferredLanguage){
983       if ($this->is_new) {
984         unset($this->attrs["preferredLanguage"]);
985       } else {
986         $this->attrs["preferredLanguage"]= array();
987       }
988     }
990     /* Special handling for attribute jpegPhote needed, scale image via
991        image magick to 147x200 pixels and inject resulting data. */
992     if ($this->jpegPhoto == "*removed*"){
993     
994       /* Reset attribute to avoid writing *removed* as value */    
995       $this->attrs["jpegPhoto"] = array();
997     } else {
999       /* Fallback if there's no image magick inside PHP */
1000       if (!function_exists("imagick_blob2image")){
1001         /* Get temporary file name for conversation */
1002         $fname = tempnam (TEMP_DIR, "GOsa");
1003   
1004         /* Open file and write out photoData */
1005         $fp = fopen ($fname, "w");
1006         fwrite ($fp, $this->photoData);
1007         fclose ($fp);
1009         /* Build conversation query. Filename is generated automatically, so
1010            we do not need any special security checks. Exec command and save
1011            output. For PHP safe mode, you'll need a configuration which respects
1012            image magick as executable... */
1013         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
1014         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
1015             $query, "Execute");
1016   
1017         /* Read data written by convert */
1018         $output= "";
1019         $sh= popen($query, 'r');
1020         while (!feof($sh)){
1021           $output.= fread($sh, 4096);
1022         }
1023         pclose($sh);
1025         unlink($fname);
1027         /* Save attribute */
1028         $this->attrs["jpegPhoto"] = $output;
1030       } else {
1032         /* Load the new uploaded Photo */
1033         if(!$handle  =  imagick_blob2image($this->photoData))  {
1034           new log("debug","users/".get_class($this),$this->dn,array(),"Could not access uploaded image");
1035         }
1037         /* Resizing image to 147x200 and blur */
1038         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
1039           new log("debug","users/".get_class($this),$this->dn,array(),"Could not resize uploaded image");
1040         }
1042         /* Converting image to JPEG */
1043         if(!imagick_convert($handle,"JPEG")) {
1044           new log("debug","users/".get_class($this),$this->dn,array(),"Could not convert uploaded image to jepg");
1045         }
1047         /* Creating binary Code for the Image */
1048         if(!$dump = imagick_image2blob($handle)){
1049           new log("debug","users/".get_class($this),$this->dn,array(),"Could not create new user image");
1050         }
1052         /* Sending Image */
1053         $output=  $dump;
1055         /* Save attribute */
1056         $this->attrs["jpegPhoto"] = $output;
1057       }
1059     }
1061     /* This only gets called when user is renaming himself */
1062     $ldap= $this->config->get_ldap_link();
1063     if ($this->dn != $this->new_dn){
1065       /* Write entry on new 'dn' */
1066       $this->update_acls($this->dn,$this->new_dn);
1067       $this->move($this->dn, $this->new_dn);
1069       /* Happen to use the new one */
1070       change_ui_dn($this->dn, $this->new_dn);
1071       $this->dn= $this->new_dn;
1072     }
1075     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
1076        new entries. So do a check first... */
1077     $ldap->cat ($this->dn, array('dn'));
1078     if ($ldap->fetch()){
1079       $mode= "modify";
1080     } else {
1081       $mode= "add";
1082       $ldap->cd($this->config->current['BASE']);
1083       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
1084     }
1086     /* Set password to some junk stuff in case of templates */
1087     if ($this->is_template){
1088       $temp= passwordMethod::get_available_methods();
1089       foreach($temp as $id => $data){
1090         if(isset($data['name']) && $data['name'] == $this->pw_storage){
1091           $tmp = new  $temp[$this->pw_storage]($this->config,$this->dn);
1092           $tmp->set_hash($this->pw_storage);
1093           $this->attrs['userPassword'] = $tmp->create_template_hash($this->attrs);
1094           break;
1095         }
1096       }
1097     }
1099     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
1100         $this->attributes, "Save via $mode");
1102     /* Finally write data with selected 'mode' */
1103     $this->cleanup();
1105     /* Update current locale settings, if we have edited ourselves */
1106     $ui = session::get('ui');
1107     if(isset($this->attrs['preferredLanguage']) && $this->dn == $ui->dn){
1108       $ui->language = $this->preferredLanguage;
1109       session::set('ui',$ui);
1110       session::set('Last_init_lang',"update");
1111     }
1113     $ldap->cd ($this->dn);
1114     $ldap->$mode ($this->attrs);
1115     if (!$ldap->success()){
1116       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
1117       return (1);
1118     }
1120     /* Remove ACL dependencies too */
1121     if($this->dn != $this->orig_dn && $this->orig_dn != "new"){
1122       $tmp = new acl($this->config,$this->parent,$this->dn);
1123       $tmp->update_acl_membership($this->orig_dn,$this->dn);
1124     }
1126     if($mode == "modify"){
1127       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1128     }else{
1129       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1130     }
1132     /* Remove cert? 
1133        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
1134        to work around myself. */
1135     if ($remove_userCertificate == true && !$this->is_new && $this->had_userCertificate){
1137       /* Reset array, assemble new, this should be reworked */
1138       $this->attrs= array();
1139       $this->attrs['userCertificate;binary']= array();
1141       /* Prepare connection */
1142       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
1143         die ("Could not connect to LDAP server");
1144       }
1145       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1146       if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true") {
1147         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1148         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1149       }
1150       if($this->config->get_cfg_value("ldapTLS") == "true"){
1151         ldap_start_tls($ds);
1152       }
1153       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
1154               $this->config->current['PASSWORD']))) {
1155         die ("Could not bind to LDAP");
1156       }
1158       /* Modify using attrs */
1159       ldap_mod_del($ds,$this->dn,$this->attrs);
1160       ldap_close($ds);
1161     }
1163     /* If needed, let the password method do some cleanup */
1164     if ($this->pw_storage != $this->last_pw_storage){
1165       $tmp = new passwordMethod($this->config);
1166       $available = $tmp->get_available_methods();
1167       if (in_array_ics($this->last_pw_storage, $available['name'])){
1168         $test= new $available[$this->last_pw_storage]($this->config,$this->dn);
1169         $test->attrs= $this->attrs;
1170         $test->remove_from_parent();
1171       }
1172     }
1174     /* Maybe the current password method want's to do some changes... */
1175     if (is_object($this->pwObject)){
1176       $this->pwObject->save($this->dn);
1177     }
1179     /* Optionally execute a command after we're done */
1180     if ($mode == "add"){
1181       $this->handle_post_events("add", array("uid" => $this->uid));
1182     } elseif ($this->is_modified){
1183       $this->handle_post_events("modify", array("uid" => $this->uid));
1184     }
1186     return (0);
1187   }
1190   function create_initial_rdn($pattern)
1191   {
1192     // Only generate single RDNs
1193     if (preg_match('/\+/', $pattern)){
1194       msg_dialog::display(_("Error"), _("Cannot build RDN: no + allowed to build sub RDN!"), ERROR_DIALOG);
1195       return "";
1196     }
1198     // Extract attribute
1199     $attribute= preg_replace('/=.*$/', '', $pattern);
1200     if (!in_array_ics($attribute, $this->attributes)) {
1201       msg_dialog::display(_("Error"), _("Cannot build RDN: attribute is not defined!"), ERROR_DIALOG);
1202       return "";
1203     }
1205     // Sort attributes for length
1206     $attrl= array();
1207     foreach ($this->attributes as $attr) {
1208       $attrl[$attr]= strlen($attr);
1209     }
1210     arsort($attrl);
1211     
1212     // Walk thru sorted attributes and replace them in pattern
1213     foreach ($attrl as $attr => $dummy) {
1214       if (!is_array($this->$attr)){
1215         $pattern= preg_replace("/%$attr/", $this->$attr, $pattern);
1216       } else {
1217         // Array elements cannot be used for ID generation
1218         if (preg_match("/%$attr/", $pattern)) {
1219           msg_dialog::display(_("Error"), _("Cannot build RDN: invalid attribute parameters!"), ERROR_DIALOG);
1220           break;
1221         }
1222       }
1223     }
1225     // Internally assign value
1226     $this->$attribute= preg_replace('/^[^=]+=/', '', $pattern);
1228     return $pattern;
1229   }
1231   
1232   function update_new_dn()
1233   {
1234     // Alternative way to handle DN
1235     $pattern= $this->config->get_cfg_value("accountRDN");
1236     if ($pattern != "") {
1237       $rdn= $this->create_initial_rdn($pattern);
1238       $attribute= preg_replace('/=.*$/', '', $rdn);
1239       $value= preg_replace('/^[^=]+=$/', '', $rdn);
1241       /* Don't touch dn, if $attribute hasn't changed */
1242       if (isset($this->saved_attributes[$attribute]) && $this->saved_attributes[$attribute] == $this->$attribute &&
1243             $this->orig_base == $this->base ){
1244         $this->new_dn= $this->dn;
1245       } else {
1246         $this->new_dn= $this->create_unique_dn2($rdn, get_people_ou().$this->base);
1247       }
1249     // Original way to handle DN
1250     } else {
1252       $pt= "";
1253       if($this->config->get_cfg_value("personalTitleInDN") == "true"){
1254         if(!empty($this->personalTitle)){
1255           $pt = $this->personalTitle." ";
1256         }
1257       }
1259       $this->cn= $pt.$this->givenName." ".$this->sn;
1261       /* Permissions for that base? */
1262       if ($this->config->get_cfg_value("accountPrimaryAttribute") == "uid"){
1263         $this->new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
1264       } else {
1265         /* Don't touch dn, if cn hasn't changed */
1266         if (isset($this->saved_attributes['cn']) && $this->saved_attributes['cn'] == $this->cn &&
1267             $this->orig_base == $this->base ){
1268           $this->new_dn= $this->dn;
1269         } else {
1270           $this->new_dn= $this->create_unique_dn('cn', get_people_ou().$this->base);
1271         }
1272       }
1273     }
1274   }
1275   
1277   /* Check formular input */
1278   function check()
1279   {
1280     /* Call common method to give check the hook */
1281     $message= plugin::check();
1283     /* Configurable password methods should be configured initially. 
1284      */ 
1285     if($this->last_pw_storage != $this->pw_storage){
1286       $temp= passwordMethod::get_available_methods();
1287       foreach($temp['name'] as $id => $name){
1288         if($name == $this->pw_storage){
1289           if($temp['is_configurable'][$id] && !$this->pwObject instanceof $temp[$name] ){
1290             $message[] = _("The selected password method requires initial configuration!");
1291           }
1292           break;
1293         }
1294       }
1295     }
1297     $this->update_new_dn();
1299     /* Set the new acl base */
1300     if($this->dn == "new") {
1301       $this->set_acl_base($this->base);
1302     }
1304     /* Check if we are allowed to create/move this user */
1305     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
1306       $message[]= msgPool::permCreate();
1307     }elseif($this->orig_dn != "new" && $this->new_dn != $this->orig_dn && !$this->acl_is_moveable($this->base)){
1308       $message[]= msgPool::permMove();
1309     }
1311     /* UID already used? */
1312     $ldap= $this->config->get_ldap_link();
1313     $ldap->cd($this->config->current['BASE']);
1314     $ldap->search("(uid=$this->uid)", array("uid"));
1315     $ldap->fetch();
1316     if ($ldap->count() != 0 && $this->dn == 'new'){
1317       $message[]= msgPool::duplicated(_("Login"));
1318     }
1320     /* In template mode, the uid and givenName are autogenerated... */
1321     if ($this->sn == ""){
1322       $message[]= msgPool::required(_("Name"));
1323     }
1325     // Check if a wrong base was supplied
1326     if(!$this->baseSelector->checkLastBaseUpdate()){
1327       $message[]= msgPool::check_base();;
1328     }
1330     if (!$this->is_template){
1331       if ($this->givenName == ""){
1332         $message[]= msgPool::required(_("Given name"));
1333       }
1334       if ($this->uid == ""){
1335         $message[]= msgPool::required(_("Login"));
1336       }
1337       if ($this->config->get_cfg_value("accountPrimaryAttribute") != "uid"){
1338         $ldap->cat($this->new_dn);
1339         if ($ldap->count() != 0 && $this->dn != $this->new_dn && $this->dn == 'new'){
1340           $message[]= msgPool::duplicated(_("Name"));
1341         }
1342       }
1343     }
1345     /* Check for valid input */
1346     if ($this->is_modified && !tests::is_uid($this->uid)){
1348       if (strict_uid_mode()){
1349         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/");
1350       } else {
1351         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/i");
1352       }
1353     }
1354     if (!tests::is_url($this->labeledURI)){
1355       $message[]= msgPool::invalid(_("Homepage"), "", "", "http://www.your-domain.com/yourname");
1356     }
1358     /* Check phone numbers */
1359     if (!tests::is_phone_nr($this->telephoneNumber)){
1360       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1361     }
1362     if (!tests::is_phone_nr($this->facsimileTelephoneNumber)){
1363       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1364     }
1365     if (!tests::is_phone_nr($this->mobile)){
1366       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1367     }
1368     if (!tests::is_phone_nr($this->pager)){
1369       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1370     }
1372     /* Check dates */
1373     if (!tests::is_date($this->dateOfBirth)){
1374       $message[]= msgPool::invalid(_("Date of birth"), $this->dateOfBirth,"" ,"23.02.2009");
1375     }
1377     /* Check for reserved characers */
1378     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName)){
1379       $message[]= msgPool::invalid(_("Given name"), $this->givenName, '/[^,+"?\'()=<>;\\\\]/');
1380     }
1381     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn)){
1382       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1383     }
1385     return $message;
1386   }
1389   /* Indicate whether a password change is needed or not */
1390   function password_change_needed()
1391   {
1392     if(in_array("pw_storage",$this->multi_boxes)){
1393       return(TRUE);
1394     }
1395     return($this->pw_storage != $this->last_pw_storage && !$this->is_template);
1396   }
1399   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1400   function load_picture()
1401   {
1402     $ldap = $this->config->get_ldap_link();
1403     $ldap->cd ($this->dn);
1404     $data = $ldap->get_attribute($this->dn,"jpegPhoto");
1406     if((!$data) || ($data == "*removed*")){ 
1408       /* In case we don't get an entry, load a default picture */
1409       $this->set_picture ();
1410       $this->jpegPhoto= "*removed*";
1411     }else{
1413       /* Set picture */
1414       $this->photoData= $data;
1415       session::set('binary',$this->photoData);
1416       session::set('binarytype',"image/jpeg");
1417       $this->jpegPhoto= "";
1418     }
1419   }
1422   /* Load a certificate from LDAP, this is going to be simplified later on */
1423   function load_cert()
1424   {
1425     $ds= ldap_connect($this->config->current['SERVER']);
1426     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1427     if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true"){
1428       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1429       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1430     }
1431     if ($this->config->get_cfg_value("ldapTLS") == "true"){
1432       ldap_start_tls($ds);
1433     }
1435     $r= ldap_bind($ds);
1436     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1438     if ($sr) {
1439       $ei= @ldap_first_entry($ds, $sr);
1440       
1441       if ($ei) {
1442         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1443           $this->userCertificate= "";
1444         } else {
1445           $this->userCertificate= $info[0];
1446         }
1447       }
1448     } else {
1449       $this->userCertificate= "";
1450     }
1452     ldap_unbind($ds);
1453   }
1456   /* Load picture from file to object */
1457   function set_picture($filename ="")
1458   {
1459     if (!is_file($filename) || $filename =="" ){
1460       $filename= "./plugins/users/images/default.jpg";
1461       $this->jpegPhoto= "*removed*";
1462     }
1464     $fd = fopen ($filename, "rb");
1465     $this->photoData= fread ($fd, filesize ($filename));
1466     session::set('binary',$this->photoData);
1467     session::set('binarytype',"image/jpeg");
1468     $this->jpegPhoto= "";
1470     fclose ($fd);
1471   }
1474   /* Load certificate from file to object */
1475   function set_cert($cert, $filename)
1476   {
1477     if(!$this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))) return;
1478     $fd = fopen ($filename, "rb");
1479     if (filesize($filename)>0) {
1480       $this->$cert= fread ($fd, filesize ($filename));
1481       fclose ($fd);
1482       $this->is_modified= TRUE;
1483     } else {
1484       msg_dialog::display(_("Error"), _("Cannot open certificate!"), ERROR_DIALOG);
1485     }
1486   }
1488   /* Adapt from given 'dn' */
1489   function adapt_from_template($dn, $skip= array())
1490   {
1491     plugin::adapt_from_template($dn, $skip);
1493     /* Get password method from template 
1494      */
1495     $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
1496     if(is_object($tmp)){
1497       if($tmp->is_configurable()){
1498         $tmp->adapt_from_template($dn);
1499         $this->pwObject = &$tmp;
1500       }
1501       $this->pw_storage= $tmp->get_hash();
1502     }
1504     /* Get base */
1505     $this->base= preg_replace('/^[^,]+,'.preg_quote(get_people_ou(), '/').'/i', '', $dn);
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     if ($this->dateOfBirth) {
1541       /* This entry is ISO 8601 conform */
1542       list($year, $month, $day)= explode("-", $this->dateOfBirth, 3);
1543     
1544       #TODO: use $lang to convert date
1545       $this->dateOfBirth= "$day.$month.$year";
1546     }
1547   }
1549  
1550   /* This avoids that users move themselves out of their rights. 
1551    */
1552   function allowedBasesToMoveTo()
1553   {
1554     /* Get bases */
1555     $bases  = $this->get_allowed_bases();
1556     return($bases);
1557   } 
1560   function getCopyDialog()
1561   {
1562     $str = "";
1564     session::set('binary',$this->photoData); 
1565     session::set('binarytype',"image/jpeg");
1567     /* Get random number for pictures */
1568     srand((double)microtime()*1000000); 
1569     $rand = rand(0, 10000);
1571     $smarty = get_smarty();
1573     $smarty->assign("passwordTodo","clear");
1575     if(isset($_POST['passwordTodo'])){
1576       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1577     }
1579     $smarty->assign("sn",       $this->sn);
1580     $smarty->assign("givenName",$this->givenName);
1581     $smarty->assign("uid",      $this->uid);
1582     $smarty->assign("rand",     $rand);
1583     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1586     $ret = array();
1587     $ret['string'] = $str;
1588     $ret['status'] = "";  
1589     return($ret);
1590   }
1592   function saveCopyDialog()
1593   {
1594     /* Set_acl_base */
1595     $this->set_acl_base($this->base);
1597     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1598       $this->set_picture($_FILES['picture_file']['tmp_name']);
1599     }
1601     /* Remove picture? */
1602     if (isset($_POST['picture_remove'])){
1603       $this->jpegPhoto= "*removed*";
1604       $this->set_picture ("./plugins/users/images/default.jpg");
1605       $this->is_modified= TRUE;
1606     }
1608     $attrs = array("uid","givenName","sn");
1609     foreach($attrs as $attr){
1610       if(isset($_POST[$attr])){
1611         $this->$attr = $_POST[$attr];
1612       }
1613     } 
1614   }
1617   function PrepareForCopyPaste($source)
1618   {
1619     plugin::PrepareForCopyPaste($source);
1621     /* Reset certificate information addepted from source user
1622        to avoid setting the same user certificate for the destination user. */
1623     $this->userPKCS12= "";
1624     $this->userSMIMECertificate= "";
1625     $this->userCertificate= "";
1626     $this->certificateSerialNumber= "";
1627     $this->old_certificateSerialNumber= "";
1628     $this->old_userPKCS12= "";
1629     $this->old_userSMIMECertificate= "";
1630     $this->old_userCertificate= "";
1631   }
1634   static function plInfo()
1635   {
1636   
1637     $govattrs= array(
1638         "gouvernmentOrganizationalUnit"             =>  _("Unit"), 
1639         "houseIdentifier"                           =>  _("House identifier"), 
1640         "vocation"                                  =>  _("Vocation"),
1641         "ivbbLastDeliveryCollective"                =>  _("Last delivery"), 
1642         "gouvernmentOrganizationalPersonLocality"   =>  _("Person locality"),
1643         "gouvernmentOrganizationalUnitDescription"  =>  _("Unit description"),
1644         "gouvernmentOrganizationalUnitSubjectArea"  =>  _("Subject area"),
1645         "functionalTitle"                           =>  _("Functional title"),
1646         "certificateSerialNumber"                   =>  _("Certificate serial number"),
1647         "publicVisible"                             =>  _("Public visible"),
1648         "street"                                    =>  _("Street"),
1649         "role"                                      =>  _("Role"),
1650         "postalCode"                                =>  _("Postal code"));
1652     $ret = array(
1653         "plShortName" => _("Generic"),
1654         "plDescription" => _("Generic user settings"),
1655         "plSelfModify"  => TRUE,
1656         "plDepends"     => array(),
1657         "plPriority"    => 1,
1658         "plSection"     => array("personal" => _("My account")),
1659         "plCategory"    => array("users" => array("description" => _("Users"),
1660                                                   "objectClass" => "gosaAccount")),
1662         "plProvidedAcls" => array(
1664           "sn"                => _("Surname"),
1665           "givenName"         => _("Given name"),
1666           "uid"               => _("User identification"),
1667           "personalTitle"     => _("Personal title"),
1668           "academicTitle"     => _("Academic title"),
1670           "dateOfBirth"       => _("Date of birth"),
1671           "gender"            => _("Sex"),
1672           "preferredLanguage" => _("Preferred language"),
1673           "base"              => _("Base"), 
1675           "userPicture"       => _("User picture"),
1677           "gosaLoginRestriction" => _("Login restrictions"),         
1679           "o"                 => _("Organization"),
1680           "ou"                => _("Department"),
1681           "departmentNumber"  => _("Department number"),
1682           "manager"           => _("Manager"),
1683           "employeeNumber"    => _("Employee number"),
1684           "employeeType"      => _("Employee type"),
1686           "roomNumber"        => _("Room number"),
1687           "telephoneNumber"   => _("Telefon number"),
1688           "pager"             => _("Pager number"),
1689           "mobile"            => _("Mobile number"),
1690           "facsimileTelephoneNumber"     => _("Fax number"),
1692           "st"                => _("State"),
1693           "l"                 => _("Location"),
1694           "postalAddress"     => _("Postal address"),
1696           "homePostalAddress" => _("Home postal address"),
1697           "homePhone"         => _("Home phone number"),
1698           "labeledURI"        => _("Homepage"),
1699           "userPassword"      => _("User password method"), 
1700           "Certificate"       => _("User certificates"))
1702         );
1704     /* Append government attributes if required */
1705     global $config;
1706     if($config->get_cfg_value("honourIvbbAttributes") == "true"){
1707       foreach($govattrs as $attr => $desc){
1708         $ret["plProvidedAcls"][$attr] = $desc;
1709       }
1710     }
1711     return($ret);
1712   }
1714   function get_multi_edit_values()
1715   {
1716     $ret = plugin::get_multi_edit_values();
1717     if(in_array("pw_storage",$this->multi_boxes)){
1718       $ret['pw_storage'] = $this->pw_storage;
1719     }
1720     if(in_array("edit_picture",$this->multi_boxes)){
1721       $ret['jpegPhoto'] = $this->jpegPhoto;
1722       $ret['photoData'] = $this->photoData;
1723       $ret['old_jpegPhoto'] = $this->old_jpegPhoto;
1724       $ret['old_photoData'] = $this->old_photoData;
1725     }
1726     if(isset($ret['dateOfBirth'])){
1727       unset($ret['dateOfBirth']);
1728     }
1729     if(isset($ret['cn'])){
1730       unset($ret['cn']);
1731     }
1732     $ret['is_modified'] = $this->is_modified;
1733     if(in_array("base",$this->multi_boxes)){
1734       $ret['orig_base']="Changed_by_Multi_Plug";
1735       $ret['base']=$this->base;
1736     }
1738     $ret['gosaLoginRestriction'] = $this->gosaLoginRestriction;
1739     $ret['gosaLoginRestriction_some'] = $this->gosaLoginRestriction_some;
1741     return($ret); 
1742   }
1745   function multiple_save_object()
1746   {
1748     if(!isset($_POST['user_mulitple_edit'])) return;
1750     plugin::multiple_save_object();
1752     /* Get pw_storage mode */
1753     if (isset($_POST['pw_storage'])){
1754       foreach(array("pw_storage") as $val){
1755         if(isset($_POST[$val])){
1756           $data= validate(get_post($val));
1757           if ($data != $this->$val){
1758             $this->is_modified= TRUE;
1759           }
1760           $this->$val= $data;
1761         }
1762       }
1763     }
1764   
1765     /* Refresh base */
1766     if ($this->acl_is_moveable($this->base)){
1767       if (!$this->baseSelector->update()) {
1768         msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
1769       }
1770       if ($this->base != $this->baseSelector->getBase()) {
1771         $this->base= $this->baseSelector->getBase();
1772       }
1773     }
1775     if(isset($_POST['user_mulitple_edit'])){
1776       foreach(array("base","pw_storage","edit_picture") as $val){
1777         if(isset($_POST["use_".$val])){
1778           $this->multi_boxes[] = $val;
1779         }
1780       }
1781     }
1783     /* Sync lists */
1784     $this->gosaLoginRestrictionWidget->save_object();
1785     if ($this->gosaLoginRestrictionWidget->isModified()) {
1786       $this->gosaLoginRestriction= array_values($this->gosaLoginRestrictionWidget->getMaintainedData());
1787     }
1788   }
1790   
1791   function multiple_check()
1792   {
1793     /* Call check() to set new_dn correctly ... */
1794     $message = plugin::multiple_check();
1796     /* Set the new acl base */
1797     if($this->dn == "new") {
1798       $this->set_acl_base($this->base);
1799     }
1800     if (!tests::is_url($this->labeledURI) && in_array("labeledURI",$this->multi_boxes)){
1801       $message[]= msgPool::invalid(_("Homepage"));
1802     }
1803     if (!tests::is_phone_nr($this->telephoneNumber) && in_array("telephoneNumber",$this->multi_boxes)){
1804       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1805     }
1806     if (!tests::is_phone_nr($this->facsimileTelephoneNumber) &&  in_array("facsimileTelephoneNumber",$this->multi_boxes)){
1807       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1808     }
1809     if (!tests::is_phone_nr($this->mobile) && in_array("mobile",$this->multi_boxes)){
1810       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1811     }
1812     if (!tests::is_phone_nr($this->pager) && in_array("pager",$this->multi_boxes)){
1813       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1814     }
1815     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName) && in_array("givenName",$this->multi_boxes)){
1816       $message[]= msgPool::invalid(_("Given name"), $this->giveName, '/[^,+"?\'()=<>;\\\\]/');
1817     }
1818     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn) && in_array("sn",$this->multi_boxes)){
1819       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1820     }
1821     return($message);
1822   }
1826   function multiple_execute()
1827   {
1828     return($this->execute());
1829   }
1832   /*! \brief  Prepares the plugin to be used for multiple edit
1833    *          Update plugin attributes with given array of attribtues.
1834    *  \param  array   Array with attributes that must be updated.
1835    */
1836   function init_multiple_support($attrs,$all)
1837   {
1838     plugin::init_multiple_support($attrs,$all);
1840     // Get login restrictions
1841     if(isset($attrs['gosaLoginRestriction'])){
1842       $this->gosaLoginRestriction  =array();
1843       for($i =0;$i < $attrs['gosaLoginRestriction']['count']; $i++){
1844         $this->gosaLoginRestriction[] = $attrs['gosaLoginRestriction'][$i];
1845       }
1846     }
1848     // Detect the managers name
1849     $this->manager_name = "";
1850     $ldap = $this->config->get_ldap_link();
1851     if(!empty($this->manager)){
1852       $ldap->cat($this->manager, array('cn'));
1853       if($ldap->count()){
1854         $attrs = $ldap->fetch();
1855         $this->manager_name = $attrs['cn'][0];
1856       }else{
1857         $this->manager_name = "("._("Unknown")."!): ".$this->manager;
1858       }
1859     }
1861     // Detect login restriction not used in all user objects.
1862     $this->gosaLoginRestriction_some = array();
1863     if(isset($all['gosaLoginRestriction'])){
1864       for($i=0;$i<$all['gosaLoginRestriction']['count'];$i++){
1865         $this->gosaLoginRestriction_some[] = $all['gosaLoginRestriction'][$i];
1866       }
1867     }
1870     // Reinit the login restriction list.
1871     $data = $this->convertLoginRestriction();
1872     if(count($data)){
1873       $this->gosaLoginRestrictionWidget->setListData($data['data'], $data['displayData']);
1874     }
1875   }
1878   function set_multi_edit_values($attrs)
1879   {
1880     $lR = array();
1882     // Update loginRestrictions, keep my settings while ip is optional
1883     foreach($attrs['gosaLoginRestriction_some'] as $ip){
1884       if(in_array($ip, $this->gosaLoginRestriction) && in_array($ip, $attrs['gosaLoginRestriction'])){
1885         $lR[] = $ip;
1886       }
1887     }
1889     // Add enforced loginRestrictions 
1890     foreach($attrs['gosaLoginRestriction'] as $ip){
1891       $lR[] = $ip;
1892     }
1894     $lR = array_values(array_unique($lR));
1895     $this->is_modified |=  array_differs($this->gosaLoginRestriction, $lR);
1896     plugin::set_multi_edit_values($attrs);
1897     $this->gosaLoginRestriction = $lR;
1898   }
1901   function convertLoginRestriction()
1902   {
1903     $all = array_unique(array_merge($this->gosaLoginRestriction,$this->gosaLoginRestriction_some));
1904     $data = array();
1905     foreach($all as $ip){
1906       $data['data'][] = $ip;
1907       if(!in_array($ip, $this->gosaLoginRestriction)){
1908         $data['displayData'][] = array('mode' => LIST_MARKED , 'data' => array($ip.' ('._("Entries differ").')'));
1909       }else{
1910         $data['displayData'][] = array('mode' => 0 , 'data' => array($ip));
1911       }
1912     }   
1913     return($data);
1914   }
1917 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1918 ?>