Code

Updated password handling
[gosa.git] / gosa-core / plugins / personal / generic / class_user.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 /*!
24   \brief   user plugin
25   \author  Cajus Pollmeier <pollmeier@gonicus.de>
26   \version 2.00
27   \date    24.07.2003
29   This class provides the functionality to read and write all attributes
30   relevant for person, organizationalPerson, inetOrgPerson and gosaAccount
31   from/to the LDAP. It does syntax checking and displays the formulars required.
32  */
34 class user extends plugin
35 {
36   /* Definitions */
37   var $plHeadline= "Generic";
38   var $plDescription= "Edit organizational user settings";
40   /* Plugin specific values */
41   var $base= "";
42   var $orig_base= "";
43   var $cn= "";
44   var $new_dn= "";
45   var $personalTitle= "";
46   var $academicTitle= "";
47   var $homePostalAddress= "";
48   var $homePhone= "";
49   var $labeledURI= "";
50   var $o= "";
51   var $ou= "";
52   var $departmentNumber= "";
53   var $gosaLoginRestriction= array();
54   var $gosaLoginRestrictionWidget;
55   var $employeeNumber= "";
56   var $employeeType= "";
57   var $roomNumber= "";
58   var $telephoneNumber= "";
59   var $facsimileTelephoneNumber= "";
60   var $mobile= "";
61   var $pager= "";
62   var $l= "";
63   var $st= "";
64   var $postalAddress= "";
65   var $dateOfBirth;
66   var $use_dob= "0";
67   var $gender="0";
68   var $preferredLanguage="0";
69   var $baseSelector;
71   var $jpegPhoto= "*removed*";
72   var $photoData= "";
73   var $old_jpegPhoto= "";
74   var $old_photoData= "";
75   var $cert_dialog= FALSE;
76   var $picture_dialog= FALSE;
77   var $pwObject= NULL;
79   var $userPKCS12= "";
80   var $userSMIMECertificate= "";
81   var $userCertificate= "";
82   var $certificateSerialNumber= "";
83   var $old_certificateSerialNumber= "";
84   var $old_userPKCS12= "";
85   var $old_userSMIMECertificate= "";
86   var $old_userCertificate= "";
88   var $gouvernmentOrganizationalUnit= "";
89   var $houseIdentifier= "";
90   var $street= "";
91   var $postalCode= "";
92   var $vocation= "";
93   var $ivbbLastDeliveryCollective= "";
94   var $gouvernmentOrganizationalPersonLocality= "";
95   var $gouvernmentOrganizationalUnitDescription= "";
96   var $gouvernmentOrganizationalUnitSubjectArea= "";
97   var $functionalTitle= "";
98   var $role= "";
99   var $publicVisible= "";
101   var $orig_dn;
102   var $dialog;
104   /* variables to trigger password changes */
105   var $pw_storage= "md5";
106   var $last_pw_storage= "unset";
107   var $had_userCertificate= FALSE;
109   var $view_logged = FALSE;
111   var $manager = "";
112   var $manager_name = "";
115   /* attribute list for save action */
116   var $attributes= array("sn", "givenName", "uid", "personalTitle", "academicTitle",
117       "homePostalAddress", "homePhone", "labeledURI", "ou", "o", "dateOfBirth", "gender","preferredLanguage",
118       "departmentNumber", "employeeNumber", "employeeType", "l", "st","jpegPhoto",
119       "roomNumber", "telephoneNumber", "mobile", "pager", "cn", "userPKCS12",
120       "postalAddress", "facsimileTelephoneNumber", "userSMIMECertificate", "gosaLoginRestriction", "manager");
122   var $objectclasses= array("top", "person", "organizationalPerson", "inetOrgPerson",
123       "gosaAccount");
125   /* attributes that are part of the government mode */
126   var $govattrs= array("gouvernmentOrganizationalUnit", "houseIdentifier", "vocation",
127       "ivbbLastDeliveryCollective", "gouvernmentOrganizationalPersonLocality",
128       "gouvernmentOrganizationalUnitDescription","gouvernmentOrganizationalUnitSubjectArea",
129       "functionalTitle", "certificateSerialNumber", "publicVisible", "street", "role",
130       "postalCode");
132   var $multiple_support = TRUE;
134   var $governmentmode = FALSE;
136   /* constructor, if 'dn' is set, the node loads the given
137      'dn' from LDAP */
138   function user (&$config, $dn= NULL)
139   {
140     global $lang;
142     $this->config= $config;
143     /* Configuration is fine, allways */
144     if($this->config->get_cfg_value("honourIvbbAttributes") == "true"){
145       $this->governmentmode = TRUE;
146       $this->attributes=array_merge($this->attributes,$this->govattrs);
147     }
149     /* Load base attributes */
150     plugin::plugin ($config, $dn);
152     $this->orig_dn  = $this->dn;
153     $this->new_dn   = $dn;
155     if ($this->governmentmode){
156       /* Fix public visible attribute if unset */
157       if (!isset($this->attrs['publicVisible'])){
158         $this->publicVisible == "nein";
159       }
160     }
162     /* Load government mode attributes */
163     if ($this->governmentmode){
164       /* Copy all attributs */
165       foreach ($this->govattrs as $val){
166         if (isset($this->attrs["$val"][0])){
167           $this->$val= $this->attrs["$val"][0];
168         }
169       }
170     }
172     /* Create me for new accounts */
173     if ($dn == "new"){
174       $this->is_account= TRUE;
175     }
177     /* Make hash default to md5 if not set in config */
178     $hash= $this->config->get_cfg_value("passwordDefaultHash", "crypt/md5");
180     /* Load data from LDAP? */
181     if ($dn !== NULL){
183       /* Do base conversation */
184       if ($this->dn == "new"){
185         $ui= get_userinfo();
186         $this->base= dn2base(session::global_is_set("CurrentMainBase")?"cn=dummy,".session::global_get("CurrentMainBase"):$ui->dn);
187       } else {
188         $this->base= dn2base($dn);
189       }
191       /* get password storage type */
192       if (isset ($this->attrs['userPassword'][0])){
193         /* Initialize local array */
194         $matches= array();
195         if (preg_match ("/^{[^}]+}/", $this->attrs['userPassword'][0])){
196           $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
197           if(is_object($tmp)){
198             $this->pw_storage= $tmp->get_hash(); 
199           }
201         } else {
202           if ($this->attrs['userPassword'][0] != ""){
203             $this->pw_storage= "clear";
204           } else {
205             $this->pw_storage= $hash;
206           }
207         }
208       } else {
209         /* Preset with vaule from configuration */
210         $this->pw_storage= $hash;
211       }
213       /* Load extra attributes: certificate and picture */
214       $this->load_cert();
215       $this->load_picture();
216       if ($this->userCertificate != ""){
217         $this->had_userCertificate= TRUE;
218       }
219     }
221     /* Reset password storage indicator, used by password_change_needed() */
222     if ($dn == "new"){
223       $this->last_pw_storage= "unset";
224     } else {
225       $this->last_pw_storage= $this->pw_storage;
226     }
228     /* Generate dateOfBirth entry */
229     if (isset ($this->attrs['dateOfBirth'])){
230       /* This entry is ISO 8601 conform */
231       list($year, $month, $day)= explode("-", $this->attrs['dateOfBirth'][0], 3);
232     
233       #TODO: use $lang to convert date
234       $this->dateOfBirth= "$day.$month.$year";
235     } else {
236       $this->dateOfBirth= "";
237     }
239     /* Put gender attribute to upper case */
240     if (isset ($this->attrs['gender'])){
241       $this->gender= strtoupper($this->attrs['gender'][0]);
242     }
244     // Get login restrictions
245     if(isset($this->attrs['gosaLoginRestriction'])){
246       $this->gosaLoginRestriction  =array();
247       for($i =0;$i < $this->attrs['gosaLoginRestriction']['count']; $i++){
248         $this->gosaLoginRestriction[] = $this->attrs['gosaLoginRestriction'][$i];
249       }
250     }
251     $this->gosaLoginRestrictionWidget= new sortableListing($this->gosaLoginRestriction);
252     $this->gosaLoginRestrictionWidget->setDeleteable(true);
253     $this->gosaLoginRestrictionWidget->setColspecs(array('*'));
254     $this->gosaLoginRestrictionWidget->setWidth("100%");
255     $this->gosaLoginRestrictionWidget->setHeight("70px");
256  
257     $this->orig_base = $this->base;
258     $this->baseSelector= new baseSelector($this->allowedBasesToMoveTo(), $this->base);
259     $this->baseSelector->setSubmitButton(false);
260     $this->baseSelector->setHeight(300);
261     $this->baseSelector->update(true);
264     // Detect the managers name
265     $this->manager_name = "";
266     $ldap = $this->config->get_ldap_link();
267     if(!empty($this->manager)){
268       $ldap->cat($this->manager, array('cn'));
269       if($ldap->count()){
270         $attrs = $ldap->fetch();
271         $this->manager_name = $attrs['cn'][0];
272       }else{
273         $this->manager_name = "("._("Unknown")."!): ".$this->manager;
274       }
275     }
276   }
279   /* execute generates the html output for this node */
280   function execute()
281   {
282     /* Call parent execute */
283     plugin::execute();
285     /* Set list ACL */
286     $this->gosaLoginRestrictionWidget->setAcl($this->getacl('gosaLoginRestriction', (!is_object($this->parent) && !session::is_set('edit'))));
287     $this->gosaLoginRestrictionWidget->update();
289     /* Handle add/delete for restriction mode */
290     if (isset($_POST['add_res']) && isset($_POST['res'])) {
291       $val= validate($_POST['res']);
292       if (preg_match('/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/', $val) ||
293           preg_match('/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\/([0-9]+)$/', $val) ||
294           preg_match('/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\/([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$/', $val)) {
295         $this->gosaLoginRestrictionWidget->addEntry($val);
296       } else {
297         msg_dialog::display(_("Error"), _("Please add a single IP address or a network/netmask combination!"), ERROR_DIALOG);
298       }
299     }
301     /* Log view */
302     if($this->is_account && !$this->view_logged){
303       $this->view_logged = TRUE;
304       new log("view","users/".get_class($this),$this->dn);
305     }
307     // Clear manager attribute if requested
308     if(preg_match("/ removeManager/i", " ".implode(array_keys($_POST),' ')." ")){
309       $this->manager = "";
310       $this->manager_name = "";
311     }
313     // Allow to select a new inetOrgPersion:manager 
314     if(preg_match("/ editManager/i", " ".implode(array_keys($_POST),' ')." ")){
315       $this->dialog = new singleUserSelect($this->config, get_userinfo());
316     }
317     if($this->dialog instanceOf singleUserSelect && count($this->dialog->detectPostActions())){
318       $users = $this->dialog->detectPostActions();
319       if(isset($users['targets']) && count($users['targets'])){
321         $headpage = $this->dialog->getHeadpage();
322         $dn = $users['targets'][0];
323         $attrs = $headpage->getEntry($dn);
324         $this->manager = $dn;
325         $this->manager_name = $attrs['cn'][0];
326         $this->dialog = NULL;
327       }
328     }
329     if(isset($_POST['add_users_cancel'])){
330       $this->dialog = NULL;
331     }
332     if($this->dialog instanceOf singleUserSelect) return($this->dialog->execute()); 
335     $smarty= get_smarty();
336     $smarty->assign("usePrototype", "true");
337     $smarty->assign("gosaLoginRestrictionWidget", $this->gosaLoginRestrictionWidget->render());
339     /* Assign sex */
340     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
341     $smarty->assign("gender_list", $sex);
342     $language= array_merge(array(0 => "&nbsp;") ,get_languages(TRUE));
343     $smarty->assign("preferredLanguage_list", $language);
345     /* Get random number for pictures */
346     srand((double)microtime()*1000000); 
347     $smarty->assign("rand", rand(0, 10000));
350     /* Do we represent a valid gosaAccount? */
351     if (!$this->is_account){
352       $str = "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
353         msgPool::noValidExtension("GOsa")."</b>";
354       return($str);
355     }
357     /* Password configure dialog handling */
358     if(is_object($this->pwObject) && $this->pwObject->display){
359       $output= $this->pwObject->configure();
360       if ($output != ""){
361         $this->dialog= TRUE;
362         return $output;
363       }
364       $this->dialog= false;
365     }
367     /* Want password method editing? */
368     if ($this->acl_is_writeable("userPassword")){
369       if (isset($_POST['edit_pw_method'])){
370         if (!is_object($this->pwObject) || $this->pw_storage != $this->pwObject->get_hash_name()){
371           $temp= passwordMethod::get_available_methods();
372           $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
373         }
374         $this->pwObject->display = TRUE;
375         $this->dialog= TRUE;
376         return ($this->pwObject->configure());
377       }
378     }
380     /* Want picture edit dialog? */
381     if($this->acl_is_writeable("userPicture")) {
382       if (isset($_POST['edit_picture'])){
383         /* Save values for later recovery, in case some presses
384            the cancel button. */
385         $this->old_jpegPhoto= $this->jpegPhoto;
386         $this->old_photoData= $this->photoData;
387         $this->picture_dialog= TRUE;
388         $this->dialog= TRUE;
389       }
390     }
392     /* Remove picture? */
393     if($this->acl_is_writeable("userPicture",(!is_object($this->parent) && !session::is_set('edit'))) ){
394       if (isset($_POST['picture_remove'])){
395         $this->set_picture ();
396         $this->jpegPhoto= "*removed*";
397         $this->is_modified= TRUE;
398         return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
399       }
400     }
402     /* Save picture */
403     if (isset($_POST['picture_edit_finish'])){
405       /* Check for clean upload */
406       if ($_FILES['picture_file']['name'] != ""){
407         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
408           msg_dialog::display(_("Error"), _("Cannot upload file!"), ERROR_DIALOG);
409         }else{
410           /* Activate new picture */
411           $this->set_picture($_FILES['picture_file']['tmp_name']);
412         }
413       }
414       $this->picture_dialog= FALSE;
415       $this->dialog= FALSE;
416       $this->is_modified= TRUE;
417     }
420     /* Cancel picture */
421     if (isset($_POST['picture_edit_cancel'])){
423       /* Restore values */
424       $this->jpegPhoto= $this->old_jpegPhoto;
425       $this->photoData= $this->old_photoData;
427       /* Update picture */
428       session::set('binary',$this->photoData);
429       session::set('binarytype',"image/jpeg");
430       $this->picture_dialog= FALSE;
431       $this->dialog= FALSE;
432     }
434     /* Want certificate= */
435     if ((isset($_POST['edit_cert'])) && $this->acl_is_readable("Certificate")){
437       /* Save original values for later reconstruction */
438       foreach (array("certificateSerialNumber", "userCertificate",
439             "userSMIMECertificate", "userPKCS12") as $val){
441         $oval= "old_$val";
442         $this->$oval= $this->$val;
443       }
445       $this->cert_dialog= TRUE;
446       $this->dialog= TRUE;
447     }
450     /* Cancel certificate dialog */
451     if (isset($_POST['cert_edit_cancel'])){
453       /* Restore original values in case of 'cancel' */
454       foreach (array("certificateSerialNumber", "userCertificate",
455             "userSMIMECertificate", "userPKCS12") as $val){
457         $oval= "old_$val";
458         $this->$val= $this->$oval;
459       }
460       $this->cert_dialog= FALSE;
461       $this->dialog= FALSE;
462     }
465     /* Remove certificate? */
466     if($this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))){ 
467       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
468         if (isset($_POST["remove_$val"])){
470           /* Reset specified cert*/
471           $this->$val= "";
472           $this->is_modified= TRUE;
473         }
474       }
475     }
477     /* Upload new cert and close dialog? */     
478     if($this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))){ 
480       $fail =false;
482       if (isset($_POST['cert_edit_finish'])){
484         /* for all certificates do */
485         foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
486             as $val){
488           /* Check for clean upload */
489           if (array_key_exists($val."_file", $_FILES) &&
490               array_key_exists('name', $_FILES[$val."_file"]) &&
491               $_FILES[$val."_file"]['name'] != "" &&
492               is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
493             $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
494           }
495         }
497         /* Save serial number */
498         if (isset($_POST["certificateSerialNumber"]) &&
499             $_POST["certificateSerialNumber"] != ""){
501           if (!tests::is_id($_POST["certificateSerialNumber"])){
502             $fail = true;
503             msg_dialog::display(_("Error"), msgPool::invalid(_("Serial number"),$_POST["certificateSerialNumber"],"/[0-9]/"),ERROR_DIALOG);
505             foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
506               if ($this->$cert != ""){
507                 $smarty->assign("$cert"."_state", "true");
508               } else {
509                 $smarty->assign("$cert"."_state", "");
510               }
511             }
512           }
514           $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
515           $this->is_modified= TRUE;
516         }
517         if(!$fail){
518           $this->cert_dialog= FALSE;
519           $this->dialog= FALSE;
520         }
521       }
522     }
523     /* Display picture dialog */
524     if ($this->picture_dialog){
525       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
526     }
528     /* Display cert dialog */
529     if ($this->cert_dialog){
530       $smarty->assign("CertificateACL",$this->getacl("Certificate",(!is_object($this->parent) && !session::is_set('edit'))));
531       $smarty->assign("Certificate_readable",$this->acl_is_readable("Certificate"));
532       $smarty->assign("certificateSerialNumber",$this->certificateSerialNumber);
534       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
535         if ($this->$cert != ""){
536           /* import certificate */
537           $certificate = new certificate;
538           $certificate->import($this->$cert);
539       
540           /* Read out data*/
541           $timeto   = $certificate->getvalidto_date();
542           $timefrom = $certificate->getvalidfrom_date();
543          
544           
545           /* Additional info if start end time is '0' */
546           $add_str_info = "";
547           if($timeto == 0 && $timefrom == 0){
548             $add_str_info = "<br><i>"._("(Some types of certificates are currently not supported and may be displayed as 'invalid'.)")."</i>";
549           }
551           $str = "<table summary=\"\" border=0>
552                     <tr>
553                       <td style='vertical-align:top'>CN</td>
554                       <td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td>
555                     </tr>
556                   </table><br>".
558                   sprintf(_("Certificate is valid from %s to %s and is currently %s."),
559                         "<b>".date('d M Y',$timefrom)."</b>",
560                         "<b>".date('d M Y',$timeto)."</b>",
561                         $certificate->isvalid()?"<b><font style='color:green'>"._("valid")."</font></b>":
562                                                 "<b><font style='color:red'>"._("invalid")."</font></b>").$add_str_info;
564           $smarty->assign($cert."info",$str);
565           $smarty->assign($cert."_state","true");
566         } else {
567           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
568           $smarty->assign($cert."_state","");
569         }
570       }
571   
572       if($this->governmentmode){
573         $smarty->assign("honourIvbbAttributes", "true");
574       }else{
575         $smarty->assign("honourIvbbAttributes", "false");
576       }
577       $smarty->assign("governmentmode", $this->governmentmode);
578       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
579     }
581     /* Prepare password hashes */
582     if ($this->pw_storage == ""){
583       $this->pw_storage= $this->config->get_cfg_value("passwordDefaultHash");
584     }
586     $temp= passwordMethod::get_available_methods();
587     $is_configurable= FALSE;
588     $hashes = $temp['name'];
589     if(isset($temp[$this->pw_storage])){
590       $test= new $temp[$this->pw_storage]($this->config);
591       $is_configurable= $test->is_configurable();
592     }else{
593       new msg_dialog(_("Password method"),_("The selected password method is no longer available."),WARNING_DIALOG);
594     }
597     /* Create password methods array */
598     $pwd_methods = array();
599     foreach($hashes as $id => $name){
600       if(!empty($temp['desc'][$id])){
601         $pwd_methods[$name] = $name." (".$temp['desc'][$id].")";
602       }else{
603         $pwd_methods[$name] = $name;
604       }
605     }
606  
607     /* Load attributes and acl's */
608     $ui =get_userinfo();
609     foreach($this->attributes as $val){
610       $smarty->assign("$val", $this->$val);
611       if(in_array($val,$this->multi_boxes)){
612         $smarty->assign("use_".$val,TRUE);
613       }else{
614         $smarty->assign("use_".$val,FALSE);
615       }
616     }
617     foreach(array("base","pw_storage","edit_picture") as $val){
618       if(in_array($val,$this->multi_boxes)){
619         $smarty->assign("use_".$val,TRUE);
620       }else{
621         $smarty->assign("use_".$val,FALSE);
622       }
623     }
625     /* Set acls */
626     $tmp = $this->plinfo();
627     foreach($tmp['plProvidedAcls'] as $val => $translation){
628       $smarty->assign("$val"."ACL", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit'))));
629     }
631     // Special ACL for gosaLoginRestrictions - 
632     // In case of multiple edit, we need a readonly ACL for the list. 
633     $smarty->assign('gosaLoginRestriction_ONLY_R_ACL', 
634       preg_replace("/[^r]/i","", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit')))));
636     $smarty->assign("pwmode", $pwd_methods);
637     $smarty->assign("pwmode_select", $this->pw_storage);
638     $smarty->assign("pw_configurable", $is_configurable);
639     $smarty->assign("passwordStorageACL", $this->getacl("userPassword",(!is_object($this->parent) && !session::is_set('edit'))));
641     if(!session::is_set('edit')){
642       $smarty->assign("CertificatesACL","");
643     }else{
644       $smarty->assign("CertificatesACL",  $this->getacl("Certificate"));
645     }
646     
647     $smarty->assign("userPictureACL",   $this->getacl("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));
648     $smarty->assign("userPicture_is_readable",   $this->acl_is_readable("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));
650     /* Create base acls */
651     $smarty->assign("base", $this->baseSelector->render());
653     /* Save government mode attributes */
654     if($this->governmentmode){
655       $smarty->assign("governmentmode", "true");
656       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
657           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
658       $smarty->assign("ivbbmodes", $ivbbmodes);
659       foreach ($this->govattrs as $val){
660         $smarty->assign("$val", $this->$val);
661         $smarty->assign("$val"."ACL", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit'))));
662       }
663     } else {
664       $smarty->assign("governmentmode", "false");
665     }
667     /* Special mode for uid */
668     $uidACL= $this->getacl("uid",(!is_object($this->parent) && !session::is_set('edit')));
669     if (isset ($this->dn)){
670       if ($this->dn != "new"){
671         $uidACL= preg_replace("/w/","",$uidACL);
672       }
673     }  else {
674       $uidACL= preg_replace("/w/","",$uidACL);
675     }
676     
677     $smarty->assign("uidACL", $uidACL);
678     $smarty->assign("is_template", $this->is_template);
679     $smarty->assign("use_dob", $this->use_dob);
681     if (isset($this->parent)){
682       if (isset($this->parent->by_object['phoneAccount']) &&
683           $this->parent->by_object['phoneAccount']->is_account){
684         $smarty->assign("has_phoneaccount", "true");
685       } else {
686         $smarty->assign("has_phoneaccount", "false");
687       }
688     } else {
689       $smarty->assign("has_phoneaccount", "false");
690     }
691     $smarty->assign("multiple_support" , $this->multiple_support_active);
692     $smarty->assign("manager_name",$this->manager_name);
693     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
694   }
697   /* remove object from parent */
698   function remove_from_parent()
699   {
700     /* Only remove valid accounts */
701     if(!$this->initially_was_account) return;
703     /* Remove password extension */
704     $temp= passwordMethod::get_available_methods();
706     /* Remove password method from user account */
707     if(isset($temp[$this->pw_storage]) && class_available($temp[$this->pw_storage])){
708       $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
709       $this->pwObject->remove_from_parent();
710     }
712     /* Remove user */
713     $ldap= $this->config->get_ldap_link();
714     $ldap->rmdir ($this->dn);
715     if (!$ldap->success()){
716       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
717     }
718   
719     new log("remove","users/".get_class($this),$this->dn,$this->attributes,$ldap->get_error());
720   
721     /* Delete references to groups */
722     $ldap->cd ($this->config->current['BASE']);
723     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
724     while ($ldap->fetch()){
725       $g= new group($this->config, $ldap->getDN());
726       $g->removeUser($this->uid);
727       $g->save ();
728     }
730     /* Delete references to object groups */
731     $ldap->cd ($this->config->current['BASE']);
732     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
733     while ($ldap->fetch()){
734       $og= new ogroup($this->config, $ldap->getDN());
735       unset($og->member[$this->dn]);
736       $og->save ();
737     }
739     // Update 'manager' attributes from gosaDepartment and inetOrgPerson
740     $filter = "(&(objectClass=inetOrgPerson)(manager=".LDAP::prepare4filter($this->dn)."))";
741     $ocs = $ldap->get_objectclasses();
742     if(isset($ocs['gosaDepartment']['MAY']) && in_array('manager', $ocs['gosaDepartment']['MAY'])){
743       $filter = "(|".$filter."(&(objectClass=gosaDepartment)(manager=".LDAP::prepare4filter($this->dn).")))";
744     }
745     $leaf_deps=  get_list($filter,array("all"),$this->config->current['BASE'],
746         array("manager","dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
747     foreach($leaf_deps as $entry){
748       $update = array('manager' => array());
749       $ldap->cd($entry['dn']);
750       $ldap->modify($update);
751       if(!$ldap->success()){
752         trigger_error(sprintf("Failed to update manager for '%s', error was '%s'", $entry['dn'], $ldap->get_error()));
753       }
754     }
756     /* Delete references to roles */
757     $ldap->cd ($this->config->current['BASE']);
758     $ldap->search ("(&(objectClass=organizationalRole)(roleOccupant=".LDAP::prepare4filter($this->dn)."))", array("cn"));
759     while ($ldap->fetch()){
760       $role= new roleGeneric($this->config, $ldap->getDN());
761       $key = array_search($this->dn,$role->roleOccupant);
762       if($key !== FALSE){
763         unset($role->roleOccupant[$key]);
764         $role->roleOccupant= array_values($role->roleOccupant);
765         $role->save ();
766       }
767     }
769     /* If needed, let the password method do some cleanup */
770     $tmp = new passwordMethod($this->config);
771     $available = $tmp->get_available_methods();
772     if (in_array_ics($this->pw_storage, $available['name'])){
773       $test= new $available[$this->pw_storage]($this->config);
774       $test->attrs= $this->attrs;
775       $test->dn= $this->dn;
776       $test->remove_from_parent();
777     }
779     /* Remove ACL dependencies too */
780     acl::remove_acl_for($this->dn);
782     /* Optionally execute a command after we're done */
783     $this->handle_post_events("remove",array("uid" => $this->uid));
784   }
787   /* Save data to object */
788   function save_object()
789   {
790     if(isset($_POST['generic']) || isset($_POST['multiple_user_posted'])){
792       /* Make a backup of the current selected base */
793       $base_tmp = $this->base;
795       /* Parents save function */
796       plugin::save_object ();
798       /* Refresh base */
799       if ($this->acl_is_moveable($this->base)){
800         if (!$this->baseSelector->update()) {
801           msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
802         }
803         if ($this->base != $this->baseSelector->getBase()) {
804           $this->base= $this->baseSelector->getBase();
805           $this->is_modified= TRUE;
806         }
807       }
808       
809       /* Sync lists */
810       $this->gosaLoginRestrictionWidget->save_object();
811       if ($this->gosaLoginRestrictionWidget->isModified()) {
812         $this->gosaLoginRestriction= array_values($this->gosaLoginRestrictionWidget->getMaintainedData());
813       }
815       /* Save government mode attributes */
816       if ($this->governmentmode){
817         foreach ($this->govattrs as $val){
818           if ($this->acl_is_writeable($val,(!is_object($this->parent) && !session::is_set('edit'))) && isset($_POST["$val"])){
819             $data= stripcslashes($_POST["$val"]);
820             if ($data != $this->$val){
821               $this->is_modified= TRUE;
822             }
823             $this->$val= $data;
824           }
825         }
826       }
828       /* In template mode, the uid is autogenerated... */
829       if ($this->is_template){
830         $this->uid= strtolower($this->sn);
831         $this->givenName= $this->sn;
832       }
834       /* Get pw_storage mode */
835       if (isset($_POST['pw_storage'])){
836         foreach(array("pw_storage") as $val){
837           if(isset($_POST[$val])){
838             $data= validate($_POST[$val]);
839             if ($data != $this->$val){
840               $this->is_modified= TRUE;
841             }
842             $this->$val= $data;
843           }
844         }
845       }
847       if($this->pw_storage != $this->last_pw_storage && isset($_POST['pw_storage'])){
848         if ($this->acl_is_writeable("userPassword")){
849           $temp= passwordMethod::get_available_methods();
850           if (!is_object($this->pwObject) || !($this->pwObject instanceOf $temp[$this->pw_storage])){
851             foreach($temp as $id => $data){
852               if(isset($data['name']) && $data['name'] == $this->pw_storage && $data['is_configurable']){
853                 $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
854                 break;
855               }
856             }
857           }
858         }
859       }
861       /* Save current cn
862        */
863       $this->cn = $this->givenName." ".$this->sn;
864     }
865   }
867   function rebind($ldap, $referral)
868   {
869     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
870     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
871       $this->error = "Success";
872       $this->hascon=true;
873       $this->reconnect= true;
874       return (0);
875     } else {
876       $this->error = "Could not bind to " . $credentials['ADMIN'];
877       return NULL;
878     }
879   }
881   
882   /* Save data to LDAP, depending on is_account we save or delete */
883   function save()
884   {
885     global $lang;
887     /* Only force save of changes .... 
888        If this attributes aren't changed, avoid saving.
889      */
890   
891     if($this->gender=="0") $this->gender ="";
892     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
894     /* First use parents methods to do some basic fillup in $this->attrs */
895     plugin::save ();
897     if ($this->dateOfBirth != ""){
898       if(!is_array($this->attrs['dateOfBirth'])) {
899         #TODO: use $lang to convert date
900         list($day, $month, $year)= explode(".", $this->dateOfBirth);
901         $this->attrs['dateOfBirth'] = sprintf("%04d-%02d-%02d", $year, $month, $day);
902       }
903     }
905     /* Remove additional objectClasses */
906     $tmp= array();
907     foreach ($this->attrs['objectClass'] as $key => $set){
908       $found= false;
909       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
910         if (preg_match ("/^$set$/i", $val)){
911           $found= true;
912           break;
913         }
914       }
915       if (!$found){
916         $tmp[]= $set;
917       }
918     }
920     /* Replace the objectClass array. This is done because of the
921        separation into government and normal mode. */
922     $this->attrs['objectClass']= $tmp;
924     /* Add objectClasss for template mode? */
925     if ($this->is_template){
926       $this->attrs['objectClass'][]= "gosaUserTemplate";
927     }
929     /* Hard coded government mode? */
930     if ($this->governmentmode){
931       $this->attrs['objectClass'][]= "ivbbentry";
933       /* Copy standard attributes */
934       foreach ($this->govattrs as $val){
935         if ($this->$val != ""){
936           $this->attrs["$val"]= $this->$val;
937         } elseif (!$this->is_new) {
938           $this->attrs["$val"]= array();
939         }
940       }
942       /* Remove attribute if set to "nein" */
943       if ($this->publicVisible == "nein"){
944         $this->attrs['publicVisible']= array();
945         if($this->is_new){
946           unset($this->attrs['publicVisible']);
947         }else{
948           $this->attrs['publicVisible']=array();
949         }
951       }
953     }
955     /* Special handling for attribute userCertificate needed */
956     if ($this->userCertificate != ""){
957       $this->attrs["userCertificate;binary"]= $this->userCertificate;
958       $remove_userCertificate= false;
959     } else {
960       $remove_userCertificate= true;
961     }
963     /* Special handling for dateOfBirth value */
964     if ($this->dateOfBirth == ""){
965       if ($this->is_new) {
966         unset($this->attrs["dateOfBirth"]);
967       } else {
968         $this->attrs["dateOfBirth"]= array();
969       }
970     }
971     if (!$this->gender){
972       if ($this->is_new) {
973         unset($this->attrs["gender"]);
974       } else {
975         $this->attrs["gender"]= array();
976       }
977     }
978     if (!$this->preferredLanguage){
979       if ($this->is_new) {
980         unset($this->attrs["preferredLanguage"]);
981       } else {
982         $this->attrs["preferredLanguage"]= array();
983       }
984     }
986     /* Special handling for attribute jpegPhote needed, scale image via
987        image magick to 147x200 pixels and inject resulting data. */
988     if ($this->jpegPhoto == "*removed*"){
989     
990       /* Reset attribute to avoid writing *removed* as value */    
991       $this->attrs["jpegPhoto"] = array();
993     } else {
995       /* Fallback if there's no image magick inside PHP */
996       if (!function_exists("imagick_blob2image")){
997         /* Get temporary file name for conversation */
998         $fname = tempnam (TEMP_DIR, "GOsa");
999   
1000         /* Open file and write out photoData */
1001         $fp = fopen ($fname, "w");
1002         fwrite ($fp, $this->photoData);
1003         fclose ($fp);
1005         /* Build conversation query. Filename is generated automatically, so
1006            we do not need any special security checks. Exec command and save
1007            output. For PHP safe mode, you'll need a configuration which respects
1008            image magick as executable... */
1009         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
1010         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
1011             $query, "Execute");
1012   
1013         /* Read data written by convert */
1014         $output= "";
1015         $sh= popen($query, 'r');
1016         while (!feof($sh)){
1017           $output.= fread($sh, 4096);
1018         }
1019         pclose($sh);
1021         unlink($fname);
1023         /* Save attribute */
1024         $this->attrs["jpegPhoto"] = $output;
1026       } else {
1028         /* Load the new uploaded Photo */
1029         if(!$handle  =  imagick_blob2image($this->photoData))  {
1030           new log("debug","users/".get_class($this),$this->dn,array(),"Could not access uploaded image");
1031         }
1033         /* Resizing image to 147x200 and blur */
1034         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
1035           new log("debug","users/".get_class($this),$this->dn,array(),"Could not resize uploaded image");
1036         }
1038         /* Converting image to JPEG */
1039         if(!imagick_convert($handle,"JPEG")) {
1040           new log("debug","users/".get_class($this),$this->dn,array(),"Could not convert uploaded image to jepg");
1041         }
1043         /* Creating binary Code for the Image */
1044         if(!$dump = imagick_image2blob($handle)){
1045           new log("debug","users/".get_class($this),$this->dn,array(),"Could not create new user image");
1046         }
1048         /* Sending Image */
1049         $output=  $dump;
1051         /* Save attribute */
1052         $this->attrs["jpegPhoto"] = $output;
1053       }
1055     }
1057     /* This only gets called when user is renaming himself */
1058     $ldap= $this->config->get_ldap_link();
1059     if ($this->dn != $this->new_dn){
1061       /* Write entry on new 'dn' */
1062       $this->update_acls($this->dn,$this->new_dn);
1063       $this->move($this->dn, $this->new_dn);
1065       /* Happen to use the new one */
1066       change_ui_dn($this->dn, $this->new_dn);
1067       $this->dn= $this->new_dn;
1068     }
1071     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
1072        new entries. So do a check first... */
1073     $ldap->cat ($this->dn, array('dn'));
1074     if ($ldap->fetch()){
1075       $mode= "modify";
1076     } else {
1077       $mode= "add";
1078       $ldap->cd($this->config->current['BASE']);
1079       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
1080     }
1082     /* Set password to some junk stuff in case of templates */
1083     if ($this->is_template){
1084       $temp= passwordMethod::get_available_methods();
1085       foreach($temp as $id => $data){
1086         if(isset($data['name']) && $data['name'] == $this->pw_storage){
1087           $tmp = new  $temp[$this->pw_storage]($this->config,$this->dn);
1088           $tmp->set_hash($this->pw_storage);
1089           $this->attrs['userPassword'] = $tmp->create_template_hash($this->attrs);
1090           break;
1091         }
1092       }
1093     }
1095     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
1096         $this->attributes, "Save via $mode");
1098     /* Finally write data with selected 'mode' */
1099     $this->cleanup();
1101     /* Update current locale settings, if we have edited ourselves */
1102     $ui = session::get('ui');
1103     if(isset($this->attrs['preferredLanguage']) && $this->dn == $ui->dn){
1104       $ui->language = $this->preferredLanguage;
1105       session::set('ui',$ui);
1106       session::set('Last_init_lang',"update");
1107     }
1109     $ldap->cd ($this->dn);
1110     $ldap->$mode ($this->attrs);
1111     if (!$ldap->success()){
1112       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
1113       return (1);
1114     }
1116     /* Remove ACL dependencies too */
1117     if($this->dn != $this->orig_dn && $this->orig_dn != "new"){
1118       $tmp = new acl($this->config,$this->parent,$this->dn);
1119       $tmp->update_acl_membership($this->orig_dn,$this->dn);
1120     }
1122     if($mode == "modify"){
1123       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1124     }else{
1125       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1126     }
1128     /* Remove cert? 
1129        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
1130        to work around myself. */
1131     if ($remove_userCertificate == true && !$this->is_new && $this->had_userCertificate){
1133       /* Reset array, assemble new, this should be reworked */
1134       $this->attrs= array();
1135       $this->attrs['userCertificate;binary']= array();
1137       /* Prepare connection */
1138       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
1139         die ("Could not connect to LDAP server");
1140       }
1141       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1142       if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true") {
1143         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1144         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1145       }
1146       if($this->config->get_cfg_value("ldapTLS") == "true"){
1147         ldap_start_tls($ds);
1148       }
1149       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
1150               $this->config->current['PASSWORD']))) {
1151         die ("Could not bind to LDAP");
1152       }
1154       /* Modify using attrs */
1155       ldap_mod_del($ds,$this->dn,$this->attrs);
1156       ldap_close($ds);
1157     }
1159     /* If needed, let the password method do some cleanup */
1160     if ($this->pw_storage != $this->last_pw_storage){
1161       $tmp = new passwordMethod($this->config);
1162       $available = $tmp->get_available_methods();
1163       if (in_array_ics($this->last_pw_storage, $available['name'])){
1164         $test= new $available[$this->last_pw_storage]($this->config,$this->dn);
1165         $test->attrs= $this->attrs;
1166         $test->remove_from_parent();
1167       }
1168     }
1170     /* Maybe the current password method want's to do some changes... */
1171     if (is_object($this->pwObject)){
1172       $this->pwObject->save($this->dn);
1173     }
1175     /* Optionally execute a command after we're done */
1176     if ($mode == "add"){
1177       $this->handle_post_events("add", array("uid" => $this->uid));
1178     } elseif ($this->is_modified){
1179       $this->handle_post_events("modify", array("uid" => $this->uid));
1180     }
1182     return (0);
1183   }
1186   function create_initial_rdn($pattern)
1187   {
1188     // Only generate single RDNs
1189     if (preg_match('/\+/', $pattern)){
1190       msg_dialog::display(_("Error"), _("Cannot build RDN: no + allowed to build sub RDN!"), ERROR_DIALOG);
1191       return "";
1192     }
1194     // Extract attribute
1195     $attribute= preg_replace('/=.*$/', '', $pattern);
1196     if (!in_array_ics($attribute, $this->attributes)) {
1197       msg_dialog::display(_("Error"), _("Cannot build RDN: attribute is not defined!"), ERROR_DIALOG);
1198       return "";
1199     }
1201     // Sort attributes for length
1202     $attrl= array();
1203     foreach ($this->attributes as $attr) {
1204       $attrl[$attr]= strlen($attr);
1205     }
1206     arsort($attrl);
1207     
1208     // Walk thru sorted attributes and replace them in pattern
1209     foreach ($attrl as $attr => $dummy) {
1210       if (!is_array($this->$attr)){
1211         $pattern= preg_replace("/%$attr/", $this->$attr, $pattern);
1212       } else {
1213         // Array elements cannot be used for ID generation
1214         if (preg_match("/%$attr/", $pattern)) {
1215           msg_dialog::display(_("Error"), _("Cannot build RDN: invalid attribute parameters!"), ERROR_DIALOG);
1216           break;
1217         }
1218       }
1219     }
1221     // Internally assign value
1222     $this->$attribute= preg_replace('/^[^=]+=/', '', $pattern);
1224     return $pattern;
1225   }
1227   
1228   function update_new_dn()
1229   {
1230     // Alternative way to handle DN
1231     $pattern= $this->config->get_cfg_value("accountRDN");
1232     if ($pattern != "") {
1233       $rdn= $this->create_initial_rdn($pattern);
1234       $attribute= preg_replace('/=.*$/', '', $rdn);
1235       $value= preg_replace('/^[^=]+=$/', '', $rdn);
1237       /* Don't touch dn, if $attribute hasn't changed */
1238       if (isset($this->saved_attributes[$attribute]) && $this->saved_attributes[$attribute] == $this->$attribute &&
1239             $this->orig_base == $this->base ){
1240         $this->new_dn= $this->dn;
1241       } else {
1242         $this->new_dn= $this->create_unique_dn2($rdn, get_people_ou().$this->base);
1243       }
1245     // Original way to handle DN
1246     } else {
1248       $pt= "";
1249       if($this->config->get_cfg_value("personalTitleInDN") == "true"){
1250         if(!empty($this->personalTitle)){
1251           $pt = $this->personalTitle." ";
1252         }
1253       }
1255       $this->cn= $pt.$this->givenName." ".$this->sn;
1257       /* Permissions for that base? */
1258       if ($this->config->get_cfg_value("accountPrimaryAttribute") == "uid"){
1259         $this->new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
1260       } else {
1261         /* Don't touch dn, if cn hasn't changed */
1262         if (isset($this->saved_attributes['cn']) && $this->saved_attributes['cn'] == $this->cn &&
1263             $this->orig_base == $this->base ){
1264           $this->new_dn= $this->dn;
1265         } else {
1266           $this->new_dn= $this->create_unique_dn('cn', get_people_ou().$this->base);
1267         }
1268       }
1269     }
1270   }
1271   
1273   /* Check formular input */
1274   function check()
1275   {
1276     /* Call common method to give check the hook */
1277     $message= plugin::check();
1279     /* Configurable password methods should be configured initially. 
1280      */ 
1281     if($this->last_pw_storage != $this->pw_storage){
1282       $temp= passwordMethod::get_available_methods();
1283       foreach($temp['name'] as $id => $name){
1284         if($name == $this->pw_storage){
1285           if($temp['is_configurable'][$id] && !$this->pwObject instanceof $temp[$name] ){
1286             $message[] = _("The selected password method requires initial configuration!");
1287           }
1288           break;
1289         }
1290       }
1291     }
1293     $this->update_new_dn();
1295     /* Set the new acl base */
1296     if($this->dn == "new") {
1297       $this->set_acl_base($this->base);
1298     }
1300     /* Check if we are allowed to create/move this user */
1301     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
1302       $message[]= msgPool::permCreate();
1303     }elseif($this->orig_dn != "new" && $this->new_dn != $this->orig_dn && !$this->acl_is_moveable($this->base)){
1304       $message[]= msgPool::permMove();
1305     }
1307     /* UID already used? */
1308     $ldap= $this->config->get_ldap_link();
1309     $ldap->cd($this->config->current['BASE']);
1310     $ldap->search("(uid=$this->uid)", array("uid"));
1311     $ldap->fetch();
1312     if ($ldap->count() != 0 && $this->dn == 'new'){
1313       $message[]= msgPool::duplicated(_("Login"));
1314     }
1316     /* In template mode, the uid and givenName are autogenerated... */
1317     if ($this->sn == ""){
1318       $message[]= msgPool::required(_("Name"));
1319     }
1321     // Check if a wrong base was supplied
1322     if(!$this->baseSelector->checkLastBaseUpdate()){
1323       $message[]= msgPool::check_base();;
1324     }
1326     if (!$this->is_template){
1327       if ($this->givenName == ""){
1328         $message[]= msgPool::required(_("Given name"));
1329       }
1330       if ($this->uid == ""){
1331         $message[]= msgPool::required(_("Login"));
1332       }
1333       if ($this->config->get_cfg_value("accountPrimaryAttribute") != "uid"){
1334         $ldap->cat($this->new_dn);
1335         if ($ldap->count() != 0 && $this->dn != $this->new_dn && $this->dn == 'new'){
1336           $message[]= msgPool::duplicated(_("Name"));
1337         }
1338       }
1339     }
1341     /* Check for valid input */
1342     if ($this->is_modified && !tests::is_uid($this->uid)){
1344       if (strict_uid_mode()){
1345         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/");
1346       } else {
1347         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/i");
1348       }
1349     }
1350     if (!tests::is_url($this->labeledURI)){
1351       $message[]= msgPool::invalid(_("Homepage"), "", "", "http://www.your-domain.com/yourname");
1352     }
1354     /* Check phone numbers */
1355     if (!tests::is_phone_nr($this->telephoneNumber)){
1356       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1357     }
1358     if (!tests::is_phone_nr($this->facsimileTelephoneNumber)){
1359       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1360     }
1361     if (!tests::is_phone_nr($this->mobile)){
1362       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1363     }
1364     if (!tests::is_phone_nr($this->pager)){
1365       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1366     }
1368     /* Check dates */
1369     if (!tests::is_date($this->dateOfBirth)){
1370       $message[]= msgPool::invalid(_("Date of birth"), $this->dateOfBirth,"" ,"23.02.2009");
1371     }
1373     /* Check for reserved characers */
1374     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName)){
1375       $message[]= msgPool::invalid(_("Given name"), $this->givenName, '/[^,+"?\'()=<>;\\\\]/');
1376     }
1377     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn)){
1378       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1379     }
1381     return $message;
1382   }
1385   /* Indicate whether a password change is needed or not */
1386   function password_change_needed()
1387   {
1388     if($this->multiple_support_active){
1389       return(FALSE);
1390     }else{
1392       if(in_array("pw_storage",$this->multi_boxes)){
1393         return(TRUE);
1394       }
1395       return($this->pw_storage != $this->last_pw_storage && !$this->is_template);
1396     }
1397   }
1400   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1401   function load_picture()
1402   {
1403     $ldap = $this->config->get_ldap_link();
1404     $ldap->cd ($this->dn);
1405     $data = $ldap->get_attribute($this->dn,"jpegPhoto");
1407     if((!$data) || ($data == "*removed*")){ 
1409       /* In case we don't get an entry, load a default picture */
1410       $this->set_picture ();
1411       $this->jpegPhoto= "*removed*";
1412     }else{
1414       /* Set picture */
1415       $this->photoData= $data;
1416       session::set('binary',$this->photoData);
1417       session::set('binarytype',"image/jpeg");
1418       $this->jpegPhoto= "";
1419     }
1420   }
1423   /* Load a certificate from LDAP, this is going to be simplified later on */
1424   function load_cert()
1425   {
1426     $ds= ldap_connect($this->config->current['SERVER']);
1427     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1428     if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true"){
1429       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1430       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1431     }
1432     if ($this->config->get_cfg_value("ldapTLS") == "true"){
1433       ldap_start_tls($ds);
1434     }
1436     $r= ldap_bind($ds);
1437     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1439     if ($sr) {
1440       $ei= @ldap_first_entry($ds, $sr);
1441       
1442       if ($ei) {
1443         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1444           $this->userCertificate= "";
1445         } else {
1446           $this->userCertificate= $info[0];
1447         }
1448       }
1449     } else {
1450       $this->userCertificate= "";
1451     }
1453     ldap_unbind($ds);
1454   }
1457   /* Load picture from file to object */
1458   function set_picture($filename ="")
1459   {
1460     if (!is_file($filename) || $filename =="" ){
1461       $filename= "./plugins/users/images/default.jpg";
1462       $this->jpegPhoto= "*removed*";
1463     }
1465     $fd = fopen ($filename, "rb");
1466     $this->photoData= fread ($fd, filesize ($filename));
1467     session::set('binary',$this->photoData);
1468     session::set('binarytype',"image/jpeg");
1469     $this->jpegPhoto= "";
1471     fclose ($fd);
1472   }
1475   /* Load certificate from file to object */
1476   function set_cert($cert, $filename)
1477   {
1478     if(!$this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))) return;
1479     $fd = fopen ($filename, "rb");
1480     if (filesize($filename)>0) {
1481       $this->$cert= fread ($fd, filesize ($filename));
1482       fclose ($fd);
1483       $this->is_modified= TRUE;
1484     } else {
1485       msg_dialog::display(_("Error"), _("Cannot open certificate!"), ERROR_DIALOG);
1486     }
1487   }
1489   /* Adapt from given 'dn' */
1490   function adapt_from_template($dn, $skip= array())
1491   {
1492     plugin::adapt_from_template($dn, $skip);
1494     /* Get password method from template 
1495      */
1496     $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
1497     if(is_object($tmp)){
1498       if($tmp->is_configurable()){
1499         $tmp->adapt_from_template($dn);
1500         $this->pwObject = &$tmp;
1501       }
1502       $this->pw_storage= $tmp->get_hash();
1503     }
1505     /* Get base */
1506     $this->base= preg_replace('/^[^,]+,'.preg_quote(get_people_ou(), '/').'/i', '', $dn);
1508     if($this->governmentmode){
1510       /* Walk through govattrs */
1511       foreach ($this->govattrs as $val){
1513         if (in_array($val, $skip)){
1514           continue;
1515         }
1517         if (isset($this->attrs["$val"][0])){
1519           /* If attribute is set, replace dynamic parts: 
1520              %sn, %givenName and %uid. Fill these in our local variables. */
1521           $value= $this->attrs["$val"][0];
1523           foreach (array("sn", "givenName", "uid") as $repl){
1524             if (preg_match("/%$repl/i", $value)){
1525               $value= preg_replace ("/%$repl/i",
1526                   $this->parent->$repl, $value);
1527             }
1528           }
1529           $this->$val= $value;
1530         }
1531       }
1532     }
1534     /* Get back uid/sn/givenName - only write if nothing's skipped */
1535     if ($this->parent !== NULL && count($skip) == 0){
1536       $this->uid= $this->parent->uid;
1537       $this->sn= $this->parent->sn;
1538       $this->givenName= $this->parent->givenName;
1539     }
1541     if ($this->dateOfBirth) {
1542       /* This entry is ISO 8601 conform */
1543       list($year, $month, $day)= explode("-", $this->dateOfBirth, 3);
1544     
1545       #TODO: use $lang to convert date
1546       $this->dateOfBirth= "$day.$month.$year";
1547     }
1548   }
1550  
1551   /* This avoids that users move themselves out of their rights. 
1552    */
1553   function allowedBasesToMoveTo()
1554   {
1555     /* Get bases */
1556     $bases  = $this->get_allowed_bases();
1557     return($bases);
1558   } 
1561   function getCopyDialog()
1562   {
1563     $str = "";
1565     session::set('binary',$this->photoData); 
1566     session::set('binarytype',"image/jpeg");
1568     /* Get random number for pictures */
1569     srand((double)microtime()*1000000); 
1570     $rand = rand(0, 10000);
1572     $smarty = get_smarty();
1574     $smarty->assign("passwordTodo","clear");
1576     if(isset($_POST['passwordTodo'])){
1577       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1578     }
1580     $smarty->assign("sn",       $this->sn);
1581     $smarty->assign("givenName",$this->givenName);
1582     $smarty->assign("uid",      $this->uid);
1583     $smarty->assign("rand",     $rand);
1584     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1587     $ret = array();
1588     $ret['string'] = $str;
1589     $ret['status'] = "";  
1590     return($ret);
1591   }
1593   function saveCopyDialog()
1594   {
1595     /* Set_acl_base */
1596     $this->set_acl_base($this->base);
1598     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1599       $this->set_picture($_FILES['picture_file']['tmp_name']);
1600     }
1602     /* Remove picture? */
1603     if (isset($_POST['picture_remove'])){
1604       $this->jpegPhoto= "*removed*";
1605       $this->set_picture ("./plugins/users/images/default.jpg");
1606       $this->is_modified= TRUE;
1607     }
1609     $attrs = array("uid","givenName","sn");
1610     foreach($attrs as $attr){
1611       if(isset($_POST[$attr])){
1612         $this->$attr = $_POST[$attr];
1613       }
1614     } 
1615   }
1618   function PrepareForCopyPaste($source)
1619   {
1620     plugin::PrepareForCopyPaste($source);
1622     /* Reset certificate information addepted from source user
1623        to avoid setting the same user certificate for the destination user. */
1624     $this->userPKCS12= "";
1625     $this->userSMIMECertificate= "";
1626     $this->userCertificate= "";
1627     $this->certificateSerialNumber= "";
1628     $this->old_certificateSerialNumber= "";
1629     $this->old_userPKCS12= "";
1630     $this->old_userSMIMECertificate= "";
1631     $this->old_userCertificate= "";
1633     /* Generate dateOfBirth entry */
1634     if (isset ($source['dateOfBirth'])){
1635         list($year, $month, $day)= explode("-", $source['dateOfBirth'][0], 3);
1636         $this->dateOfBirth= "$day.$month.$year";
1637     } else {
1638         $this->dateOfBirth= "";
1639     }
1641     // Try to load the user picture
1642     $tmp_dn = $this->dn;
1643     $this->dn = $source['dn'];
1644     $this->load_picture();
1645     $this->dn = $tmp_dn;
1646   }
1649   static function plInfo()
1650   {
1651   
1652     $govattrs= array(
1653         "gouvernmentOrganizationalUnit"             =>  _("Unit"), 
1654         "houseIdentifier"                           =>  _("House identifier"), 
1655         "vocation"                                  =>  _("Vocation"),
1656         "ivbbLastDeliveryCollective"                =>  _("Last delivery"), 
1657         "gouvernmentOrganizationalPersonLocality"   =>  _("Person locality"),
1658         "gouvernmentOrganizationalUnitDescription"  =>  _("Unit description"),
1659         "gouvernmentOrganizationalUnitSubjectArea"  =>  _("Subject area"),
1660         "functionalTitle"                           =>  _("Functional title"),
1661         "certificateSerialNumber"                   =>  _("Certificate serial number"),
1662         "publicVisible"                             =>  _("Public visible"),
1663         "street"                                    =>  _("Street"),
1664         "role"                                      =>  _("Role"),
1665         "postalCode"                                =>  _("Postal code"));
1667     $ret = array(
1668         "plShortName" => _("Generic"),
1669         "plDescription" => _("Generic user settings"),
1670         "plSelfModify"  => TRUE,
1671         "plDepends"     => array(),
1672         "plPriority"    => 1,
1673         "plSection"     => array("personal" => _("My account")),
1674         "plCategory"    => array("users" => array("description" => _("Users"),
1675                                                   "objectClass" => "gosaAccount")),
1677         "plProvidedAcls" => array(
1679           "sn"                => _("Surname"),
1680           "givenName"         => _("Given name"),
1681           "uid"               => _("User identification"),
1682           "personalTitle"     => _("Personal title"),
1683           "academicTitle"     => _("Academic title"),
1685           "dateOfBirth"       => _("Date of birth"),
1686           "gender"            => _("Sex"),
1687           "preferredLanguage" => _("Preferred language"),
1688           "base"              => _("Base"), 
1690           "userPicture"       => _("User picture"),
1692           "gosaLoginRestriction" => _("Login restrictions"),         
1694           "o"                 => _("Organization"),
1695           "ou"                => _("Department"),
1696           "departmentNumber"  => _("Department number"),
1697           "manager"           => _("Manager"),
1698           "employeeNumber"    => _("Employee number"),
1699           "employeeType"      => _("Employee type"),
1701           "roomNumber"        => _("Room number"),
1702           "telephoneNumber"   => _("Telefon number"),
1703           "pager"             => _("Pager number"),
1704           "mobile"            => _("Mobile number"),
1705           "facsimileTelephoneNumber"     => _("Fax number"),
1707           "st"                => _("State"),
1708           "l"                 => _("Location"),
1709           "postalAddress"     => _("Postal address"),
1711           "homePostalAddress" => _("Home postal address"),
1712           "homePhone"         => _("Home phone number"),
1713           "labeledURI"        => _("Homepage"),
1714           "userPassword"      => _("User password method"), 
1715           "Certificate"       => _("User certificates"))
1717         );
1719     /* Append government attributes if required */
1720     global $config;
1721     if($config->get_cfg_value("honourIvbbAttributes") == "true"){
1722       foreach($govattrs as $attr => $desc){
1723         $ret["plProvidedAcls"][$attr] = $desc;
1724       }
1725     }
1726     return($ret);
1727   }
1729   function get_multi_edit_values()
1730   {
1731     $ret = plugin::get_multi_edit_values();
1732     if(in_array("pw_storage",$this->multi_boxes)){
1733       $ret['pw_storage'] = $this->pw_storage;
1734     }
1735     if(in_array("edit_picture",$this->multi_boxes)){
1736       $ret['jpegPhoto'] = $this->jpegPhoto;
1737       $ret['photoData'] = $this->photoData;
1738       $ret['old_jpegPhoto'] = $this->old_jpegPhoto;
1739       $ret['old_photoData'] = $this->old_photoData;
1740     }
1741     if(isset($ret['dateOfBirth'])){
1742       unset($ret['dateOfBirth']);
1743     }
1744     if(isset($ret['cn'])){
1745       unset($ret['cn']);
1746     }
1747     $ret['is_modified'] = $this->is_modified;
1748     if(in_array("base",$this->multi_boxes)){
1749       $ret['orig_base']="Changed_by_Multi_Plug";
1750       $ret['base']=$this->base;
1751     }
1753     $ret['gosaLoginRestriction'] = $this->gosaLoginRestriction;
1754     $ret['gosaLoginRestriction_some'] = $this->gosaLoginRestriction_some;
1756     return($ret); 
1757   }
1760   function multiple_save_object()
1761   {
1763     if(!isset($_POST['user_mulitple_edit'])) return;
1765     plugin::multiple_save_object();
1767     /* Get pw_storage mode */
1768     if (isset($_POST['pw_storage'])){
1769       foreach(array("pw_storage") as $val){
1770         if(isset($_POST[$val])){
1771           $data= validate(get_post($val));
1772           if ($data != $this->$val){
1773             $this->is_modified= TRUE;
1774           }
1775           $this->$val= $data;
1776         }
1777       }
1778     }
1779   
1780     /* Refresh base */
1781     if ($this->acl_is_moveable($this->base)){
1782       if (!$this->baseSelector->update()) {
1783         msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
1784       }
1785       if ($this->base != $this->baseSelector->getBase()) {
1786         $this->base= $this->baseSelector->getBase();
1787       }
1788     }
1790     if(isset($_POST['user_mulitple_edit'])){
1791       foreach(array("base","pw_storage","edit_picture") as $val){
1792         if(isset($_POST["use_".$val])){
1793           $this->multi_boxes[] = $val;
1794         }
1795       }
1796     }
1798     /* Sync lists */
1799     $this->gosaLoginRestrictionWidget->save_object();
1800     if ($this->gosaLoginRestrictionWidget->isModified()) {
1801       $this->gosaLoginRestriction= array_values($this->gosaLoginRestrictionWidget->getMaintainedData());
1802     }
1803   }
1805   
1806   function multiple_check()
1807   {
1808     /* Call check() to set new_dn correctly ... */
1809     $message = plugin::multiple_check();
1811     /* Set the new acl base */
1812     if($this->dn == "new") {
1813       $this->set_acl_base($this->base);
1814     }
1815     if (!tests::is_url($this->labeledURI) && in_array("labeledURI",$this->multi_boxes)){
1816       $message[]= msgPool::invalid(_("Homepage"));
1817     }
1818     if (!tests::is_phone_nr($this->telephoneNumber) && in_array("telephoneNumber",$this->multi_boxes)){
1819       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1820     }
1821     if (!tests::is_phone_nr($this->facsimileTelephoneNumber) &&  in_array("facsimileTelephoneNumber",$this->multi_boxes)){
1822       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1823     }
1824     if (!tests::is_phone_nr($this->mobile) && in_array("mobile",$this->multi_boxes)){
1825       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1826     }
1827     if (!tests::is_phone_nr($this->pager) && in_array("pager",$this->multi_boxes)){
1828       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1829     }
1830     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName) && in_array("givenName",$this->multi_boxes)){
1831       $message[]= msgPool::invalid(_("Given name"), $this->giveName, '/[^,+"?\'()=<>;\\\\]/');
1832     }
1833     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn) && in_array("sn",$this->multi_boxes)){
1834       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1835     }
1836     return($message);
1837   }
1841   function multiple_execute()
1842   {
1843     return($this->execute());
1844   }
1847   /*! \brief  Prepares the plugin to be used for multiple edit
1848    *          Update plugin attributes with given array of attribtues.
1849    *  \param  array   Array with attributes that must be updated.
1850    */
1851   function init_multiple_support($attrs,$all)
1852   {
1853     plugin::init_multiple_support($attrs,$all);
1855     // Get login restrictions
1856     if(isset($attrs['gosaLoginRestriction'])){
1857       $this->gosaLoginRestriction  =array();
1858       for($i =0;$i < $attrs['gosaLoginRestriction']['count']; $i++){
1859         $this->gosaLoginRestriction[] = $attrs['gosaLoginRestriction'][$i];
1860       }
1861     }
1863     // Detect the managers name
1864     $this->manager_name = "";
1865     $ldap = $this->config->get_ldap_link();
1866     if(!empty($this->manager)){
1867       $ldap->cat($this->manager, array('cn'));
1868       if($ldap->count()){
1869         $attrs = $ldap->fetch();
1870         $this->manager_name = $attrs['cn'][0];
1871       }else{
1872         $this->manager_name = "("._("Unknown")."!): ".$this->manager;
1873       }
1874     }
1876     // Detect login restriction not used in all user objects.
1877     $this->gosaLoginRestriction_some = array();
1878     if(isset($all['gosaLoginRestriction'])){
1879       for($i=0;$i<$all['gosaLoginRestriction']['count'];$i++){
1880         $this->gosaLoginRestriction_some[] = $all['gosaLoginRestriction'][$i];
1881       }
1882     }
1885     // Reinit the login restriction list.
1886     $data = $this->convertLoginRestriction();
1887     if(count($data)){
1888       $this->gosaLoginRestrictionWidget->setListData($data['data'], $data['displayData']);
1889     }
1890   }
1893   function set_multi_edit_values($attrs)
1894   {
1895     $lR = array();
1897     // Update loginRestrictions, keep my settings while ip is optional
1898     foreach($attrs['gosaLoginRestriction_some'] as $ip){
1899       if(in_array($ip, $this->gosaLoginRestriction) && in_array($ip, $attrs['gosaLoginRestriction'])){
1900         $lR[] = $ip;
1901       }
1902     }
1904     // Add enforced loginRestrictions 
1905     foreach($attrs['gosaLoginRestriction'] as $ip){
1906       $lR[] = $ip;
1907     }
1909     $lR = array_values(array_unique($lR));
1910     $this->is_modified |=  array_differs($this->gosaLoginRestriction, $lR);
1911     plugin::set_multi_edit_values($attrs);
1912     $this->gosaLoginRestriction = $lR;
1913   }
1916   function convertLoginRestriction()
1917   {
1918     $all = array_unique(array_merge($this->gosaLoginRestriction,$this->gosaLoginRestriction_some));
1919     $data = array();
1920     foreach($all as $ip){
1921       $data['data'][] = $ip;
1922       if(!in_array($ip, $this->gosaLoginRestriction)){
1923         $data['displayData'][] = array('mode' => LIST_MARKED , 'data' => array($ip.' ('._("Entries differ").')'));
1924       }else{
1925         $data['displayData'][] = array('mode' => 0 , 'data' => array($ip));
1926       }
1927     }   
1928     return($data);
1929   }
1932 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1933 ?>