Code

Updated changelog, speed up object removal
[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 $employeeNumber= "";
55   var $employeeType= "";
56   var $roomNumber= "";
57   var $telephoneNumber= "";
58   var $facsimileTelephoneNumber= "";
59   var $mobile= "";
60   var $pager= "";
61   var $l= "";
62   var $st= "";
63   var $postalAddress= "";
64   var $dateOfBirth;
65   var $use_dob= "0";
66   var $gender="0";
67   var $preferredLanguage="0";
69   var $jpegPhoto= "*removed*";
70   var $photoData= "";
71   var $old_jpegPhoto= "";
72   var $old_photoData= "";
73   var $cert_dialog= FALSE;
74   var $picture_dialog= FALSE;
75   var $pwObject= NULL;
77   var $userPKCS12= "";
78   var $userSMIMECertificate= "";
79   var $userCertificate= "";
80   var $certificateSerialNumber= "";
81   var $old_certificateSerialNumber= "";
82   var $old_userPKCS12= "";
83   var $old_userSMIMECertificate= "";
84   var $old_userCertificate= "";
86   var $gouvernmentOrganizationalUnit= "";
87   var $houseIdentifier= "";
88   var $street= "";
89   var $postalCode= "";
90   var $vocation= "";
91   var $ivbbLastDeliveryCollective= "";
92   var $gouvernmentOrganizationalPersonLocality= "";
93   var $gouvernmentOrganizationalUnitDescription= "";
94   var $gouvernmentOrganizationalUnitSubjectArea= "";
95   var $functionalTitle= "";
96   var $role= "";
97   var $publicVisible= "";
99   var $orig_dn;
100   var $dialog;
102   /* variables to trigger password changes */
103   var $pw_storage= "md5";
104   var $last_pw_storage= "unset";
105   var $had_userCertificate= FALSE;
107   var $view_logged = FALSE;
109   /* attribute list for save action */
110   var $attributes= array("sn", "givenName", "uid", "personalTitle", "academicTitle",
111       "homePostalAddress", "homePhone", "labeledURI", "ou", "o", "dateOfBirth", "gender","preferredLanguage",
112       "departmentNumber", "employeeNumber", "employeeType", "l", "st","jpegPhoto",
113       "roomNumber", "telephoneNumber", "mobile", "pager", "cn", "userPKCS12",
114       "postalAddress", "facsimileTelephoneNumber", "userSMIMECertificate", "gosaLoginRestriction");
116   var $objectclasses= array("top", "person", "organizationalPerson", "inetOrgPerson",
117       "gosaAccount");
119   /* attributes that are part of the government mode */
120   var $govattrs= array("gouvernmentOrganizationalUnit", "houseIdentifier", "vocation",
121       "ivbbLastDeliveryCollective", "gouvernmentOrganizationalPersonLocality",
122       "gouvernmentOrganizationalUnitDescription","gouvernmentOrganizationalUnitSubjectArea",
123       "functionalTitle", "certificateSerialNumber", "publicVisible", "street", "role",
124       "postalCode");
126   var $multiple_support = TRUE;
128   var $governmentmode = FALSE;
130   /* constructor, if 'dn' is set, the node loads the given
131      'dn' from LDAP */
132   function user (&$config, $dn= NULL)
133   {
134     global $lang;
136     $this->config= $config;
137     /* Configuration is fine, allways */
138     if($this->config->get_cfg_value("honourIvbbAttributes") == "true"){
139       $this->governmentmode = TRUE;
140       $this->attributes=array_merge($this->attributes,$this->govattrs);
141     }
143     /* Load base attributes */
144     plugin::plugin ($config, $dn);
146     $this->orig_dn  = $this->dn;
147     $this->new_dn   = $dn;
149     if ($this->governmentmode){
150       /* Fix public visible attribute if unset */
151       if (!isset($this->attrs['publicVisible'])){
152         $this->publicVisible == "nein";
153       }
154     }
156     /* Load government mode attributes */
157     if ($this->governmentmode){
158       /* Copy all attributs */
159       foreach ($this->govattrs as $val){
160         if (isset($this->attrs["$val"][0])){
161           $this->$val= $this->attrs["$val"][0];
162         }
163       }
164     }
166     /* Create me for new accounts */
167     if ($dn == "new"){
168       $this->is_account= TRUE;
169     }
171     /* Make hash default to md5 if not set in config */
172     $hash= $this->config->get_cfg_value("passwordDefaultHash", "crypt/md5");
174     /* Load data from LDAP? */
175     if ($dn !== NULL){
177       /* Do base conversation */
178       if ($this->dn == "new"){
179         $ui= get_userinfo();
180         $this->base= dn2base(session::global_is_set("CurrentMainBase")?"cn=dummy,".session::global_get("CurrentMainBase"):$ui->dn);
181       } else {
182         $this->base= dn2base($dn);
183       }
185       /* get password storage type */
186       if (isset ($this->attrs['userPassword'][0])){
187         /* Initialize local array */
188         $matches= array();
189         if (preg_match ("/^{[^}]+}/", $this->attrs['userPassword'][0])){
190           $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
191           if(is_object($tmp)){
192             $this->pw_storage= $tmp->get_hash(); 
193           }
195         } else {
196           if ($this->attrs['userPassword'][0] != ""){
197             $this->pw_storage= "clear";
198           } else {
199             $this->pw_storage= $hash;
200           }
201         }
202       } else {
203         /* Preset with vaule from configuration */
204         $this->pw_storage= $hash;
205       }
207       /* Load extra attributes: certificate and picture */
208       $this->load_cert();
209       $this->load_picture();
210       if ($this->userCertificate != ""){
211         $this->had_userCertificate= TRUE;
212       }
213     }
215     /* Reset password storage indicator, used by password_change_needed() */
216     if ($dn == "new"){
217       $this->last_pw_storage= "unset";
218     } else {
219       $this->last_pw_storage= $this->pw_storage;
220     }
222     /* Generate dateOfBirth entry */
223     if (isset ($this->attrs['dateOfBirth'])){
224       /* This entry is ISO 8601 conform */
225       list($year, $month, $day)= split("-", $this->attrs['dateOfBirth'][0], 3);
226     
227       #TODO: use $lang to convert date
228       $this->dateOfBirth= "$day.$month.$year";
229     } else {
230       $this->dateOfBirth= "";
231     }
233     /* Put gender attribute to upper case */
234     if (isset ($this->attrs['gender'])){
235       $this->gender= strtoupper($this->attrs['gender'][0]);
236     }
238     // Get login restrictions
239     if(isset($this->attrs['gosaLoginRestriction'])){
240       $this->gosaLoginRestriction  =array();
241       for($i =0;$i < $this->attrs['gosaLoginRestriction']['count']; $i++){
242         $this->gosaLoginRestriction[] = $this->attrs['gosaLoginRestriction'][$i];
243       }
244     }
245  
246     $this->orig_base = $this->base;
247   }
250   /* execute generates the html output for this node */
251   function execute()
252   {
253     /* Call parent execute */
254     plugin::execute();
256     /* Handle add/delete for restriction mode */
257     if (isset($_POST['add_res']) && isset($_POST['res'])) {
258       $val= validate($_POST['res']);
259       if (preg_match('/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/', $val) ||
260           preg_match('/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\/([0-9]+)$/', $val) ||
261           preg_match('/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\/([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$/', $val)) {
262         $this->gosaLoginRestriction[]= $val;
263       } else {
264         msg_dialog::display(_("Error"), _("Please add a single IP address or a network/netmask combination!"), ERROR_DIALOG);
265       }
266     }
267     if (isset($_POST['del_res']) && isset($_POST['restrictions'])) {
268       $res= $_POST['restrictions'];
269       if (!is_array($res)){
270         $res= array($res);
271       }
272       foreach ($res as $restriction) {
273         if (in_array($restriction, $this->gosaLoginRestriction)) {
274           $this->gosaLoginRestriction= array_remove_entries(array($restriction), $this->gosaLoginRestriction);
275         }
276       }
277     }
279     /* Log view */
280     if($this->is_account && !$this->view_logged){
281       $this->view_logged = TRUE;
282       new log("view","users/".get_class($this),$this->dn);
283     }
285     $smarty= get_smarty();
286     $smarty->assign("usePrototype", "true");
288     /* Assign sex */
289     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
290     $smarty->assign("gender_list", $sex);
291     $language= array_merge(array(0 => "&nbsp;") ,get_languages(TRUE));
292     $smarty->assign("preferredLanguage_list", $language);
294     /* Get random number for pictures */
295     srand((double)microtime()*1000000); 
296     $smarty->assign("rand", rand(0, 10000));
299     /* Do we represent a valid gosaAccount? */
300     if (!$this->is_account){
301       $str = "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
302         msgPool::noValidExtension("GOsa")."</b>";
303       return($str);
304     }
306     /* Base select dialog */
307     $once = true;
308     foreach($_POST as $name => $value){
309       if(preg_match("/^chooseBase/",$name) && $once && $this->acl_is_writeable("base")){
310         $once = false;
311         $this->dialog = new baseSelectDialog($this->config,$this,$this->allowedBasesToMoveTo());
312         $this->dialog->setCurrentBase($this->base);
313       }
314     }
316     /* Password configure dialog handling */
317     if(is_object($this->pwObject) && $this->pwObject->display){
318       $output= $this->pwObject->configure();
319       if ($output != ""){
320         $this->dialog= TRUE;
321         return $output;
322       }
323       $this->dialog= false;
324     }
326     /* Dialog handling */
327     if(is_object($this->dialog)){
328       /* Must be called before save_object */
329       $this->dialog->save_object();
330    
331       if($this->dialog->isClosed()){
332         $this->dialog = false;
333       }elseif($this->dialog->isSelected()){
335         /* check if selected base is allowed to move to / create a new object */
336         $tmp = $this->get_allowed_bases();
337         if(isset($tmp[$this->dialog->isSelected()])){
338           $this->base = $this->dialog->isSelected();
339         }
340         $this->dialog= false;
341       }else{
342         return($this->dialog->execute());
343       }
344     }
346     /* Want password method editing? */
347     if ($this->acl_is_writeable("userPassword")){
348       if (isset($_POST['edit_pw_method'])){
349         if (!is_object($this->pwObject) || $this->pw_storage != $this->pwObject->get_hash_name()){
350           $temp= passwordMethod::get_available_methods();
351           $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
352         }
353         $this->pwObject->display = TRUE;
354         $this->dialog= TRUE;
355         return ($this->pwObject->configure());
356       }
357     }
359     /* Want picture edit dialog? */
360     if($this->acl_is_writeable("userPicture")) {
361       if (isset($_POST['edit_picture'])){
362         /* Save values for later recovery, in case some presses
363            the cancel button. */
364         $this->old_jpegPhoto= $this->jpegPhoto;
365         $this->old_photoData= $this->photoData;
366         $this->picture_dialog= TRUE;
367         $this->dialog= TRUE;
368       }
369     }
371     /* Remove picture? */
372     if($this->acl_is_writeable("userPicture",(!is_object($this->parent) && !session::is_set('edit'))) ){
373       if (isset($_POST['picture_remove'])){
374         $this->set_picture ();
375         $this->jpegPhoto= "*removed*";
376         $this->is_modified= TRUE;
377         return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
378       }
379     }
381     /* Save picture */
382     if (isset($_POST['picture_edit_finish'])){
384       /* Check for clean upload */
385       if ($_FILES['picture_file']['name'] != ""){
386         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
387           msg_dialog::display(_("Error"), _("Cannot upload file!"), ERROR_DIALOG);
388         }else{
389           /* Activate new picture */
390           $this->set_picture($_FILES['picture_file']['tmp_name']);
391         }
392       }
393       $this->picture_dialog= FALSE;
394       $this->dialog= FALSE;
395       $this->is_modified= TRUE;
396     }
399     /* Cancel picture */
400     if (isset($_POST['picture_edit_cancel'])){
402       /* Restore values */
403       $this->jpegPhoto= $this->old_jpegPhoto;
404       $this->photoData= $this->old_photoData;
406       /* Update picture */
407       session::set('binary',$this->photoData);
408       session::set('binarytype',"image/jpeg");
409       $this->picture_dialog= FALSE;
410       $this->dialog= FALSE;
411     }
413     /* Want certificate= */
414     if ((isset($_POST['edit_cert'])) && $this->acl_is_readable("Certificate")){
416       /* Save original values for later reconstruction */
417       foreach (array("certificateSerialNumber", "userCertificate",
418             "userSMIMECertificate", "userPKCS12") as $val){
420         $oval= "old_$val";
421         $this->$oval= $this->$val;
422       }
424       $this->cert_dialog= TRUE;
425       $this->dialog= TRUE;
426     }
429     /* Cancel certificate dialog */
430     if (isset($_POST['cert_edit_cancel'])){
432       /* Restore original values in case of 'cancel' */
433       foreach (array("certificateSerialNumber", "userCertificate",
434             "userSMIMECertificate", "userPKCS12") as $val){
436         $oval= "old_$val";
437         $this->$val= $this->$oval;
438       }
439       $this->cert_dialog= FALSE;
440       $this->dialog= FALSE;
441     }
444     /* Remove certificate? */
445     if($this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))){ 
446       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
447         if (isset($_POST["remove_$val"])){
449           /* Reset specified cert*/
450           $this->$val= "";
451           $this->is_modified= TRUE;
452         }
453       }
454     }
456     /* Upload new cert and close dialog? */     
457     if($this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))){ 
459       $fail =false;
461       if (isset($_POST['cert_edit_finish'])){
463         /* for all certificates do */
464         foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
465             as $val){
467           /* Check for clean upload */
468           if (array_key_exists($val."_file", $_FILES) &&
469               array_key_exists('name', $_FILES[$val."_file"]) &&
470               $_FILES[$val."_file"]['name'] != "" &&
471               is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
472             $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
473           }
474         }
476         /* Save serial number */
477         if (isset($_POST["certificateSerialNumber"]) &&
478             $_POST["certificateSerialNumber"] != ""){
480           if (!tests::is_id($_POST["certificateSerialNumber"])){
481             $fail = true;
482             msg_dialog::display(_("Error"), msgPool::invalid(_("Serial number"),$_POST["certificateSerialNumber"],"/[0-9]/"),ERROR_DIALOG);
484             foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
485               if ($this->$cert != ""){
486                 $smarty->assign("$cert"."_state", "true");
487               } else {
488                 $smarty->assign("$cert"."_state", "");
489               }
490             }
491           }
493           $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
494           $this->is_modified= TRUE;
495         }
496         if(!$fail){
497           $this->cert_dialog= FALSE;
498           $this->dialog= FALSE;
499         }
500       }
501     }
502     /* Display picture dialog */
503     if ($this->picture_dialog){
504       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
505     }
507     /* Display cert dialog */
508     if ($this->cert_dialog){
509       $smarty->assign("CertificateACL",$this->getacl("Certificate",(!is_object($this->parent) && !session::is_set('edit'))));
510       $smarty->assign("Certificate_readable",$this->acl_is_readable("Certificate"));
511       $smarty->assign("certificateSerialNumber",$this->certificateSerialNumber);
513       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
514         if ($this->$cert != ""){
515           /* import certificate */
516           $certificate = new certificate;
517           $certificate->import($this->$cert);
518       
519           /* Read out data*/
520           $timeto   = $certificate->getvalidto_date();
521           $timefrom = $certificate->getvalidfrom_date();
522          
523           
524           /* Additional info if start end time is '0' */
525           $add_str_info = "";
526           if($timeto == 0 && $timefrom == 0){
527             $add_str_info = "<br><i>"._("(Some types of certificates are currently not supported and may be displayed as 'invalid'.)")."</i>";
528           }
530           $str = "<table summary=\"\" border=0>
531                     <tr>
532                       <td style='vertical-align:top'>CN</td>
533                       <td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td>
534                     </tr>
535                   </table><br>".
537                   sprintf(_("Certificate is valid from %s to %s and is currently %s."),
538                         "<b>".date('d M Y',$timefrom)."</b>",
539                         "<b>".date('d M Y',$timeto)."</b>",
540                         $certificate->isvalid()?"<b><font style='color:green'>"._("valid")."</font></b>":
541                                                 "<b><font style='color:red'>"._("invalid")."</font></b>").$add_str_info;
543           $smarty->assign($cert."info",$str);
544           $smarty->assign($cert."_state","true");
545         } else {
546           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
547           $smarty->assign($cert."_state","");
548         }
549       }
550   
551       if($this->governmentmode){
552         $smarty->assign("honourIvbbAttributes", "true");
553       }else{
554         $smarty->assign("honourIvbbAttributes", "false");
555       }
556       $smarty->assign("governmentmode", $this->governmentmode);
557       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
558     }
560     /* Prepare password hashes */
561     if ($this->pw_storage == ""){
562       $this->pw_storage= $this->config->get_cfg_value("hash");
563     }
565     $temp= passwordMethod::get_available_methods();
566     $is_configurable= FALSE;
567     $hashes = $temp['name'];
568     if(isset($temp[$this->pw_storage])){
569       $test= new $temp[$this->pw_storage]($this->config);
570       $is_configurable= $test->is_configurable();
571     }else{
572       new msg_dialog(_("Password method"),_("The selected password method is no longer available."),WARNING_DIALOG);
573     }
576     /* Create password methods array */
577     $pwd_methods = array();
578     foreach($hashes as $id => $name){
579       if(!empty($temp['desc'][$id])){
580         $pwd_methods[$name] = $name." (".$temp['desc'][$id].")";
581       }else{
582         $pwd_methods[$name] = $name;
583       }
584     }
585  
586     /* Load attributes and acl's */
587     $ui =get_userinfo();
588     foreach($this->attributes as $val){
589       $smarty->assign("$val", $this->$val);
590       if(in_array($val,$this->multi_boxes)){
591         $smarty->assign("use_".$val,TRUE);
592       }else{
593         $smarty->assign("use_".$val,FALSE);
594       }
595     }
596     foreach(array("base","pw_storage","edit_picture") as $val){
597       if(in_array($val,$this->multi_boxes)){
598         $smarty->assign("use_".$val,TRUE);
599       }else{
600         $smarty->assign("use_".$val,FALSE);
601       }
602     }
604     /* Set acls */
605     $tmp = $this->plinfo();
606     foreach($tmp['plProvidedAcls'] as $val => $translation){
607       $smarty->assign("$val"."ACL", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit'))));
608     }
610     $smarty->assign("gosaLoginRestriction", $this->gosaLoginRestriction);
611     $smarty->assign("gosaLoginRestrictionACL", $this->getacl('gosaLoginRestriction', (!is_object($this->parent) && !session::is_set('edit'))));
612     $smarty->assign("pwmode", $pwd_methods);
613     $smarty->assign("pwmode_select", $this->pw_storage);
614     $smarty->assign("pw_configurable", $is_configurable);
615     $smarty->assign("passwordStorageACL", $this->getacl("userPassword",(!is_object($this->parent) && !session::is_set('edit'))));
616     $smarty->assign("base_select",      $this->base);
618     if(!session::is_set('edit')){
619       $smarty->assign("CertificatesACL","");
620     }else{
621       $smarty->assign("CertificatesACL",  $this->getacl("Certificate"));
622     }
623     
624     $smarty->assign("userPictureACL",   $this->getacl("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));
625     $smarty->assign("userPicture_is_readable",   $this->acl_is_readable("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));
627     /* Create base acls */
628     $tmp = @$this->allowedBasesToMoveTo();
629     $smarty->assign("bases", $tmp);
631     /* Save government mode attributes */
632     if($this->governmentmode){
633       $smarty->assign("governmentmode", "true");
634       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
635           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
636       $smarty->assign("ivbbmodes", $ivbbmodes);
637       foreach ($this->govattrs as $val){
638         $smarty->assign("$val", $this->$val);
639         $smarty->assign("$val"."ACL", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit'))));
640       }
641     } else {
642       $smarty->assign("governmentmode", "false");
643     }
645     /* Special mode for uid */
646     $uidACL= $this->getacl("uid",(!is_object($this->parent) && !session::is_set('edit')));
647     if (isset ($this->dn)){
648       if ($this->dn != "new"){
649         $uidACL= preg_replace("/w/","",$uidACL);
650       }
651     }  else {
652       $uidACL= preg_replace("/w/","",$uidACL);
653     }
654     
655     $smarty->assign("uidACL", $uidACL);
656     $smarty->assign("is_template", $this->is_template);
657     $smarty->assign("use_dob", $this->use_dob);
659     if (isset($this->parent)){
660       if (isset($this->parent->by_object['phoneAccount']) &&
661           $this->parent->by_object['phoneAccount']->is_account){
662         $smarty->assign("has_phoneaccount", "true");
663       } else {
664         $smarty->assign("has_phoneaccount", "false");
665       }
666     } else {
667       $smarty->assign("has_phoneaccount", "false");
668     }
669     $smarty->assign("multiple_support" , $this->multiple_support_active);
670     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
671   }
674   /* remove object from parent */
675   function remove_from_parent()
676   {
677     /* Only remove valid accounts */
678     if(!$this->initially_was_account) return;
680     /* Remove password extension */
681     $temp= passwordMethod::get_available_methods();
683     /* Remove password method from user account */
684     if(isset($temp[$this->pw_storage]) && class_available($temp[$this->pw_storage])){
685       $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
686       $this->pwObject->remove_from_parent();
687     }
689     /* Remove user */
690     $ldap= $this->config->get_ldap_link();
691     $ldap->rmdir ($this->dn);
692     if (!$ldap->success()){
693       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
694     }
695   
696     new log("remove","users/".get_class($this),$this->dn,$this->attributes,$ldap->get_error());
697   
698     /* Delete references to groups */
699     $ldap->cd ($this->config->current['BASE']);
700     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
701     while ($ldap->fetch()){
702       $g= new group($this->config, $ldap->getDN());
703       $g->removeUser($this->uid);
704       $g->save ();
705     }
707     /* Delete references to object groups */
708     $ldap->cd ($this->config->current['BASE']);
709     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
710     while ($ldap->fetch()){
711       $og= new ogroup($this->config, $ldap->getDN());
712       unset($og->member[$this->dn]);
713       $og->save ();
714     }
716     /* Delete references to roles */
717     $ldap->cd ($this->config->current['BASE']);
718     $ldap->search ("(&(objectClass=organizationalRole)(roleOccupant=".LDAP::prepare4filter($this->dn)."))", array("cn"));
719     while ($ldap->fetch()){
720       $role= new roleGeneric($this->config, $ldap->getDN());
721       $key = array_search($this->dn,$role->roleOccupant);
722       if($key !== FALSE){
723         unset($role->roleOccupant[$key]);
724         $role->reload();
725         $role->save ();
726       }
727     }
729     /* If needed, let the password method do some cleanup */
730     $tmp = new passwordMethod($this->config);
731     $available = $tmp->get_available_methods();
732     if (in_array_ics($this->pw_storage, $available['name'])){
733       $test= new $available[$this->pw_storage]($this->config);
734       $test->attrs= $this->attrs;
735       $test->dn= $this->dn;
736       $test->remove_from_parent();
737     }
739     /* Remove ACL dependencies too */
740     acl::remove_acl_for($this->dn);
742     /* Optionally execute a command after we're done */
743     $this->handle_post_events("remove",array("uid" => $this->uid));
744   }
747   /* Save data to object */
748   function save_object()
749   {
750     if(isset($_POST['generic']) || isset($_POST['multiple_user_posted'])){
752       /* Make a backup of the current selected base */
753       $base_tmp = $this->base;
755       /* Parents save function */
756       plugin::save_object ();
758       /* Save government mode attributes */
759       if ($this->governmentmode){
760         foreach ($this->govattrs as $val){
761           if ($this->acl_is_writeable($val,(!is_object($this->parent) && !session::is_set('edit'))) && isset($_POST["$val"])){
762             $data= stripcslashes($_POST["$val"]);
763             if ($data != $this->$val){
764               $this->is_modified= TRUE;
765             }
766             $this->$val= $data;
767           }
768         }
769       }
771       /* In template mode, the uid is autogenerated... */
772       if ($this->is_template){
773         $this->uid= strtolower($this->sn);
774         $this->givenName= $this->sn;
775       }
777       /* Save base - its no no LDAP attribute */
778       if (isset($_POST['base'])){
779         $base= get_post('base');
780         if ($base != $this->base){
781           $tmp = $this->get_allowed_bases();
782           if(isset($tmp[$base])){
783             if ($base != $this->base){
784               $this->is_modified= TRUE;
785             }
786             $this->base= $base;
787           }else{
788             $this->base = $base_tmp;
789             msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
790           }
791         }
792       }
794       /* Get pw_storage mode */
795       if (isset($_POST['pw_storage'])){
796         foreach(array("pw_storage") as $val){
797           if(isset($_POST[$val])){
798             $data= validate($_POST[$val]);
799             if ($data != $this->$val){
800               $this->is_modified= TRUE;
801             }
802             $this->$val= $data;
803           }
804         }
805       }
807       if($this->pw_storage != $this->last_pw_storage && isset($_POST['pw_storage'])){
808         if ($this->acl_is_writeable("userPassword")){
809           $temp= passwordMethod::get_available_methods();
810           if (!is_object($this->pwObject) || !($this->pwObject instanceOf $temp[$this->pw_storage])){
811             foreach($temp as $id => $data){
812               if(isset($data['name']) && $data['name'] == $this->pw_storage && $data['is_configurable']){
813                 $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
814                 break;
815               }
816             }
817           }
818         }
819       }
821       /* Save current cn
822        */
823       $this->cn = $this->givenName." ".$this->sn;
824     }
825   }
827   function rebind($ldap, $referral)
828   {
829     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
830     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
831       $this->error = "Success";
832       $this->hascon=true;
833       $this->reconnect= true;
834       return (0);
835     } else {
836       $this->error = "Could not bind to " . $credentials['ADMIN'];
837       return NULL;
838     }
839   }
841   
842   /* Save data to LDAP, depending on is_account we save or delete */
843   function save()
844   {
845     global $lang;
847     /* Only force save of changes .... 
848        If this attributes aren't changed, avoid saving.
849      */
850   
851     if($this->gender=="0") $this->gender ="";
852     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
854     /* First use parents methods to do some basic fillup in $this->attrs */
855     plugin::save ();
857     if ($this->dateOfBirth != ""){
858       if(!is_array($this->attrs['dateOfBirth'])) {
859         #TODO: use $lang to convert date
860         list($day, $month, $year)= split("\.", $this->dateOfBirth);
861         $this->attrs['dateOfBirth'] = sprintf("%04d-%02d-%02d", $year, $month, $day);
862       }
863     }
865     /* Remove additional objectClasses */
866     $tmp= array();
867     foreach ($this->attrs['objectClass'] as $key => $set){
868       $found= false;
869       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
870         if (preg_match ("/^$set$/i", $val)){
871           $found= true;
872           break;
873         }
874       }
875       if (!$found){
876         $tmp[]= $set;
877       }
878     }
880     /* Replace the objectClass array. This is done because of the
881        separation into government and normal mode. */
882     $this->attrs['objectClass']= $tmp;
884     /* Add objectClasss for template mode? */
885     if ($this->is_template){
886       $this->attrs['objectClass'][]= "gosaUserTemplate";
887     }
889     /* Hard coded government mode? */
890     if ($this->governmentmode){
891       $this->attrs['objectClass'][]= "ivbbentry";
893       /* Copy standard attributes */
894       foreach ($this->govattrs as $val){
895         if ($this->$val != ""){
896           $this->attrs["$val"]= $this->$val;
897         } elseif (!$this->is_new) {
898           $this->attrs["$val"]= array();
899         }
900       }
902       /* Remove attribute if set to "nein" */
903       if ($this->publicVisible == "nein"){
904         $this->attrs['publicVisible']= array();
905         if($this->is_new){
906           unset($this->attrs['publicVisible']);
907         }else{
908           $this->attrs['publicVisible']=array();
909         }
911       }
913     }
915     /* Special handling for attribute userCertificate needed */
916     if ($this->userCertificate != ""){
917       $this->attrs["userCertificate;binary"]= $this->userCertificate;
918       $remove_userCertificate= false;
919     } else {
920       $remove_userCertificate= true;
921     }
923     /* Special handling for dateOfBirth value */
924     if ($this->dateOfBirth == ""){
925       if ($this->is_new) {
926         unset($this->attrs["dateOfBirth"]);
927       } else {
928         $this->attrs["dateOfBirth"]= array();
929       }
930     }
931     if (!$this->gender){
932       if ($this->is_new) {
933         unset($this->attrs["gender"]);
934       } else {
935         $this->attrs["gender"]= array();
936       }
937     }
938     if (!$this->preferredLanguage){
939       if ($this->is_new) {
940         unset($this->attrs["preferredLanguage"]);
941       } else {
942         $this->attrs["preferredLanguage"]= array();
943       }
944     }
946     /* Special handling for attribute jpegPhote needed, scale image via
947        image magick to 147x200 pixels and inject resulting data. */
948     if ($this->jpegPhoto == "*removed*"){
949     
950       /* Reset attribute to avoid writing *removed* as value */    
951       $this->attrs["jpegPhoto"] = array();
953     } else {
955       /* Fallback if there's no image magick inside PHP */
956       if (!function_exists("imagick_blob2image")){
957         /* Get temporary file name for conversation */
958         $fname = tempnam (TEMP_DIR, "GOsa");
959   
960         /* Open file and write out photoData */
961         $fp = fopen ($fname, "w");
962         fwrite ($fp, $this->photoData);
963         fclose ($fp);
965         /* Build conversation query. Filename is generated automatically, so
966            we do not need any special security checks. Exec command and save
967            output. For PHP safe mode, you'll need a configuration which respects
968            image magick as executable... */
969         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
970         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
971             $query, "Execute");
972   
973         /* Read data written by convert */
974         $output= "";
975         $sh= popen($query, 'r');
976         while (!feof($sh)){
977           $output.= fread($sh, 4096);
978         }
979         pclose($sh);
981         unlink($fname);
983         /* Save attribute */
984         $this->attrs["jpegPhoto"] = $output;
986       } else {
988         /* Load the new uploaded Photo */
989         if(!$handle  =  imagick_blob2image($this->photoData))  {
990           new log("debug","users/".get_class($this),$this->dn,array(),"Could not access uploaded image");
991         }
993         /* Resizing image to 147x200 and blur */
994         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
995           new log("debug","users/".get_class($this),$this->dn,array(),"Could not resize uploaded image");
996         }
998         /* Converting image to JPEG */
999         if(!imagick_convert($handle,"JPEG")) {
1000           new log("debug","users/".get_class($this),$this->dn,array(),"Could not convert uploaded image to jepg");
1001         }
1003         /* Creating binary Code for the Image */
1004         if(!$dump = imagick_image2blob($handle)){
1005           new log("debug","users/".get_class($this),$this->dn,array(),"Could not create new user image");
1006         }
1008         /* Sending Image */
1009         $output=  $dump;
1011         /* Save attribute */
1012         $this->attrs["jpegPhoto"] = $output;
1013       }
1015     }
1017     /* This only gets called when user is renaming himself */
1018     $ldap= $this->config->get_ldap_link();
1019     if ($this->dn != $this->new_dn){
1021       /* Write entry on new 'dn' */
1022       $this->update_acls($this->dn,$this->new_dn);
1023       $this->move($this->dn, $this->new_dn);
1025       /* Happen to use the new one */
1026       change_ui_dn($this->dn, $this->new_dn);
1027       $this->dn= $this->new_dn;
1028     }
1031     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
1032        new entries. So do a check first... */
1033     $ldap->cat ($this->dn, array('dn'));
1034     if ($ldap->fetch()){
1035       $mode= "modify";
1036     } else {
1037       $mode= "add";
1038       $ldap->cd($this->config->current['BASE']);
1039       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
1040     }
1042     /* Set password to some junk stuff in case of templates */
1043     if ($this->is_template){
1044       $temp= passwordMethod::get_available_methods();
1045       foreach($temp as $id => $data){
1046         if(isset($data['name']) && $data['name'] == $this->pw_storage){
1047           $tmp = new  $temp[$this->pw_storage]($this->config,$this->dn);
1048           $tmp->set_hash($this->pw_storage);
1049           $this->attrs['userPassword'] = $tmp->create_template_hash($this->attrs);
1050           break;
1051         }
1052       }
1053     }
1055     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
1056         $this->attributes, "Save via $mode");
1058     /* Finally write data with selected 'mode' */
1059     $this->cleanup();
1061     /* Update current locale settings, if we have edited ourselves */
1062     $ui = session::get('ui');
1063     if(isset($this->attrs['preferredLanguage']) && $this->dn == $ui->dn){
1064       $ui->language = $this->preferredLanguage;
1065       session::set('ui',$ui);
1066       session::set('Last_init_lang',"update");
1067     }
1069     $ldap->cd ($this->dn);
1070     $ldap->$mode ($this->attrs);
1071     if (!$ldap->success()){
1072       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
1073       return (1);
1074     }
1076     /* Remove ACL dependencies too */
1077     if($this->dn != $this->orig_dn && $this->orig_dn != "new"){
1078       $tmp = new acl($this->config,$this->parent,$this->dn);
1079       $tmp->update_acl_membership($this->orig_dn,$this->dn);
1080     }
1082     if($mode == "modify"){
1083       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1084     }else{
1085       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1086     }
1088     /* Remove cert? 
1089        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
1090        to work around myself. */
1091     if ($remove_userCertificate == true && !$this->is_new && $this->had_userCertificate){
1093       /* Reset array, assemble new, this should be reworked */
1094       $this->attrs= array();
1095       $this->attrs['userCertificate;binary']= array();
1097       /* Prepare connection */
1098       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
1099         die ("Could not connect to LDAP server");
1100       }
1101       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1102       if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true") {
1103         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1104         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1105       }
1106       if($this->config->get_cfg_value("ldapTLS") == "true"){
1107         ldap_start_tls($ds);
1108       }
1109       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
1110               $this->config->current['PASSWORD']))) {
1111         die ("Could not bind to LDAP");
1112       }
1114       /* Modify using attrs */
1115       ldap_mod_del($ds,$this->dn,$this->attrs);
1116       ldap_close($ds);
1117     }
1119     /* If needed, let the password method do some cleanup */
1120     if ($this->pw_storage != $this->last_pw_storage){
1121       $tmp = new passwordMethod($this->config);
1122       $available = $tmp->get_available_methods();
1123       if (in_array_ics($this->last_pw_storage, $available['name'])){
1124         $test= new $available[$this->last_pw_storage]($this->config,$this->dn);
1125         $test->attrs= $this->attrs;
1126         $test->remove_from_parent();
1127       }
1128     }
1130     /* Maybe the current password method want's to do some changes... */
1131     if (is_object($this->pwObject)){
1132       $this->pwObject->save($this->dn);
1133     }
1135     /* Optionally execute a command after we're done */
1136     if ($mode == "add"){
1137       $this->handle_post_events("add", array("uid" => $this->uid));
1138     } elseif ($this->is_modified){
1139       $this->handle_post_events("modify", array("uid" => $this->uid));
1140     }
1142     return (0);
1143   }
1146   function create_initial_rdn($pattern)
1147   {
1148     // Only generate single RDNs
1149     if (preg_match('/\+/', $pattern)){
1150       msg_dialog::display(_("Error"), _("Cannot build RDN: no + allowed to build sub RDN!"), ERROR_DIALOG);
1151       return "";
1152     }
1154     // Extract attribute
1155     $attribute= preg_replace('/=.*$/', '', $pattern);
1156     if (!in_array_ics($attribute, $this->attributes)) {
1157       msg_dialog::display(_("Error"), _("Cannot build RDN: attribute is not defined!"), ERROR_DIALOG);
1158       return "";
1159     }
1161     // Sort attributes for length
1162     $attrl= array();
1163     foreach ($this->attributes as $attr) {
1164       $attrl[$attr]= strlen($attr);
1165     }
1166     arsort($attrl);
1167     
1168     // Walk thru sorted attributes and replace them in pattern
1169     foreach ($attrl as $attr => $dummy) {
1170       if (!is_array($this->$attr)){
1171         $pattern= preg_replace("/%$attr/", $this->$attr, $pattern);
1172       } else {
1173         // Array elements cannot be used for ID generation
1174         if (preg_match("/%$attr/", $pattern)) {
1175           msg_dialog::display(_("Error"), _("Cannot build RDN: invalid attribute parameters!"), ERROR_DIALOG);
1176           break;
1177         }
1178       }
1179     }
1181     // Internally assign value
1182     $this->$attribute= preg_replace('/^[^=]+=/', '', $pattern);
1184     return $pattern;
1185   }
1187   
1188   function update_new_dn()
1189   {
1190     // Alternative way to handle DN
1191     $pattern= $this->config->get_cfg_value("accountRDN");
1192     if ($pattern != "") {
1193       $rdn= $this->create_initial_rdn($pattern);
1194       $attribute= preg_replace('/=.*$/', '', $rdn);
1195       $value= preg_replace('/^[^=]+=$/', '', $rdn);
1197       /* Don't touch dn, if $attribute hasn't changed */
1198       if (isset($this->saved_attributes[$attribute]) && $this->saved_attributes[$attribute] == $this->$attribute &&
1199             $this->orig_base == $this->base ){
1200         $this->new_dn= $this->dn;
1201       } else {
1202         $this->new_dn= $this->create_unique_dn2($rdn, get_people_ou().$this->base);
1203       }
1205     // Original way to handle DN
1206     } else {
1208       $pt= "";
1209       if($this->config->get_cfg_value("personalTitleInDN") == "true"){
1210         if(!empty($this->personalTitle)){
1211           $pt = $this->personalTitle." ";
1212         }
1213       }
1215       $this->cn= $pt.$this->givenName." ".$this->sn;
1217       /* Permissions for that base? */
1218       if ($this->config->get_cfg_value("accountPrimaryAttribute") == "uid"){
1219         $this->new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
1220       } else {
1221         /* Don't touch dn, if cn hasn't changed */
1222         if (isset($this->saved_attributes['cn']) && $this->saved_attributes['cn'] == $this->cn &&
1223             $this->orig_base == $this->base ){
1224           $this->new_dn= $this->dn;
1225         } else {
1226           $this->new_dn= $this->create_unique_dn('cn', get_people_ou().$this->base);
1227         }
1228       }
1229     }
1230   }
1231   
1233   /* Check formular input */
1234   function check()
1235   {
1236     /* Call common method to give check the hook */
1237     $message= plugin::check();
1239     /* Configurable password methods should be configured initially. 
1240      */ 
1241     if($this->last_pw_storage != $this->pw_storage){
1242       $temp= passwordMethod::get_available_methods();
1243       foreach($temp['name'] as $id => $name){
1244         if($name == $this->pw_storage){
1245           if($temp['is_configurable'][$id] && !$this->pwObject instanceof $temp[$name] ){
1246             $message[] = _("The selected password method requires initial configuration!");
1247           }
1248           break;
1249         }
1250       }
1251     }
1253     $this->update_new_dn();
1255     /* Set the new acl base */
1256     if($this->dn == "new") {
1257       $this->set_acl_base($this->base);
1258     }
1260     /* Check if we are allowed to create/move this user */
1261     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
1262       $message[]= msgPool::permCreate();
1263     }elseif($this->orig_dn != "new" && $this->new_dn != $this->orig_dn && !$this->acl_is_moveable($this->base)){
1264       $message[]= msgPool::permMove();
1265     }
1267     /* UID already used? */
1268     $ldap= $this->config->get_ldap_link();
1269     $ldap->cd($this->config->current['BASE']);
1270     $ldap->search("(uid=$this->uid)", array("uid"));
1271     $ldap->fetch();
1272     if ($ldap->count() != 0 && $this->dn == 'new'){
1273       $message[]= msgPool::duplicated(_("Login"));
1274     }
1276     /* In template mode, the uid and givenName are autogenerated... */
1277     if ($this->sn == ""){
1278       $message[]= msgPool::required(_("Name"));
1279     }
1281     if (!$this->is_template){
1282       if ($this->givenName == ""){
1283         $message[]= msgPool::required(_("Given name"));
1284       }
1285       if ($this->uid == ""){
1286         $message[]= msgPool::required(_("Login"));
1287       }
1288       if ($this->config->get_cfg_value("accountPrimaryAttribute") != "uid"){
1289         $ldap->cat($this->new_dn);
1290         if ($ldap->count() != 0 && $this->dn != $this->new_dn && $this->dn == 'new'){
1291           $message[]= msgPool::duplicated(_("Name"));
1292         }
1293       }
1294     }
1296     /* Check for valid input */
1297     if ($this->is_modified && !tests::is_uid($this->uid)){
1299       if (strict_uid_mode()){
1300         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/");
1301       } else {
1302         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/i");
1303       }
1304     }
1305     if (!tests::is_url($this->labeledURI)){
1306       $message[]= msgPool::invalid(_("Homepage"), "", "", "http://www.your-domain.com/yourname");
1307     }
1309     /* Check phone numbers */
1310     if (!tests::is_phone_nr($this->telephoneNumber)){
1311       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1312     }
1313     if (!tests::is_phone_nr($this->facsimileTelephoneNumber)){
1314       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1315     }
1316     if (!tests::is_phone_nr($this->mobile)){
1317       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1318     }
1319     if (!tests::is_phone_nr($this->pager)){
1320       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1321     }
1323     /* Check dates */
1324     if (!tests::is_date($this->dateOfBirth)){
1325       $message[]= msgPool::invalid(_("Date of birth"), $this->dateOfBirth,"" ,"23.02.2009");
1326     }
1328     /* Check for reserved characers */
1329     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName)){
1330       $message[]= msgPool::invalid(_("Given name"), $this->givenName, '/[^,+"?\'()=<>;\\\\]/');
1331     }
1332     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn)){
1333       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1334     }
1336     return $message;
1337   }
1340   /* Indicate whether a password change is needed or not */
1341   function password_change_needed()
1342   {
1343     if(in_array("pw_storage",$this->multi_boxes)){
1344       return(TRUE);
1345     }
1346     return($this->pw_storage != $this->last_pw_storage && !$this->is_template);
1347   }
1350   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1351   function load_picture()
1352   {
1353     $ldap = $this->config->get_ldap_link();
1354     $ldap->cd ($this->dn);
1355     $data = $ldap->get_attribute($this->dn,"jpegPhoto");
1357     if((!$data) || ($data == "*removed*")){ 
1359       /* In case we don't get an entry, load a default picture */
1360       $this->set_picture ();
1361       $this->jpegPhoto= "*removed*";
1362     }else{
1364       /* Set picture */
1365       $this->photoData= $data;
1366       session::set('binary',$this->photoData);
1367       session::set('binarytype',"image/jpeg");
1368       $this->jpegPhoto= "";
1369     }
1370   }
1373   /* Load a certificate from LDAP, this is going to be simplified later on */
1374   function load_cert()
1375   {
1376     $ds= ldap_connect($this->config->current['SERVER']);
1377     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1378     if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true"){
1379       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1380       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1381     }
1382     if ($this->config->get_cfg_value("ldapTLS") == "true"){
1383       ldap_start_tls($ds);
1384     }
1386     $r= ldap_bind($ds);
1387     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1389     if ($sr) {
1390       $ei= @ldap_first_entry($ds, $sr);
1391       
1392       if ($ei) {
1393         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1394           $this->userCertificate= "";
1395         } else {
1396           $this->userCertificate= $info[0];
1397         }
1398       }
1399     } else {
1400       $this->userCertificate= "";
1401     }
1403     ldap_unbind($ds);
1404   }
1407   /* Load picture from file to object */
1408   function set_picture($filename ="")
1409   {
1410     if (!is_file($filename) || $filename =="" ){
1411       $filename= "./plugins/users/images/default.jpg";
1412       $this->jpegPhoto= "*removed*";
1413     }
1415     $fd = fopen ($filename, "rb");
1416     $this->photoData= fread ($fd, filesize ($filename));
1417     session::set('binary',$this->photoData);
1418     session::set('binarytype',"image/jpeg");
1419     $this->jpegPhoto= "";
1421     fclose ($fd);
1422   }
1425   /* Load certificate from file to object */
1426   function set_cert($cert, $filename)
1427   {
1428     if(!$this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))) return;
1429     $fd = fopen ($filename, "rb");
1430     if (filesize($filename)>0) {
1431       $this->$cert= fread ($fd, filesize ($filename));
1432       fclose ($fd);
1433       $this->is_modified= TRUE;
1434     } else {
1435       msg_dialog::display(_("Error"), _("Cannot open certificate!"), ERROR_DIALOG);
1436     }
1437   }
1439   /* Adapt from given 'dn' */
1440   function adapt_from_template($dn, $skip= array())
1441   {
1442     plugin::adapt_from_template($dn, $skip);
1444     /* Get password method from template 
1445      */
1446     $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
1447     if(is_object($tmp)){
1448       if($tmp->is_configurable()){
1449         $tmp->adapt_from_template($dn);
1450         $this->pwObject = &$tmp;
1451       }
1452       $this->pw_storage= $tmp->get_hash();
1453     }
1455     /* Get base */
1456     $this->base= preg_replace('/^[^,]+,'.preg_quote(get_people_ou(), '/').'/i', '', $dn);
1458     if($this->governmentmode){
1460       /* Walk through govattrs */
1461       foreach ($this->govattrs as $val){
1463         if (in_array($val, $skip)){
1464           continue;
1465         }
1467         if (isset($this->attrs["$val"][0])){
1469           /* If attribute is set, replace dynamic parts: 
1470              %sn, %givenName and %uid. Fill these in our local variables. */
1471           $value= $this->attrs["$val"][0];
1473           foreach (array("sn", "givenName", "uid") as $repl){
1474             if (preg_match("/%$repl/i", $value)){
1475               $value= preg_replace ("/%$repl/i",
1476                   $this->parent->$repl, $value);
1477             }
1478           }
1479           $this->$val= $value;
1480         }
1481       }
1482     }
1484     /* Get back uid/sn/givenName - only write if nothing's skipped */
1485     if ($this->parent !== NULL && count($skip) == 0){
1486       $this->uid= $this->parent->uid;
1487       $this->sn= $this->parent->sn;
1488       $this->givenName= $this->parent->givenName;
1489     }
1490   }
1492  
1493   /* This avoids that users move themselves out of their rights. 
1494    */
1495   function allowedBasesToMoveTo()
1496   {
1497     /* Get bases */
1498     $bases  = $this->get_allowed_bases();
1499     return($bases);
1500   } 
1503   function getCopyDialog()
1504   {
1505     $str = "";
1507     session::set('binary',$this->photoData); 
1508     session::set('binarytype',"image/jpeg");
1510     /* Get random number for pictures */
1511     srand((double)microtime()*1000000); 
1512     $rand = rand(0, 10000);
1514     $smarty = get_smarty();
1516     $smarty->assign("passwordTodo","clear");
1518     if(isset($_POST['passwordTodo'])){
1519       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1520     }
1522     $smarty->assign("sn",       $this->sn);
1523     $smarty->assign("givenName",$this->givenName);
1524     $smarty->assign("uid",      $this->uid);
1525     $smarty->assign("rand",     $rand);
1526     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1529     $ret = array();
1530     $ret['string'] = $str;
1531     $ret['status'] = "";  
1532     return($ret);
1533   }
1535   function saveCopyDialog()
1536   {
1537     /* Set_acl_base */
1538     $this->set_acl_base($this->base);
1540     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1541       $this->set_picture($_FILES['picture_file']['tmp_name']);
1542     }
1544     /* Remove picture? */
1545     if (isset($_POST['picture_remove'])){
1546       $this->jpegPhoto= "*removed*";
1547       $this->set_picture ("./plugins/users/images/default.jpg");
1548       $this->is_modified= TRUE;
1549     }
1551     $attrs = array("uid","givenName","sn");
1552     foreach($attrs as $attr){
1553       if(isset($_POST[$attr])){
1554         $this->$attr = $_POST[$attr];
1555       }
1556     } 
1557   }
1560   function PrepareForCopyPaste($source)
1561   {
1562     plugin::PrepareForCopyPaste($source);
1564     /* Reset certificate information addepted from source user
1565        to avoid setting the same user certificate for the destination user. */
1566     $this->userPKCS12= "";
1567     $this->userSMIMECertificate= "";
1568     $this->userCertificate= "";
1569     $this->certificateSerialNumber= "";
1570     $this->old_certificateSerialNumber= "";
1571     $this->old_userPKCS12= "";
1572     $this->old_userSMIMECertificate= "";
1573     $this->old_userCertificate= "";
1574   }
1577   static function plInfo()
1578   {
1579   
1580     $govattrs= array(
1581         "gouvernmentOrganizationalUnit"             =>  _("Unit"), 
1582         "houseIdentifier"                           =>  _("House identifier"), 
1583         "vocation"                                  =>  _("Vocation"),
1584         "ivbbLastDeliveryCollective"                =>  _("Last delivery"), 
1585         "gouvernmentOrganizationalPersonLocality"   =>  _("Person locality"),
1586         "gouvernmentOrganizationalUnitDescription"  =>  _("Unit description"),
1587         "gouvernmentOrganizationalUnitSubjectArea"  =>  _("Subject area"),
1588         "functionalTitle"                           =>  _("Functional title"),
1589         "certificateSerialNumber"                   =>  _("Certificate serial number"),
1590         "publicVisible"                             =>  _("Public visible"),
1591         "street"                                    =>  _("Street"),
1592         "role"                                      =>  _("Role"),
1593         "postalCode"                                =>  _("Postal code"));
1595     $ret = array(
1596         "plShortName" => _("Generic"),
1597         "plDescription" => _("Generic user settings"),
1598         "plSelfModify"  => TRUE,
1599         "plDepends"     => array(),
1600         "plPriority"    => 1,
1601         "plSection"     => array("personal" => _("My account")),
1602         "plCategory"    => array("users" => array("description" => _("Users"),
1603                                                   "objectClass" => "gosaAccount")),
1605         "plProvidedAcls" => array(
1607           "sn"                => _("Surname"),
1608           "givenName"         => _("Given name"),
1609           "uid"               => _("User identification"),
1610           "personalTitle"     => _("Personal title"),
1611           "academicTitle"     => _("Academic title"),
1613           "dateOfBirth"       => _("Date of birth"),
1614           "gender"            => _("Sex"),
1615           "preferredLanguage" => _("Preferred language"),
1616           "base"              => _("Base"), 
1618           "userPicture"       => _("User picture"),
1620           "o"                 => _("Organization"),
1621           "ou"                => _("Department"),
1622           "departmentNumber"  => _("Department number"),
1623           "employeeNumber"    => _("Employee number"),
1624           "employeeType"      => _("Employee type"),
1626           "roomNumber"        => _("Room number"),
1627           "telephoneNumber"   => _("Telefon number"),
1628           "pager"             => _("Pager number"),
1629           "mobile"            => _("Mobile number"),
1630           "facsimileTelephoneNumber"     => _("Fax number"),
1632           "st"                => _("State"),
1633           "l"                 => _("Location"),
1634           "postalAddress"     => _("Postal address"),
1636           "homePostalAddress" => _("Home postal address"),
1637           "homePhone"         => _("Home phone number"),
1638           "labeledURI"        => _("Homepage"),
1639           "userPassword"      => _("User password method"), 
1640           "Certificate"       => _("User certificates"))
1642         );
1644     /* Append government attributes if required */
1645     global $config;
1646     if($config->get_cfg_value("honourIvbbAttributes") == "true"){
1647       foreach($govattrs as $attr => $desc){
1648         $ret["plProvidedAcls"][$attr] = $desc;
1649       }
1650     }
1651     return($ret);
1652   }
1654   function get_multi_edit_values()
1655   {
1656     $ret = plugin::get_multi_edit_values();
1657     if(in_array("pw_storage",$this->multi_boxes)){
1658       $ret['pw_storage'] = $this->pw_storage;
1659     }
1660     if(in_array("edit_picture",$this->multi_boxes)){
1661       $ret['jpegPhoto'] = $this->jpegPhoto;
1662       $ret['photoData'] = $this->photoData;
1663       $ret['old_jpegPhoto'] = $this->old_jpegPhoto;
1664       $ret['old_photoData'] = $this->old_photoData;
1665     }
1666     if(isset($ret['dateOfBirth'])){
1667       unset($ret['dateOfBirth']);
1668     }
1669     if(isset($ret['cn'])){
1670       unset($ret['cn']);
1671     }
1672     $ret['is_modified'] = $this->is_modified;
1673     if(in_array("base",$this->multi_boxes)){
1674       $ret['orig_base']="Changed_by_Multi_Plug";
1675       $ret['base']=$this->base;
1676     }
1677     return($ret); 
1678   }
1681   function multiple_save_object()
1682   {
1683     plugin::multiple_save_object();
1685     /* Get pw_storage mode */
1686     if (isset($_POST['pw_storage'])){
1687       foreach(array("pw_storage") as $val){
1688         if(isset($_POST[$val])){
1689           $data= validate(get_post($val));
1690           if ($data != $this->$val){
1691             $this->is_modified= TRUE;
1692           }
1693           $this->$val= $data;
1694         }
1695       }
1696     }
1697     if(isset($_POST['base'])){
1698       $this->base = get_post('base');
1699     }
1701     if(isset($_POST['user_mulitple_edit'])){
1702       foreach(array("base","pw_storage","edit_picture") as $val){
1703         if(isset($_POST["use_".$val])){
1704           $this->multi_boxes[] = $val;
1705         }
1706       }
1707     }
1708   }
1710   
1711   function multiple_check()
1712   {
1713     /* Call check() to set new_dn correctly ... */
1714     $message = plugin::multiple_check();
1716     /* Set the new acl base */
1717     if($this->dn == "new") {
1718       $this->set_acl_base($this->base);
1719     }
1720     if (!tests::is_url($this->labeledURI) && in_array("labeledURI",$this->multi_boxes)){
1721       $message[]= msgPool::invalid(_("Homepage"));
1722     }
1723     if (!tests::is_phone_nr($this->telephoneNumber) && in_array("telephoneNumber",$this->multi_boxes)){
1724       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1725     }
1726     if (!tests::is_phone_nr($this->facsimileTelephoneNumber) &&  in_array("facsimileTelephoneNumber",$this->multi_boxes)){
1727       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1728     }
1729     if (!tests::is_phone_nr($this->mobile) && in_array("mobile",$this->multi_boxes)){
1730       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1731     }
1732     if (!tests::is_phone_nr($this->pager) && in_array("pager",$this->multi_boxes)){
1733       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1734     }
1735     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName) && in_array("givenName",$this->multi_boxes)){
1736       $message[]= msgPool::invalid(_("Given name"), $this->giveName, '/[^,+"?\'()=<>;\\\\]/');
1737     }
1738     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn) && in_array("sn",$this->multi_boxes)){
1739       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1740     }
1741     return($message);
1742   }
1746   function multiple_execute()
1747   {
1748     return($this->execute());
1749   }
1754 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1755 ?>