summaryrefslogtreecommitdiff
path: root/lib/api/kolab_api_service_form_value.php
blob: f85f45d6b632f63e3a3e12af712bc1735f1a6ffb (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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
<?php
/*
 +--------------------------------------------------------------------------+
 | This file is part of the Kolab Web Admin Panel                           |
 |                                                                          |
 | Copyright (C) 2011-2012, Kolab Systems AG                                |
 |                                                                          |
 | This program is free software: you can redistribute it and/or modify     |
 | it under the terms of the GNU Affero General Public License as published |
 | by the Free Software Foundation, either version 3 of the License, or     |
 | (at your option) any later version.                                      |
 |                                                                          |
 | This program is distributed in the hope that it will be useful,          |
 | but WITHOUT ANY WARRANTY; without even the implied warranty of           |
 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the             |
 | GNU Affero General Public License for more details.                      |
 |                                                                          |
 | You should have received a copy of the GNU Affero General Public License |
 | along with this program. If not, see <http://www.gnu.org/licenses/>      |
 +--------------------------------------------------------------------------+
 | Author: Aleksander Machniak <machniak@kolabsys.com>                      |
 | Author: Jeroen van Meeuwen <vanmeeuwen@kolabsys.com>                     |
 +--------------------------------------------------------------------------+
*/

/**
 * Service providing functionality related to HTML forms generation/validation.
 */
class kolab_api_service_form_value extends kolab_api_service
{

    /**
     * Returns service capabilities.
     *
     * @param string $domain Domain name
     *
     * @return array Capabilities list
     */
    public function capabilities($domain)
    {
        return array(
            'generate'       => 'r',
            'validate'       => 'r',
            'select_options' => 'r',
            'list_options'   => 'r',
        );
    }

    /**
     * Generation of auto-filled field values.
     *
     * @param array $getdata   GET parameters
     * @param array $postdata  POST parameters. Required parameters:
     *                         - attributes: list of attribute names
     *                         - type_id: Type identifier
     *                         - object_type: Object type (user, group, etc.)
     *
     * @return array Response with attribute name as a key
     */
    public function generate($getdata, $postdata)
    {
        $attribs    = $this->object_type_attributes($postdata['object_type'], $postdata['type_id']);

        $attributes = (array) $postdata['attributes'];
        $result     = array();

        foreach ($attributes as $attr_name) {
            if (empty($attr_name)) {
                continue;
            }

            $method_name = 'generate_' . strtolower($attr_name) . '_' . strtolower($postdata['object_type']);

            if (!method_exists($this, $method_name)) {
                //console("Method $method_name doesn't exist");

                $method_name = 'generate_' . strtolower($attr_name);

                if (!method_exists($this, $method_name)) {
                    continue;
                }
            }

            $result[$attr_name] = $this->{$method_name}($postdata, $attribs);
        }

        return $result;
    }

    /**
     * Generation of values for fields of type LIST.
     *
     * @param array $getdata   GET parameters
     * @param array $postdata  POST parameters. Required parameters:
     *                         - attribute: attribute name
     *                         - type_id: Type identifier
     *                         - object_type: Object type (user, group, etc.)
     *
     * @return array Response with attribute name as a key
     */
    public function list_options($getdata, $postdata)
    {
        //console($postdata);

        $attribs   = $this->object_type_attributes($postdata['object_type'], $postdata['type_id']);
        $attr_name = $postdata['attribute'];
        $result    = array(
            // return search value, so client can match response to request
            'search' => $postdata['search'],
            'list'   => array(),
        );

        if (empty($attr_name)) {
            return $result;
        }


        $method_name = 'list_options_' . strtolower($attr_name) . '_' . strtolower($postdata['object_type']);

        if (!method_exists($this, $method_name)) {
            //console("Method $method_name doesn't exist");

            $method_name = 'list_options_' . strtolower($attr_name);

            if (!method_exists($this, $method_name)) {
                return $result;
            }
        }

        //console($method_name);

        $result['list'] = $this->{$method_name}($postdata, $attribs);

        return $result;
    }

    /**
     * Generation of values for fields of type SELECT.
     *
     * @param array $getdata   GET parameters
     * @param array $postdata  POST parameters. Required parameters:
     *                         - attributes: list of attribute names
     *                         - type_id: Type identifier
     *                         - object_type: Object type (user, group, etc.)
     *
     * @return array Response with attribute name as a key
     */
    public function select_options($getdata, $postdata)
    {
        //console("form_value.select_options postdata", $postdata);

        $attribs    = $this->object_type_attributes($postdata['object_type'], $postdata['type_id']);
        $attributes = (array) $postdata['attributes'];
        $result     = array();

        foreach ($attributes as $attr_name) {
            if (empty($attr_name)) {
                continue;
            }

            $method_name = 'select_options_' . strtolower($attr_name);

            if (!method_exists($this, $method_name)) {
                $result[$attr_name] = array();
                continue;
            }

            $result[$attr_name] = $this->{$method_name}($postdata, $attribs);
        }

        return $result;
    }

    /**
     * Validation of field values.
     *
     * @param array $getdata   GET parameters
     * @param array $postdata  POST parameters. Required parameters:
     *                         - type_id: Type identifier
     *                         - object_type: Object type (user, group, etc.)
     *
     * @return array Response with attribute name as a key
     */
    public function validate($getdata, $postdata)
    {
        console("Executing validate() for \$getdata, \$postdata", $getdata, $postdata);

        $attribs = $this->object_type_attributes($postdata['object_type'], $postdata['type_id']);
        $result  = array();

        foreach ((array)$postdata as $attr_name => $attr_value) {
            if (empty($attr_name) || $attr_name == 'type_id' || $attr_name == 'object_type') {
                continue;
            }

            $method_name = 'validate_' . strtolower($attr_name) . '_' . strtolower($postdata['object_type']);

            if (!method_exists($this, $method_name)) {
                //console("Method $method_name doesn't exist");

                $method_name = 'validate_' . strtolower($attr_name);

                if (!method_exists($this, $method_name)) {
                    $result[$attr_name] = 'OK';
                    continue;
                }
            }

            $result[$attr_name] = $this->{$method_name}($attr_value);
        }

        return $result;
    }

    private function generate_alias($postdata, $attribs = array())
    {
        return $this->generate_secondary_mail($postdata, $attribs);
    }

    private function generate_cn($postdata, $attribs = array())
    {
        if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['cn'])) {
            // Use Data Please
            foreach ($attribs['auto_form_fields']['cn']['data'] as $key) {
                if (!isset($postdata[$key])) {
                    throw new Exception("Key not set: " . $key, 12356);
                }
            }

            // TODO: Generate using policy from configuration
            $cn = trim($postdata['givenname'] . " " . $postdata['sn']);

            return $cn;
        }
    }

    private function generate_displayname($postdata, $attribs = array())
    {
        if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['displayname'])) {
            // Use Data Please
            foreach ($attribs['auto_form_fields']['displayname']['data'] as $key) {
                if (!isset($postdata[$key])) {
                    throw new Exception("Key not set: " . $key, 12356);
                }
            }

            // TODO: Generate using policy from configuration
            $displayname = $postdata['givenname'];
            if ($postdata['sn']) {
                $displayname = $postdata['sn'] . ", " . $displayname;
            }

            // TODO: Figure out what may be sent as an additional comment;
            //
            // Examples:
            //
            //  - van Meeuwen, Jeroen (Kolab Systems)
            //  - Doe, John (Contractor)
            //

            return $displayname;
        }
    }

    private function generate_gidnumber($postdata, $attribs = array())
    {
        if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['gidnumber'])) {
            $auth = Auth::get_instance($_SESSION['user']->get_domain());
            $conf = Conf::get_instance();

            // TODO: Take a policy to use a known group ID, a known group (by name?)
            // and/or create user private groups.

            $search = Array(
                    'params' => Array(
                            'objectclass' => Array(
                                    'type' => 'exact',
                                    'value' => 'posixgroup',
                                ),
                        ),
                );

            $groups = $auth->list_groups(NULL, Array('gidnumber'), $search);

            $highest_gidnumber = $conf->get('gidnumber_lower_barrier');
            if (!$highest_gidnumber) {
                $highest_gidnumber = 999;
            }

            foreach ($groups as $dn => $attributes) {
                if (!array_key_exists('gidnumber', $attributes)) {
                    continue;
                }

                if ($attributes['gidnumber'] > $highest_gidnumber) {
                    $highest_gidnumber = $attributes['gidnumber'];
                }
            }

            $gidnumber = ($highest_gidnumber + 1);
            $postdata['gidnumber'] = $gidnumber;
            if (empty($postdata['uidnumber'])) {
                $uidnumber = $this->generate_uidnumber($postdata, $attribs);
                $gidnumber = $this->_highest_of_two($uidnumber, $gidnumber);
            }

            return $gidnumber;
        }
    }

    private function generate_homedirectory($postdata, $attribs = array())
    {
        if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['homedirectory'])) {
            // Use Data Please
            foreach ($attribs['auto_form_fields']['homedirectory']['data'] as $key) {
                if (!isset($postdata[$key])) {
                    throw new Exception("Key not set: " . $key, 12356);
                }
            }

            // TODO: Home directory attribute to use
            $uid = $this->generate_uid($postdata, $attribs);

            // TODO: Home directory base path from configuration?

            return '/home/' . $uid;
        }
    }

    private function generate_mail($postdata, $attribs = array())
    {
        return $this->generate_primary_mail($postdata, $attribs);
    }

    private function generate_mail_group($postdata, $attribs = array())
    {
        return $this->generate_primary_mail_group($postdata, $attribs);
    }

    private function generate_mailalternateaddress($postdata, $attribs = array())
    {
        return $this->generate_secondary_mail($postdata, $attribs);
    }

    private function generate_mailhost($postdata, $attribs = array())
    {
        if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['uidnumber'])) {
            // This value is determined by the Kolab Daemon
            return '';
        }
    }

    private function generate_password($postdata, $attribs = array())
    {
        // TODO: Password complexity policy.
        exec("head -c 200 /dev/urandom | tr -dc _A-Z-a-z-0-9 | head -c15", $userpassword_plain);
        return $userpassword_plain[0];
    }

    private function generate_userpassword($postdata, $attribs = array())
    {
        return $this->generate_password($postdata, $attribs);
    }

    private function generate_primary_mail($postdata, $attribs = array())
    {
        if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['mail'])) {
            // Use Data Please
            foreach ($attribs['auto_form_fields']['mail']['data'] as $key) {
                if (!isset($postdata[$key])) {
                    throw new Exception("Key not set: " . $key, 12356);
                }
            }

            if (array_key_exists('uid', $attribs['auto_form_fields'])) {
                if (!array_key_exists('uid', $postdata)) {
                    $postdata['uid'] = $this->generate_uid($postdata, $attribs);
                }
            }

            $primary_mail = kolab_recipient_policy::primary_mail($postdata);

            return $primary_mail;
        }
    }

    private function generate_primary_mail_group($postdata, $attribs = array())
    {
        if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['mail'])) {
            // Use Data Please
            foreach ($attribs['auto_form_fields']['mail']['data'] as $key) {
                if (!isset($postdata[$key])) {
                    throw new Exception("Key not set: " . $key, 12356);
                }
            }

            $primary_mail = kolab_recipient_policy::primary_mail_group($postdata);

            return $primary_mail;
        }
    }

    private function generate_secondary_mail($postdata, $attribs = array())
    {
        $secondary_mail_addresses = Array();

        if (isset($attribs['auto_form_fields'])) {
            if (isset($attribs['auto_form_fields']['alias'])) {
                $secondary_mail_key = 'alias';
            } elseif (isset($attribs['auto_form_fields']['mailalternateaddress'])) {
                $secondary_mail_key = 'mailalternateaddress';
            } else {
                throw new Exception("No valid input for secondary mail address(es)", 478);
            }

            foreach ($attribs['auto_form_fields'][$secondary_mail_key]['data'] as $key) {
                if (!isset($postdata[$key])) {
                    throw new Exception("Key not set: " . $key, 456789);
                }
            }

            if (array_key_exists('uid', $attribs['auto_form_fields'])) {
                if (!array_key_exists('uid', $postdata)) {
                    $postdata['uid'] = $this->generate_uid($postdata, $attribs);
                }
            }

            if (array_key_exists('mail', $attribs['auto_form_fields'])) {
                if (!array_key_exists('mail', $postdata)) {
                    $postdata['mail'] = $this->generate_primary_mail($postdata, $attribs);
                }
            }

            $secondary_mail_addresses = kolab_recipient_policy::secondary_mail($postdata);

            // TODO: Check for uniqueness. Not sure what to do if not unique.

            return $secondary_mail_addresses;
        }
    }

    private function generate_uid($postdata, $attribs = array())
    {
        if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['uid'])) {
            // Use Data Please
            foreach ($attribs['auto_form_fields']['uid']['data'] as $key) {
                if (!isset($postdata[$key])) {
                    throw new Exception("Key not set: " . $key, 12356);
                }
            }

            // TODO: Use preferredlanguage
            if (isset($postdata['preferredlanguage'])) {
                //console("Using locale for " . $postdata['preferredlanguage']);
                setlocale(LC_ALL, $postdata['preferredlanguage']);
            }
/*            else {
                console("No locale specified...!");
            }
*/

            $uid = iconv('UTF-8', 'ASCII//TRANSLIT', $postdata['sn']);
            $uid = strtolower($uid);
            $uid = preg_replace('/[^a-z-_]/i', '', $uid);

            $orig_uid = $uid;

            $auth = Auth::get_instance($_SESSION['user']->get_domain());
            $conf = Conf::get_instance();
            
            $unique_attr = $conf->get('unique_attribute');
            if (!$unique_attr) {
                $unique_attr = 'nsuniqueid';
            }

            $x = 2;
            while (($user_found = $auth->user_find_by_attribute(array('uid' => $uid)))) {
                if (!empty($postdata['id'])) {
                    $user_found_dn = key($user_found);
                    $user_found_unique_attr = $auth->get_attribute($user_found_dn, $unique_attr);
                    //console("user with uid $uid found", $user_found_unique_attr);
                    if ($user_found_unique_attr == $postdata['id']) {
                        //console("that's us.");
                        break;
                    }
                }

                $uid = $orig_uid . $x;
                $x++;
            }

            return $uid;
        }
    }

    private function generate_uidnumber($postdata, $attribs = array())
    {
        if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['uidnumber'])) {
            $auth = Auth::get_instance($_SESSION['user']->get_domain());
            $conf = Conf::get_instance();

            $search = Array(
                    'params' => Array(
                            'objectclass' => Array(
                                    'type' => 'exact',
                                    'value' => 'posixaccount',
                                ),
                        ),
                );

            $users = $auth->list_users(NULL, Array('uidnumber'), $search);

            $highest_uidnumber = $conf->get('uidnumber_lower_barrier');
            if (!$highest_uidnumber) {
                $highest_uidnumber = 999;
            }

            foreach ($users as $dn => $attributes) {
                if (!array_key_exists('uidnumber', $attributes)) {
                    continue;
                }

                if ($attributes['uidnumber'] > $highest_uidnumber) {
                    $highest_uidnumber = $attributes['uidnumber'];
                }
            }

            $uidnumber = ($highest_uidnumber + 1);
            $postdata['uidnumber'] = $uidnumber;
            if (empty($postdata['gidnumber'])) {
                $gidnumber = $this->generate_gidnumber($postdata, $attribs);
                $uidnumber = $this->_highest_of_two($uidnumber, $gidnumber);
            }

            return $uidnumber;
        }
    }

    private function list_options_kolabdelegate($postdata, $attribs = array())
    {
        // return specified records only, by exact DN attributes
        if (!empty($postdata['list'])) {
            $data['search'] = array(
                'entrydn' => array(
                    'value' => $postdata['list'],
                    'type'  => 'exact',
                ),
            );
        }
        // return records with specified string
        else {
            $keyword = array('value' => $postdata['search']);
            $data['page_size'] = 15;
            $data['search']    = array(
                'displayname' => $keyword,
                'cn'          => $keyword,
                'mail'        => $keyword,
            );
        }

        $data['attributes'] = array('displayname', 'mail');

        $service = $this->controller->get_service('users');
        $result  = $service->users_list(null, $data);
        $list    = $result['list'];

        // convert to key=>value array
        foreach ($list as $idx => $value) {
            $list[$idx] = $value['displayname'];
            if (!empty($value['mail'])) {
                $list[$idx] .= ' <' . $value['mail'] . '>';
            }
        }

        return $list;
    }

    private function list_options_member($postdata, $attribs = array())
    {
        return $this->_list_options_members($postdata, $attribs);
    }

    private function list_options_nsrole($postdata, $attribs = array())
    {
        //console("Listing options for attribute 'nsrole', while the expected attribute to use is 'nsroledn'");
        return $this->list_options_nsroledn($postdata, $attribs);
    }

    private function list_options_nsroledn($postdata, $attribs = Array())
    {
        // return specified records only, by exact DN attributes
        if (!empty($postdata['list'])) {
            $data['search'] = array(
                'entrydn' => array(
                    'value' => $postdata['list'],
                    'type'  => 'exact',
                ),
            );
        }
        // return records with specified string
        else {
            $keyword = array('value' => $postdata['search']);
            $data['page_size']  = 15;
            $data['search']     = array(
                'displayname' => $keyword,
                'cn'          => $keyword,
                'mail'        => $keyword,
            );
        }

        $data['attributes'] = array('cn');

        $service = $this->controller->get_service('roles');
        $result  = $service->roles_list(null, $data);
        $list    = $result['list'];

        // convert to key=>value array
        foreach ($list as $idx => $value) {
            $list[$idx] = $value['cn'];
        }

        return $list;
    }

    private function list_options_uniquemember($postdata, $attribs = array())
    {
        return $this->_list_options_members($postdata, $attribs);
    }

    private function select_options_c($postdata, $attribs = array())
    {
        return $this->_select_options_from_db('c');
    }

    private function select_options_ou($postdata, $attribs = array())
    {
        $auth = Auth::get_instance();
        $conf = Conf::get_instance();

        $unique_attr = $conf->get('unique_attribute');
        if (!$unique_attr) {
            $unique_attr = 'nsuniqueid';
        }

        $base_dn = $conf->get('user_base_dn');
        if (!$base_dn) {
            $base_dn = $conf->get('base_dn');
        }

        if (!empty($postdata['id'])) {
            $subject = $auth->search($base_dn, '(' . $unique_attr . '=' . $postdata['id'] . ')');
            $subject_dn = $subject[0];
            $subject_dn_components = ldap_explode_dn($subject_dn, 0);
            unset($subject_dn_components['count']);
            array_shift($subject_dn_components);
            $default = strtolower(implode(',', $subject_dn_components));
        } else {
            $default = $base_dn;
        }

        $ous = $auth->search($base_dn, '(objectclass=organizationalunit)');

        $_ous = array();

        foreach ($ous as $ou) {
            $_ous[] = strtolower($ou);
        }

        sort($_ous);

        $_ous['default'] = strtolower($default);

        return $_ous;
    }

    private function select_options_preferredlanguage($postdata, $attribs = array())
    {
        $options = $this->_select_options_from_db('preferredlanguage');

        $conf = Conf::get_instance();
        $default = $conf->get('default_locale');
        if (!$default) {
            $default = 'en_US';
        }

        if (!empty($postdata['preferredlanguage'])) {
            $default = $postdata['preferredlanguage'];
        }

        $options['default'] = $default;

        return $options;
    }

    private function validate_alias($value)
    {
        $auth = Auth::get_instance();
        $conf = Conf::get_instance();
        if (!is_array($value)) {
            $value = (array)($value);
        }

        foreach ($value as $mail_address) {
            if (!$this->_validate_email_address($mail_address)) {
                throw new Exception("Invalid email address '$mail_address'", 692);
            }

            // Only validate the 'alias' attribute is in any of my domain name
            // spaces if indeed it is listed as a mail attribute.
            if (in_array('alias', $conf->get_list('mail_attributes'))) {
                if (!$this->_validate_email_address_in_any_of_my_domains($mail_address)) {
                    throw new Exception("Email address '$mail_address' not in local domain", 693);
                }
            }
        }

    }

    private function validate_mail($value)
    {
        $auth = Auth::get_instance();
        $conf = Conf::get_instance();
        if (!is_array($value)) {
            $value = (array)($value);
        }

        foreach ($value as $mail_address) {
            if (!$this->_validate_email_address($mail_address)) {
                throw new Exception("Invalid email address '$mail_address'", 692);
            }

            // Only validate the 'mail' attribute is in any of my domain name
            // spaces if indeed it is listed as a mail attribute.
            if (in_array('mail', $conf->get_list('mail_attributes'))) {
                if (!$this->_validate_email_address_in_any_of_my_domains($mail_address)) {
                    throw new Exception("Email address '$mail_address' not in local domain", 693);
                }
            }
        }
    }

    private function validate_mailalternateaddress($value)
    {
        $auth = Auth::get_instance();
        $conf = Conf::get_instance();
        if (!is_array($value)) {
            $value = (array)($value);
        }

        foreach ($value as $mail_address) {
            if (!$this->_validate_email_address($mail_address)) {
                throw new Exception("Invalid email address '$mail_address'", 692);
            }

            // Only validate the 'mailalternateaddress' attribute is in any of my domain name
            // spaces if indeed it is listed as a mail attribute.
            if (in_array('mailalternateaddress', $conf->get_list('mail_attributes'))) {
                if (!$this->_validate_email_address_in_any_of_my_domains($mail_address)) {
                    throw new Exception("Email address '$mail_address' not in local domain", 693);
                }
            }
        }
    }

    private function _highest_of_two($one, $two) {
        if ($one > $two) {
            return $one;
        } elseif ($one == $two) {
            return $one;
        } else {
            return $two;
        }
    }

    private function _list_options_members($postdata, $attribs = array())
    {
        // return specified records only, by exact DN attributes
        if (!empty($postdata['list'])) {
            $data['search'] = array(
                'entrydn' => array(
                    'value' => $postdata['list'],
                    'type'  => 'exact',
                ),
            );
        }
        // return records with specified string
        else {
            $keyword = array('value' => $postdata['search']);
            $data['page_size'] = 15;
            $data['search']    = array(
                'displayname' => $keyword,
                'cn'          => $keyword,
                'mail'        => $keyword,
            );
        }

        $data['attributes'] = array('displayname', 'cn', 'mail');

        $service = $this->controller->get_service('users');
        $result  = $service->users_list(null, $data);
        $list    = $result['list'];

        $data['attributes'] = array('cn', 'mail');

        $service = $this->controller->get_service('groups');
        $result  = $service->groups_list(null, $data);
        $list    = array_merge($list, $result['list']);

        // convert to key=>value array
        foreach ($list as $idx => $value) {
            if (!empty($value['displayname'])) {
                $list[$idx] = $value['displayname'];
            } elseif (!empty($value['cn'])) {
                $list[$idx] = $value['cn'];
            } else {
                console("No display name or cn for $idx");
            }

            if (!empty($value['mail'])) {
                $list[$idx] .= ' <' . $value['mail'] . '>';
            }
        }

        return $list;
    }

    private function _list_options_resources($postdata, $attribs = array())
    {
        // return specified records only, by exact DN attributes
        if (!empty($postdata['list'])) {
            $data['search'] = array(
                'entrydn' => array(
                    'value' => $postdata['list'],
                    'type'  => 'exact',
                ),
            );
        }
        // return records with specified string
        else {
            $keyword = array('value' => $postdata['search']);
            $data['page_size'] = 15;
            $data['search']    = array(
                'cn'          => $keyword,
            );
        }

        $data['attributes'] = array('cn');

        //console("api/form_value._list_options_resources() searching with data", $data);

        $service = $this->controller->get_service('resources');
        $result  = $service->resources_list(null, $data);
        $list    = $result['list'];

        // convert to key=>value array
        foreach ($list as $idx => $value) {
            if (!empty($value['displayname'])) {
                $list[$idx] = $value['displayname'];
            } elseif (!empty($value['cn'])) {
                $list[$idx] = $value['cn'];
            } else {
                //console("No display name or cn for $idx");
            }

        }

        return $list;
    }

    private function _select_options_from_db($attribute)
    {

        if (empty($attribute)) {
            return false;
        }

        $db = SQL::get_instance();
        $result = $db->fetch_assoc($db->query("SELECT option_values FROM options WHERE attribute = ?", $attribute));

        $result = json_decode($result['option_values']);

        if (empty($result)) {
            return false;
        } else {
            return $result;
        }
    }

    private function _validate_email_address($mail_address) {
        $valid = true;

        $at_index = strrpos($mail_address, "@");
        if (is_bool($at_index) && !$at_index) {
            $valid = false;

        } else {
            $domain = substr($mail_address, $at_index+1);
            $local = substr($mail_address, 0, $at_index);

            if (strlen($local) < 1 || strlen($local) > 64) {
                // local part length exceeded
                $valid = false;

            } else if (strlen($domain) < 1 || strlen($domain) > 255) {
                // domain part length exceeded
                $valid = false;

            } else if ($local[0] == '.' || $local[strlen($local)-1] == '.') {
                // local part starts or ends with '.'
                $valid = false;

            } else if (preg_match('/\\.\\./', $local)) {
                // local part has two consecutive dots
                $valid = false;

            } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
                // character not valid in domain part
                $valid = false;

            } else if (preg_match('/\\.\\./', $domain)) {
                // domain part has two consecutive dots
                $valid = false;

            } else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) {
                // character not valid in local part unless
                // local part is quoted
                if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) {
                    $valid = false;
                }
            }

            if ($valid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) {
                // domain not found in DNS
                $valid = false;
            }
        }

        return $valid;
    }

    private function _validate_email_address_in_any_of_my_domains($mail_address) {
        $valid = false;

        $auth = Auth::get_instance();
        $conf = Conf::get_instance();

        $my_primary_domain = $_SESSION['user']->get_domain();
        $all_domains = $auth->list_domains();

        $valid_domains = array();

        $dna = $conf->get('domain_name_attribute');

        $at_index = strrpos($mail_address, "@");
        if (is_bool($at_index) && !$at_index) {
            throw new Exception("Invalid email address: No domain name space", 235);
        } else {
            $email_domain = substr($mail_address, $at_index+1);
        }

        foreach ($all_domains as $domain_id => $domain_attrs) {
            if (!is_array($domain_attrs[$dna])) {
                $domain_attrs[$dna] = (array)($domain_attrs[$dna]);
            }

            if (in_array($my_primary_domain, $domain_attrs[$dna])) {
                $valid_domains = array_merge($valid_domains, $domain_attrs[$dna]);
            }
        }

        if (in_array($email_domain, $valid_domains)) {
            $valid = true;
        }

        return $valid;
    }

}