Code

Moved to POST for selector lists
[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     $smarty->assign("gosaLoginRestrictionACL", $this->getacl('gosaLoginRestriction', (!is_object($this->parent) && !session::is_set('edit'))));
606     $smarty->assign("pwmode", $pwd_methods);
607     $smarty->assign("pwmode_select", $this->pw_storage);
608     $smarty->assign("pw_configurable", $is_configurable);
609     $smarty->assign("passwordStorageACL", $this->getacl("userPassword",(!is_object($this->parent) && !session::is_set('edit'))));
611     if(!session::is_set('edit')){
612       $smarty->assign("CertificatesACL","");
613     }else{
614       $smarty->assign("CertificatesACL",  $this->getacl("Certificate"));
615     }
616     
617     $smarty->assign("userPictureACL",   $this->getacl("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));
618     $smarty->assign("userPicture_is_readable",   $this->acl_is_readable("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));
620     /* Create base acls */
621     $smarty->assign("base", $this->baseSelector->render());
623     /* Save government mode attributes */
624     if($this->governmentmode){
625       $smarty->assign("governmentmode", "true");
626       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
627           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
628       $smarty->assign("ivbbmodes", $ivbbmodes);
629       foreach ($this->govattrs as $val){
630         $smarty->assign("$val", $this->$val);
631         $smarty->assign("$val"."ACL", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit'))));
632       }
633     } else {
634       $smarty->assign("governmentmode", "false");
635     }
637     /* Special mode for uid */
638     $uidACL= $this->getacl("uid",(!is_object($this->parent) && !session::is_set('edit')));
639     if (isset ($this->dn)){
640       if ($this->dn != "new"){
641         $uidACL= preg_replace("/w/","",$uidACL);
642       }
643     }  else {
644       $uidACL= preg_replace("/w/","",$uidACL);
645     }
646     
647     $smarty->assign("uidACL", $uidACL);
648     $smarty->assign("is_template", $this->is_template);
649     $smarty->assign("use_dob", $this->use_dob);
651     if (isset($this->parent)){
652       if (isset($this->parent->by_object['phoneAccount']) &&
653           $this->parent->by_object['phoneAccount']->is_account){
654         $smarty->assign("has_phoneaccount", "true");
655       } else {
656         $smarty->assign("has_phoneaccount", "false");
657       }
658     } else {
659       $smarty->assign("has_phoneaccount", "false");
660     }
661     $smarty->assign("multiple_support" , $this->multiple_support_active);
662     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
663   }
666   /* remove object from parent */
667   function remove_from_parent()
668   {
669     /* Only remove valid accounts */
670     if(!$this->initially_was_account) return;
672     /* Remove password extension */
673     $temp= passwordMethod::get_available_methods();
675     /* Remove password method from user account */
676     if(isset($temp[$this->pw_storage]) && class_available($temp[$this->pw_storage])){
677       $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
678       $this->pwObject->remove_from_parent();
679     }
681     /* Remove user */
682     $ldap= $this->config->get_ldap_link();
683     $ldap->rmdir ($this->dn);
684     if (!$ldap->success()){
685       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
686     }
687   
688     new log("remove","users/".get_class($this),$this->dn,$this->attributes,$ldap->get_error());
689   
690     /* Delete references to groups */
691     $ldap->cd ($this->config->current['BASE']);
692     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
693     while ($ldap->fetch()){
694       $g= new group($this->config, $ldap->getDN());
695       $g->removeUser($this->uid);
696       $g->save ();
697     }
699     /* Delete references to object groups */
700     $ldap->cd ($this->config->current['BASE']);
701     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
702     while ($ldap->fetch()){
703       $og= new ogroup($this->config, $ldap->getDN());
704       unset($og->member[$this->dn]);
705       $og->member= array_values($og->member);
706       $og->save ();
707     }
709     /* Delete references to roles */
710     $ldap->cd ($this->config->current['BASE']);
711     $ldap->search ("(&(objectClass=organizationalRole)(roleOccupant=".LDAP::prepare4filter($this->dn)."))", array("cn"));
712     while ($ldap->fetch()){
713       $role= new roleGeneric($this->config, $ldap->getDN());
714       $key = array_search($this->dn,$role->roleOccupant);
715       if($key !== FALSE){
716         unset($role->roleOccupant[$key]);
717         $role->roleOccupant= array_values($role->roleOccupant);
718         $role->save ();
719       }
720     }
722     /* If needed, let the password method do some cleanup */
723     $tmp = new passwordMethod($this->config);
724     $available = $tmp->get_available_methods();
725     if (in_array_ics($this->pw_storage, $available['name'])){
726       $test= new $available[$this->pw_storage]($this->config);
727       $test->attrs= $this->attrs;
728       $test->dn= $this->dn;
729       $test->remove_from_parent();
730     }
732     /* Remove ACL dependencies too */
733     acl::remove_acl_for($this->dn);
735     /* Optionally execute a command after we're done */
736     $this->handle_post_events("remove",array("uid" => $this->uid));
737   }
740   /* Save data to object */
741   function save_object()
742   {
743     if(isset($_POST['generic']) || isset($_POST['multiple_user_posted'])){
745       /* Make a backup of the current selected base */
746       $base_tmp = $this->base;
748       /* Parents save function */
749       plugin::save_object ();
751       /* Refresh base */
752       if ($this->acl_is_moveable($this->base)){
753         if (!$this->baseSelector->update()) {
754           msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
755         }
756         if ($this->base != $this->baseSelector->getBase()) {
757           $this->base= $this->baseSelector->getBase();
758           $this->is_modified= TRUE;
759         }
760       }
761       
762       /* Sync lists */
763       $this->gosaLoginRestrictionWidget->save_object();
764       if ($this->gosaLoginRestrictionWidget->isModified()) {
765         $this->gosaLoginRestriction= $this->gosaLoginRestrictionWidget->getMaintainedData();
766       }
768       /* Save government mode attributes */
769       if ($this->governmentmode){
770         foreach ($this->govattrs as $val){
771           if ($this->acl_is_writeable($val,(!is_object($this->parent) && !session::is_set('edit'))) && isset($_POST["$val"])){
772             $data= stripcslashes($_POST["$val"]);
773             if ($data != $this->$val){
774               $this->is_modified= TRUE;
775             }
776             $this->$val= $data;
777           }
778         }
779       }
781       /* In template mode, the uid is autogenerated... */
782       if ($this->is_template){
783         $this->uid= strtolower($this->sn);
784         $this->givenName= $this->sn;
785       }
787       /* Get pw_storage mode */
788       if (isset($_POST['pw_storage'])){
789         foreach(array("pw_storage") as $val){
790           if(isset($_POST[$val])){
791             $data= validate($_POST[$val]);
792             if ($data != $this->$val){
793               $this->is_modified= TRUE;
794             }
795             $this->$val= $data;
796           }
797         }
798       }
800       if($this->pw_storage != $this->last_pw_storage && isset($_POST['pw_storage'])){
801         if ($this->acl_is_writeable("userPassword")){
802           $temp= passwordMethod::get_available_methods();
803           if (!is_object($this->pwObject) || !($this->pwObject instanceOf $temp[$this->pw_storage])){
804             foreach($temp as $id => $data){
805               if(isset($data['name']) && $data['name'] == $this->pw_storage && $data['is_configurable']){
806                 $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
807                 break;
808               }
809             }
810           }
811         }
812       }
814       /* Save current cn
815        */
816       $this->cn = $this->givenName." ".$this->sn;
817     }
818   }
820   function rebind($ldap, $referral)
821   {
822     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
823     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
824       $this->error = "Success";
825       $this->hascon=true;
826       $this->reconnect= true;
827       return (0);
828     } else {
829       $this->error = "Could not bind to " . $credentials['ADMIN'];
830       return NULL;
831     }
832   }
834   
835   /* Save data to LDAP, depending on is_account we save or delete */
836   function save()
837   {
838     global $lang;
840     /* Only force save of changes .... 
841        If this attributes aren't changed, avoid saving.
842      */
843   
844     if($this->gender=="0") $this->gender ="";
845     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
847     /* First use parents methods to do some basic fillup in $this->attrs */
848     plugin::save ();
850     if ($this->dateOfBirth != ""){
851       if(!is_array($this->attrs['dateOfBirth'])) {
852         #TODO: use $lang to convert date
853         list($day, $month, $year)= explode(".", $this->dateOfBirth);
854         $this->attrs['dateOfBirth'] = sprintf("%04d-%02d-%02d", $year, $month, $day);
855       }
856     }
858     /* Remove additional objectClasses */
859     $tmp= array();
860     foreach ($this->attrs['objectClass'] as $key => $set){
861       $found= false;
862       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
863         if (preg_match ("/^$set$/i", $val)){
864           $found= true;
865           break;
866         }
867       }
868       if (!$found){
869         $tmp[]= $set;
870       }
871     }
873     /* Replace the objectClass array. This is done because of the
874        separation into government and normal mode. */
875     $this->attrs['objectClass']= $tmp;
877     /* Add objectClasss for template mode? */
878     if ($this->is_template){
879       $this->attrs['objectClass'][]= "gosaUserTemplate";
880     }
882     /* Hard coded government mode? */
883     if ($this->governmentmode){
884       $this->attrs['objectClass'][]= "ivbbentry";
886       /* Copy standard attributes */
887       foreach ($this->govattrs as $val){
888         if ($this->$val != ""){
889           $this->attrs["$val"]= $this->$val;
890         } elseif (!$this->is_new) {
891           $this->attrs["$val"]= array();
892         }
893       }
895       /* Remove attribute if set to "nein" */
896       if ($this->publicVisible == "nein"){
897         $this->attrs['publicVisible']= array();
898         if($this->is_new){
899           unset($this->attrs['publicVisible']);
900         }else{
901           $this->attrs['publicVisible']=array();
902         }
904       }
906     }
908     /* Special handling for attribute userCertificate needed */
909     if ($this->userCertificate != ""){
910       $this->attrs["userCertificate;binary"]= $this->userCertificate;
911       $remove_userCertificate= false;
912     } else {
913       $remove_userCertificate= true;
914     }
916     /* Special handling for dateOfBirth value */
917     if ($this->dateOfBirth == ""){
918       if ($this->is_new) {
919         unset($this->attrs["dateOfBirth"]);
920       } else {
921         $this->attrs["dateOfBirth"]= array();
922       }
923     }
924     if (!$this->gender){
925       if ($this->is_new) {
926         unset($this->attrs["gender"]);
927       } else {
928         $this->attrs["gender"]= array();
929       }
930     }
931     if (!$this->preferredLanguage){
932       if ($this->is_new) {
933         unset($this->attrs["preferredLanguage"]);
934       } else {
935         $this->attrs["preferredLanguage"]= array();
936       }
937     }
939     /* Special handling for attribute jpegPhote needed, scale image via
940        image magick to 147x200 pixels and inject resulting data. */
941     if ($this->jpegPhoto == "*removed*"){
942     
943       /* Reset attribute to avoid writing *removed* as value */    
944       $this->attrs["jpegPhoto"] = array();
946     } else {
948       /* Fallback if there's no image magick inside PHP */
949       if (!function_exists("imagick_blob2image")){
950         /* Get temporary file name for conversation */
951         $fname = tempnam (TEMP_DIR, "GOsa");
952   
953         /* Open file and write out photoData */
954         $fp = fopen ($fname, "w");
955         fwrite ($fp, $this->photoData);
956         fclose ($fp);
958         /* Build conversation query. Filename is generated automatically, so
959            we do not need any special security checks. Exec command and save
960            output. For PHP safe mode, you'll need a configuration which respects
961            image magick as executable... */
962         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
963         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
964             $query, "Execute");
965   
966         /* Read data written by convert */
967         $output= "";
968         $sh= popen($query, 'r');
969         while (!feof($sh)){
970           $output.= fread($sh, 4096);
971         }
972         pclose($sh);
974         unlink($fname);
976         /* Save attribute */
977         $this->attrs["jpegPhoto"] = $output;
979       } else {
981         /* Load the new uploaded Photo */
982         if(!$handle  =  imagick_blob2image($this->photoData))  {
983           new log("debug","users/".get_class($this),$this->dn,array(),"Could not access uploaded image");
984         }
986         /* Resizing image to 147x200 and blur */
987         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
988           new log("debug","users/".get_class($this),$this->dn,array(),"Could not resize uploaded image");
989         }
991         /* Converting image to JPEG */
992         if(!imagick_convert($handle,"JPEG")) {
993           new log("debug","users/".get_class($this),$this->dn,array(),"Could not convert uploaded image to jepg");
994         }
996         /* Creating binary Code for the Image */
997         if(!$dump = imagick_image2blob($handle)){
998           new log("debug","users/".get_class($this),$this->dn,array(),"Could not create new user image");
999         }
1001         /* Sending Image */
1002         $output=  $dump;
1004         /* Save attribute */
1005         $this->attrs["jpegPhoto"] = $output;
1006       }
1008     }
1010     /* This only gets called when user is renaming himself */
1011     $ldap= $this->config->get_ldap_link();
1012     if ($this->dn != $this->new_dn){
1014       /* Write entry on new 'dn' */
1015       $this->update_acls($this->dn,$this->new_dn);
1016       $this->move($this->dn, $this->new_dn);
1018       /* Happen to use the new one */
1019       change_ui_dn($this->dn, $this->new_dn);
1020       $this->dn= $this->new_dn;
1021     }
1024     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
1025        new entries. So do a check first... */
1026     $ldap->cat ($this->dn, array('dn'));
1027     if ($ldap->fetch()){
1028       $mode= "modify";
1029     } else {
1030       $mode= "add";
1031       $ldap->cd($this->config->current['BASE']);
1032       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
1033     }
1035     /* Set password to some junk stuff in case of templates */
1036     if ($this->is_template){
1037       $temp= passwordMethod::get_available_methods();
1038       foreach($temp as $id => $data){
1039         if(isset($data['name']) && $data['name'] == $this->pw_storage){
1040           $tmp = new  $temp[$this->pw_storage]($this->config,$this->dn);
1041           $tmp->set_hash($this->pw_storage);
1042           $this->attrs['userPassword'] = $tmp->create_template_hash($this->attrs);
1043           break;
1044         }
1045       }
1046     }
1048     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
1049         $this->attributes, "Save via $mode");
1051     /* Finally write data with selected 'mode' */
1052     $this->cleanup();
1054     /* Update current locale settings, if we have edited ourselves */
1055     $ui = session::get('ui');
1056     if(isset($this->attrs['preferredLanguage']) && $this->dn == $ui->dn){
1057       $ui->language = $this->preferredLanguage;
1058       session::set('ui',$ui);
1059       session::set('Last_init_lang',"update");
1060     }
1062     $ldap->cd ($this->dn);
1063     $ldap->$mode ($this->attrs);
1064     if (!$ldap->success()){
1065       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
1066       return (1);
1067     }
1069     /* Remove ACL dependencies too */
1070     if($this->dn != $this->orig_dn && $this->orig_dn != "new"){
1071       $tmp = new acl($this->config,$this->parent,$this->dn);
1072       $tmp->update_acl_membership($this->orig_dn,$this->dn);
1073     }
1075     if($mode == "modify"){
1076       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1077     }else{
1078       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1079     }
1081     /* Remove cert? 
1082        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
1083        to work around myself. */
1084     if ($remove_userCertificate == true && !$this->is_new && $this->had_userCertificate){
1086       /* Reset array, assemble new, this should be reworked */
1087       $this->attrs= array();
1088       $this->attrs['userCertificate;binary']= array();
1090       /* Prepare connection */
1091       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
1092         die ("Could not connect to LDAP server");
1093       }
1094       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1095       if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true") {
1096         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1097         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1098       }
1099       if($this->config->get_cfg_value("ldapTLS") == "true"){
1100         ldap_start_tls($ds);
1101       }
1102       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
1103               $this->config->current['PASSWORD']))) {
1104         die ("Could not bind to LDAP");
1105       }
1107       /* Modify using attrs */
1108       ldap_mod_del($ds,$this->dn,$this->attrs);
1109       ldap_close($ds);
1110     }
1112     /* If needed, let the password method do some cleanup */
1113     if ($this->pw_storage != $this->last_pw_storage){
1114       $tmp = new passwordMethod($this->config);
1115       $available = $tmp->get_available_methods();
1116       if (in_array_ics($this->last_pw_storage, $available['name'])){
1117         $test= new $available[$this->last_pw_storage]($this->config,$this->dn);
1118         $test->attrs= $this->attrs;
1119         $test->remove_from_parent();
1120       }
1121     }
1123     /* Maybe the current password method want's to do some changes... */
1124     if (is_object($this->pwObject)){
1125       $this->pwObject->save($this->dn);
1126     }
1128     /* Optionally execute a command after we're done */
1129     if ($mode == "add"){
1130       $this->handle_post_events("add", array("uid" => $this->uid));
1131     } elseif ($this->is_modified){
1132       $this->handle_post_events("modify", array("uid" => $this->uid));
1133     }
1135     return (0);
1136   }
1139   function create_initial_rdn($pattern)
1140   {
1141     // Only generate single RDNs
1142     if (preg_match('/\+/', $pattern)){
1143       msg_dialog::display(_("Error"), _("Cannot build RDN: no + allowed to build sub RDN!"), ERROR_DIALOG);
1144       return "";
1145     }
1147     // Extract attribute
1148     $attribute= preg_replace('/=.*$/', '', $pattern);
1149     if (!in_array_ics($attribute, $this->attributes)) {
1150       msg_dialog::display(_("Error"), _("Cannot build RDN: attribute is not defined!"), ERROR_DIALOG);
1151       return "";
1152     }
1154     // Sort attributes for length
1155     $attrl= array();
1156     foreach ($this->attributes as $attr) {
1157       $attrl[$attr]= strlen($attr);
1158     }
1159     arsort($attrl);
1160     
1161     // Walk thru sorted attributes and replace them in pattern
1162     foreach ($attrl as $attr => $dummy) {
1163       if (!is_array($this->$attr)){
1164         $pattern= preg_replace("/%$attr/", $this->$attr, $pattern);
1165       } else {
1166         // Array elements cannot be used for ID generation
1167         if (preg_match("/%$attr/", $pattern)) {
1168           msg_dialog::display(_("Error"), _("Cannot build RDN: invalid attribute parameters!"), ERROR_DIALOG);
1169           break;
1170         }
1171       }
1172     }
1174     // Internally assign value
1175     $this->$attribute= preg_replace('/^[^=]+=/', '', $pattern);
1177     return $pattern;
1178   }
1180   
1181   function update_new_dn()
1182   {
1183     // Alternative way to handle DN
1184     $pattern= $this->config->get_cfg_value("accountRDN");
1185     if ($pattern != "") {
1186       $rdn= $this->create_initial_rdn($pattern);
1187       $attribute= preg_replace('/=.*$/', '', $rdn);
1188       $value= preg_replace('/^[^=]+=$/', '', $rdn);
1190       /* Don't touch dn, if $attribute hasn't changed */
1191       if (isset($this->saved_attributes[$attribute]) && $this->saved_attributes[$attribute] == $this->$attribute &&
1192             $this->orig_base == $this->base ){
1193         $this->new_dn= $this->dn;
1194       } else {
1195         $this->new_dn= $this->create_unique_dn2($rdn, get_people_ou().$this->base);
1196       }
1198     // Original way to handle DN
1199     } else {
1201       $pt= "";
1202       if($this->config->get_cfg_value("personalTitleInDN") == "true"){
1203         if(!empty($this->personalTitle)){
1204           $pt = $this->personalTitle." ";
1205         }
1206       }
1208       $this->cn= $pt.$this->givenName." ".$this->sn;
1210       /* Permissions for that base? */
1211       if ($this->config->get_cfg_value("accountPrimaryAttribute") == "uid"){
1212         $this->new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
1213       } else {
1214         /* Don't touch dn, if cn hasn't changed */
1215         if (isset($this->saved_attributes['cn']) && $this->saved_attributes['cn'] == $this->cn &&
1216             $this->orig_base == $this->base ){
1217           $this->new_dn= $this->dn;
1218         } else {
1219           $this->new_dn= $this->create_unique_dn('cn', get_people_ou().$this->base);
1220         }
1221       }
1222     }
1223   }
1224   
1226   /* Check formular input */
1227   function check()
1228   {
1229     /* Call common method to give check the hook */
1230     $message= plugin::check();
1232     /* Configurable password methods should be configured initially. 
1233      */ 
1234     if($this->last_pw_storage != $this->pw_storage){
1235       $temp= passwordMethod::get_available_methods();
1236       foreach($temp['name'] as $id => $name){
1237         if($name == $this->pw_storage){
1238           if($temp['is_configurable'][$id] && !$this->pwObject instanceof $temp[$name] ){
1239             $message[] = _("The selected password method requires initial configuration!");
1240           }
1241           break;
1242         }
1243       }
1244     }
1246     $this->update_new_dn();
1248     /* Set the new acl base */
1249     if($this->dn == "new") {
1250       $this->set_acl_base($this->base);
1251     }
1253     /* Check if we are allowed to create/move this user */
1254     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
1255       $message[]= msgPool::permCreate();
1256     }elseif($this->orig_dn != "new" && $this->new_dn != $this->orig_dn && !$this->acl_is_moveable($this->base)){
1257       $message[]= msgPool::permMove();
1258     }
1260     /* UID already used? */
1261     $ldap= $this->config->get_ldap_link();
1262     $ldap->cd($this->config->current['BASE']);
1263     $ldap->search("(uid=$this->uid)", array("uid"));
1264     $ldap->fetch();
1265     if ($ldap->count() != 0 && $this->dn == 'new'){
1266       $message[]= msgPool::duplicated(_("Login"));
1267     }
1269     /* In template mode, the uid and givenName are autogenerated... */
1270     if ($this->sn == ""){
1271       $message[]= msgPool::required(_("Name"));
1272     }
1274     if (!$this->is_template){
1275       if ($this->givenName == ""){
1276         $message[]= msgPool::required(_("Given name"));
1277       }
1278       if ($this->uid == ""){
1279         $message[]= msgPool::required(_("Login"));
1280       }
1281       if ($this->config->get_cfg_value("accountPrimaryAttribute") != "uid"){
1282         $ldap->cat($this->new_dn);
1283         if ($ldap->count() != 0 && $this->dn != $this->new_dn && $this->dn == 'new'){
1284           $message[]= msgPool::duplicated(_("Name"));
1285         }
1286       }
1287     }
1289     /* Check for valid input */
1290     if ($this->is_modified && !tests::is_uid($this->uid)){
1292       if (strict_uid_mode()){
1293         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/");
1294       } else {
1295         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/i");
1296       }
1297     }
1298     if (!tests::is_url($this->labeledURI)){
1299       $message[]= msgPool::invalid(_("Homepage"), "", "", "http://www.your-domain.com/yourname");
1300     }
1302     /* Check phone numbers */
1303     if (!tests::is_phone_nr($this->telephoneNumber)){
1304       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1305     }
1306     if (!tests::is_phone_nr($this->facsimileTelephoneNumber)){
1307       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1308     }
1309     if (!tests::is_phone_nr($this->mobile)){
1310       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1311     }
1312     if (!tests::is_phone_nr($this->pager)){
1313       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1314     }
1316     /* Check dates */
1317     if (!tests::is_date($this->dateOfBirth)){
1318       $message[]= msgPool::invalid(_("Date of birth"), $this->dateOfBirth,"" ,"23.02.2009");
1319     }
1321     /* Check for reserved characers */
1322     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName)){
1323       $message[]= msgPool::invalid(_("Given name"), $this->givenName, '/[^,+"?\'()=<>;\\\\]/');
1324     }
1325     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn)){
1326       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1327     }
1329     return $message;
1330   }
1333   /* Indicate whether a password change is needed or not */
1334   function password_change_needed()
1335   {
1336     if(in_array("pw_storage",$this->multi_boxes)){
1337       return(TRUE);
1338     }
1339     return($this->pw_storage != $this->last_pw_storage && !$this->is_template);
1340   }
1343   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1344   function load_picture()
1345   {
1346     $ldap = $this->config->get_ldap_link();
1347     $ldap->cd ($this->dn);
1348     $data = $ldap->get_attribute($this->dn,"jpegPhoto");
1350     if((!$data) || ($data == "*removed*")){ 
1352       /* In case we don't get an entry, load a default picture */
1353       $this->set_picture ();
1354       $this->jpegPhoto= "*removed*";
1355     }else{
1357       /* Set picture */
1358       $this->photoData= $data;
1359       session::set('binary',$this->photoData);
1360       session::set('binarytype',"image/jpeg");
1361       $this->jpegPhoto= "";
1362     }
1363   }
1366   /* Load a certificate from LDAP, this is going to be simplified later on */
1367   function load_cert()
1368   {
1369     $ds= ldap_connect($this->config->current['SERVER']);
1370     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1371     if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true"){
1372       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1373       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1374     }
1375     if ($this->config->get_cfg_value("ldapTLS") == "true"){
1376       ldap_start_tls($ds);
1377     }
1379     $r= ldap_bind($ds);
1380     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1382     if ($sr) {
1383       $ei= @ldap_first_entry($ds, $sr);
1384       
1385       if ($ei) {
1386         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1387           $this->userCertificate= "";
1388         } else {
1389           $this->userCertificate= $info[0];
1390         }
1391       }
1392     } else {
1393       $this->userCertificate= "";
1394     }
1396     ldap_unbind($ds);
1397   }
1400   /* Load picture from file to object */
1401   function set_picture($filename ="")
1402   {
1403     if (!is_file($filename) || $filename =="" ){
1404       $filename= "./plugins/users/images/default.jpg";
1405       $this->jpegPhoto= "*removed*";
1406     }
1408     $fd = fopen ($filename, "rb");
1409     $this->photoData= fread ($fd, filesize ($filename));
1410     session::set('binary',$this->photoData);
1411     session::set('binarytype',"image/jpeg");
1412     $this->jpegPhoto= "";
1414     fclose ($fd);
1415   }
1418   /* Load certificate from file to object */
1419   function set_cert($cert, $filename)
1420   {
1421     if(!$this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))) return;
1422     $fd = fopen ($filename, "rb");
1423     if (filesize($filename)>0) {
1424       $this->$cert= fread ($fd, filesize ($filename));
1425       fclose ($fd);
1426       $this->is_modified= TRUE;
1427     } else {
1428       msg_dialog::display(_("Error"), _("Cannot open certificate!"), ERROR_DIALOG);
1429     }
1430   }
1432   /* Adapt from given 'dn' */
1433   function adapt_from_template($dn, $skip= array())
1434   {
1435     plugin::adapt_from_template($dn, $skip);
1437     /* Get password method from template 
1438      */
1439     $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
1440     if(is_object($tmp)){
1441       if($tmp->is_configurable()){
1442         $tmp->adapt_from_template($dn);
1443         $this->pwObject = &$tmp;
1444       }
1445       $this->pw_storage= $tmp->get_hash();
1446     }
1448     /* Get base */
1449     $this->base= preg_replace('/^[^,]+,'.preg_quote(get_people_ou(), '/').'/i', '', $dn);
1451     if($this->governmentmode){
1453       /* Walk through govattrs */
1454       foreach ($this->govattrs as $val){
1456         if (in_array($val, $skip)){
1457           continue;
1458         }
1460         if (isset($this->attrs["$val"][0])){
1462           /* If attribute is set, replace dynamic parts: 
1463              %sn, %givenName and %uid. Fill these in our local variables. */
1464           $value= $this->attrs["$val"][0];
1466           foreach (array("sn", "givenName", "uid") as $repl){
1467             if (preg_match("/%$repl/i", $value)){
1468               $value= preg_replace ("/%$repl/i",
1469                   $this->parent->$repl, $value);
1470             }
1471           }
1472           $this->$val= $value;
1473         }
1474       }
1475     }
1477     /* Get back uid/sn/givenName - only write if nothing's skipped */
1478     if ($this->parent !== NULL && count($skip) == 0){
1479       $this->uid= $this->parent->uid;
1480       $this->sn= $this->parent->sn;
1481       $this->givenName= $this->parent->givenName;
1482     }
1483   }
1485  
1486   /* This avoids that users move themselves out of their rights. 
1487    */
1488   function allowedBasesToMoveTo()
1489   {
1490     /* Get bases */
1491     $bases  = $this->get_allowed_bases();
1492     return($bases);
1493   } 
1496   function getCopyDialog()
1497   {
1498     $str = "";
1500     session::set('binary',$this->photoData); 
1501     session::set('binarytype',"image/jpeg");
1503     /* Get random number for pictures */
1504     srand((double)microtime()*1000000); 
1505     $rand = rand(0, 10000);
1507     $smarty = get_smarty();
1509     $smarty->assign("passwordTodo","clear");
1511     if(isset($_POST['passwordTodo'])){
1512       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1513     }
1515     $smarty->assign("sn",       $this->sn);
1516     $smarty->assign("givenName",$this->givenName);
1517     $smarty->assign("uid",      $this->uid);
1518     $smarty->assign("rand",     $rand);
1519     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1522     $ret = array();
1523     $ret['string'] = $str;
1524     $ret['status'] = "";  
1525     return($ret);
1526   }
1528   function saveCopyDialog()
1529   {
1530     /* Set_acl_base */
1531     $this->set_acl_base($this->base);
1533     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1534       $this->set_picture($_FILES['picture_file']['tmp_name']);
1535     }
1537     /* Remove picture? */
1538     if (isset($_POST['picture_remove'])){
1539       $this->jpegPhoto= "*removed*";
1540       $this->set_picture ("./plugins/users/images/default.jpg");
1541       $this->is_modified= TRUE;
1542     }
1544     $attrs = array("uid","givenName","sn");
1545     foreach($attrs as $attr){
1546       if(isset($_POST[$attr])){
1547         $this->$attr = $_POST[$attr];
1548       }
1549     } 
1550   }
1553   function PrepareForCopyPaste($source)
1554   {
1555     plugin::PrepareForCopyPaste($source);
1557     /* Reset certificate information addepted from source user
1558        to avoid setting the same user certificate for the destination user. */
1559     $this->userPKCS12= "";
1560     $this->userSMIMECertificate= "";
1561     $this->userCertificate= "";
1562     $this->certificateSerialNumber= "";
1563     $this->old_certificateSerialNumber= "";
1564     $this->old_userPKCS12= "";
1565     $this->old_userSMIMECertificate= "";
1566     $this->old_userCertificate= "";
1567   }
1570   static function plInfo()
1571   {
1572   
1573     $govattrs= array(
1574         "gouvernmentOrganizationalUnit"             =>  _("Unit"), 
1575         "houseIdentifier"                           =>  _("House identifier"), 
1576         "vocation"                                  =>  _("Vocation"),
1577         "ivbbLastDeliveryCollective"                =>  _("Last delivery"), 
1578         "gouvernmentOrganizationalPersonLocality"   =>  _("Person locality"),
1579         "gouvernmentOrganizationalUnitDescription"  =>  _("Unit description"),
1580         "gouvernmentOrganizationalUnitSubjectArea"  =>  _("Subject area"),
1581         "functionalTitle"                           =>  _("Functional title"),
1582         "certificateSerialNumber"                   =>  _("Certificate serial number"),
1583         "publicVisible"                             =>  _("Public visible"),
1584         "street"                                    =>  _("Street"),
1585         "role"                                      =>  _("Role"),
1586         "postalCode"                                =>  _("Postal code"));
1588     $ret = array(
1589         "plShortName" => _("Generic"),
1590         "plDescription" => _("Generic user settings"),
1591         "plSelfModify"  => TRUE,
1592         "plDepends"     => array(),
1593         "plPriority"    => 1,
1594         "plSection"     => array("personal" => _("My account")),
1595         "plCategory"    => array("users" => array("description" => _("Users"),
1596                                                   "objectClass" => "gosaAccount")),
1598         "plProvidedAcls" => array(
1600           "sn"                => _("Surname"),
1601           "givenName"         => _("Given name"),
1602           "uid"               => _("User identification"),
1603           "personalTitle"     => _("Personal title"),
1604           "academicTitle"     => _("Academic title"),
1606           "dateOfBirth"       => _("Date of birth"),
1607           "gender"            => _("Sex"),
1608           "preferredLanguage" => _("Preferred language"),
1609           "base"              => _("Base"), 
1611           "userPicture"       => _("User picture"),
1613           "o"                 => _("Organization"),
1614           "ou"                => _("Department"),
1615           "departmentNumber"  => _("Department number"),
1616           "employeeNumber"    => _("Employee number"),
1617           "employeeType"      => _("Employee type"),
1619           "roomNumber"        => _("Room number"),
1620           "telephoneNumber"   => _("Telefon number"),
1621           "pager"             => _("Pager number"),
1622           "mobile"            => _("Mobile number"),
1623           "facsimileTelephoneNumber"     => _("Fax number"),
1625           "st"                => _("State"),
1626           "l"                 => _("Location"),
1627           "postalAddress"     => _("Postal address"),
1629           "homePostalAddress" => _("Home postal address"),
1630           "homePhone"         => _("Home phone number"),
1631           "labeledURI"        => _("Homepage"),
1632           "userPassword"      => _("User password method"), 
1633           "Certificate"       => _("User certificates"))
1635         );
1637     /* Append government attributes if required */
1638     global $config;
1639     if($config->get_cfg_value("honourIvbbAttributes") == "true"){
1640       foreach($govattrs as $attr => $desc){
1641         $ret["plProvidedAcls"][$attr] = $desc;
1642       }
1643     }
1644     return($ret);
1645   }
1647   function get_multi_edit_values()
1648   {
1649     $ret = plugin::get_multi_edit_values();
1650     if(in_array("pw_storage",$this->multi_boxes)){
1651       $ret['pw_storage'] = $this->pw_storage;
1652     }
1653     if(in_array("edit_picture",$this->multi_boxes)){
1654       $ret['jpegPhoto'] = $this->jpegPhoto;
1655       $ret['photoData'] = $this->photoData;
1656       $ret['old_jpegPhoto'] = $this->old_jpegPhoto;
1657       $ret['old_photoData'] = $this->old_photoData;
1658     }
1659     if(isset($ret['dateOfBirth'])){
1660       unset($ret['dateOfBirth']);
1661     }
1662     if(isset($ret['cn'])){
1663       unset($ret['cn']);
1664     }
1665     $ret['is_modified'] = $this->is_modified;
1666     if(in_array("base",$this->multi_boxes)){
1667       $ret['orig_base']="Changed_by_Multi_Plug";
1668       $ret['base']=$this->base;
1669     }
1670     return($ret); 
1671   }
1674   function multiple_save_object()
1675   {
1676     plugin::multiple_save_object();
1678     /* Get pw_storage mode */
1679     if (isset($_POST['pw_storage'])){
1680       foreach(array("pw_storage") as $val){
1681         if(isset($_POST[$val])){
1682           $data= validate(get_post($val));
1683           if ($data != $this->$val){
1684             $this->is_modified= TRUE;
1685           }
1686           $this->$val= $data;
1687         }
1688       }
1689     }
1691     /* Refresh base */
1692     if ($this->acl_is_moveable($this->base)){
1693       if (!$this->baseSelector->update()) {
1694         msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
1695       }
1696       if ($this->base != $this->baseSelector->getBase()) {
1697         $this->base= $this->baseSelector->getBase();
1698       }
1699     }
1701     if(isset($_POST['user_mulitple_edit'])){
1702       foreach(array("base","pw_storage","edit_picture") as $val){
1703         if(isset($_POST["use_".$val])){
1704           $this->multi_boxes[] = $val;
1705         }
1706       }
1707     }
1708   }
1710   
1711   function multiple_check()
1712   {
1713     /* Call check() to set new_dn correctly ... */
1714     $message = plugin::multiple_check();
1716     /* Set the new acl base */
1717     if($this->dn == "new") {
1718       $this->set_acl_base($this->base);
1719     }
1720     if (!tests::is_url($this->labeledURI) && in_array("labeledURI",$this->multi_boxes)){
1721       $message[]= msgPool::invalid(_("Homepage"));
1722     }
1723     if (!tests::is_phone_nr($this->telephoneNumber) && in_array("telephoneNumber",$this->multi_boxes)){
1724       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1725     }
1726     if (!tests::is_phone_nr($this->facsimileTelephoneNumber) &&  in_array("facsimileTelephoneNumber",$this->multi_boxes)){
1727       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1728     }
1729     if (!tests::is_phone_nr($this->mobile) && in_array("mobile",$this->multi_boxes)){
1730       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1731     }
1732     if (!tests::is_phone_nr($this->pager) && in_array("pager",$this->multi_boxes)){
1733       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1734     }
1735     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName) && in_array("givenName",$this->multi_boxes)){
1736       $message[]= msgPool::invalid(_("Given name"), $this->giveName, '/[^,+"?\'()=<>;\\\\]/');
1737     }
1738     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn) && in_array("sn",$this->multi_boxes)){
1739       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1740     }
1741     return($message);
1742   }
1746   function multiple_execute()
1747   {
1748     return($this->execute());
1749   }
1754 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1755 ?>