summaryrefslogtreecommitdiff
path: root/www/admin/user/user.php.in
blob: 994fc76edc5dfcb98ce893d44f2169f57df10da8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
<?php
/*
 (c) 2004-2006 Klaraelvdalens Datakonsult AB
 (c) 2004 Martin Konold erfrakon <martin.konold@erfrakon.de>
 This program is Free Software under the GNU General Public License (>=v2).
 Read the file COPYING that comes with this packages for details.
*/

require_once('@kolab_php_module_prefix@admin/include/mysmarty.php');
require_once('@kolab_php_module_prefix@admin/include/headers.php');
require_once('@kolab_php_module_prefix@admin/include/locale.php');
require_once('@kolab_php_module_prefix@admin/include/authenticate.php');
require_once('@kolab_php_module_prefix@admin/include/form.class.php');

/**** Functions ***/
function comment( $s ) {
  return $s;
}

function is_unique ($a, $b) {
  global $ldap;
  if (($result = $ldap->search( $_SESSION['base_dn'],"(".$a."=".$ldap->escape($b).")")) &&
      (ldap_count_entries($ldap->connection,$result) <= 0))
    return true;
  return false;
}

function domain_dn()
{
  /*
  global $ldap;
  global $errors;
  if ($dattrs = $ldap->read( 'k=kolab,'.$_SESSION['base_dn'])) {
    $domain = $dattrs['postfix-mydomain'][0];
    $dcs = array_reverse(explode('.', $domain));
    $domain_dn = $_SESSION['base_dn'];
    foreach ($dcs as $dc) $domain_dn = "dc=$dc,".$domain_dn;

  } else {
    array_push($errors, "LDAP Error: could not determin domain");
    $domain_dn = $_SESSION['base_dn'];
  }
  return $domain_dn;
  */
  return $_SESSION['base_dn'];
}

// return tru if $str ends with $sub
function endsWith( $str, $sub ) {
  return ( substr( $str, strlen( $str ) - strlen( $sub ) ) == $sub );
}

// Check that a uid is unique
function checkuniquemail( $form, $key, $value ) {
  debug("checkuniquemail( $form, $key, $value )");
  global $ldap;
  global $auth;
  $value = trim($value);
  if( $value == '' ) return _('Please enter an email address');

  // Check that we are in the domain
  $kolab = $ldap->read( 'k=kolab,'.$_SESSION['base_dn'] );
  if( $auth->group() == 'domain-maintainer' ) {
	$domains = $ldap->domainsForMaintainerDn($auth->dn());
  } else {
	$domains = $kolab['postfix-mydestination'];
	unset($domains['count']);
  }
  debug("value=$value, domain=$domains");
  $ok = false;
  foreach( $domains as $domain ) {
	if( endsWith( $value, '@'.$domain ) ) {	
	  $ok = true;
	}
  }
  if(!$ok) return sprintf(_("Email address %1\$s not in domains %2\$s"), $value, join(", ", $domain));

  if( $ldap->countMail( $_SESSION['base_dn'], $value ) > 0 ) {	
	return _('User, vCard or distribution list with this email address already exists');
  } else {
	return '';
  }
}

function checkuniquealias( $form, $key, $value ) {
  global $ldap;
  global $action;
  global $dn;
  $excludedn = false;
  if( $action == 'save' ) $excludedn = trim($dn);
  $lst = array_unique( array_filter( array_map( 'trim', preg_split( '/\n/', $value ) ), 'strlen') );
  $str = '';
  foreach( $lst as $alias ) {
	debug( "looking at $alias, exluding $dn" );
	if( $ldap->countMail( $_SESSION['base_dn'], $alias, $excludedn ) > 0 ) {
	  $str .= _('Email address ').MySmarty::htmlentities($alias)._(' collision <br />');
	}
  }
  return $str;
}

function checkuid( $form, $key, $value ) {
  global $ldap;
  global $action;
  global $dn;
  $excludedn = false;
  if( $action == 'save' ) $excludedn = trim($dn);
  $lst = array_unique( array_filter( array_map( 'trim', preg_split( '/\n/', $value ) ), 'strlen') );
  $str = '';
  foreach( $lst as $uid ) {
    if( $ldap->countMail( $_SESSION['base_dn'], $uid, $excludedn ) > 0 ) {
      $str .= _('UID ').MySmarty::htmlentities($uid)._(' collision <br />');
    }
  }
  return $str;
}

function checkdelegate( $form, $key, $value ) {
  global $ldap;
  global $action;
  global $dn;

  $lst = array_unique( array_filter( array_map( 'trim', preg_split( '/\n/', $value ) ), 'strlen') );
  $str = '';
  foreach( $lst as $delegate ) {
	if( $ldap->count( $ldap->search( $_SESSION['base_dn'], '(mail='.$ldap->escape($delegate).')' ) ) == 0 ) {
	  return sprintf(_("Email-Delegate %s does not exist"), $delegate);
	} 
  }
  return '';
}

// Check uid/gid used in invitation policy
// We're pretty relaxed about what is entered 
// here and only check some basic syntax
function checkpolicy( $form, $key, $value ) {
  foreach( $value as $v ) {
	$v = trim($v);
	if( !empty($v) && !ereg('^([0-9a-zA-Z._@ ]|-)*$', $v ) ) {
	  return sprintf(_("Illegal user or group %s"), $v);
	}
  }
  return '';
}

// Check that password match
function checkpw( $form, $key, $value ) {
  global $action;
  if( $action == 'firstsave' ) {
    if( $key == 'password_0' ) {
      if( $value == '' ) return _('Password is empty');
    } else if( $key == 'password_1' ) {
      if( $value != $_POST['password_0'] ) {
        return _('Passwords dont match');
      }
    }
  } else {
    if( $value != $_POST['password_0'] ) {
      return _('Passwords dont match');
    }
  }
  return '';
}

// Due to a cyrus imapd bug we can't currently
// support quotas over 4095 MB, see issue1262
function checkquota( $form, $key, $value )
{
	if( empty($value) ) return ''; // OK
	else if( $value >= 4096 ) return _('Quota must be smaller than 4096');
	else if( $value < 0 ) return _('Quota can not be negative');
	else return '';
}

function policy2number( $pol, $default = 3 )
{
  // Translate policy to number
  switch ($pol) {
  case 'ACT_ALWAYS_ACCEPT': return 0;
  case 'ACT_ALWAYS_REJECT': return 1;
  case 'ACT_REJECT_IF_CONFLICTS': return 2;
  case 'ACT_MANUAL_IF_CONFLICTS': return 3;
  case 'ACT_MANUAL': return 4;
  default: return $default;
  }
}

function apply_attributeaccess( &$entries ) {
  global $params;
  $attributeaccess =& $params['attribute_access'];
  foreach( $entries as $key=>$value ) {
	if( ereg( '(.*)_[0-9]', $key, $regs ) ) {
	  $akey = $regs[1];
	} else {
	  $akey = $key;
	}
	if( isset($attributeaccess[$akey] ) ) {
	  if( $attributeaccess[$akey] == 'ro' ) {
		$entries[$key]['attrs'] = 'readonly';
	  } else if( $attributeaccess[$akey] == 'hidden' ) {
		  //$entries[$key]['attrs'] = 'hidden';
		unset($entries[$key]);
	  } else if( $attributeaccess[$akey] == 'mandatory' ) {
		if( isset( $entries[$key]['validation'] ) ) {
		  if( is_array( $entries[$key]['validation'] ) ) {
			$entries[$key]['validation'][] = 'notempty';
		  } else {
			$entries[$key]['validation'][] = array( $entries[$key]['validation'], 'notempty' );
		  }
		} else {
		  $entries[$key]['validation'] = 'notempty';		  
		}
	  }
	}
  }
}

function fill_form_for_modify( &$form, $dn, &$ldap_object ) {
  global $auth;
  if (is_array($ldap_object['sn'])) $sn = $ldap_object['sn'][0];
  else $sn = $ldap_object['sn'];
  if (is_array($ldap_object['cn'])) $cn = $ldap_object['cn'][0];
  else $cn = $ldap_object['cn'];
  if ($sn) {
    $a = strlen($sn);
    if ($cn) {
      $b = strlen($cn);
      $givenname = substr($cn, 0, $b - $a);
    }
  }
  if (is_array($ldap_object['mail'])) $mail = $ldap_object['mail'][0];
  else $mail = $ldap_object['mail'];
  if (is_array($ldap_object['uid'])) $uid = $ldap_object['uid'][0];
  else $uid = $ldap_object['uid'];
  if(array_key_exists('givenname',$form->entries)) $form->entries['givenname']['value'] = $givenname;
  if(array_key_exists('sn',$form->entries)) $form->entries['sn']['value'] = $sn;
  if(array_key_exists('password_0',$form->entries))  $form->entries['password_0']['value'] = '';
  if(array_key_exists('password_1',$form->entries))  $form->entries['password_1']['value'] = '';
  if(array_key_exists('mail',$form->entries))  $form->entries['mail']['value'] = $mail;
  if(array_key_exists('mail',$form->entries))  $form->entries['mail']['attrs'] = 'readonly';
  if(array_key_exists('uid',$form->entries))  $form->entries['uid']['value'] = $uid;
  // accttype
  $dncomp = split( ',', $dn );
  if(array_key_exists('acctype',$form->entries)) {
	  if( in_array('cn=groups',$dncomp) ) {
		  $form->entries['accttype']['value'] = 2;
	  } else if( in_array('cn=resources',$dncomp) ) {
		  $form->entries['accttype']['value'] = 3;	
	  } else if( in_array('cn=internal',$dncomp) ) {
		  $form->entries['accttype']['value'] = 1;	
	  } else {
		  $form->entries['accttype']['value'] = 0;
	  }
	  if( $auth->group() == 'user' ) $form->entries['accttype']['attrs'] = 'readonly';
  }

  // Automatic invitation handling
  if(array_key_exists('kolabinvitationpolicy',$form->entries)) {
	  $policies = array();
	  for( $i = 0; $i < $ldap_object['kolabInvitationPolicy']['count']; $i++ ) {
		  $resact = $ldap_object['kolabInvitationPolicy'][$i];
		  debug("resact=$resact");
		  if( ereg( '(.*):(.*)', trim($resact), $regs ) ) {
			  $user = trim($regs[1]);
			  $pol  = trim($regs[2]);
			  if( empty($user) ) continue;
		  } else {
			  $user = 'anyone';
			  $pol = trim($resact);
		  }
		  if( $form->entries['accttype']['value'] == 1 ) {
			  // default for groups
			  $pol = policy2number( $pol, 3 /*ACT_MANUAL_IF_CONFLICTS*/ );
		  } else {
			  // default for resources
			  $pol = policy2number( $pol, 2 /*ACT_REJECT_IF_CONFLICTS*/ );
		  }
		  $policies[$user] = $pol;
	  }
	  if( !isset( $policies['anyone'] ) ) $policies['anyone'] = 4 /*ACT_MANUAL*/;
	  $form->entries['kolabinvitationpolicy']['policies'] = $policies;  
  }

  foreach( array( 'title', 'o', 'ou', 'roomNumber', 'street', 
				  'postOfficeBox', 'postalCode', 'l', 'c', 
				  'telephoneNumber', 'facsimileTelephoneNumber' ) as $attr ) {
	if(!array_key_exists($attr.'_0',$form->entries)) continue;
    if (is_array($ldap_object[$attr])) $v = $ldap_object[$attr][0];
    else $v = $ldap_object[$attr];
    $form->entries[$attr.'_0']['value'] = $v;
  }

  // alias
  if(array_key_exists('alias',$form->entries)) {
	  if (is_array($ldap_object['alias'])) {
		  $arr = $ldap_object['alias'];
		  unset( $arr['count'] );
		  $v = join("\n", $arr );
	  }
	  else $v = "";
	  $form->entries['alias']['value'] = $v;
  }

  // kolabdelegate
  if (is_array($ldap_object['kolabDelegate'])) {
	$arr = $ldap_object['kolabDelegate'];
	unset( $arr['count'] );
	$v = join("\n", $arr );
  }
  else $v = "";
  if(array_key_exists('kolabdelegate',$form->entries)) $form->entries['kolabdelegate']['value'] = $v;

  // kolabhomeserver
  if(array_key_exists('kolabhomeserver',$form->entries)) {
	  if( is_array($ldap_object['kolabHomeServer']) ) {
		  $form->entries['kolabhomeserver']['value'] = $ldap_object['kolabHomeServer'][0];
	  }
	  $form->entries['kolabhomeserver']['attrs'] = 'readonly';
  }
  $form->entries['action']['value'] = 'save';

  // userquota
  if( isset( $form->entries['cyrus-userquota'] ) ) {
    if (is_array($ldap_object['cyrus-userquota'])) $userquota = $ldap_object['cyrus-userquota'][0];
    else $userquota = $ldap_object['cyrus-userquota'];
    if( $userquota > 0 ) {
      $form->entries['cyrus-userquota']['value'] = $userquota;
    } else {
      $form->entries['cyrus-userquota']['value'] = '';
    }
  }

  // freebusyfuture
  if( isset( $form->entries['kolabFreeBusyFuture_0'] ) ) {
	if( is_array( $ldap_object['kolabFreeBusyFuture'] ) ) 
	  $freebusyfuture = $ldap_object['kolabFreeBusyFuture'][0];
	else $freebusyfuture = $ldap_object['kolabFreeBusyFuture'];
	$form->entries['kolabFreeBusyFuture_0']['value'] = $freebusyfuture;
  }
}

/**** Authentication etc. ***/
$sidx = 'user';

require_once('@kolab_php_module_prefix@admin/include/menu.php');
$menuitems[$sidx]['selected'] = 'selected';

/**** Logic ***/
$errors = array();
$messages = array();
$valid_actions = array('save','firstsave','modify','create','delete','kill');
$contenttemplate = 'formcontainer.tpl';

// Get request data
if (!empty($_REQUEST['action']) &&
    in_array($_REQUEST['action'],$valid_actions)) $action = trim($_REQUEST['action']);
else array_push($errors, _("Error: need valid action to proceed") );
$dn="";
if (!empty($_REQUEST['dn'])) $dn = trim($_REQUEST['dn']);

if( $auth->group() == 'user' ) {
	$dn = $auth->dn();
}

// Check auth
if (!$errors && $auth->group() != 'maintainer' && $auth->group() != 'admin' &&
	$auth->group() != 'domain-maintainer' &&
    !($auth->group() == 'user' && $dn == $auth->dn() )) {
  array_push($errors, _("Error: You don't have the required Permissions") );
} else if( $auth->group() == 'domain-maintainer' ) {
  // TODO(steffen): Check that user is in correct domain(s)
}


if( !$errors && $auth->group() == 'user' && ($action == 'firstsave' || $action == 'kill' ) ) {
  $errors[] = _("Error: You don't have the required Permissions");
}

// Fill in data
if ($action == "create") {
  $comment_mail = _('Required, non volatile');
  $comment_password = _('Required');
  $comment_kolabhomeserver = _('Required, non volatile');
} else {
  $comment_mail = _('Non volatile');
  $comment_password = _('Leave blank to keep password unchanged');
  $comment_kolabhomeserver = _('Non volatile');
}

$entries = array( 'givenname' => array( 'name' => _('First Name'),
					'validation' => 'notempty',
					'comment' => _('Required') ),
		  'sn' => array( 'name' => _('Last Name'),
				       'validation' => 'notempty',
				       'comment' => _('Required') ),
		  'password_0' => array( 'name' => _('Password'),
					 'type' => 'password',
					 'validation' => 'checkpw',
					 'comment' => $comment_password ),
		  'password_1' => array( 'name' => _('Verify Password'),
					 'type' => 'password',
					 'validation' => 'checkpw',
					 'comment' => $comment_password ),
		  'mail' => array( 'name' => _('Primary Email Address'),
					 'type'       => 'email',
					 'domains'    => ($auth->group()=='domain-maintainer')?$ldap->domainsForMaintainerDn($auth->dn()):$ldap->domains(),
				     'validation' => 'notempty',
				     'comment'    => $comment_mail ),
		  'uid'    => array( 'name' => _('Unique Identity (UID)'),
                                     'validation' => 'checkuid',
                                     'comment' => _('Optional - Defaults to Primary Email Address') ),
		  'kolabhomeserver' => array( 'name' => _('Mailbox Home Server'),
									  'validation' => 'notempty',
									  'comment' => $comment_kolabhomeserver,
									  'value' => $_SESSION['fqdnhostname'] ),
		  'accttype' => array( 'name' => _('Account Type'),
							   'type' => 'select',
							   'options' => array( _('User Account'), _('Internal User Account'), _('Group Account'), _('Resource Account') ),
							   'value'   => 0,
							   'comment' => _('NOTE: An internal user is a user that will not be visible in the address book')),
		  'kolabinvitationpolicy' => array( 'name' => _('Invitation Policy'),
									 'type' => 'resourcepolicy',
									 'policies' => array('anyone' => 4),
									 'validation' => 'checkpolicy',
									 'comment' => _('For automatic invitation handling') . '<br/>' .
									 _("NOTE: For regular accounts to use this feature, give the 'calendar' user access to the Calendar folder") ),
		  'title_0' => array( 'name' => _('Title') ) );
$entries['alias'] = array( 'name' => _('Email Aliases'), 
						   'type' => 'textarea',
						   'validation' => 'checkuniquealias',
						   'comment' => _('One address per line') );
$entries['kolabdelegate'] =array( 'name' => _('Email-Delegates'),
		'type' => 'textarea',
		'validation' => 'checkdelegate',
		'comment' => _('Others allowed to send emails with a "from" address of this account.') . '<br/>' .
			_('One email address per line.') );
$entries['o_0'] = array( 'name' => _('Organisation') );
$entries['ou_0'] = array( 'name' => _('Organisational Unit') );
$entries['roomNumber_0'] = array( 'name' => _('Room Number') );
$entries['street_0'] = array( 'name' => _('Street Address') );
$entries['postOfficeBox_0'] = array( 'name' => _('Postbox') );
$entries['postalCode_0'] = array( 'name' => _('Postal Code') );
$entries['l_0'] = array( 'name' => _('City') );
$entries['c_0'] = array( 'name' => _('Country') );
$entries['telephoneNumber_0'] = array( 'name' => _('Telephone Number') );
$entries['facsimileTelephoneNumber_0'] = array( 'name' => _('Fax Number') );
if( $auth->group() == 'admin' || $auth->group() == 'maintainer' || $auth->group() == 'domain-maintainer' ) {
  $entries['cyrus-userquota'] = array( 'name' => _('User Quota in MBytes'),
				       'comment' => _('Leave blank for unlimited'),
				       'validation' => 'checkquota');
} else {
  $entries['givenname']['attrs'] = 'readonly';
  $entries['sn']['attrs'] = 'readonly';
  $entries['givenname']['comment'] = '';
  $entries['sn']['comment'] = '';
  $entries['alias']['attrs'] = 'readonly';
  $entries['kolabhomeserver']['attrs'] = 'readonly';
  $entries['accttype']['attrs'] = 'readonly';
  $entries['uid']['attrs'] = 'readonly';
}
$entries['kolabFreeBusyFuture_0'] = array( 'name' => _('Free/Busy interval in days'),
									 'comment' => _('Leave blank for default (60 days)') );
$entries['action'] = array( 'name' => 'action',
			    'type' => 'hidden' );

if( $dn ) {
  $ldap_object = $ldap->read( $dn );
  if( !$ldap_object ) {
    array_push($errors, sprintf(_("LDAP Error: No such dn: %s: %s"), $dn, ldap_error($ldap->connection)));
  }
}

if( $auth->group() == 'user' ) {
  apply_attributeaccess( $entries );
}
$form =& new KolabForm( 'user', 'createuser.tpl', $entries );
/***************** Main action swicth **********************/
switch( $action ) {
 case 'firstsave':
   debug("adding checkuniquemail to validation");
   $form->entries['mail']['validation'] = array( $form->entries['mail']['validation'], 'checkuniquemail');
 case 'save':
   if( $form->isSubmitted() ) {
     if( !$form->validate() ) {
       $form->setValues();
       $content = $form->outputForm();
     } else {
       $ldap_object = array();
       $ldap_object['objectClass'] = array('top', 'inetOrgPerson','kolabInetOrgPerson');
       $ldap_object['sn'] = trim($_POST['sn']);
       $ldap_object['cn'] = trim($_POST['givenname']).' '.$ldap_object['sn'];
	   $ldap_object['givenName'] = trim($_POST['givenname']);
       if( !empty( $_POST['password_0'] ) ) {
		 $ldap_object['userPassword'] = '{sha}'.base64_encode( pack('H*', 
																	sha1( $_POST['password_0'])));
		 if( $action == 'save' && $auth->dn() == $dn ) {
		   // We are editing our own password, let's update the session!
		   $auth->setPassword($_POST['password_0']);
		 }

		 /* The code below is disabled for now because we're
			not going to use that encrypted password anyway.
			
			TODO: Clean it up once we're sure we don't want it
		 */
		 if( false && isset( $_POST['accttype'] ) && $_POST['accttype'] > 1 ) {
		   // We have a group or resource, create encrypted pw
		   $pubkeydata=file_get_contents("@sysconfdir@/kolab/res_pub.pem" );		   
		   $pkey = openssl_pkey_get_public( $pubkeydata );
		   if( $pkey === false ) {
			 $sslerr = "Could not read resource encryption public key file://@sysconfdir@/kolab/res_pub.pem: "; 
							   
			 while( $msg = openssl_error_string() )
			   $sslerr .= $msg.' ';
			 $errors[] = $sslerr;
		   } else {
			 if( !openssl_public_encrypt( $_POST['password_0'], $encpw, $pkey ) ) {
			   $sslerr = _("Could not encrypt password: ");
			   while( $msg = openssl_error_string() )
				 $sslerr .= $msg.' ';
			   $errors[] = $sslerr;
			 } else {
			   $ldap_object['kolabEncryptedPassword'] = base64_encode( $encpw );
			 }
			 openssl_free_key( $pkey );
		   }
		 }
       }
       $ldap_object['mail'] = trim( strtolower( $_POST['user_mail'] ) ).'@'.trim( strtolower( $_POST['domain_mail'] ) );
       $ldap_object['uid'] = trim( strtolower( $_POST['uid'] ) );
       if( $action == 'firstsave' ) {
		 if ($ldap_object['uid'] == "") $ldap_object['uid'] = $ldap_object['mail'];
		 $ldap_object['kolabHomeServer'] = trim($_POST['kolabhomeserver']);
	   } else {
		 unset($ldap_object['kolabHomeServer']);
	   }
       foreach( array( 'title', 'o', 'ou', 'roomNumber', 'street', 'postOfficeBox',
		       'postalCode', 'l', 'c', 'telephoneNumber',
		       'facsimileTelephoneNumber', 'kolabFreeBusyFuture' ) as $attr ) {
		 $count = 0;
		 $key = $attr."_0";
		 $args = array();
		 while (!empty($_POST[$key])) {
		   $args[$count] = trim($_POST[$key]);
		   $count++;
		   $key = $attr."_".$count;
		 }
		 if ($count > 0) $ldap_object[$attr] = $args;
		 elseif (!empty($_POST[$key])) $ldap_object[$attr] = $_POST[$key];  
		 else/*if (in_array($key,$_POST))*/ $ldap_object[$attr] = array();
       }
	   {
		 // Handle group/resource policies
		 $i = 0;
		 $ldap_object['kolabInvitationPolicy'] = array();
		 while( isset( $_POST['user_kolabinvitationpolicy_'.$i] ) ) {
		   $user = $_POST['user_kolabinvitationpolicy_'.$i];
		   $pol  = (int)$_POST['policy_kolabinvitationpolicy_'.$i];
		   debug("Looking at $user:$pol");
		   $i++;
		   if( !empty($user) && 0 <= $pol && $pol < 5  ) {
			 $ra = array('ACT_ALWAYS_ACCEPT', 
						 'ACT_ALWAYS_REJECT', 
						 'ACT_REJECT_IF_CONFLICTS', 
						 'ACT_MANUAL_IF_CONFLICTS', 
						 'ACT_MANUAL' );
			 if( $ra[$pol] ) {
			   $ldap_object['kolabInvitationPolicy'][] = ($user=='anyone'?"":"$user:").$ra[$pol];
			 }
		   }
		 }		 
	   }
	   $dn_add = "";

	   // kolabdelegate
	   $ldap_object['kolabDelegate'] = array_unique( array_filter( array_map( 'trim', 
												preg_split( '/\n/', $_POST['kolabdelegate'] ) ), 'strlen') );
	   if( !$ldap_object['kolabDelegate'] && $action == 'firstsave' ) unset($ldap_object['kolabDelegate']);


       if ($auth->group() == "maintainer" || $auth->group() == "admin") {
		 // alias
		 $ldap_object['alias'] = array_unique( array_filter( array_map( 'trim', preg_split( '/\n/', $_POST['alias'] ) ), 'strlen') );	   
		 if( !$ldap_object['alias'] && $action == 'firstsave' ) unset($ldap_object['alias']);

		 // userquota
		 if( isset( $_POST['cyrus-userquota'] ) ) {
		   $ldap_object['cyrus-userquota'] = trim($_POST['cyrus-userquota']);
		   if( empty( $ldap_object['cyrus-userquota'] ) ) {
			 $ldap_object['cyrus-userquota'] = array();
		   }
		 }
       }
	   if( $_POST['accttype'] == 0 ) $dn_accttype='';
	   else if( $_POST['accttype'] == 1 ) $dn_accttype='cn=internal,';
	   else if( $_POST['accttype'] == 2 ) $dn_accttype='cn=groups,';
	   else if( $_POST['accttype'] == 3 ) $dn_accttype='cn=resources,';
       $domain_dn = $dn_accttype.domain_dn();
	   
       if ($action == "save") {
		 if (!$errors) {
		   if (!empty($ldap_object['cn'])) $newdn = "cn=".$ldap->dn_escape($ldap_object['cn']).",".$domain_dn;
		   else $newdn = $dn;
		   if (strcmp($dn,$newdn) != 0) {
			 // Check for distribution lists with this user as member
			 $ldap->search( $_SESSION['base_dn'], 
							'(&(objectClass=kolabGroupOfNames)(!(kolabDeleteFlag=*))(member='.$ldap->escape($dn).'))',
							array( 'dn', 'mail' ) );
			 $distlists = $ldap->getEntries();
			 unset( $distlists['count'] );
			 foreach( $distlists as $distlist ) {
				 $dlcn = $distlist['mail'][0];
				 $errors[] = sprintf(_("Account DN could not be modified, distribution list <a href='@webserver_web_prefix@/admin/distributionlist/list.php?action=modify&dn=%s'>'%s'</a> depends on it. To modify this account, first remove it from the distribution list."), urlencode($distlist['dn']), $dlcn );
			 }

			 if (($result=ldap_read($ldap->connection,$dn,"(objectclass=*)")) &&
				 ($entry=ldap_first_entry($ldap->connection,$result)) &&
				 ($oldattrs=ldap_get_attributes($ldap->connection,$entry))) {
			   $ldap_object['uid'] = $oldattrs['uid'][0];
			   $ldap_object['mail'] = $oldattrs['mail'][0];
			   unset( $oldattrs['count'] );
			   foreach( $oldattrs as $k => $v ) {
				 if( is_int($k) ) continue;
				 if( !$ldap_object[$k] ) {
				   unset($v['count'] );
				   if( count($v) > 1 ) { 
					 $ldap_object[$k] = $v;
				   } else {
					 $ldap_object[$k] = $v[0];
				   }
				 }
			   }
			   if( !$ldap_object['userPassword'] ) $ldap_object['userPassword'] = $oldattrs['userPassword'][0];
			   foreach( $ldap_object as $k => $v ) {
				 if( $v == array() ) unset($ldap_object[$k]);
			   }
			   $tmprdn = "cn=".str_rand(16);
			   $explodeddn = ldap_explode_dn( $dn, 0 );
			   unset($explodeddn['count']);
			   unset($explodeddn[0]);
			   $tmpbasedn = join(",",$explodeddn);			   
			   if ( !$errors && !ldap_rename($ldap->connection,$dn,$tmprdn,$tmpbasedn,false) ) {
				 array_push($errors, sprintf(_("LDAP Error: Could not rename %1\$s to %2\$s: %3\$s"), $dn, $tmprdn,
											 ldap_error($ldap->connection)));
			   }
			   if ( !$errors && !ldap_add($ldap->connection,$newdn, $ldap_object) ) {
				 array_push($errors, sprintf(_("LDAP Error: Could not rename %1\$s to %2\$s: %3\$s"), $dn, $newdn,
											 ldap_error($ldap->connection)));
			   }
			   if( !$errors ) {
				 if( !ldap_delete($ldap->connection,$tmprdn.','.$tmpbasedn)) {
				   array_push($errors, sprintf(_("LDAP Error: Could not remove old entry %s,%s: %s"), 
											   $tmprdn, $tmpbasedn,
											   ldap_error($ldap->connection)));
				 }
			   }
			   $dn = $newdn;
			 } else array_push($errors, sprintf(_("LDAP Error: Could not read %s: %s"), $dn,
												ldap_error($ldap->connection)));
		   } else {
			 //$ldap_object = fill_up($ldap_object);
			 if ($auth->group() == "user") {
			   unset($ldap_object['sn']);
			   unset($ldap_object['cn']);
			   unset($ldap_object['mail']);
			   unset($ldap_object['uid']);
			   unset($ldap_object['kolabHomeServer']);
			 }
			 if (!ldap_modify($ldap->connection, $dn, $ldap_object)) {			   
			   array_push($errors, sprintf(_("LDAP Error: Could not modify object %s: %s"), $dn,
										   ldap_error($ldap->connection)));
			   debug_var_dump( $ldap_object );
			 }
		   }
		   // Check for collisions on alias
		   for( $i = 0; $i < count($ldap_object['alias']); ++$i ) {
			 if( $ldap->countMail( $_SESSION['base_dn'], $alias, $dn ) > 0 ) {
			   // Ups!!!
			   $alias = $ldap_object['alias'][$i];
			   $newalias = md5sum( $dn.$alias ).'@'.substr( $alias, 0, strpos( $alias, '@' ) );
			   $ldap_object['alias'][$i] = $newalias;
			   if (!ldap_modify($ldap->connection, $dn, $ldap_object)) {
				 $errors[] = sprintf(_("LDAP Error: Could not modify object %s: %s"), $dn, 
									 ldap_error($ldap->connection));
			   }
			   $error[] = sprintf(_("Mid-air collision detected, alias %1\$s renamed to %2\$s"), 
								  $alias, $newalias);
			 }
		   }
		 }
		 $heading = _('Modify User');
		 if( !$errors ) $messages[] = sprintf(_("User '%s' successfully modified"), $dn);
		 $form->setValues();
		 $form->entries['mail']['attrs'] = 'readonly';
		 $form->entries['kolabhomeserver']['attrs'] = 'readonly';
		 $form->entries['action']['value'] = 'save';
		 $form->entries['dn'] = array( 'name' => 'dn',
									   'type' => 'hidden',
									   'value' => $dn );
		 $content = $form->outputForm();
       } else {
		 // firstsave
		 if (!$errors) {
		   $dn = "cn=".$ldap->dn_escape($ldap_object['cn']).$dn_add.",".$domain_dn;
		   foreach( $ldap_object as $k => $v ) {
			 if( $v == array() ) unset($ldap_object[$k]);
		   }
		   debug("Calling ldap_add with dn=$dn");
		   if ($dn && !ldap_add($ldap->connection, $dn, $ldap_object)) 
			 array_push($errors, sprintf(_("LDAP Error: could not add object %s: %s"), $dn,
										 ldap_error($ldap->connection)));

		   // Check for mid-air collisions on mail
		   if( $ldap->countMail( $_SESSION['base_dn'], $ldap_object['mail'], $dn ) > 0 ) {
			 // Ups!!!
			 $mail = $ldap_object['mail'];
			 $newmail = md5sum( $dn.$mail ).'@'.substr( $mail, 0, strpos( $mail, '@' ) );
			 $ldap_object['uid'] = $ldap_object['mail'] = $newmail;
			 if (!ldap_modify($ldap->connection, $dn, $ldap_object)) {
			   $errors[] = sprintf(_("LDAP Error: Could not modify object %s: %s"), $dn, 
								   ldap_error($ldap->connection));
			 }
			 $error[] = sprintf(_("Mid-air collision detected, email address %1\$s renamed to %2\$s"), 
								$mail, $newmail);
		   }

		   // Check for collisions on alias
		   for( $i = 0; $i < count($ldap_object['alias']); ++$i ) {
			 if( $ldap->countMail( $_SESSION['base_dn'], $alias, $dn ) > 0 ) {
			   // Ups!!!
			   $alias = $ldap_object['alias'][$i];
			   $newalias = md5sum( $dn.$alias ).'@'.substr( $alias, 0, strpos( $alias, '@' ) );
			   $ldap_object['alias'][$i] = $newalias;
			   if (!ldap_modify($ldap->connection, $dn, $ldap_object)) {
				 $errors[] = sprintf(_("LDAP Error: Could not modify object %s: %s"), $dn,
									 ldap_error($ldap->connection));
			   }
			   $error[] = sprintf(_("Mid-air collision detected, alias %1\$s renamed to %2\$s"), 
								  $alias, $newalias);
			 }
		   }

		   if( !$errors ) {
			 $messages[] = _('User ').$ldap_object['dn']._(' successfully created');
			 $heading = _('Create New User');
			 $form->entries['action']['value'] = 'firstsave';
			 $content = $form->outputForm();
			 break;
		   }
		 } else {
		   $heading = _('Create New User');
		   $blacklist = array('mail');
		   $form->entries['action']['value'] = 'firstsave';
		   $form->outputForm();
		   break;
		 }
       }
     }
     break;
   }
 case 'create':
   $heading = _('Create New User');
   if( !$dn ) {
     $form->entries['action']['value'] = 'firstsave';
   } else {
     $form->entries['action']['value'] = 'save';
   }
   $content = $form->outputForm();
   break;
 case 'modify':
   $heading = _('Modify User');
   fill_form_for_modify( $form, $dn, $ldap_object );
   $form->entries['action']['value'] = 'save';
   $content = $form->outputForm();
   break;
 case 'delete':
   $heading = _('Delete User');
   foreach( $form->entries as $k => $v ) {
     if( $v['type'] != 'hidden' ) {
       $form->entries[$k]['attrs'] = 'readonly';
     }
   }
   fill_form_for_modify( $form, $dn, $ldap_object );
   $form->entries['action']['value'] = 'kill';
   $form->submittext = _('Delete');
   $content = $form->outputForm();
   break;
 case 'kill':
   if (!$dn) array_push($errors, _("Error: need DN for delete operation"));
   elseif ($auth->group() != "maintainer" && $auth->group() != "admin") 
     array_push($errors, _("Error: you need administrative permissions to delete users"));

   // Check for distribution lists with only this user as member
   $ldap->search( $_SESSION['base_dn'], 
				  '(&(objectClass=kolabGroupOfNames)(member='.$ldap->escape($dn).'))',
				  array( 'dn', 'cn', 'mail', 'member' ) );
   $distlists = $ldap->getEntries();
   unset($distlists['count']);
   foreach( $distlists as $distlist ) {
	 $dlmail = $distlist['mail'][0];
	 if( !$dlmail ) $dlmail = $distlist['cn'][0]; # Compatibility with old stuff
	 if( $distlist['member']['count'] == 1 ) {
	   $errors[] = sprintf(_("Account could not be deleted, distribution list '%s' depends on it."), $dlmail);
	 }
   }
   if( !$errors ) foreach( $distlists as $distlist ) {
	 $dlmail = $distlist['mail'][0];
	 if( !$dlmail ) $dlmail = $distlist['cn'][0]; # Compatibility with old stuff
	 if( ldap_mod_del( $ldap->connection, $distlist['dn'], array('member' => $dn ) ) ) {
	   $messages[] = sprintf(_("Account removed from distribution list '%s'."), $dlmail);
	 } else {
	   $errors[] = sprintf(_("Failure to remove account from distribution list '%s', account will not be deleted."),
						   $dlmail);
	   break;
	 }
   }

   if( !$errors ) {
	 if (!$ldap->deleteObject($dn)) {
	   array_push($errors, sprintf(_("LDAP Error: could not mark '%s' for deletion: %s"), $dn, 
								   $ldap->error()));
	 } else {
	   $heading = _("User Deleted");
	   $contenttemplate = 'userdeleted.tpl';
	 }
   }

   if( $errors ) {
	 $heading = _('Delete User');
	 foreach( $form->entries as $k => $v ) {
	   if( $v['type'] != 'hidden' ) {
		 $form->entries[$k]['attrs'] = 'readonly';
	   }
	 }
	 fill_form_for_modify( $form, $dn, $ldap_object );
	 $form->entries['action']['value'] = 'kill';
	 $form->submittext = _('Delete');
	 $content = $form->outputForm();
   }   
   break;
}


$smarty = new MySmarty();
$smarty->assign( 'topdir', $topdir );
$smarty->assign( 'errors', array_merge((array)$errors,(array)$form->errors) );
$smarty->assign( 'uid', $auth->uid() );
$smarty->assign( 'group', $auth->group() );
$smarty->assign( 'page_title', $menuitems[$sidx]['title'] );
$smarty->assign( 'menuitems', $menuitems );
$smarty->assign( 'submenuitems', 
				 array_key_exists('submenu', 
								  $menuitems[$sidx])?$menuitems[$sidx]['submenu']:array() );
$smarty->assign( 'heading', $heading );
$smarty->assign( 'form', $content );
if( isset( $dn ) ) $smarty->assign( 'dn', $dn );
if( count($messages)>0) $smarty->assign( 'messages', $messages );
$smarty->assign( 'maincontent', $contenttemplate );
$smarty->display('page.tpl');

/*
  Local variables:
  mode: php
  indent-tabs-mode: t
  tab-width: 4
  buffer-file-coding-system: utf-8
  End:
 */
?>