Code

Updated class user.inc
[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("hash");
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->member= array_values($og->member);
737       $og->save ();
738     }
740     // Update 'manager' attributes from gosaDepartment and inetOrgPerson
741     $filter = "(&(objectClass=inetOrgPerson)(manager=".LDAP::prepare4filter($this->dn)."))";
742     $ocs = $ldap->get_objectclasses();
743     if(isset($ocs['gosaDepartment']['MAY']) && in_array('manager', $ocs['gosaDepartment']['MAY'])){
744       $filter = "(|".$filter."(&(objectClass=gosaDepartment)(manager=".LDAP::prepare4filter($this->dn).")))";
745     }
746     $leaf_deps=  get_list($filter,array("all"),$this->config->current['BASE'],
747         array("manager","dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
748     foreach($leaf_deps as $entry){
749       $update = array('manager' => array());
750       $ldap->cd($entry['dn']);
751       $ldap->modify($update);
752       if(!$ldap->success()){
753         trigger_error(sprintf("Failed to update manager for '%s', error was '%s'", $entry['dn'], $ldap->get_error()));
754       }
755     }
757     /* Delete references to roles */
758     $ldap->cd ($this->config->current['BASE']);
759     $ldap->search ("(&(objectClass=organizationalRole)(roleOccupant=".LDAP::prepare4filter($this->dn)."))", array("cn"));
760     while ($ldap->fetch()){
761       $role= new roleGeneric($this->config, $ldap->getDN());
762       $key = array_search($this->dn,$role->roleOccupant);
763       if($key !== FALSE){
764         unset($role->roleOccupant[$key]);
765         $role->roleOccupant= array_values($role->roleOccupant);
766         $role->save ();
767       }
768     }
770     /* If needed, let the password method do some cleanup */
771     $tmp = new passwordMethod($this->config);
772     $available = $tmp->get_available_methods();
773     if (in_array_ics($this->pw_storage, $available['name'])){
774       $test= new $available[$this->pw_storage]($this->config);
775       $test->attrs= $this->attrs;
776       $test->dn= $this->dn;
777       $test->remove_from_parent();
778     }
780     /* Remove ACL dependencies too */
781     acl::remove_acl_for($this->dn);
783     /* Optionally execute a command after we're done */
784     $this->handle_post_events("remove",array("uid" => $this->uid));
785   }
788   /* Save data to object */
789   function save_object()
790   {
791     if(isset($_POST['generic']) || isset($_POST['multiple_user_posted'])){
793       /* Make a backup of the current selected base */
794       $base_tmp = $this->base;
796       /* Parents save function */
797       plugin::save_object ();
799       /* Refresh base */
800       if ($this->acl_is_moveable($this->base)){
801         if (!$this->baseSelector->update()) {
802           msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
803         }
804         if ($this->base != $this->baseSelector->getBase()) {
805           $this->base= $this->baseSelector->getBase();
806           $this->is_modified= TRUE;
807         }
808       }
809       
810       /* Sync lists */
811       $this->gosaLoginRestrictionWidget->save_object();
812       if ($this->gosaLoginRestrictionWidget->isModified()) {
813         $this->gosaLoginRestriction= array_values($this->gosaLoginRestrictionWidget->getMaintainedData());
814       }
816       /* Save government mode attributes */
817       if ($this->governmentmode){
818         foreach ($this->govattrs as $val){
819           if ($this->acl_is_writeable($val,(!is_object($this->parent) && !session::is_set('edit'))) && isset($_POST["$val"])){
820             $data= stripcslashes($_POST["$val"]);
821             if ($data != $this->$val){
822               $this->is_modified= TRUE;
823             }
824             $this->$val= $data;
825           }
826         }
827       }
829       /* In template mode, the uid is autogenerated... */
830       if ($this->is_template){
831         $this->uid= strtolower($this->sn);
832         $this->givenName= $this->sn;
833       }
835       /* Get pw_storage mode */
836       if (isset($_POST['pw_storage'])){
837         foreach(array("pw_storage") as $val){
838           if(isset($_POST[$val])){
839             $data= validate($_POST[$val]);
840             if ($data != $this->$val){
841               $this->is_modified= TRUE;
842             }
843             $this->$val= $data;
844           }
845         }
846       }
848       if($this->pw_storage != $this->last_pw_storage && isset($_POST['pw_storage'])){
849         if ($this->acl_is_writeable("userPassword")){
850           $temp= passwordMethod::get_available_methods();
851           if (!is_object($this->pwObject) || !($this->pwObject instanceOf $temp[$this->pw_storage])){
852             foreach($temp as $id => $data){
853               if(isset($data['name']) && $data['name'] == $this->pw_storage && $data['is_configurable']){
854                 $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
855                 break;
856               }
857             }
858           }
859         }
860       }
862       /* Save current cn
863        */
864       $this->cn = $this->givenName." ".$this->sn;
865     }
866   }
868   function rebind($ldap, $referral)
869   {
870     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
871     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
872       $this->error = "Success";
873       $this->hascon=true;
874       $this->reconnect= true;
875       return (0);
876     } else {
877       $this->error = "Could not bind to " . $credentials['ADMIN'];
878       return NULL;
879     }
880   }
882   
883   /* Save data to LDAP, depending on is_account we save or delete */
884   function save()
885   {
886     global $lang;
888     /* Only force save of changes .... 
889        If this attributes aren't changed, avoid saving.
890      */
891   
892     if($this->gender=="0") $this->gender ="";
893     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
895     /* First use parents methods to do some basic fillup in $this->attrs */
896     plugin::save ();
898     if ($this->dateOfBirth != ""){
899       if(!is_array($this->attrs['dateOfBirth'])) {
900         #TODO: use $lang to convert date
901         list($day, $month, $year)= explode(".", $this->dateOfBirth);
902         $this->attrs['dateOfBirth'] = sprintf("%04d-%02d-%02d", $year, $month, $day);
903       }
904     }
906     /* Remove additional objectClasses */
907     $tmp= array();
908     foreach ($this->attrs['objectClass'] as $key => $set){
909       $found= false;
910       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
911         if (preg_match ("/^$set$/i", $val)){
912           $found= true;
913           break;
914         }
915       }
916       if (!$found){
917         $tmp[]= $set;
918       }
919     }
921     /* Replace the objectClass array. This is done because of the
922        separation into government and normal mode. */
923     $this->attrs['objectClass']= $tmp;
925     /* Add objectClasss for template mode? */
926     if ($this->is_template){
927       $this->attrs['objectClass'][]= "gosaUserTemplate";
928     }
930     /* Hard coded government mode? */
931     if ($this->governmentmode){
932       $this->attrs['objectClass'][]= "ivbbentry";
934       /* Copy standard attributes */
935       foreach ($this->govattrs as $val){
936         if ($this->$val != ""){
937           $this->attrs["$val"]= $this->$val;
938         } elseif (!$this->is_new) {
939           $this->attrs["$val"]= array();
940         }
941       }
943       /* Remove attribute if set to "nein" */
944       if ($this->publicVisible == "nein"){
945         $this->attrs['publicVisible']= array();
946         if($this->is_new){
947           unset($this->attrs['publicVisible']);
948         }else{
949           $this->attrs['publicVisible']=array();
950         }
952       }
954     }
956     /* Special handling for attribute userCertificate needed */
957     if ($this->userCertificate != ""){
958       $this->attrs["userCertificate;binary"]= $this->userCertificate;
959       $remove_userCertificate= false;
960     } else {
961       $remove_userCertificate= true;
962     }
964     /* Special handling for dateOfBirth value */
965     if ($this->dateOfBirth == ""){
966       if ($this->is_new) {
967         unset($this->attrs["dateOfBirth"]);
968       } else {
969         $this->attrs["dateOfBirth"]= array();
970       }
971     }
972     if (!$this->gender){
973       if ($this->is_new) {
974         unset($this->attrs["gender"]);
975       } else {
976         $this->attrs["gender"]= array();
977       }
978     }
979     if (!$this->preferredLanguage){
980       if ($this->is_new) {
981         unset($this->attrs["preferredLanguage"]);
982       } else {
983         $this->attrs["preferredLanguage"]= array();
984       }
985     }
987     /* Special handling for attribute jpegPhote needed, scale image via
988        image magick to 147x200 pixels and inject resulting data. */
989     if ($this->jpegPhoto == "*removed*"){
990     
991       /* Reset attribute to avoid writing *removed* as value */    
992       $this->attrs["jpegPhoto"] = array();
994     } else {
996       /* Fallback if there's no image magick inside PHP */
997       if (!function_exists("imagick_blob2image")){
998         /* Get temporary file name for conversation */
999         $fname = tempnam (TEMP_DIR, "GOsa");
1000   
1001         /* Open file and write out photoData */
1002         $fp = fopen ($fname, "w");
1003         fwrite ($fp, $this->photoData);
1004         fclose ($fp);
1006         /* Build conversation query. Filename is generated automatically, so
1007            we do not need any special security checks. Exec command and save
1008            output. For PHP safe mode, you'll need a configuration which respects
1009            image magick as executable... */
1010         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
1011         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
1012             $query, "Execute");
1013   
1014         /* Read data written by convert */
1015         $output= "";
1016         $sh= popen($query, 'r');
1017         while (!feof($sh)){
1018           $output.= fread($sh, 4096);
1019         }
1020         pclose($sh);
1022         unlink($fname);
1024         /* Save attribute */
1025         $this->attrs["jpegPhoto"] = $output;
1027       } else {
1029         /* Load the new uploaded Photo */
1030         if(!$handle  =  imagick_blob2image($this->photoData))  {
1031           new log("debug","users/".get_class($this),$this->dn,array(),"Could not access uploaded image");
1032         }
1034         /* Resizing image to 147x200 and blur */
1035         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
1036           new log("debug","users/".get_class($this),$this->dn,array(),"Could not resize uploaded image");
1037         }
1039         /* Converting image to JPEG */
1040         if(!imagick_convert($handle,"JPEG")) {
1041           new log("debug","users/".get_class($this),$this->dn,array(),"Could not convert uploaded image to jepg");
1042         }
1044         /* Creating binary Code for the Image */
1045         if(!$dump = imagick_image2blob($handle)){
1046           new log("debug","users/".get_class($this),$this->dn,array(),"Could not create new user image");
1047         }
1049         /* Sending Image */
1050         $output=  $dump;
1052         /* Save attribute */
1053         $this->attrs["jpegPhoto"] = $output;
1054       }
1056     }
1058     /* This only gets called when user is renaming himself */
1059     $ldap= $this->config->get_ldap_link();
1060     if ($this->dn != $this->new_dn){
1062       /* Write entry on new 'dn' */
1063       $this->update_acls($this->dn,$this->new_dn);
1064       $this->move($this->dn, $this->new_dn);
1066       /* Happen to use the new one */
1067       change_ui_dn($this->dn, $this->new_dn);
1068       $this->dn= $this->new_dn;
1069     }
1072     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
1073        new entries. So do a check first... */
1074     $ldap->cat ($this->dn, array('dn'));
1075     if ($ldap->fetch()){
1076       $mode= "modify";
1077     } else {
1078       $mode= "add";
1079       $ldap->cd($this->config->current['BASE']);
1080       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
1081     }
1083     /* Set password to some junk stuff in case of templates */
1084     if ($this->is_template){
1085       $temp= passwordMethod::get_available_methods();
1086       foreach($temp as $id => $data){
1087         if(isset($data['name']) && $data['name'] == $this->pw_storage){
1088           $tmp = new  $temp[$this->pw_storage]($this->config,$this->dn);
1089           $tmp->set_hash($this->pw_storage);
1090           $this->attrs['userPassword'] = $tmp->create_template_hash($this->attrs);
1091           break;
1092         }
1093       }
1094     }
1096     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
1097         $this->attributes, "Save via $mode");
1099     /* Finally write data with selected 'mode' */
1100     $this->cleanup();
1102     /* Update current locale settings, if we have edited ourselves */
1103     $ui = session::get('ui');
1104     if(isset($this->attrs['preferredLanguage']) && $this->dn == $ui->dn){
1105       $ui->language = $this->preferredLanguage;
1106       session::set('ui',$ui);
1107       session::set('Last_init_lang',"update");
1108     }
1110     $ldap->cd ($this->dn);
1111     $ldap->$mode ($this->attrs);
1112     if (!$ldap->success()){
1113       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
1114       return (1);
1115     }
1117     /* Remove ACL dependencies too */
1118     if($this->dn != $this->orig_dn && $this->orig_dn != "new"){
1119       $tmp = new acl($this->config,$this->parent,$this->dn);
1120       $tmp->update_acl_membership($this->orig_dn,$this->dn);
1121     }
1123     if($mode == "modify"){
1124       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1125     }else{
1126       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1127     }
1129     /* Remove cert? 
1130        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
1131        to work around myself. */
1132     if ($remove_userCertificate == true && !$this->is_new && $this->had_userCertificate){
1134       /* Reset array, assemble new, this should be reworked */
1135       $this->attrs= array();
1136       $this->attrs['userCertificate;binary']= array();
1138       /* Prepare connection */
1139       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
1140         die ("Could not connect to LDAP server");
1141       }
1142       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1143       if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true") {
1144         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1145         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1146       }
1147       if($this->config->get_cfg_value("ldapTLS") == "true"){
1148         ldap_start_tls($ds);
1149       }
1150       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
1151               $this->config->current['PASSWORD']))) {
1152         die ("Could not bind to LDAP");
1153       }
1155       /* Modify using attrs */
1156       ldap_mod_del($ds,$this->dn,$this->attrs);
1157       ldap_close($ds);
1158     }
1160     /* If needed, let the password method do some cleanup */
1161     if ($this->pw_storage != $this->last_pw_storage){
1162       $tmp = new passwordMethod($this->config);
1163       $available = $tmp->get_available_methods();
1164       if (in_array_ics($this->last_pw_storage, $available['name'])){
1165         $test= new $available[$this->last_pw_storage]($this->config,$this->dn);
1166         $test->attrs= $this->attrs;
1167         $test->remove_from_parent();
1168       }
1169     }
1171     /* Maybe the current password method want's to do some changes... */
1172     if (is_object($this->pwObject)){
1173       $this->pwObject->save($this->dn);
1174     }
1176     /* Optionally execute a command after we're done */
1177     if ($mode == "add"){
1178       $this->handle_post_events("add", array("uid" => $this->uid));
1179     } elseif ($this->is_modified){
1180       $this->handle_post_events("modify", array("uid" => $this->uid));
1181     }
1183     return (0);
1184   }
1187   function create_initial_rdn($pattern)
1188   {
1189     // Only generate single RDNs
1190     if (preg_match('/\+/', $pattern)){
1191       msg_dialog::display(_("Error"), _("Cannot build RDN: no + allowed to build sub RDN!"), ERROR_DIALOG);
1192       return "";
1193     }
1195     // Extract attribute
1196     $attribute= preg_replace('/=.*$/', '', $pattern);
1197     if (!in_array_ics($attribute, $this->attributes)) {
1198       msg_dialog::display(_("Error"), _("Cannot build RDN: attribute is not defined!"), ERROR_DIALOG);
1199       return "";
1200     }
1202     // Sort attributes for length
1203     $attrl= array();
1204     foreach ($this->attributes as $attr) {
1205       $attrl[$attr]= strlen($attr);
1206     }
1207     arsort($attrl);
1208     
1209     // Walk thru sorted attributes and replace them in pattern
1210     foreach ($attrl as $attr => $dummy) {
1211       if (!is_array($this->$attr)){
1212         $pattern= preg_replace("/%$attr/", $this->$attr, $pattern);
1213       } else {
1214         // Array elements cannot be used for ID generation
1215         if (preg_match("/%$attr/", $pattern)) {
1216           msg_dialog::display(_("Error"), _("Cannot build RDN: invalid attribute parameters!"), ERROR_DIALOG);
1217           break;
1218         }
1219       }
1220     }
1222     // Internally assign value
1223     $this->$attribute= preg_replace('/^[^=]+=/', '', $pattern);
1225     return $pattern;
1226   }
1228   
1229   function update_new_dn()
1230   {
1231     // Alternative way to handle DN
1232     $pattern= $this->config->get_cfg_value("accountRDN");
1233     if ($pattern != "") {
1234       $rdn= $this->create_initial_rdn($pattern);
1235       $attribute= preg_replace('/=.*$/', '', $rdn);
1236       $value= preg_replace('/^[^=]+=$/', '', $rdn);
1238       /* Don't touch dn, if $attribute hasn't changed */
1239       if (isset($this->saved_attributes[$attribute]) && $this->saved_attributes[$attribute] == $this->$attribute &&
1240             $this->orig_base == $this->base ){
1241         $this->new_dn= $this->dn;
1242       } else {
1243         $this->new_dn= $this->create_unique_dn2($rdn, get_people_ou().$this->base);
1244       }
1246     // Original way to handle DN
1247     } else {
1249       $pt= "";
1250       if($this->config->get_cfg_value("personalTitleInDN") == "true"){
1251         if(!empty($this->personalTitle)){
1252           $pt = $this->personalTitle." ";
1253         }
1254       }
1256       $this->cn= $pt.$this->givenName." ".$this->sn;
1258       /* Permissions for that base? */
1259       if ($this->config->get_cfg_value("accountPrimaryAttribute") == "uid"){
1260         $this->new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
1261       } else {
1262         /* Don't touch dn, if cn hasn't changed */
1263         if (isset($this->saved_attributes['cn']) && $this->saved_attributes['cn'] == $this->cn &&
1264             $this->orig_base == $this->base ){
1265           $this->new_dn= $this->dn;
1266         } else {
1267           $this->new_dn= $this->create_unique_dn('cn', get_people_ou().$this->base);
1268         }
1269       }
1270     }
1271   }
1272   
1274   /* Check formular input */
1275   function check()
1276   {
1277     /* Call common method to give check the hook */
1278     $message= plugin::check();
1280     /* Configurable password methods should be configured initially. 
1281      */ 
1282     if($this->last_pw_storage != $this->pw_storage){
1283       $temp= passwordMethod::get_available_methods();
1284       foreach($temp['name'] as $id => $name){
1285         if($name == $this->pw_storage){
1286           if($temp['is_configurable'][$id] && !$this->pwObject instanceof $temp[$name] ){
1287             $message[] = _("The selected password method requires initial configuration!");
1288           }
1289           break;
1290         }
1291       }
1292     }
1294     $this->update_new_dn();
1296     /* Set the new acl base */
1297     if($this->dn == "new") {
1298       $this->set_acl_base($this->base);
1299     }
1301     /* Check if we are allowed to create/move this user */
1302     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
1303       $message[]= msgPool::permCreate();
1304     }elseif($this->orig_dn != "new" && $this->new_dn != $this->orig_dn && !$this->acl_is_moveable($this->base)){
1305       $message[]= msgPool::permMove();
1306     }
1308     /* UID already used? */
1309     $ldap= $this->config->get_ldap_link();
1310     $ldap->cd($this->config->current['BASE']);
1311     $ldap->search("(uid=$this->uid)", array("uid"));
1312     $ldap->fetch();
1313     if ($ldap->count() != 0 && $this->dn == 'new'){
1314       $message[]= msgPool::duplicated(_("Login"));
1315     }
1317     /* In template mode, the uid and givenName are autogenerated... */
1318     if ($this->sn == ""){
1319       $message[]= msgPool::required(_("Name"));
1320     }
1322     // Check if a wrong base was supplied
1323     if(!$this->baseSelector->checkLastBaseUpdate()){
1324       $message[]= msgPool::check_base();;
1325     }
1327     if (!$this->is_template){
1328       if ($this->givenName == ""){
1329         $message[]= msgPool::required(_("Given name"));
1330       }
1331       if ($this->uid == ""){
1332         $message[]= msgPool::required(_("Login"));
1333       }
1334       if ($this->config->get_cfg_value("accountPrimaryAttribute") != "uid"){
1335         $ldap->cat($this->new_dn);
1336         if ($ldap->count() != 0 && $this->dn != $this->new_dn && $this->dn == 'new'){
1337           $message[]= msgPool::duplicated(_("Name"));
1338         }
1339       }
1340     }
1342     /* Check for valid input */
1343     if ($this->is_modified && !tests::is_uid($this->uid)){
1345       if (strict_uid_mode()){
1346         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/");
1347       } else {
1348         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/i");
1349       }
1350     }
1351     if (!tests::is_url($this->labeledURI)){
1352       $message[]= msgPool::invalid(_("Homepage"), "", "", "http://www.your-domain.com/yourname");
1353     }
1355     /* Check phone numbers */
1356     if (!tests::is_phone_nr($this->telephoneNumber)){
1357       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1358     }
1359     if (!tests::is_phone_nr($this->facsimileTelephoneNumber)){
1360       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1361     }
1362     if (!tests::is_phone_nr($this->mobile)){
1363       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1364     }
1365     if (!tests::is_phone_nr($this->pager)){
1366       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1367     }
1369     /* Check dates */
1370     if (!tests::is_date($this->dateOfBirth)){
1371       $message[]= msgPool::invalid(_("Date of birth"), $this->dateOfBirth,"" ,"23.02.2009");
1372     }
1374     /* Check for reserved characers */
1375     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName)){
1376       $message[]= msgPool::invalid(_("Given name"), $this->givenName, '/[^,+"?\'()=<>;\\\\]/');
1377     }
1378     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn)){
1379       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1380     }
1382     return $message;
1383   }
1386   /* Indicate whether a password change is needed or not */
1387   function password_change_needed()
1388   {
1389     if($this->multiple_support_active){
1390       return(FALSE);
1391     }else{
1393       if(in_array("pw_storage",$this->multi_boxes)){
1394         return(TRUE);
1395       }
1396       return($this->pw_storage != $this->last_pw_storage && !$this->is_template);
1397     }
1398   }
1401   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1402   function load_picture()
1403   {
1404     $ldap = $this->config->get_ldap_link();
1405     $ldap->cd ($this->dn);
1406     $data = $ldap->get_attribute($this->dn,"jpegPhoto");
1408     if((!$data) || ($data == "*removed*")){ 
1410       /* In case we don't get an entry, load a default picture */
1411       $this->set_picture ();
1412       $this->jpegPhoto= "*removed*";
1413     }else{
1415       /* Set picture */
1416       $this->photoData= $data;
1417       session::set('binary',$this->photoData);
1418       session::set('binarytype',"image/jpeg");
1419       $this->jpegPhoto= "";
1420     }
1421   }
1424   /* Load a certificate from LDAP, this is going to be simplified later on */
1425   function load_cert()
1426   {
1427     $ds= ldap_connect($this->config->current['SERVER']);
1428     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1429     if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true"){
1430       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1431       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1432     }
1433     if ($this->config->get_cfg_value("ldapTLS") == "true"){
1434       ldap_start_tls($ds);
1435     }
1437     $r= ldap_bind($ds);
1438     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1440     if ($sr) {
1441       $ei= @ldap_first_entry($ds, $sr);
1442       
1443       if ($ei) {
1444         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1445           $this->userCertificate= "";
1446         } else {
1447           $this->userCertificate= $info[0];
1448         }
1449       }
1450     } else {
1451       $this->userCertificate= "";
1452     }
1454     ldap_unbind($ds);
1455   }
1458   /* Load picture from file to object */
1459   function set_picture($filename ="")
1460   {
1461     if (!is_file($filename) || $filename =="" ){
1462       $filename= "./plugins/users/images/default.jpg";
1463       $this->jpegPhoto= "*removed*";
1464     }
1466     $fd = fopen ($filename, "rb");
1467     $this->photoData= fread ($fd, filesize ($filename));
1468     session::set('binary',$this->photoData);
1469     session::set('binarytype',"image/jpeg");
1470     $this->jpegPhoto= "";
1472     fclose ($fd);
1473   }
1476   /* Load certificate from file to object */
1477   function set_cert($cert, $filename)
1478   {
1479     if(!$this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))) return;
1480     $fd = fopen ($filename, "rb");
1481     if (filesize($filename)>0) {
1482       $this->$cert= fread ($fd, filesize ($filename));
1483       fclose ($fd);
1484       $this->is_modified= TRUE;
1485     } else {
1486       msg_dialog::display(_("Error"), _("Cannot open certificate!"), ERROR_DIALOG);
1487     }
1488   }
1490   /* Adapt from given 'dn' */
1491   function adapt_from_template($dn, $skip= array())
1492   {
1493     plugin::adapt_from_template($dn, $skip);
1495     /* Get password method from template 
1496      */
1497     $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
1498     if(is_object($tmp)){
1499       if($tmp->is_configurable()){
1500         $tmp->adapt_from_template($dn);
1501         $this->pwObject = &$tmp;
1502       }
1503       $this->pw_storage= $tmp->get_hash();
1504     }
1506     /* Get base */
1507     $this->base= preg_replace('/^[^,]+,'.preg_quote(get_people_ou(), '/').'/i', '', $dn);
1509     if($this->governmentmode){
1511       /* Walk through govattrs */
1512       foreach ($this->govattrs as $val){
1514         if (in_array($val, $skip)){
1515           continue;
1516         }
1518         if (isset($this->attrs["$val"][0])){
1520           /* If attribute is set, replace dynamic parts: 
1521              %sn, %givenName and %uid. Fill these in our local variables. */
1522           $value= $this->attrs["$val"][0];
1524           foreach (array("sn", "givenName", "uid") as $repl){
1525             if (preg_match("/%$repl/i", $value)){
1526               $value= preg_replace ("/%$repl/i",
1527                   $this->parent->$repl, $value);
1528             }
1529           }
1530           $this->$val= $value;
1531         }
1532       }
1533     }
1535     /* Get back uid/sn/givenName - only write if nothing's skipped */
1536     if ($this->parent !== NULL && count($skip) == 0){
1537       $this->uid= $this->parent->uid;
1538       $this->sn= $this->parent->sn;
1539       $this->givenName= $this->parent->givenName;
1540     }
1542     if ($this->dateOfBirth) {
1543       /* This entry is ISO 8601 conform */
1544       list($year, $month, $day)= explode("-", $this->dateOfBirth, 3);
1545     
1546       #TODO: use $lang to convert date
1547       $this->dateOfBirth= "$day.$month.$year";
1548     }
1549   }
1551  
1552   /* This avoids that users move themselves out of their rights. 
1553    */
1554   function allowedBasesToMoveTo()
1555   {
1556     /* Get bases */
1557     $bases  = $this->get_allowed_bases();
1558     return($bases);
1559   } 
1562   function getCopyDialog()
1563   {
1564     $str = "";
1566     session::set('binary',$this->photoData); 
1567     session::set('binarytype',"image/jpeg");
1569     /* Get random number for pictures */
1570     srand((double)microtime()*1000000); 
1571     $rand = rand(0, 10000);
1573     $smarty = get_smarty();
1575     $smarty->assign("passwordTodo","clear");
1577     if(isset($_POST['passwordTodo'])){
1578       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1579     }
1581     $smarty->assign("sn",       $this->sn);
1582     $smarty->assign("givenName",$this->givenName);
1583     $smarty->assign("uid",      $this->uid);
1584     $smarty->assign("rand",     $rand);
1585     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1588     $ret = array();
1589     $ret['string'] = $str;
1590     $ret['status'] = "";  
1591     return($ret);
1592   }
1594   function saveCopyDialog()
1595   {
1596     /* Set_acl_base */
1597     $this->set_acl_base($this->base);
1599     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1600       $this->set_picture($_FILES['picture_file']['tmp_name']);
1601     }
1603     /* Remove picture? */
1604     if (isset($_POST['picture_remove'])){
1605       $this->jpegPhoto= "*removed*";
1606       $this->set_picture ("./plugins/users/images/default.jpg");
1607       $this->is_modified= TRUE;
1608     }
1610     $attrs = array("uid","givenName","sn");
1611     foreach($attrs as $attr){
1612       if(isset($_POST[$attr])){
1613         $this->$attr = $_POST[$attr];
1614       }
1615     } 
1616   }
1619   function PrepareForCopyPaste($source)
1620   {
1621     plugin::PrepareForCopyPaste($source);
1623     /* Reset certificate information addepted from source user
1624        to avoid setting the same user certificate for the destination user. */
1625     $this->userPKCS12= "";
1626     $this->userSMIMECertificate= "";
1627     $this->userCertificate= "";
1628     $this->certificateSerialNumber= "";
1629     $this->old_certificateSerialNumber= "";
1630     $this->old_userPKCS12= "";
1631     $this->old_userSMIMECertificate= "";
1632     $this->old_userCertificate= "";
1633   }
1636   static function plInfo()
1637   {
1638   
1639     $govattrs= array(
1640         "gouvernmentOrganizationalUnit"             =>  _("Unit"), 
1641         "houseIdentifier"                           =>  _("House identifier"), 
1642         "vocation"                                  =>  _("Vocation"),
1643         "ivbbLastDeliveryCollective"                =>  _("Last delivery"), 
1644         "gouvernmentOrganizationalPersonLocality"   =>  _("Person locality"),
1645         "gouvernmentOrganizationalUnitDescription"  =>  _("Unit description"),
1646         "gouvernmentOrganizationalUnitSubjectArea"  =>  _("Subject area"),
1647         "functionalTitle"                           =>  _("Functional title"),
1648         "certificateSerialNumber"                   =>  _("Certificate serial number"),
1649         "publicVisible"                             =>  _("Public visible"),
1650         "street"                                    =>  _("Street"),
1651         "role"                                      =>  _("Role"),
1652         "postalCode"                                =>  _("Postal code"));
1654     $ret = array(
1655         "plShortName" => _("Generic"),
1656         "plDescription" => _("Generic user settings"),
1657         "plSelfModify"  => TRUE,
1658         "plDepends"     => array(),
1659         "plPriority"    => 1,
1660         "plSection"     => array("personal" => _("My account")),
1661         "plCategory"    => array("users" => array("description" => _("Users"),
1662                                                   "objectClass" => "gosaAccount")),
1664         "plProvidedAcls" => array(
1666           "sn"                => _("Surname"),
1667           "givenName"         => _("Given name"),
1668           "uid"               => _("User identification"),
1669           "personalTitle"     => _("Personal title"),
1670           "academicTitle"     => _("Academic title"),
1672           "dateOfBirth"       => _("Date of birth"),
1673           "gender"            => _("Sex"),
1674           "preferredLanguage" => _("Preferred language"),
1675           "base"              => _("Base"), 
1677           "userPicture"       => _("User picture"),
1679           "gosaLoginRestriction" => _("Login restrictions"),         
1681           "o"                 => _("Organization"),
1682           "ou"                => _("Department"),
1683           "departmentNumber"  => _("Department number"),
1684           "manager"           => _("Manager"),
1685           "employeeNumber"    => _("Employee number"),
1686           "employeeType"      => _("Employee type"),
1688           "roomNumber"        => _("Room number"),
1689           "telephoneNumber"   => _("Telefon number"),
1690           "pager"             => _("Pager number"),
1691           "mobile"            => _("Mobile number"),
1692           "facsimileTelephoneNumber"     => _("Fax number"),
1694           "st"                => _("State"),
1695           "l"                 => _("Location"),
1696           "postalAddress"     => _("Postal address"),
1698           "homePostalAddress" => _("Home postal address"),
1699           "homePhone"         => _("Home phone number"),
1700           "labeledURI"        => _("Homepage"),
1701           "userPassword"      => _("User password method"), 
1702           "Certificate"       => _("User certificates"))
1704         );
1706     /* Append government attributes if required */
1707     global $config;
1708     if($config->get_cfg_value("honourIvbbAttributes") == "true"){
1709       foreach($govattrs as $attr => $desc){
1710         $ret["plProvidedAcls"][$attr] = $desc;
1711       }
1712     }
1713     return($ret);
1714   }
1716   function get_multi_edit_values()
1717   {
1718     $ret = plugin::get_multi_edit_values();
1719     if(in_array("pw_storage",$this->multi_boxes)){
1720       $ret['pw_storage'] = $this->pw_storage;
1721     }
1722     if(in_array("edit_picture",$this->multi_boxes)){
1723       $ret['jpegPhoto'] = $this->jpegPhoto;
1724       $ret['photoData'] = $this->photoData;
1725       $ret['old_jpegPhoto'] = $this->old_jpegPhoto;
1726       $ret['old_photoData'] = $this->old_photoData;
1727     }
1728     if(isset($ret['dateOfBirth'])){
1729       unset($ret['dateOfBirth']);
1730     }
1731     if(isset($ret['cn'])){
1732       unset($ret['cn']);
1733     }
1734     $ret['is_modified'] = $this->is_modified;
1735     if(in_array("base",$this->multi_boxes)){
1736       $ret['orig_base']="Changed_by_Multi_Plug";
1737       $ret['base']=$this->base;
1738     }
1740     $ret['gosaLoginRestriction'] = $this->gosaLoginRestriction;
1741     $ret['gosaLoginRestriction_some'] = $this->gosaLoginRestriction_some;
1743     return($ret); 
1744   }
1747   function multiple_save_object()
1748   {
1750     if(!isset($_POST['user_mulitple_edit'])) return;
1752     plugin::multiple_save_object();
1754     /* Get pw_storage mode */
1755     if (isset($_POST['pw_storage'])){
1756       foreach(array("pw_storage") as $val){
1757         if(isset($_POST[$val])){
1758           $data= validate(get_post($val));
1759           if ($data != $this->$val){
1760             $this->is_modified= TRUE;
1761           }
1762           $this->$val= $data;
1763         }
1764       }
1765     }
1766   
1767     /* Refresh base */
1768     if ($this->acl_is_moveable($this->base)){
1769       if (!$this->baseSelector->update()) {
1770         msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
1771       }
1772       if ($this->base != $this->baseSelector->getBase()) {
1773         $this->base= $this->baseSelector->getBase();
1774       }
1775     }
1777     if(isset($_POST['user_mulitple_edit'])){
1778       foreach(array("base","pw_storage","edit_picture") as $val){
1779         if(isset($_POST["use_".$val])){
1780           $this->multi_boxes[] = $val;
1781         }
1782       }
1783     }
1785     /* Sync lists */
1786     $this->gosaLoginRestrictionWidget->save_object();
1787     if ($this->gosaLoginRestrictionWidget->isModified()) {
1788       $this->gosaLoginRestriction= array_values($this->gosaLoginRestrictionWidget->getMaintainedData());
1789     }
1790   }
1792   
1793   function multiple_check()
1794   {
1795     /* Call check() to set new_dn correctly ... */
1796     $message = plugin::multiple_check();
1798     /* Set the new acl base */
1799     if($this->dn == "new") {
1800       $this->set_acl_base($this->base);
1801     }
1802     if (!tests::is_url($this->labeledURI) && in_array("labeledURI",$this->multi_boxes)){
1803       $message[]= msgPool::invalid(_("Homepage"));
1804     }
1805     if (!tests::is_phone_nr($this->telephoneNumber) && in_array("telephoneNumber",$this->multi_boxes)){
1806       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1807     }
1808     if (!tests::is_phone_nr($this->facsimileTelephoneNumber) &&  in_array("facsimileTelephoneNumber",$this->multi_boxes)){
1809       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1810     }
1811     if (!tests::is_phone_nr($this->mobile) && in_array("mobile",$this->multi_boxes)){
1812       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1813     }
1814     if (!tests::is_phone_nr($this->pager) && in_array("pager",$this->multi_boxes)){
1815       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1816     }
1817     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName) && in_array("givenName",$this->multi_boxes)){
1818       $message[]= msgPool::invalid(_("Given name"), $this->giveName, '/[^,+"?\'()=<>;\\\\]/');
1819     }
1820     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn) && in_array("sn",$this->multi_boxes)){
1821       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1822     }
1823     return($message);
1824   }
1828   function multiple_execute()
1829   {
1830     return($this->execute());
1831   }
1834   /*! \brief  Prepares the plugin to be used for multiple edit
1835    *          Update plugin attributes with given array of attribtues.
1836    *  \param  array   Array with attributes that must be updated.
1837    */
1838   function init_multiple_support($attrs,$all)
1839   {
1840     plugin::init_multiple_support($attrs,$all);
1842     // Get login restrictions
1843     if(isset($attrs['gosaLoginRestriction'])){
1844       $this->gosaLoginRestriction  =array();
1845       for($i =0;$i < $attrs['gosaLoginRestriction']['count']; $i++){
1846         $this->gosaLoginRestriction[] = $attrs['gosaLoginRestriction'][$i];
1847       }
1848     }
1850     // Detect the managers name
1851     $this->manager_name = "";
1852     $ldap = $this->config->get_ldap_link();
1853     if(!empty($this->manager)){
1854       $ldap->cat($this->manager, array('cn'));
1855       if($ldap->count()){
1856         $attrs = $ldap->fetch();
1857         $this->manager_name = $attrs['cn'][0];
1858       }else{
1859         $this->manager_name = "("._("Unknown")."!): ".$this->manager;
1860       }
1861     }
1863     // Detect login restriction not used in all user objects.
1864     $this->gosaLoginRestriction_some = array();
1865     if(isset($all['gosaLoginRestriction'])){
1866       for($i=0;$i<$all['gosaLoginRestriction']['count'];$i++){
1867         $this->gosaLoginRestriction_some[] = $all['gosaLoginRestriction'][$i];
1868       }
1869     }
1872     // Reinit the login restriction list.
1873     $data = $this->convertLoginRestriction();
1874     if(count($data)){
1875       $this->gosaLoginRestrictionWidget->setListData($data['data'], $data['displayData']);
1876     }
1877   }
1880   function set_multi_edit_values($attrs)
1881   {
1882     $lR = array();
1884     // Update loginRestrictions, keep my settings while ip is optional
1885     foreach($attrs['gosaLoginRestriction_some'] as $ip){
1886       if(in_array($ip, $this->gosaLoginRestriction) && in_array($ip, $attrs['gosaLoginRestriction'])){
1887         $lR[] = $ip;
1888       }
1889     }
1891     // Add enforced loginRestrictions 
1892     foreach($attrs['gosaLoginRestriction'] as $ip){
1893       $lR[] = $ip;
1894     }
1896     $lR = array_values(array_unique($lR));
1897     $this->is_modified |=  array_differs($this->gosaLoginRestriction, $lR);
1898     plugin::set_multi_edit_values($attrs);
1899     $this->gosaLoginRestriction = $lR;
1900   }
1903   function convertLoginRestriction()
1904   {
1905     $all = array_unique(array_merge($this->gosaLoginRestriction,$this->gosaLoginRestriction_some));
1906     $data = array();
1907     foreach($all as $ip){
1908       $data['data'][] = $ip;
1909       if(!in_array($ip, $this->gosaLoginRestriction)){
1910         $data['displayData'][] = array('mode' => LIST_MARKED , 'data' => array($ip.' ('._("Entries differ").')'));
1911       }else{
1912         $data['displayData'][] = array('mode' => 0 , 'data' => array($ip));
1913       }
1914     }   
1915     return($data);
1916   }
1919 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1920 ?>