summaryrefslogtreecommitdiff
path: root/lib/kolab_api_service.php
blob: f19486a27f88b692329c47cede4dbeebc8397667 (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
<?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>                     |
 +--------------------------------------------------------------------------+
*/

/**
 * Interface class for Kolab Admin Services
 */
abstract class kolab_api_service
{
    protected $cache = array();
    protected $conf;
    protected $controller;
    protected $db;
    protected $supported_types_db = array('ou', 'group', 'resource', 'role', 'sharedfolder', 'user');
    protected $supported_types    = array('domain', 'ou', 'group', 'resource', 'role', 'sharedfolder', 'user');

    /**
     * Class constructor.
     *
     * @param kolab_api_controller Controller
     */
    public function __construct($ctrl)
    {
        $this->controller = $ctrl;
        $this->conf       = Conf::get_instance();
        $this->db         = SQL::get_instance();
    }

    /**
     * Advertise this service's capabilities
     */
    abstract public function capabilities($domain);

    /**
     * Returns attributes of specified user type.
     *
     * @param string $object_name  Name of the object (user, group, etc.)
     * @param int    $type_id      User type identifier
     * @param string $key_name     Reference to a variable which will be set to type key
     *
     * @return array User type attributes
     */
    protected function object_type_attributes($object_name, $type_id, &$key_name = null)
    {
        if (!$object_name || !in_array($object_name, $this->supported_types)) {
            return array();
        }

        $object_types = $this->object_types($object_name);

        if (empty($type_id)) {
            if (count($object_types) == 1) {
                $type_id = key($object_types);
            }
            else {
                throw new Exception($this->controller->translate('api.notypeid'), 34);
            }
        }
        else if ($type_id && empty($object_types[$type_id])) {
            throw new Exception($this->controller->translate('api.invalidtypeid'), 35);
        }

        $key_name = $object_types[$type_id]['key'];

        return $object_types[$type_id]['attributes'];
    }

    /**
     * Detects object type ID for specified objectClass attribute value
     *
     * @param string $object_name   Name of the object (user, group, etc.)
     * @param array  $attributes    Array of attributes and values
     *
     * @return int Object type identifier
     */
    protected function object_type_id($object_name, $attributes)
    {
        if ($object_name == 'domain') return 1;

        $object_class = $attributes['objectclass'];

        if (empty($object_class)) {
            return null;
        }

        $object_types = $this->object_types($object_name);

        if (count($object_types) == 1) {
            return key($object_types);
        }

        $object_class = array_map('strtolower', $object_class);
        $object_keys  = array_diff(array_keys($attributes), array(self::unique_attribute()));
        $keys_count   = count($object_keys);
        $class_count  = count($object_class);
        $type_score   = null;
        $type_id      = null;

        Log::trace("kolab_api_service::object_type_id objectClasses: " . implode(", ", $object_class));

        foreach ($object_types as $idx => $elem) {
            $ref_class = $elem['attributes']['fields']['objectclass'];

            if (empty($ref_class)) {
                continue;
            }

            Log::trace("Reference objectclasses for " . $elem['key'] . ": " . implode(", ", $ref_class));

            $elem_keys_score   = 0;
            $elem_values_score = 0;
            $delta             = 0;

            // Eliminate the duplicates between the $data_ocs and $ref_ocs
            $_object_class = array_diff($object_class, $ref_class);
            $_ref_class    = array_diff($ref_class, $object_class);

            // Object classes score
            $differences   = count($_object_class) + count($_ref_class);
            $commonalities = $class_count - $differences;
            $elem_score    = $differences > 0 ? round($commonalities / $differences, 2) : $commonalities;

            // Attributes score
            if ($keys_count) {
                $ref_keys = array_unique(array_merge(
                    array_keys((array) $elem['attributes']['auto_form_fields']),
                    array_keys((array) $elem['attributes']['form_fields']),
                    array_keys($elem['attributes']['fields'])
                ));

                $elem_keys_score = $keys_count - count(array_diff($object_keys, $ref_keys));
            }

            // Static attributes score
            $elem_values_score = 0;
            foreach ((array) $elem['attributes']['fields'] as $attr => $value) {
                $v = $attributes[$attr];
                if (is_array($value)) {
                    $value = implode('', $value);
                }
                if (is_array($v)) {
                    $v = implode('', $v);
                }
                $elem_values_score += intval($v == $value);
            }

            // Position in tree score
            if (!empty($elem['attributes']['fields']['ou'])) {
                if (!empty($attributes['ou'])) {
                    if (strtolower($elem['attributes']['fields']['ou']) == strtolower($attributes['ou'])) {
                        Log::trace("object_type " . $elem['key'] . " fields ou setting matches entry, bumping scores.");
                        $elem_score += 2;
                        $elem_keys_score += 10;
                    }
                }
            }

            // On the likely chance that the object is a resource (types of which likely have the same
            // set of objectclass attribute values), consider the other attributes. (#853)
            if ($object_name == 'resource') {
                //console("From database", $elem);
                //console("Element key is " . $elem['key'] . " and \$attributes['mail'] is " . $attributes['mail']);
                if (strpos($attributes['mail'], 'resource-' . $elem['key'] . '-') === 0) {
                    $elem_score += 10;
                }
            }

            // degrade class score if object contains more attributes
            // than defined in object type
            if ($keys_count && $elem_keys_score < $keys_count) {
                $delta -= $class_count - round(($keys_count / $elem_keys_score) * $class_count, 2);
                if ($delta > 0) {
                    $elem_score -= $delta;
                }
            }

            $elem_score .= ':' . $elem_keys_score . ':' . $elem_values_score;

            // fix decimal separator for score_compare() and consistent log (#4799)
            $elem_score = str_replace(',', '.', $elem_score);
            $delta      = str_replace(',', '.', $delta);

            Log::trace("Score for $object_name type " . $elem['name'] . ": $elem_score ($commonalities/$differences/$delta)");

            // Compare last and current element (object type) score
            if ($this->score_compare($elem_score, $type_score)) {
                $type_id    = $idx;
                $type_score = $elem_score;
            }
        }

        return $type_id;
    }

    /**
     * Returns object types definitions.
     *
     * @param string $object_name  Name of the object (user, group, etc.)
     *
     * @return array Object types.
     */
    protected function object_types($object_name)
    {
        if (!$object_name || !in_array($object_name, $this->supported_types)) {
            return array();
        }

        $conf = Conf::get_instance();

        $devel_mode = $conf->get('kolab_wap', 'devel_mode');

        if ($devel_mode == null) {
            if (!empty($this->cache['object_types']) && !empty($this->cache['object_types'][$object_name])) {
                return $this->cache['object_types'][$object_name];
            }
        }

        // get list of object types
        if ($object_name == 'domain') {
            $object_types = array(
                '1' => array(
                    'key'        => 'default',
                    'attributes' => kolab_api_service_domain_types::$DEFAULT_TYPE_ATTRS,
                ),
            );
            $object_types['1']['attributes']['form_fields']['aci'] = array(
                'type'     => 'list',
                'optional' => true,
            );
        }
        else {
            $sql_result   = $this->db->query("SELECT * FROM `{$object_name}_types` ORDER BY `name`");
            $object_types = array();

            while ($row = $this->db->fetch_assoc($sql_result)) {
                $object_types[$row['id']] = array();

                foreach ($row as $key => $value) {
                    if ($key != "id") {
                        if ($key == "attributes") {
                            $object_types[$row['id']][$key] = json_decode($value, true);
                        }
                        else {
                            $object_types[$row['id']][$key] = $value;
                        }
                    }
                }
            }
        }

        if ($devel_mode == null) {
            return $this->cache['object_types'][$object_name] = $object_types;
        }
        else {
            return $object_types;
        }

    }

    /**
     * Parses input (for add/edit) attributes
     *
     * @param string $object_name  Name of the object (user, group, etc.)
     * @param array  $attrs        Entry attributes
     *
     * @return array Entry attributes
     */
    protected function parse_input_attributes($object_name, $attribs)
    {
        $type_attrs = $this->object_type_attributes($object_name, $attribs['type_id']);

        Log::trace("kolab_api_service::parse_input_attributes for $object_name: " . var_export($type_attrs, TRUE));
        Log::trace("called with \$attribs: " . var_export($attribs, TRUE));

        $form_service = $this->controller->get_service('form_value');

        // With the result, start validating the input
        $attribs['object_type'] = $object_name;
        $validate_result = $form_service->validate(null, $attribs);

        $special_attr_validate = Array();

        foreach ($validate_result as $attr_name => $value) {
            if ($value !== false && $value !== '' && $value !== null && $value !== "OK") {
                $special_attr_validate[$attr_name] = $value;
            }
        }

        Log::trace("kolab_api_service::parse_input_attributes() \$special_attr_validate: " . var_export($special_attr_validate, TRUE));

        $result = array();

        if (isset($type_attrs['form_fields'])) {
            foreach ($type_attrs['form_fields'] as $key => $value) {
                Log::trace("Running parse input attributes for key $key");

                $type = $value['type'] ?: ($type_attrs['auto_form_fields'][$key] ? $type_attrs['auto_form_fields'][$key]['type'] : '');

                if (($type == 'text' || empty($type)) && is_array($attribs[$key])) {
                    $attribs[$key] = array_shift($attribs[$key]);
                }

                if (empty($attribs[$key]) && empty($value['optional'])) {
                    Log::error("\$attribs['" . $key . "'] is empty, and the field is not optional");
                    throw new Exception("Missing input value for $key", 345);
                }
                else {
                    Log::trace("Either \$attribs['" . $key . "'] is not empty or the field is optional");
                    $result[$key] = $attribs[$key];
                }
            }
        }

        if (isset($type_attrs['auto_form_fields'])) {
            foreach ($type_attrs['auto_form_fields'] as $key => $value) {
                if (empty($attribs[$key])) {
                    if (empty($value['optional'])) {
                        $attribs['attributes'] = array($key);
                        $res                   = $form_service->generate(null, $attribs);
                        $attribs[$key]         = $res[$key];
                        $result[$key]          = $attribs[$key];
                    }
                } else {
                    $result[$key] = $attribs[$key];
                }
            }
        }

        if (isset($type_attrs['fields'])) {
            foreach ($type_attrs['fields'] as $key => $value) {
                if (!is_array($value)) {
                    $value2 = $this->conf->expand($value);
                    if ($value !== $value2) {
                        Log::trace("Made value " . var_export($value, TRUE) . " in to: " . var_export($value2, TRUE));
                        $value = $value2;
                    }
                }

                if (empty($attribs[$key])) {
                    $result[$key] = $type_attrs['fields'][$key] = $value;
                } else {
                    $result[$key] = $attribs[$key] = $value;
                }
            }
        }

        // OU's parent attribute
        if ($object_name == 'ou' && !empty($attribs['base_dn'])) {
            // @TODO: validate?
            $result['base_dn'] = $attribs['base_dn'];
        }

        $result = array_merge($result, $special_attr_validate);

        Log::trace("parse_input_attributes result (merge of \$result and \$special_attr_validate)", $result);

        return $result;
    }

    protected function parse_list_attributes($post)
    {
        $attributes = Array();
        // Attributes to return
        if (!empty($post['attributes']) && is_array($post['attributes'])) {
            // get only supported attributes
            $attributes = array_intersect($this->list_attribs, $post['attributes']);
            // need to fix array keys
            $attributes = array_values($attributes);

            // unique attribute is always allowed
            if (($key = array_search('id', $post['attributes'])) !== false) {
                $attributes[] = self::unique_attribute();
            }
        }

        if (empty($attributes)) {
            $attributes = (array)$this->list_attribs[0];
        }

        return $attributes;
    }

    protected function parse_list_result($result)
    {
        if (!empty($result) && !empty($result['count'])) {
            $unique_attr = self::unique_attribute();

            // replace back unique attribute name with 'id'
            foreach ($result['list'] as $idx => $record) {
                // if not set, we assume unique attribute wasn't requested
                if (!isset($record[$unique_attr])) {
                    break;
                }
                $result['list'][$idx]['id'] = $record[$unique_attr];
                unset($result['list'][$idx][$unique_attr]);
            }
        }

        return $result;
    }

    protected function parse_list_params($post)
    {
        $params = Array();
        if (!empty($post['sort_by'])) {
            if (is_array($post['sort_by'])) {
                $params['sort_by'] = Array();
                foreach ($post['sort_by'] as $attrib) {
                    if (in_array($attrib, $this->list_attribs)) {
                        $params['sort_by'][] = $attrib;
                    }
                }
            } else {
                // check if sort attribute is supported
                if (in_array($post['sort_by'], $this->list_attribs)) {
                    $params['sort_by'] = $post['sort_by'];
                }
            }
        }

        if (!empty($post['sort_order'])) {
            $params['sort_order'] = $post['sort_order'] == 'DESC' ? 'DESC' : 'ASC';
        }

        if (!empty($post['page'])) {
            $params['page'] = $post['page'];
        }

        if (!empty($post['page_size'])) {
            $params['page_size'] = $post['page_size'];
        }

        return $params;
    }

    protected function parse_list_search($post)
    {
        $search = Array();
        // Search parameters
        if (!empty($post['search']) && is_array($post['search'])) {
            if (array_key_exists('params', $post['search'])) {
                $search = $post['search'];
            } else {
                $search['params'] = $post['search'];
            }
            if (!empty($post['search_operator'])) {
                $search['operator'] = $post['search_operator'];
            }
        }
        return $search;
    }

    /**
     * Parses result attributes
     *
     * @param string $object_name  Name of the object (user, group, etc.)
     * @param array  $attrs        Entry attributes
     *
     * @return array Entry attributes
     */
    public function parse_result_attributes($object_name, $attrs = array())
    {
        if (empty($attrs) || !is_array($attrs)) {
            return $attrs;
        }

        $dn          = key($attrs);
        $attrs       = $attrs[$dn];
        $extra_attrs = array();
        $type_id     = $this->object_type_id($object_name, $attrs);
        $unique_attr = self::unique_attribute();

        // Search for attributes associated with the type_id that are not part
        // of the result returned earlier. Example: nsrole / nsroledn / aci, etc.
        if ($type_id) {
            $uta = $this->object_type_attributes($object_name, $type_id);

            $attributes = array_merge(
                array_keys((array) $uta['auto_form_fields']),
                array_keys((array) $uta['form_fields']),
                array_keys((array) $uta['fields'])
            );
            $attributes = array_filter($attributes);
            $attributes = array_unique($attributes);

            $object_attributes = array_keys($attrs);

            // extra attributes
            $extra_attrs = array_diff($attributes, $object_attributes);

            // remove attributes not listed in object type definition
            // @TODO: make this optional?
            $attributes = array_flip(array_merge($attributes, array($unique_attr)));
            $attrs      = array_intersect_key($attrs, $attributes);
        }
/*
        $auth = Auth::get_instance();

        // Insert the persistent, unique attribute
        if (!array_key_exists($unique_attr, $attrs)) {
            $extra_attrs[] = $unique_attr;
        }

        // Get extra attributes
        if (!empty($extra_attrs)) {
            $extra_attrs = $auth->get_entry_attributes($dn, array_values($extra_attrs));

            if (!empty($extra_attrs)) {
                $attrs = array_merge($attrs, $extra_attrs);
            }
        }
*/
        // Replace unique attribute with 'id' key
        $attrs['id'] = $attrs[$unique_attr];
        unset($attrs[$unique_attr]);

        // add object type id to the result
        $attrs['type_id'] = $type_id;

        // always return entrydn
        $attrs['entrydn'] = $dn;

        // add organizational unit to the result
        if (empty($attrs['ou']) && isset($attributes['ou'])) {
            $dn = kolab_utils::explode_dn($dn);
            // pop the rdn
            unset($dn[0]);
            $attrs['ou'] = implode(',', $dn);
        }

        return $attrs;
    }

    /**
     * Returns all supported attributes of specified object type
     *
     * @param string $object_name Name of the object (user, group, etc.)
     *
     * @return array Entry attributes
     */
    public function object_attributes($object_name)
    {
        $unique_attr  = self::unique_attribute();
        $object_types = $this->object_types($object_name);
        $attributes   = array();

        // because we don't know the object type identifier before
        // we get it from LDAP we need to get try attributes of all types
        foreach ($object_types as $type) {
            $attributes = array_merge(
                $attributes,
                array_keys((array) $type['attributes']['auto_form_fields']),
                array_keys((array) $type['attributes']['form_fields']),
                array_keys((array) $type['attributes']['fields'])
            );
        }

        // use array_values, because ldap_read() does not like an array
        // with removed elements (holes in the index)
        $attributes = array_values(array_unique($attributes));

        if (empty($attributes)) {
            $attributes = array('*');
        }

        // Insert the persistent, unique attribute
        if (!array_key_exists($unique_attr, $attributes)) {
            $attributes[] = $unique_attr;
        }

        return $attributes;
    }

    /**
     * Compare two score values
     *
     * @param string $s1 Score
     * @param string $s2 Score
     *
     * @return bool True when $s1 is greater than $s2
     */
    protected function score_compare($s1, $s2)
    {
        if (empty($s2) && !empty($s1)) {
            return true;
        }

        $s1 = explode(':', $s1);
        $s2 = explode(':', $s2);

        foreach ($s1 as $key => $val) {
            if ($val > $s2[$key]) {
                return true;
            }
            if ($val < $s2[$key]) {
                return false;
            }
        }

        return false;
    }

    /**
     * Returns name of unique attribute
     *
     * @return string Unique attribute name
     */
    public static function unique_attribute()
    {
        $conf        = Conf::get_instance();
        $unique_attr = $conf->get('unique_attribute');

        if (!$unique_attr) {
            $unique_attr = 'nsuniqueid';
        }

        return $unique_attr;
    }

    /**
     * Returns unique attribute for specified entry DN
     *
     * @return string Unique attribute value
     */
    protected function unique_attribute_value($dn)
    {
        // this method can be called internally quite often
        // let's cache results in memory
        if (!empty($this->cache['unique_attributes'][$dn])) {
            return $this->cache['unique_attributes'][$dn];
        }

        $unique_attr = self::unique_attribute();
        $auth        = Auth::get_instance();
        $result      = $auth->get_entry_attribute($dn, $unique_attr);

        return $this->cache['unique_attributes'][$dn] = $result;
    }
}