Code

Updated user plugin capabilities
[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   /* attribute list for save action */
112   var $attributes= array("sn", "givenName", "uid", "personalTitle", "academicTitle",
113       "homePostalAddress", "homePhone", "labeledURI", "ou", "o", "dateOfBirth", "gender","preferredLanguage",
114       "departmentNumber", "employeeNumber", "employeeType", "l", "st","jpegPhoto",
115       "roomNumber", "telephoneNumber", "mobile", "pager", "cn", "userPKCS12",
116       "postalAddress", "facsimileTelephoneNumber", "userSMIMECertificate", "gosaLoginRestriction");
118   var $objectclasses= array("top", "person", "organizationalPerson", "inetOrgPerson",
119       "gosaAccount");
121   /* attributes that are part of the government mode */
122   var $govattrs= array("gouvernmentOrganizationalUnit", "houseIdentifier", "vocation",
123       "ivbbLastDeliveryCollective", "gouvernmentOrganizationalPersonLocality",
124       "gouvernmentOrganizationalUnitDescription","gouvernmentOrganizationalUnitSubjectArea",
125       "functionalTitle", "certificateSerialNumber", "publicVisible", "street", "role",
126       "postalCode");
128   var $multiple_support = TRUE;
130   var $governmentmode = FALSE;
132   /* constructor, if 'dn' is set, the node loads the given
133      'dn' from LDAP */
134   function user (&$config, $dn= NULL)
135   {
136     global $lang;
138     $this->config= $config;
139     /* Configuration is fine, allways */
140     if($this->config->get_cfg_value("honourIvbbAttributes") == "true"){
141       $this->governmentmode = TRUE;
142       $this->attributes=array_merge($this->attributes,$this->govattrs);
143     }
145     /* Load base attributes */
146     plugin::plugin ($config, $dn);
148     $this->orig_dn  = $this->dn;
149     $this->new_dn   = $dn;
151     if ($this->governmentmode){
152       /* Fix public visible attribute if unset */
153       if (!isset($this->attrs['publicVisible'])){
154         $this->publicVisible == "nein";
155       }
156     }
158     /* Load government mode attributes */
159     if ($this->governmentmode){
160       /* Copy all attributs */
161       foreach ($this->govattrs as $val){
162         if (isset($this->attrs["$val"][0])){
163           $this->$val= $this->attrs["$val"][0];
164         }
165       }
166     }
168     /* Create me for new accounts */
169     if ($dn == "new"){
170       $this->is_account= TRUE;
171     }
173     /* Make hash default to md5 if not set in config */
174     $hash= $this->config->get_cfg_value("passwordDefaultHash", "crypt/md5");
176     /* Load data from LDAP? */
177     if ($dn !== NULL){
179       /* Do base conversation */
180       if ($this->dn == "new"){
181         $ui= get_userinfo();
182         $this->base= dn2base(session::global_is_set("CurrentMainBase")?"cn=dummy,".session::global_get("CurrentMainBase"):$ui->dn);
183       } else {
184         $this->base= dn2base($dn);
185       }
187       /* get password storage type */
188       if (isset ($this->attrs['userPassword'][0])){
189         /* Initialize local array */
190         $matches= array();
191         if (preg_match ("/^{[^}]+}/", $this->attrs['userPassword'][0])){
192           $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
193           if(is_object($tmp)){
194             $this->pw_storage= $tmp->get_hash(); 
195           }
197         } else {
198           if ($this->attrs['userPassword'][0] != ""){
199             $this->pw_storage= "clear";
200           } else {
201             $this->pw_storage= $hash;
202           }
203         }
204       } else {
205         /* Preset with vaule from configuration */
206         $this->pw_storage= $hash;
207       }
209       /* Load extra attributes: certificate and picture */
210       $this->load_cert();
211       $this->load_picture();
212       if ($this->userCertificate != ""){
213         $this->had_userCertificate= TRUE;
214       }
215     }
217     /* Reset password storage indicator, used by password_change_needed() */
218     if ($dn == "new"){
219       $this->last_pw_storage= "unset";
220     } else {
221       $this->last_pw_storage= $this->pw_storage;
222     }
224     /* Generate dateOfBirth entry */
225     if (isset ($this->attrs['dateOfBirth'])){
226       /* This entry is ISO 8601 conform */
227       list($year, $month, $day)= explode("-", $this->attrs['dateOfBirth'][0], 3);
228     
229       #TODO: use $lang to convert date
230       $this->dateOfBirth= "$day.$month.$year";
231     } else {
232       $this->dateOfBirth= "";
233     }
235     /* Put gender attribute to upper case */
236     if (isset ($this->attrs['gender'])){
237       $this->gender= strtoupper($this->attrs['gender'][0]);
238     }
240     // Get login restrictions
241     if(isset($this->attrs['gosaLoginRestriction'])){
242       $this->gosaLoginRestriction  =array();
243       for($i =0;$i < $this->attrs['gosaLoginRestriction']['count']; $i++){
244         $this->gosaLoginRestriction[] = $this->attrs['gosaLoginRestriction'][$i];
245       }
246     }
247     $this->gosaLoginRestrictionWidget= new sortableListing($this->gosaLoginRestriction);
248     $this->gosaLoginRestrictionWidget->setDeleteable(true);
249     $this->gosaLoginRestrictionWidget->setColspecs(array('*'));
250     $this->gosaLoginRestrictionWidget->setWidth("100%");
251     $this->gosaLoginRestrictionWidget->setHeight("70px");
252  
253     $this->orig_base = $this->base;
254     $this->baseSelector= new baseSelector($this->allowedBasesToMoveTo(), $this->base);
255     $this->baseSelector->setSubmitButton(false);
256     $this->baseSelector->setHeight(300);
257     $this->baseSelector->update(true);
258   }
261   /* execute generates the html output for this node */
262   function execute()
263   {
264     /* Call parent execute */
265     plugin::execute();
267     /* Set list ACL */
268     $this->gosaLoginRestrictionWidget->setAcl($this->getacl('gosaLoginRestriction', (!is_object($this->parent) && !session::is_set('edit'))));
269     $this->gosaLoginRestrictionWidget->update();
271     /* Handle add/delete for restriction mode */
272     if (isset($_POST['add_res']) && isset($_POST['res'])) {
273       $val= validate($_POST['res']);
274       if (preg_match('/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/', $val) ||
275           preg_match('/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\/([0-9]+)$/', $val) ||
276           preg_match('/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\/([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$/', $val)) {
277         $this->gosaLoginRestrictionWidget->addEntry($val);
278       } else {
279         msg_dialog::display(_("Error"), _("Please add a single IP address or a network/netmask combination!"), ERROR_DIALOG);
280       }
281     }
283     /* Log view */
284     if($this->is_account && !$this->view_logged){
285       $this->view_logged = TRUE;
286       new log("view","users/".get_class($this),$this->dn);
287     }
289     $smarty= get_smarty();
290     $smarty->assign("usePrototype", "true");
291     $smarty->assign("gosaLoginRestrictionWidget", $this->gosaLoginRestrictionWidget->render());
293     /* Assign sex */
294     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
295     $smarty->assign("gender_list", $sex);
296     $language= array_merge(array(0 => "&nbsp;") ,get_languages(TRUE));
297     $smarty->assign("preferredLanguage_list", $language);
299     /* Get random number for pictures */
300     srand((double)microtime()*1000000); 
301     $smarty->assign("rand", rand(0, 10000));
304     /* Do we represent a valid gosaAccount? */
305     if (!$this->is_account){
306       $str = "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
307         msgPool::noValidExtension("GOsa")."</b>";
308       return($str);
309     }
311     /* Password configure dialog handling */
312     if(is_object($this->pwObject) && $this->pwObject->display){
313       $output= $this->pwObject->configure();
314       if ($output != ""){
315         $this->dialog= TRUE;
316         return $output;
317       }
318       $this->dialog= false;
319     }
321     /* Dialog handling */
322     if(is_object($this->dialog)){
323       /* Must be called before save_object */
324       $this->dialog->save_object();
325    
326       if($this->dialog->isClosed()){
327         $this->dialog = false;
328       }elseif($this->dialog->isSelected()){
330         /* check if selected base is allowed to move to / create a new object */
331         $tmp = $this->get_allowed_bases();
332         if(isset($tmp[$this->dialog->isSelected()])){
333           $this->base = $this->dialog->isSelected();
334         }
335         $this->dialog= false;
336       }else{
337         return($this->dialog->execute());
338       }
339     }
341     /* Want password method editing? */
342     if ($this->acl_is_writeable("userPassword")){
343       if (isset($_POST['edit_pw_method'])){
344         if (!is_object($this->pwObject) || $this->pw_storage != $this->pwObject->get_hash_name()){
345           $temp= passwordMethod::get_available_methods();
346           $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
347         }
348         $this->pwObject->display = TRUE;
349         $this->dialog= TRUE;
350         return ($this->pwObject->configure());
351       }
352     }
354     /* Want picture edit dialog? */
355     if($this->acl_is_writeable("userPicture")) {
356       if (isset($_POST['edit_picture'])){
357         /* Save values for later recovery, in case some presses
358            the cancel button. */
359         $this->old_jpegPhoto= $this->jpegPhoto;
360         $this->old_photoData= $this->photoData;
361         $this->picture_dialog= TRUE;
362         $this->dialog= TRUE;
363       }
364     }
366     /* Remove picture? */
367     if($this->acl_is_writeable("userPicture",(!is_object($this->parent) && !session::is_set('edit'))) ){
368       if (isset($_POST['picture_remove'])){
369         $this->set_picture ();
370         $this->jpegPhoto= "*removed*";
371         $this->is_modified= TRUE;
372         return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
373       }
374     }
376     /* Save picture */
377     if (isset($_POST['picture_edit_finish'])){
379       /* Check for clean upload */
380       if ($_FILES['picture_file']['name'] != ""){
381         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
382           msg_dialog::display(_("Error"), _("Cannot upload file!"), ERROR_DIALOG);
383         }else{
384           /* Activate new picture */
385           $this->set_picture($_FILES['picture_file']['tmp_name']);
386         }
387       }
388       $this->picture_dialog= FALSE;
389       $this->dialog= FALSE;
390       $this->is_modified= TRUE;
391     }
394     /* Cancel picture */
395     if (isset($_POST['picture_edit_cancel'])){
397       /* Restore values */
398       $this->jpegPhoto= $this->old_jpegPhoto;
399       $this->photoData= $this->old_photoData;
401       /* Update picture */
402       session::set('binary',$this->photoData);
403       session::set('binarytype',"image/jpeg");
404       $this->picture_dialog= FALSE;
405       $this->dialog= FALSE;
406     }
408     /* Want certificate= */
409     if ((isset($_POST['edit_cert'])) && $this->acl_is_readable("Certificate")){
411       /* Save original values for later reconstruction */
412       foreach (array("certificateSerialNumber", "userCertificate",
413             "userSMIMECertificate", "userPKCS12") as $val){
415         $oval= "old_$val";
416         $this->$oval= $this->$val;
417       }
419       $this->cert_dialog= TRUE;
420       $this->dialog= TRUE;
421     }
424     /* Cancel certificate dialog */
425     if (isset($_POST['cert_edit_cancel'])){
427       /* Restore original values in case of 'cancel' */
428       foreach (array("certificateSerialNumber", "userCertificate",
429             "userSMIMECertificate", "userPKCS12") as $val){
431         $oval= "old_$val";
432         $this->$val= $this->$oval;
433       }
434       $this->cert_dialog= FALSE;
435       $this->dialog= FALSE;
436     }
439     /* Remove certificate? */
440     if($this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))){ 
441       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
442         if (isset($_POST["remove_$val"])){
444           /* Reset specified cert*/
445           $this->$val= "";
446           $this->is_modified= TRUE;
447         }
448       }
449     }
451     /* Upload new cert and close dialog? */     
452     if($this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))){ 
454       $fail =false;
456       if (isset($_POST['cert_edit_finish'])){
458         /* for all certificates do */
459         foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
460             as $val){
462           /* Check for clean upload */
463           if (array_key_exists($val."_file", $_FILES) &&
464               array_key_exists('name', $_FILES[$val."_file"]) &&
465               $_FILES[$val."_file"]['name'] != "" &&
466               is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
467             $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
468           }
469         }
471         /* Save serial number */
472         if (isset($_POST["certificateSerialNumber"]) &&
473             $_POST["certificateSerialNumber"] != ""){
475           if (!tests::is_id($_POST["certificateSerialNumber"])){
476             $fail = true;
477             msg_dialog::display(_("Error"), msgPool::invalid(_("Serial number"),$_POST["certificateSerialNumber"],"/[0-9]/"),ERROR_DIALOG);
479             foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
480               if ($this->$cert != ""){
481                 $smarty->assign("$cert"."_state", "true");
482               } else {
483                 $smarty->assign("$cert"."_state", "");
484               }
485             }
486           }
488           $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
489           $this->is_modified= TRUE;
490         }
491         if(!$fail){
492           $this->cert_dialog= FALSE;
493           $this->dialog= FALSE;
494         }
495       }
496     }
497     /* Display picture dialog */
498     if ($this->picture_dialog){
499       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
500     }
502     /* Display cert dialog */
503     if ($this->cert_dialog){
504       $smarty->assign("CertificateACL",$this->getacl("Certificate",(!is_object($this->parent) && !session::is_set('edit'))));
505       $smarty->assign("Certificate_readable",$this->acl_is_readable("Certificate"));
506       $smarty->assign("certificateSerialNumber",$this->certificateSerialNumber);
508       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
509         if ($this->$cert != ""){
510           /* import certificate */
511           $certificate = new certificate;
512           $certificate->import($this->$cert);
513       
514           /* Read out data*/
515           $timeto   = $certificate->getvalidto_date();
516           $timefrom = $certificate->getvalidfrom_date();
517          
518           
519           /* Additional info if start end time is '0' */
520           $add_str_info = "";
521           if($timeto == 0 && $timefrom == 0){
522             $add_str_info = "<br><i>"._("(Some types of certificates are currently not supported and may be displayed as 'invalid'.)")."</i>";
523           }
525           $str = "<table summary=\"\" border=0>
526                     <tr>
527                       <td style='vertical-align:top'>CN</td>
528                       <td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td>
529                     </tr>
530                   </table><br>".
532                   sprintf(_("Certificate is valid from %s to %s and is currently %s."),
533                         "<b>".date('d M Y',$timefrom)."</b>",
534                         "<b>".date('d M Y',$timeto)."</b>",
535                         $certificate->isvalid()?"<b><font style='color:green'>"._("valid")."</font></b>":
536                                                 "<b><font style='color:red'>"._("invalid")."</font></b>").$add_str_info;
538           $smarty->assign($cert."info",$str);
539           $smarty->assign($cert."_state","true");
540         } else {
541           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
542           $smarty->assign($cert."_state","");
543         }
544       }
545   
546       if($this->governmentmode){
547         $smarty->assign("honourIvbbAttributes", "true");
548       }else{
549         $smarty->assign("honourIvbbAttributes", "false");
550       }
551       $smarty->assign("governmentmode", $this->governmentmode);
552       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
553     }
555     /* Prepare password hashes */
556     if ($this->pw_storage == ""){
557       $this->pw_storage= $this->config->get_cfg_value("hash");
558     }
560     $temp= passwordMethod::get_available_methods();
561     $is_configurable= FALSE;
562     $hashes = $temp['name'];
563     if(isset($temp[$this->pw_storage])){
564       $test= new $temp[$this->pw_storage]($this->config);
565       $is_configurable= $test->is_configurable();
566     }else{
567       new msg_dialog(_("Password method"),_("The selected password method is no longer available."),WARNING_DIALOG);
568     }
571     /* Create password methods array */
572     $pwd_methods = array();
573     foreach($hashes as $id => $name){
574       if(!empty($temp['desc'][$id])){
575         $pwd_methods[$name] = $name." (".$temp['desc'][$id].")";
576       }else{
577         $pwd_methods[$name] = $name;
578       }
579     }
580  
581     /* Load attributes and acl's */
582     $ui =get_userinfo();
583     foreach($this->attributes as $val){
584       $smarty->assign("$val", $this->$val);
585       if(in_array($val,$this->multi_boxes)){
586         $smarty->assign("use_".$val,TRUE);
587       }else{
588         $smarty->assign("use_".$val,FALSE);
589       }
590     }
591     foreach(array("base","pw_storage","edit_picture") as $val){
592       if(in_array($val,$this->multi_boxes)){
593         $smarty->assign("use_".$val,TRUE);
594       }else{
595         $smarty->assign("use_".$val,FALSE);
596       }
597     }
599     /* Set acls */
600     $tmp = $this->plinfo();
601     foreach($tmp['plProvidedAcls'] as $val => $translation){
602       $smarty->assign("$val"."ACL", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit'))));
603     }
605     // Special ACL for gosaLoginRestrictions - 
606     // In case of multiple edit, we need a readonly ACL for the list. 
607     $smarty->assign('gosaLoginRestriction_ONLY_R_ACL', 
608       preg_replace("/[^r]/i","", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit')))));
610     $smarty->assign("pwmode", $pwd_methods);
611     $smarty->assign("pwmode_select", $this->pw_storage);
612     $smarty->assign("pw_configurable", $is_configurable);
613     $smarty->assign("passwordStorageACL", $this->getacl("userPassword",(!is_object($this->parent) && !session::is_set('edit'))));
615     if(!session::is_set('edit')){
616       $smarty->assign("CertificatesACL","");
617     }else{
618       $smarty->assign("CertificatesACL",  $this->getacl("Certificate"));
619     }
620     
621     $smarty->assign("userPictureACL",   $this->getacl("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));
622     $smarty->assign("userPicture_is_readable",   $this->acl_is_readable("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));
624     /* Create base acls */
625     $smarty->assign("base", $this->baseSelector->render());
627     /* Save government mode attributes */
628     if($this->governmentmode){
629       $smarty->assign("governmentmode", "true");
630       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
631           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
632       $smarty->assign("ivbbmodes", $ivbbmodes);
633       foreach ($this->govattrs as $val){
634         $smarty->assign("$val", $this->$val);
635         $smarty->assign("$val"."ACL", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit'))));
636       }
637     } else {
638       $smarty->assign("governmentmode", "false");
639     }
641     /* Special mode for uid */
642     $uidACL= $this->getacl("uid",(!is_object($this->parent) && !session::is_set('edit')));
643     if (isset ($this->dn)){
644       if ($this->dn != "new"){
645         $uidACL= preg_replace("/w/","",$uidACL);
646       }
647     }  else {
648       $uidACL= preg_replace("/w/","",$uidACL);
649     }
650     
651     $smarty->assign("uidACL", $uidACL);
652     $smarty->assign("is_template", $this->is_template);
653     $smarty->assign("use_dob", $this->use_dob);
655     if (isset($this->parent)){
656       if (isset($this->parent->by_object['phoneAccount']) &&
657           $this->parent->by_object['phoneAccount']->is_account){
658         $smarty->assign("has_phoneaccount", "true");
659       } else {
660         $smarty->assign("has_phoneaccount", "false");
661       }
662     } else {
663       $smarty->assign("has_phoneaccount", "false");
664     }
665     $smarty->assign("multiple_support" , $this->multiple_support_active);
666     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
667   }
670   /* remove object from parent */
671   function remove_from_parent()
672   {
673     /* Only remove valid accounts */
674     if(!$this->initially_was_account) return;
676     /* Remove password extension */
677     $temp= passwordMethod::get_available_methods();
679     /* Remove password method from user account */
680     if(isset($temp[$this->pw_storage]) && class_available($temp[$this->pw_storage])){
681       $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
682       $this->pwObject->remove_from_parent();
683     }
685     /* Remove user */
686     $ldap= $this->config->get_ldap_link();
687     $ldap->rmdir ($this->dn);
688     if (!$ldap->success()){
689       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
690     }
691   
692     new log("remove","users/".get_class($this),$this->dn,$this->attributes,$ldap->get_error());
693   
694     /* Delete references to groups */
695     $ldap->cd ($this->config->current['BASE']);
696     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
697     while ($ldap->fetch()){
698       $g= new group($this->config, $ldap->getDN());
699       $g->removeUser($this->uid);
700       $g->save ();
701     }
703     /* Delete references to object groups */
704     $ldap->cd ($this->config->current['BASE']);
705     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
706     while ($ldap->fetch()){
707       $og= new ogroup($this->config, $ldap->getDN());
708       unset($og->member[$this->dn]);
709       $og->member= array_values($og->member);
710       $og->save ();
711     }
713     /* Delete references to roles */
714     $ldap->cd ($this->config->current['BASE']);
715     $ldap->search ("(&(objectClass=organizationalRole)(roleOccupant=".LDAP::prepare4filter($this->dn)."))", array("cn"));
716     while ($ldap->fetch()){
717       $role= new roleGeneric($this->config, $ldap->getDN());
718       $key = array_search($this->dn,$role->roleOccupant);
719       if($key !== FALSE){
720         unset($role->roleOccupant[$key]);
721         $role->roleOccupant= array_values($role->roleOccupant);
722         $role->save ();
723       }
724     }
726     /* If needed, let the password method do some cleanup */
727     $tmp = new passwordMethod($this->config);
728     $available = $tmp->get_available_methods();
729     if (in_array_ics($this->pw_storage, $available['name'])){
730       $test= new $available[$this->pw_storage]($this->config);
731       $test->attrs= $this->attrs;
732       $test->dn= $this->dn;
733       $test->remove_from_parent();
734     }
736     /* Remove ACL dependencies too */
737     acl::remove_acl_for($this->dn);
739     /* Optionally execute a command after we're done */
740     $this->handle_post_events("remove",array("uid" => $this->uid));
741   }
744   /* Save data to object */
745   function save_object()
746   {
747     if(isset($_POST['generic']) || isset($_POST['multiple_user_posted'])){
749       /* Make a backup of the current selected base */
750       $base_tmp = $this->base;
752       /* Parents save function */
753       plugin::save_object ();
755       /* Refresh base */
756       if ($this->acl_is_moveable($this->base)){
757         if (!$this->baseSelector->update()) {
758           msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
759         }
760         if ($this->base != $this->baseSelector->getBase()) {
761           $this->base= $this->baseSelector->getBase();
762           $this->is_modified= TRUE;
763         }
764       }
765       
766       /* Sync lists */
767       $this->gosaLoginRestrictionWidget->save_object();
768       if ($this->gosaLoginRestrictionWidget->isModified()) {
769         $this->gosaLoginRestriction= array_values($this->gosaLoginRestrictionWidget->getMaintainedData());
770       }
772       /* Save government mode attributes */
773       if ($this->governmentmode){
774         foreach ($this->govattrs as $val){
775           if ($this->acl_is_writeable($val,(!is_object($this->parent) && !session::is_set('edit'))) && isset($_POST["$val"])){
776             $data= stripcslashes($_POST["$val"]);
777             if ($data != $this->$val){
778               $this->is_modified= TRUE;
779             }
780             $this->$val= $data;
781           }
782         }
783       }
785       /* In template mode, the uid is autogenerated... */
786       if ($this->is_template){
787         $this->uid= strtolower($this->sn);
788         $this->givenName= $this->sn;
789       }
791       /* Get pw_storage mode */
792       if (isset($_POST['pw_storage'])){
793         foreach(array("pw_storage") as $val){
794           if(isset($_POST[$val])){
795             $data= validate($_POST[$val]);
796             if ($data != $this->$val){
797               $this->is_modified= TRUE;
798             }
799             $this->$val= $data;
800           }
801         }
802       }
804       if($this->pw_storage != $this->last_pw_storage && isset($_POST['pw_storage'])){
805         if ($this->acl_is_writeable("userPassword")){
806           $temp= passwordMethod::get_available_methods();
807           if (!is_object($this->pwObject) || !($this->pwObject instanceOf $temp[$this->pw_storage])){
808             foreach($temp as $id => $data){
809               if(isset($data['name']) && $data['name'] == $this->pw_storage && $data['is_configurable']){
810                 $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
811                 break;
812               }
813             }
814           }
815         }
816       }
818       /* Save current cn
819        */
820       $this->cn = $this->givenName." ".$this->sn;
821     }
822   }
824   function rebind($ldap, $referral)
825   {
826     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
827     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
828       $this->error = "Success";
829       $this->hascon=true;
830       $this->reconnect= true;
831       return (0);
832     } else {
833       $this->error = "Could not bind to " . $credentials['ADMIN'];
834       return NULL;
835     }
836   }
838   
839   /* Save data to LDAP, depending on is_account we save or delete */
840   function save()
841   {
842     global $lang;
844     /* Only force save of changes .... 
845        If this attributes aren't changed, avoid saving.
846      */
847   
848     if($this->gender=="0") $this->gender ="";
849     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
851     /* First use parents methods to do some basic fillup in $this->attrs */
852     plugin::save ();
854     if ($this->dateOfBirth != ""){
855       if(!is_array($this->attrs['dateOfBirth'])) {
856         #TODO: use $lang to convert date
857         list($day, $month, $year)= explode(".", $this->dateOfBirth);
858         $this->attrs['dateOfBirth'] = sprintf("%04d-%02d-%02d", $year, $month, $day);
859       }
860     }
862     /* Remove additional objectClasses */
863     $tmp= array();
864     foreach ($this->attrs['objectClass'] as $key => $set){
865       $found= false;
866       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
867         if (preg_match ("/^$set$/i", $val)){
868           $found= true;
869           break;
870         }
871       }
872       if (!$found){
873         $tmp[]= $set;
874       }
875     }
877     /* Replace the objectClass array. This is done because of the
878        separation into government and normal mode. */
879     $this->attrs['objectClass']= $tmp;
881     /* Add objectClasss for template mode? */
882     if ($this->is_template){
883       $this->attrs['objectClass'][]= "gosaUserTemplate";
884     }
886     /* Hard coded government mode? */
887     if ($this->governmentmode){
888       $this->attrs['objectClass'][]= "ivbbentry";
890       /* Copy standard attributes */
891       foreach ($this->govattrs as $val){
892         if ($this->$val != ""){
893           $this->attrs["$val"]= $this->$val;
894         } elseif (!$this->is_new) {
895           $this->attrs["$val"]= array();
896         }
897       }
899       /* Remove attribute if set to "nein" */
900       if ($this->publicVisible == "nein"){
901         $this->attrs['publicVisible']= array();
902         if($this->is_new){
903           unset($this->attrs['publicVisible']);
904         }else{
905           $this->attrs['publicVisible']=array();
906         }
908       }
910     }
912     /* Special handling for attribute userCertificate needed */
913     if ($this->userCertificate != ""){
914       $this->attrs["userCertificate;binary"]= $this->userCertificate;
915       $remove_userCertificate= false;
916     } else {
917       $remove_userCertificate= true;
918     }
920     /* Special handling for dateOfBirth value */
921     if ($this->dateOfBirth == ""){
922       if ($this->is_new) {
923         unset($this->attrs["dateOfBirth"]);
924       } else {
925         $this->attrs["dateOfBirth"]= array();
926       }
927     }
928     if (!$this->gender){
929       if ($this->is_new) {
930         unset($this->attrs["gender"]);
931       } else {
932         $this->attrs["gender"]= array();
933       }
934     }
935     if (!$this->preferredLanguage){
936       if ($this->is_new) {
937         unset($this->attrs["preferredLanguage"]);
938       } else {
939         $this->attrs["preferredLanguage"]= array();
940       }
941     }
943     /* Special handling for attribute jpegPhote needed, scale image via
944        image magick to 147x200 pixels and inject resulting data. */
945     if ($this->jpegPhoto == "*removed*"){
946     
947       /* Reset attribute to avoid writing *removed* as value */    
948       $this->attrs["jpegPhoto"] = array();
950     } else {
952       /* Fallback if there's no image magick inside PHP */
953       if (!function_exists("imagick_blob2image")){
954         /* Get temporary file name for conversation */
955         $fname = tempnam (TEMP_DIR, "GOsa");
956   
957         /* Open file and write out photoData */
958         $fp = fopen ($fname, "w");
959         fwrite ($fp, $this->photoData);
960         fclose ($fp);
962         /* Build conversation query. Filename is generated automatically, so
963            we do not need any special security checks. Exec command and save
964            output. For PHP safe mode, you'll need a configuration which respects
965            image magick as executable... */
966         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
967         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
968             $query, "Execute");
969   
970         /* Read data written by convert */
971         $output= "";
972         $sh= popen($query, 'r');
973         while (!feof($sh)){
974           $output.= fread($sh, 4096);
975         }
976         pclose($sh);
978         unlink($fname);
980         /* Save attribute */
981         $this->attrs["jpegPhoto"] = $output;
983       } else {
985         /* Load the new uploaded Photo */
986         if(!$handle  =  imagick_blob2image($this->photoData))  {
987           new log("debug","users/".get_class($this),$this->dn,array(),"Could not access uploaded image");
988         }
990         /* Resizing image to 147x200 and blur */
991         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
992           new log("debug","users/".get_class($this),$this->dn,array(),"Could not resize uploaded image");
993         }
995         /* Converting image to JPEG */
996         if(!imagick_convert($handle,"JPEG")) {
997           new log("debug","users/".get_class($this),$this->dn,array(),"Could not convert uploaded image to jepg");
998         }
1000         /* Creating binary Code for the Image */
1001         if(!$dump = imagick_image2blob($handle)){
1002           new log("debug","users/".get_class($this),$this->dn,array(),"Could not create new user image");
1003         }
1005         /* Sending Image */
1006         $output=  $dump;
1008         /* Save attribute */
1009         $this->attrs["jpegPhoto"] = $output;
1010       }
1012     }
1014     /* This only gets called when user is renaming himself */
1015     $ldap= $this->config->get_ldap_link();
1016     if ($this->dn != $this->new_dn){
1018       /* Write entry on new 'dn' */
1019       $this->update_acls($this->dn,$this->new_dn);
1020       $this->move($this->dn, $this->new_dn);
1022       /* Happen to use the new one */
1023       change_ui_dn($this->dn, $this->new_dn);
1024       $this->dn= $this->new_dn;
1025     }
1028     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
1029        new entries. So do a check first... */
1030     $ldap->cat ($this->dn, array('dn'));
1031     if ($ldap->fetch()){
1032       $mode= "modify";
1033     } else {
1034       $mode= "add";
1035       $ldap->cd($this->config->current['BASE']);
1036       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
1037     }
1039     /* Set password to some junk stuff in case of templates */
1040     if ($this->is_template){
1041       $temp= passwordMethod::get_available_methods();
1042       foreach($temp as $id => $data){
1043         if(isset($data['name']) && $data['name'] == $this->pw_storage){
1044           $tmp = new  $temp[$this->pw_storage]($this->config,$this->dn);
1045           $tmp->set_hash($this->pw_storage);
1046           $this->attrs['userPassword'] = $tmp->create_template_hash($this->attrs);
1047           break;
1048         }
1049       }
1050     }
1052     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
1053         $this->attributes, "Save via $mode");
1055     /* Finally write data with selected 'mode' */
1056     $this->cleanup();
1058     /* Update current locale settings, if we have edited ourselves */
1059     $ui = session::get('ui');
1060     if(isset($this->attrs['preferredLanguage']) && $this->dn == $ui->dn){
1061       $ui->language = $this->preferredLanguage;
1062       session::set('ui',$ui);
1063       session::set('Last_init_lang',"update");
1064     }
1066     $ldap->cd ($this->dn);
1067     $ldap->$mode ($this->attrs);
1068     if (!$ldap->success()){
1069       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
1070       return (1);
1071     }
1073     /* Remove ACL dependencies too */
1074     if($this->dn != $this->orig_dn && $this->orig_dn != "new"){
1075       $tmp = new acl($this->config,$this->parent,$this->dn);
1076       $tmp->update_acl_membership($this->orig_dn,$this->dn);
1077     }
1079     if($mode == "modify"){
1080       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1081     }else{
1082       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1083     }
1085     /* Remove cert? 
1086        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
1087        to work around myself. */
1088     if ($remove_userCertificate == true && !$this->is_new && $this->had_userCertificate){
1090       /* Reset array, assemble new, this should be reworked */
1091       $this->attrs= array();
1092       $this->attrs['userCertificate;binary']= array();
1094       /* Prepare connection */
1095       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
1096         die ("Could not connect to LDAP server");
1097       }
1098       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1099       if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true") {
1100         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1101         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1102       }
1103       if($this->config->get_cfg_value("ldapTLS") == "true"){
1104         ldap_start_tls($ds);
1105       }
1106       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
1107               $this->config->current['PASSWORD']))) {
1108         die ("Could not bind to LDAP");
1109       }
1111       /* Modify using attrs */
1112       ldap_mod_del($ds,$this->dn,$this->attrs);
1113       ldap_close($ds);
1114     }
1116     /* If needed, let the password method do some cleanup */
1117     if ($this->pw_storage != $this->last_pw_storage){
1118       $tmp = new passwordMethod($this->config);
1119       $available = $tmp->get_available_methods();
1120       if (in_array_ics($this->last_pw_storage, $available['name'])){
1121         $test= new $available[$this->last_pw_storage]($this->config,$this->dn);
1122         $test->attrs= $this->attrs;
1123         $test->remove_from_parent();
1124       }
1125     }
1127     /* Maybe the current password method want's to do some changes... */
1128     if (is_object($this->pwObject)){
1129       $this->pwObject->save($this->dn);
1130     }
1132     /* Optionally execute a command after we're done */
1133     if ($mode == "add"){
1134       $this->handle_post_events("add", array("uid" => $this->uid));
1135     } elseif ($this->is_modified){
1136       $this->handle_post_events("modify", array("uid" => $this->uid));
1137     }
1139     return (0);
1140   }
1143   function create_initial_rdn($pattern)
1144   {
1145     // Only generate single RDNs
1146     if (preg_match('/\+/', $pattern)){
1147       msg_dialog::display(_("Error"), _("Cannot build RDN: no + allowed to build sub RDN!"), ERROR_DIALOG);
1148       return "";
1149     }
1151     // Extract attribute
1152     $attribute= preg_replace('/=.*$/', '', $pattern);
1153     if (!in_array_ics($attribute, $this->attributes)) {
1154       msg_dialog::display(_("Error"), _("Cannot build RDN: attribute is not defined!"), ERROR_DIALOG);
1155       return "";
1156     }
1158     // Sort attributes for length
1159     $attrl= array();
1160     foreach ($this->attributes as $attr) {
1161       $attrl[$attr]= strlen($attr);
1162     }
1163     arsort($attrl);
1164     
1165     // Walk thru sorted attributes and replace them in pattern
1166     foreach ($attrl as $attr => $dummy) {
1167       if (!is_array($this->$attr)){
1168         $pattern= preg_replace("/%$attr/", $this->$attr, $pattern);
1169       } else {
1170         // Array elements cannot be used for ID generation
1171         if (preg_match("/%$attr/", $pattern)) {
1172           msg_dialog::display(_("Error"), _("Cannot build RDN: invalid attribute parameters!"), ERROR_DIALOG);
1173           break;
1174         }
1175       }
1176     }
1178     // Internally assign value
1179     $this->$attribute= preg_replace('/^[^=]+=/', '', $pattern);
1181     return $pattern;
1182   }
1184   
1185   function update_new_dn()
1186   {
1187     // Alternative way to handle DN
1188     $pattern= $this->config->get_cfg_value("accountRDN");
1189     if ($pattern != "") {
1190       $rdn= $this->create_initial_rdn($pattern);
1191       $attribute= preg_replace('/=.*$/', '', $rdn);
1192       $value= preg_replace('/^[^=]+=$/', '', $rdn);
1194       /* Don't touch dn, if $attribute hasn't changed */
1195       if (isset($this->saved_attributes[$attribute]) && $this->saved_attributes[$attribute] == $this->$attribute &&
1196             $this->orig_base == $this->base ){
1197         $this->new_dn= $this->dn;
1198       } else {
1199         $this->new_dn= $this->create_unique_dn2($rdn, get_people_ou().$this->base);
1200       }
1202     // Original way to handle DN
1203     } else {
1205       $pt= "";
1206       if($this->config->get_cfg_value("personalTitleInDN") == "true"){
1207         if(!empty($this->personalTitle)){
1208           $pt = $this->personalTitle." ";
1209         }
1210       }
1212       $this->cn= $pt.$this->givenName." ".$this->sn;
1214       /* Permissions for that base? */
1215       if ($this->config->get_cfg_value("accountPrimaryAttribute") == "uid"){
1216         $this->new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
1217       } else {
1218         /* Don't touch dn, if cn hasn't changed */
1219         if (isset($this->saved_attributes['cn']) && $this->saved_attributes['cn'] == $this->cn &&
1220             $this->orig_base == $this->base ){
1221           $this->new_dn= $this->dn;
1222         } else {
1223           $this->new_dn= $this->create_unique_dn('cn', get_people_ou().$this->base);
1224         }
1225       }
1226     }
1227   }
1228   
1230   /* Check formular input */
1231   function check()
1232   {
1233     /* Call common method to give check the hook */
1234     $message= plugin::check();
1236     /* Configurable password methods should be configured initially. 
1237      */ 
1238     if($this->last_pw_storage != $this->pw_storage){
1239       $temp= passwordMethod::get_available_methods();
1240       foreach($temp['name'] as $id => $name){
1241         if($name == $this->pw_storage){
1242           if($temp['is_configurable'][$id] && !$this->pwObject instanceof $temp[$name] ){
1243             $message[] = _("The selected password method requires initial configuration!");
1244           }
1245           break;
1246         }
1247       }
1248     }
1250     $this->update_new_dn();
1252     /* Set the new acl base */
1253     if($this->dn == "new") {
1254       $this->set_acl_base($this->base);
1255     }
1257     /* Check if we are allowed to create/move this user */
1258     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
1259       $message[]= msgPool::permCreate();
1260     }elseif($this->orig_dn != "new" && $this->new_dn != $this->orig_dn && !$this->acl_is_moveable($this->base)){
1261       $message[]= msgPool::permMove();
1262     }
1264     /* UID already used? */
1265     $ldap= $this->config->get_ldap_link();
1266     $ldap->cd($this->config->current['BASE']);
1267     $ldap->search("(uid=$this->uid)", array("uid"));
1268     $ldap->fetch();
1269     if ($ldap->count() != 0 && $this->dn == 'new'){
1270       $message[]= msgPool::duplicated(_("Login"));
1271     }
1273     /* In template mode, the uid and givenName are autogenerated... */
1274     if ($this->sn == ""){
1275       $message[]= msgPool::required(_("Name"));
1276     }
1278     // Check if a wrong base was supplied
1279     if(!$this->baseSelector->checkLastBaseUpdate()){
1280       $message[]= msgPool::check_base();;
1281     }
1283     if (!$this->is_template){
1284       if ($this->givenName == ""){
1285         $message[]= msgPool::required(_("Given name"));
1286       }
1287       if ($this->uid == ""){
1288         $message[]= msgPool::required(_("Login"));
1289       }
1290       if ($this->config->get_cfg_value("accountPrimaryAttribute") != "uid"){
1291         $ldap->cat($this->new_dn);
1292         if ($ldap->count() != 0 && $this->dn != $this->new_dn && $this->dn == 'new'){
1293           $message[]= msgPool::duplicated(_("Name"));
1294         }
1295       }
1296     }
1298     /* Check for valid input */
1299     if ($this->is_modified && !tests::is_uid($this->uid)){
1301       if (strict_uid_mode()){
1302         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/");
1303       } else {
1304         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/i");
1305       }
1306     }
1307     if (!tests::is_url($this->labeledURI)){
1308       $message[]= msgPool::invalid(_("Homepage"), "", "", "http://www.your-domain.com/yourname");
1309     }
1311     /* Check phone numbers */
1312     if (!tests::is_phone_nr($this->telephoneNumber)){
1313       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1314     }
1315     if (!tests::is_phone_nr($this->facsimileTelephoneNumber)){
1316       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1317     }
1318     if (!tests::is_phone_nr($this->mobile)){
1319       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1320     }
1321     if (!tests::is_phone_nr($this->pager)){
1322       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1323     }
1325     /* Check dates */
1326     if (!tests::is_date($this->dateOfBirth)){
1327       $message[]= msgPool::invalid(_("Date of birth"), $this->dateOfBirth,"" ,"23.02.2009");
1328     }
1330     /* Check for reserved characers */
1331     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName)){
1332       $message[]= msgPool::invalid(_("Given name"), $this->givenName, '/[^,+"?\'()=<>;\\\\]/');
1333     }
1334     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn)){
1335       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1336     }
1338     return $message;
1339   }
1342   /* Indicate whether a password change is needed or not */
1343   function password_change_needed()
1344   {
1345     if(in_array("pw_storage",$this->multi_boxes)){
1346       return(TRUE);
1347     }
1348     return($this->pw_storage != $this->last_pw_storage && !$this->is_template);
1349   }
1352   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1353   function load_picture()
1354   {
1355     $ldap = $this->config->get_ldap_link();
1356     $ldap->cd ($this->dn);
1357     $data = $ldap->get_attribute($this->dn,"jpegPhoto");
1359     if((!$data) || ($data == "*removed*")){ 
1361       /* In case we don't get an entry, load a default picture */
1362       $this->set_picture ();
1363       $this->jpegPhoto= "*removed*";
1364     }else{
1366       /* Set picture */
1367       $this->photoData= $data;
1368       session::set('binary',$this->photoData);
1369       session::set('binarytype',"image/jpeg");
1370       $this->jpegPhoto= "";
1371     }
1372   }
1375   /* Load a certificate from LDAP, this is going to be simplified later on */
1376   function load_cert()
1377   {
1378     $ds= ldap_connect($this->config->current['SERVER']);
1379     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1380     if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true"){
1381       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1382       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1383     }
1384     if ($this->config->get_cfg_value("ldapTLS") == "true"){
1385       ldap_start_tls($ds);
1386     }
1388     $r= ldap_bind($ds);
1389     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1391     if ($sr) {
1392       $ei= @ldap_first_entry($ds, $sr);
1393       
1394       if ($ei) {
1395         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1396           $this->userCertificate= "";
1397         } else {
1398           $this->userCertificate= $info[0];
1399         }
1400       }
1401     } else {
1402       $this->userCertificate= "";
1403     }
1405     ldap_unbind($ds);
1406   }
1409   /* Load picture from file to object */
1410   function set_picture($filename ="")
1411   {
1412     if (!is_file($filename) || $filename =="" ){
1413       $filename= "./plugins/users/images/default.jpg";
1414       $this->jpegPhoto= "*removed*";
1415     }
1417     $fd = fopen ($filename, "rb");
1418     $this->photoData= fread ($fd, filesize ($filename));
1419     session::set('binary',$this->photoData);
1420     session::set('binarytype',"image/jpeg");
1421     $this->jpegPhoto= "";
1423     fclose ($fd);
1424   }
1427   /* Load certificate from file to object */
1428   function set_cert($cert, $filename)
1429   {
1430     if(!$this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))) return;
1431     $fd = fopen ($filename, "rb");
1432     if (filesize($filename)>0) {
1433       $this->$cert= fread ($fd, filesize ($filename));
1434       fclose ($fd);
1435       $this->is_modified= TRUE;
1436     } else {
1437       msg_dialog::display(_("Error"), _("Cannot open certificate!"), ERROR_DIALOG);
1438     }
1439   }
1441   /* Adapt from given 'dn' */
1442   function adapt_from_template($dn, $skip= array())
1443   {
1444     plugin::adapt_from_template($dn, $skip);
1446     /* Get password method from template 
1447      */
1448     $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
1449     if(is_object($tmp)){
1450       if($tmp->is_configurable()){
1451         $tmp->adapt_from_template($dn);
1452         $this->pwObject = &$tmp;
1453       }
1454       $this->pw_storage= $tmp->get_hash();
1455     }
1457     /* Get base */
1458     $this->base= preg_replace('/^[^,]+,'.preg_quote(get_people_ou(), '/').'/i', '', $dn);
1460     if($this->governmentmode){
1462       /* Walk through govattrs */
1463       foreach ($this->govattrs as $val){
1465         if (in_array($val, $skip)){
1466           continue;
1467         }
1469         if (isset($this->attrs["$val"][0])){
1471           /* If attribute is set, replace dynamic parts: 
1472              %sn, %givenName and %uid. Fill these in our local variables. */
1473           $value= $this->attrs["$val"][0];
1475           foreach (array("sn", "givenName", "uid") as $repl){
1476             if (preg_match("/%$repl/i", $value)){
1477               $value= preg_replace ("/%$repl/i",
1478                   $this->parent->$repl, $value);
1479             }
1480           }
1481           $this->$val= $value;
1482         }
1483       }
1484     }
1486     /* Get back uid/sn/givenName - only write if nothing's skipped */
1487     if ($this->parent !== NULL && count($skip) == 0){
1488       $this->uid= $this->parent->uid;
1489       $this->sn= $this->parent->sn;
1490       $this->givenName= $this->parent->givenName;
1491     }
1493     if ($this->dateOfBirth) {
1494       /* This entry is ISO 8601 conform */
1495       list($year, $month, $day)= explode("-", $this->dateOfBirth, 3);
1496     
1497       #TODO: use $lang to convert date
1498       $this->dateOfBirth= "$day.$month.$year";
1499     }
1500   }
1502  
1503   /* This avoids that users move themselves out of their rights. 
1504    */
1505   function allowedBasesToMoveTo()
1506   {
1507     /* Get bases */
1508     $bases  = $this->get_allowed_bases();
1509     return($bases);
1510   } 
1513   function getCopyDialog()
1514   {
1515     $str = "";
1517     session::set('binary',$this->photoData); 
1518     session::set('binarytype',"image/jpeg");
1520     /* Get random number for pictures */
1521     srand((double)microtime()*1000000); 
1522     $rand = rand(0, 10000);
1524     $smarty = get_smarty();
1526     $smarty->assign("passwordTodo","clear");
1528     if(isset($_POST['passwordTodo'])){
1529       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1530     }
1532     $smarty->assign("sn",       $this->sn);
1533     $smarty->assign("givenName",$this->givenName);
1534     $smarty->assign("uid",      $this->uid);
1535     $smarty->assign("rand",     $rand);
1536     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1539     $ret = array();
1540     $ret['string'] = $str;
1541     $ret['status'] = "";  
1542     return($ret);
1543   }
1545   function saveCopyDialog()
1546   {
1547     /* Set_acl_base */
1548     $this->set_acl_base($this->base);
1550     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1551       $this->set_picture($_FILES['picture_file']['tmp_name']);
1552     }
1554     /* Remove picture? */
1555     if (isset($_POST['picture_remove'])){
1556       $this->jpegPhoto= "*removed*";
1557       $this->set_picture ("./plugins/users/images/default.jpg");
1558       $this->is_modified= TRUE;
1559     }
1561     $attrs = array("uid","givenName","sn");
1562     foreach($attrs as $attr){
1563       if(isset($_POST[$attr])){
1564         $this->$attr = $_POST[$attr];
1565       }
1566     } 
1567   }
1570   function PrepareForCopyPaste($source)
1571   {
1572     plugin::PrepareForCopyPaste($source);
1574     /* Reset certificate information addepted from source user
1575        to avoid setting the same user certificate for the destination user. */
1576     $this->userPKCS12= "";
1577     $this->userSMIMECertificate= "";
1578     $this->userCertificate= "";
1579     $this->certificateSerialNumber= "";
1580     $this->old_certificateSerialNumber= "";
1581     $this->old_userPKCS12= "";
1582     $this->old_userSMIMECertificate= "";
1583     $this->old_userCertificate= "";
1584   }
1587   static function plInfo()
1588   {
1589   
1590     $govattrs= array(
1591         "gouvernmentOrganizationalUnit"             =>  _("Unit"), 
1592         "houseIdentifier"                           =>  _("House identifier"), 
1593         "vocation"                                  =>  _("Vocation"),
1594         "ivbbLastDeliveryCollective"                =>  _("Last delivery"), 
1595         "gouvernmentOrganizationalPersonLocality"   =>  _("Person locality"),
1596         "gouvernmentOrganizationalUnitDescription"  =>  _("Unit description"),
1597         "gouvernmentOrganizationalUnitSubjectArea"  =>  _("Subject area"),
1598         "functionalTitle"                           =>  _("Functional title"),
1599         "certificateSerialNumber"                   =>  _("Certificate serial number"),
1600         "publicVisible"                             =>  _("Public visible"),
1601         "street"                                    =>  _("Street"),
1602         "role"                                      =>  _("Role"),
1603         "postalCode"                                =>  _("Postal code"));
1605     $ret = array(
1606         "plShortName" => _("Generic"),
1607         "plDescription" => _("Generic user settings"),
1608         "plSelfModify"  => TRUE,
1609         "plDepends"     => array(),
1610         "plPriority"    => 1,
1611         "plSection"     => array("personal" => _("My account")),
1612         "plCategory"    => array("users" => array("description" => _("Users"),
1613                                                   "objectClass" => "gosaAccount")),
1615         "plProvidedAcls" => array(
1617           "sn"                => _("Surname"),
1618           "givenName"         => _("Given name"),
1619           "uid"               => _("User identification"),
1620           "personalTitle"     => _("Personal title"),
1621           "academicTitle"     => _("Academic title"),
1623           "dateOfBirth"       => _("Date of birth"),
1624           "gender"            => _("Sex"),
1625           "preferredLanguage" => _("Preferred language"),
1626           "base"              => _("Base"), 
1628           "userPicture"       => _("User picture"),
1630           "gosaLoginRestriction" => _("Login restrictions"),         
1632           "o"                 => _("Organization"),
1633           "ou"                => _("Department"),
1634           "departmentNumber"  => _("Department number"),
1635           "employeeNumber"    => _("Employee number"),
1636           "employeeType"      => _("Employee type"),
1638           "roomNumber"        => _("Room number"),
1639           "telephoneNumber"   => _("Telefon number"),
1640           "pager"             => _("Pager number"),
1641           "mobile"            => _("Mobile number"),
1642           "facsimileTelephoneNumber"     => _("Fax number"),
1644           "st"                => _("State"),
1645           "l"                 => _("Location"),
1646           "postalAddress"     => _("Postal address"),
1648           "homePostalAddress" => _("Home postal address"),
1649           "homePhone"         => _("Home phone number"),
1650           "labeledURI"        => _("Homepage"),
1651           "userPassword"      => _("User password method"), 
1652           "Certificate"       => _("User certificates"))
1654         );
1656     /* Append government attributes if required */
1657     global $config;
1658     if($config->get_cfg_value("honourIvbbAttributes") == "true"){
1659       foreach($govattrs as $attr => $desc){
1660         $ret["plProvidedAcls"][$attr] = $desc;
1661       }
1662     }
1663     return($ret);
1664   }
1666   function get_multi_edit_values()
1667   {
1668     $ret = plugin::get_multi_edit_values();
1669     if(in_array("pw_storage",$this->multi_boxes)){
1670       $ret['pw_storage'] = $this->pw_storage;
1671     }
1672     if(in_array("edit_picture",$this->multi_boxes)){
1673       $ret['jpegPhoto'] = $this->jpegPhoto;
1674       $ret['photoData'] = $this->photoData;
1675       $ret['old_jpegPhoto'] = $this->old_jpegPhoto;
1676       $ret['old_photoData'] = $this->old_photoData;
1677     }
1678     if(isset($ret['dateOfBirth'])){
1679       unset($ret['dateOfBirth']);
1680     }
1681     if(isset($ret['cn'])){
1682       unset($ret['cn']);
1683     }
1684     $ret['is_modified'] = $this->is_modified;
1685     if(in_array("base",$this->multi_boxes)){
1686       $ret['orig_base']="Changed_by_Multi_Plug";
1687       $ret['base']=$this->base;
1688     }
1690     $ret['gosaLoginRestriction'] = $this->gosaLoginRestriction;
1691     $ret['gosaLoginRestriction_some'] = $this->gosaLoginRestriction_some;
1693     return($ret); 
1694   }
1697   function multiple_save_object()
1698   {
1699     plugin::multiple_save_object();
1701     /* Get pw_storage mode */
1702     if (isset($_POST['pw_storage'])){
1703       foreach(array("pw_storage") as $val){
1704         if(isset($_POST[$val])){
1705           $data= validate(get_post($val));
1706           if ($data != $this->$val){
1707             $this->is_modified= TRUE;
1708           }
1709           $this->$val= $data;
1710         }
1711       }
1712     }
1713   
1714     /* Refresh base */
1715     if ($this->acl_is_moveable($this->base)){
1716       if (!$this->baseSelector->update()) {
1717         msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
1718       }
1719       if ($this->base != $this->baseSelector->getBase()) {
1720         $this->base= $this->baseSelector->getBase();
1721       }
1722     }
1724     if(isset($_POST['user_mulitple_edit'])){
1725       foreach(array("base","pw_storage","edit_picture") as $val){
1726         if(isset($_POST["use_".$val])){
1727           $this->multi_boxes[] = $val;
1728         }
1729       }
1730     }
1732     /* Sync lists */
1733     $this->gosaLoginRestrictionWidget->save_object();
1734     if ($this->gosaLoginRestrictionWidget->isModified()) {
1735       $this->gosaLoginRestriction= array_values($this->gosaLoginRestrictionWidget->getMaintainedData());
1736     }
1737   }
1739   
1740   function multiple_check()
1741   {
1742     /* Call check() to set new_dn correctly ... */
1743     $message = plugin::multiple_check();
1745     /* Set the new acl base */
1746     if($this->dn == "new") {
1747       $this->set_acl_base($this->base);
1748     }
1749     if (!tests::is_url($this->labeledURI) && in_array("labeledURI",$this->multi_boxes)){
1750       $message[]= msgPool::invalid(_("Homepage"));
1751     }
1752     if (!tests::is_phone_nr($this->telephoneNumber) && in_array("telephoneNumber",$this->multi_boxes)){
1753       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1754     }
1755     if (!tests::is_phone_nr($this->facsimileTelephoneNumber) &&  in_array("facsimileTelephoneNumber",$this->multi_boxes)){
1756       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1757     }
1758     if (!tests::is_phone_nr($this->mobile) && in_array("mobile",$this->multi_boxes)){
1759       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1760     }
1761     if (!tests::is_phone_nr($this->pager) && in_array("pager",$this->multi_boxes)){
1762       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1763     }
1764     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName) && in_array("givenName",$this->multi_boxes)){
1765       $message[]= msgPool::invalid(_("Given name"), $this->giveName, '/[^,+"?\'()=<>;\\\\]/');
1766     }
1767     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn) && in_array("sn",$this->multi_boxes)){
1768       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1769     }
1770     return($message);
1771   }
1775   function multiple_execute()
1776   {
1777     return($this->execute());
1778   }
1781   /*! \brief  Prepares the plugin to be used for multiple edit
1782    *          Update plugin attributes with given array of attribtues.
1783    *  \param  array   Array with attributes that must be updated.
1784    */
1785   function init_multiple_support($attrs,$all)
1786   {
1787     plugin::init_multiple_support($attrs,$all);
1789     // Get login restrictions
1790     if(isset($attrs['gosaLoginRestriction'])){
1791       $this->gosaLoginRestriction  =array();
1792       for($i =0;$i < $attrs['gosaLoginRestriction']['count']; $i++){
1793         $this->gosaLoginRestriction[] = $attrs['gosaLoginRestriction'][$i];
1794       }
1795     }
1797     // Detect login restriction not used in all user objects.
1798     $this->gosaLoginRestriction_some = array();
1799     if(isset($all['gosaLoginRestriction'])){
1800       for($i=0;$i<$all['gosaLoginRestriction']['count'];$i++){
1801         $this->gosaLoginRestriction_some[] = $all['gosaLoginRestriction'][$i];
1802       }
1803     }
1806     // Reinit the login restriction list.
1807     $data = $this->convertLoginRestriction();
1808     if(count($data)){
1809       $this->gosaLoginRestrictionWidget->setListData($data['data'], $data['displayData']);
1810     }
1811   }
1814   function set_multi_edit_values($attrs)
1815   {
1816     $lR = array();
1818     // Update loginRestrictions, keep my settings while ip is optional
1819     foreach($attrs['gosaLoginRestriction_some'] as $ip){
1820       if(in_array($ip, $this->gosaLoginRestriction) && in_array($ip, $attrs['gosaLoginRestriction'])){
1821         $lR[] = $ip;
1822       }
1823     }
1825     // Add enforced loginRestrictions 
1826     foreach($attrs['gosaLoginRestriction'] as $ip){
1827       $lR[] = $ip;
1828     }
1830     $lR = array_values(array_unique($lR));
1831     $this->is_modified |=  array_differs($this->gosaLoginRestriction, $lR);
1832     plugin::set_multi_edit_values($attrs);
1833     $this->gosaLoginRestriction = $lR;
1834   }
1837   function convertLoginRestriction()
1838   {
1839     $all = array_unique(array_merge($this->gosaLoginRestriction,$this->gosaLoginRestriction_some));
1840     $data = array();
1841     foreach($all as $ip){
1842       $data['data'][] = $ip;
1843       if(!in_array($ip, $this->gosaLoginRestriction)){
1844         $data['displayData'][] = array('mode' => LIST_MARKED , 'data' => array($ip.' ('._("Entries differ").')'));
1845       }else{
1846         $data['displayData'][] = array('mode' => 0 , 'data' => array($ip));
1847       }
1848     }   
1849     return($data);
1850   }
1853 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1854 ?>