File: Driver.php

package info (click to toggle)
turba2 2.0.2-1sarge1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 3,996 kB
  • ctags: 1,071
  • sloc: php: 4,725; xml: 617; sql: 136; makefile: 62; sh: 46; perl: 17
file content (872 lines) | stat: -rw-r--r-- 29,430 bytes parent folder | download
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
<?php

require_once 'Horde/History.php';

/**
 * The Turba_Driver:: class provides a common abstracted interface to the
 * various directory search drivers.  It includes functions for searching,
 * adding, removing, and modifying directory entries.
 *
 * $Horde: turba/lib/Driver.php,v 1.57.2.3 2005/02/08 20:45:13 chuck Exp $
 *
 * @author  Chuck Hagenbuch <chuck@horde.org>
 * @author  Jon Parise <jon@csh.rit.edu>
 * @since   Turba 0.0.1
 * @package Turba
 */
class Turba_Driver {

    /**
     * The internal name of this source.
     * @var string $name
     */
    var $name;

    /**
     * The symbolic title of this source.
     * @var string $title
     */
    var $title;

    /**
     * Hash describing the mapping between Turba attributes and
     * driver-specific fields.
     * @var array $map
     */
    var $map = array();

    /**
     * Hash with all tabs and their fields.
     * @var array $tabs
     */
    var $tabs = array();

    /**
     * List of all fields that can be accessed in the backend
     * (excludes composite attributes, etc.).
     * @var array $fields
     */
    var $fields = array();

    /**
     * Array of fields that must match exactly.
     * @var array $strict
     */
    var $strict = array();

    /**
     * Whether this source is publicly searchable.
     * @var boolean $public
     */
    var $public = false;

    /**
     * Whether this source is read-only (not editable).
     * @var boolean $readonly
     */
    var $readonly = true;

    /**
     * Any admins for this source.
     * @var array $admin
     */
    var $admin = array();

    /**
     * Hash holding the driver's additional parameters.
     *
     * @var array $_params
     */
    var $_params = array();

    /**
     * What can this backend do?
     *
     * @var array $_capabilities
     */
    var $_capabilities = array();

    /**
     * Attempts to return a reference to a concrete Turba_Driver
     * instance based on the $config array. It will only create a new
     * instance if no Turba_Driver instance with the same parameters
     * currently exists.
     *
     * This method must be invoked as:
     *   $driver = &Turba_Driver::singleton()
     *
     * @param string $name    String containing the internal name of this source.
     * @param array  $config  Array containing the configuration information for this source.
     *
     * @return object  The concrete Turba_Driver reference, or an error object on
     *                 error.
     */
    function &singleton($name, $config)
    {
        static $instances = array();

        if (!isset($instances[$name])) {
            $instances[$name] = &Turba_Driver::factory($name, $config);
        }

        return $instances[$name];
    }

    /**
     * Constructs a new Turba_Driver object.
     *
     * @param array $params  Hash containing additional configuration parameters.
     */
    function Turba_Driver($params)
    {
        $this->_params = $params;
    }

    /**
     * Returns the current driver's additional parameters.
     *
     * @return array  Hash containing the driver's additional parameters.
     */
    function getParams()
    {
        return $this->_params;
    }

    /**
     * Check if this backend has a certain capability.
     *
     * @param string $capability  The capability to check for.
     *
     * @return boolean  Supported or not.
     */
    function hasCapability($capability)
    {
        return !empty($this->_capabilities[$capability]);
    }

    /**
     * Translates the keys of the first hash from the generalized
     * Turba attributes to the driver-specific fields. The translation
     * is based on the contents of $this->map. This ignores composite
     * fields.
     *
     * @param array $hash  Hash using Turba keys.
     *
     * @return array  Translated version of $hash.
     */
    function toDriverKeys($hash)
    {
        $fields = array();
        foreach ($hash as $key => $val) {
            if (isset($this->map[$key]) && !is_array($this->map[$key])) {
                $fields[$this->map[$key]] = $val;
            }
        }
        return $fields;
    }

    /**
     * Takes a hash of Turba key => search value and return a
     * (possibly nested) array, using backend attribute names, that
     * can be turned into a search by the driver. The translation is
     * based on the contents of $this->map, and includes nested OR
     * searches for composite fields.
     *
     * @param array  $hash         Hash of criteria using Turba keys.
     * @param string $search_type  OR search or AND search?
     * @param array  $strict       Fields that must be matched exactly.
     *
     * @return array  An array of search criteria.
     */
    function makeSearch($criteria, $search_type, $strict)
    {
        $search = array();
        $strict_search = array();
        foreach ($criteria as $key => $val) {
            if (isset($this->map[$key])) {
                if (is_array($this->map[$key])) {
                    $subsearch = array();
                    foreach ($this->map[$key]['fields'] as $field) {
                        $field = $this->toDriver($field);
                        if (!empty($strict[$field])) {
                            $strict_search[] = array('field' => $field, 'op' => '=', 'test' => $val);
                        } else {
                            $subsearch[] = array('field' => $field, 'op' => 'LIKE', 'test' => $val);
                        }
                    }
                    if (count($subsearch)) {
                        $search[] = array('OR' => $subsearch);
                    }
                } else {
                    if (!empty($strict[$this->map[$key]])) {
                        $strict_search[] = array('field' => $this->map[$key], 'op' => '=', 'test' => $val);
                    } else {
                        $search[] = array('field' => $this->map[$key], 'op' => 'LIKE', 'test' => $val);
                    }
                }
            }
        }

        if (count($strict_search) && count($search)) {
            return array('AND' => array($strict_search, array($search_type => $search)));
        } elseif (count($strict_search)) {
            return array('AND' => $strict_search);
        } elseif (count($search)) {
            return array($search_type => $search);
        } else {
            return array();
        }
    }

    /**
     * Translates a single Turba attribute to the driver-specific
     * counterpart. The translation is based on the contents of
     * $this->map. This ignores composite fields.
     *
     * @param string $attribute  The Turba attribute to translate.
     *
     * @return string  The driver name for this attribute.
     */
    function toDriver($attribute)
    {
        return isset($this->map[$attribute]) && !is_array($this->map[$attribute]) ? $this->map[$attribute] : null;
    }

    /**
     * Translates an array of hashes from being keyed on
     * driver-specific fields to being keyed on the generalized Turba
     * attributes. The translation is based on the contents of
     * $this->map.
     *
     * @param array $objects  Array of hashes using driver-specific keys.
     *
     * @return array  Translated version of $objects.
     */
    function toTurbaKeys($objects)
    {
        $attributes = array();
        foreach ($objects as $entry) {
            $new_entry = array();

            foreach ($this->map as $key => $val) {
                if (!is_array($val)) {
                    $new_entry[$key] = null;
                    if (isset($entry[$val]) && strlen($entry[$val])) {
                        $new_entry[$key] = $entry[$val];
                    }
                }
            }

            $attributes[] = $new_entry;
        }
        return $attributes;
    }

    /**
     * Searches the source based on the provided criteria.
     *
     * TODO: Allow $criteria to contain the comparison operator (<, =, >,
     *       'like') and modify the drivers accordingly.
     *
     * @param $search_criteria   Hash containing the search criteria.
     * @param $sort_criteria     The requested sort order which is passed to
     *                           Turba_List::sort().
     * @param string $search_type  (optional) Do an AND or an OR search (defaults to AND).
     *
     * @return                   The sorted, filtered list of search results.
     */
    function &search($search_criteria, $sort_criteria = 'lastname',
                     $search_type = 'AND', $sort_direction = 0)
    {
        require_once TURBA_BASE . '/lib/List.php';
        require_once TURBA_BASE . '/lib/Object.php';

        /* If this is not a public source, enforce the requirement
         * that the source's owner must be equal to the current
         * user. */
        $strict_fields = array();
        if (!$this->public && !in_array(Auth::getAuth(), $this->admin)) {
            $search_criteria['__owner'] = Auth::getAuth();
            $strict_fields = array($this->toDriver('__owner') => true);
        }

        /* Add any fields that much match exactly for this source to
         * the $strict_fields array. */
        foreach ($this->strict as $strict_field) {
            $strict_fields[$strict_field] = true;
        }

        /* Translate the Turba attributes to a driver-specific search
         * array. */
        $fields = $this->makeSearch($search_criteria, $search_type, $strict_fields);

        /* Retrieve the search results from the driver. */
        $results = $this->_search($fields, array_values($this->fields));

        /* Translate the driver-specific fields in the result back to the more
         * generalized common Turba attributes using the map. */
        $results = $this->toTurbaKeys($results);
        if (is_a($results, 'PEAR_Error')) {
            return $results;
        }

        require_once TURBA_BASE . '/lib/Object.php';
        require_once TURBA_BASE . '/lib/Group.php';
        $list = &new Turba_List();
        foreach ($results as $attributes) {
            if (!empty($attributes['__type']) &&
                $attributes['__type'] == 'Group') {
                $list->insert(new Turba_Group($this, $attributes));
            } else {
                $list->insert(new Turba_Object($this, $attributes));
            }
        }
        $list->sort($sort_criteria, $sort_direction);

        /* Return the filtered (sorted) results. */
        return $list;
    }

    /**
     * Retrieve a set of objects from the source.
     *
     * @param array $objectIds  The unique ids of the objects to retrieve.
     *
     * @return array  The array of retrieved objects (Turba_AbstractObjects).
     */
    function &getObjects($objectIds)
    {
        require_once TURBA_BASE . '/lib/Object.php';
        $criteria = $this->map['__key'];

        $objects = $this->_read($criteria, $objectIds, array_values($this->fields));
        if (!is_array($objects)) {
            return PEAR::raiseError(_("Requested object not found."));
        }

        $results = array();
        $objects = $this->toTurbaKeys($objects);
        foreach ($objects as $object) {
            $done = false;
            if (!empty($object['__type'])) {
                $type = ucwords($object['__type']);
                $class = 'Turba_' . $type;
                if (!class_exists($class)) {
                    @require_once TURBA_BASE . '/lib/' . $type . '.php';
                }

                if (class_exists($class)) {
                    $results[] = &new $class($this, $object);
                    $done = true;
                }
            }
            if (!$done) {
                $results[] = &new Turba_Object($this, $object);
            }
        }

        return $results;
    }

    /**
     * Retrieve one object from the source.
     *
     * @param string $objectId  The unique id of the object to retrieve.
     *
     * @return object Turba_AbstractObject  The retrieved object.
     */
    function &getObject($objectId)
    {
        $result = &$this->getObjects(array($objectId));
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        } elseif (empty($result[0])) {
            return PEAR::raiseError('No results');
        } else {
            if (!isset($this->map['__owner'])) {
                $result[0]->attributes['__owner'] = Auth::getAuth();
            }
            return $result[0];
        }
    }

    /**
     * Adds a new entry to the contact source.
     *
     * @param array $attributes  The attributes of the new object to add.
     *
     * @return mixed             The new __key value on success, or a
     *                           PEAR_Error object on failure.
     */
    function add($attributes)
    {
        if ($this->readonly) {
            return PEAR::raiseError(_("This address book is read-only"));
        }

        /* Always generate a new key. */
        $attributes['__key'] = $this->_makeKey($this->toDriverKeys($attributes));

        if (!isset($attributes['__type'])) {
            $attributes['__type'] = 'Object';
        }
        if (isset($this->map['__owner'])) {
            $attributes['__owner'] = Auth::getAuth();
        }
        if (!isset($attributes['__uid'])) {
            $attributes['__uid'] = $this->generateUID();
        }

        $key = $attributes['__key'];
        $uid = $attributes['__uid'];

        $attributes = $this->toDriverKeys($attributes);

        $result = $this->_add($attributes);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        /* Log the creation of this item in the history log. */
        $history = &Horde_History::singleton();
        $history->log('turba:' . (!empty($attributes['__owner']) ? $attributes['__owner'] : Auth::getAuth()) . ':' . $uid, array('action' => 'add'), true);

        return $key;
    }

    /**
     * Deletes the specified entry from the contact source.
     *
     * @param string $object_id  The ID of the object to delete.
     */
    function delete($object_id)
    {
        if ($this->readonly) {
            return PEAR::raiseError(_("This address book is read-only"));
        }

        $object = &$this->getObject($object_id);
        if (is_a($object, 'PEAR_Error')) {
            return $object;
        }

        if (!Turba::hasPermission($object, 'object', PERMS_DELETE)) {
            return PEAR::raiseError(_("Permission denied"));
        }

        $result = $this->_delete($this->toDriver('__key'), $object_id);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        /* Log the deletion of this item in the history log. */
        if ($object->getValue('__uid')) {
            $history = &Horde_History::singleton();
            $history->log('turba:' . ($object->getValue('__owner') ? $object->getValue('__owner') : Auth::getAuth()) . ':' . $object->getValue('__uid'),
                          array('action' => 'delete'), true);
        }

        return true;
    }

    /**
     * Deletes all contacts from the address book.
     *
     * @return boolean  True if the operation worked.
     */
    function deleteAll()
    {
        if (!$this->hasCapability('delete_all')) {
            return PEAR::raiseError('Not supported');
        } else {
            return $this->_deleteAll();
        }
    }

    /**
     * Modifies an existing entry in the contact source.
     *
     * @param Turba_AbstractObject $object     The object to update.
     *
     * @return string  The object id, possibly updated.
     */
    function save($object)
    {
        if ($this->readonly) {
            return PEAR::raiseError(_("Address book is read-only."));
        }

        $attributes = $this->toDriverKeys($object->getAttributes());
        list($object_key, $object_id) = each($this->toDriverKeys(array('__key' => $object->getValue('__key'))));

        $object_id = $this->_save($object_key, $object_id, $attributes);
        if (is_a($object_id, 'PEAR_Error')) {
            return $object_id;
        }

        /* Log the modification of this item in the history log. */
        if ($object->getValue('__uid')) {
            $history = &Horde_History::singleton();
            $history->log('turba:' . ($object->getValue('__owner') ? $object->getValue('__owner') : Auth::getAuth()) . ':' . $object->getValue('__uid'),
                          array('action' => 'modify'), true);
        }

        return $object_id;
    }

    /**
     * Returns the criteria available for this source except '__key'.
     *
     * @return array  An array containing the criteria.
     */
    function getCriteria()
    {
        $criteria = $this->map;
        unset($criteria['__key']);
        return $criteria;
    }

    /**
     * Returns all non-composite fields for this source. Useful for
     * importing and exporting data, etc.
     *
     * @return array  The field list.
     */
    function getFields()
    {
        return array_flip($this->fields);
    }

    /**
     * Generate a universal / unique identifier for a contact. This is
     * NOT something that we expect to be able to parse into an
     * addressbook and a contactId.
     *
     * @return string  A nice unique string (should be 255 chars or less).
     */
    function generateUID()
    {
        return date('YmdHis') . '.' .
            substr(base_convert(microtime(), 10, 36), -16) .
            '@' . $GLOBALS['conf']['server']['name'];
    }

    /**
     * Exports a given Turba_AbstractObject as an iCalendar vCard.
     *
     * @param object $object  A Turba_AbstractObject.
     *
     * @return object  A Horde_iCalendar_vcard object.
     */
    function tovCard($object)
    {
        require_once 'Horde/iCalendar/vcard.php';

        $hash = $object->getAttributes();
        $iCal = &new Horde_iCalendar();
        $vcard = Horde_iCalendar::newComponent('vcard', $iCal);

        foreach ($hash as $key => $val) {
            switch ($key) {
            case 'name':
                $vcard->setAttribute('FN', $val);
                break;

            case 'nickname':
                $vcard->setAttribute('NICKNAME', $val);
                break;

            case 'homePhone':
                $vcard->setAttribute('TEL', $val, array('TYPE'=>'HOME'));
                break;

            case 'workPhone':
                $vcard->setAttribute('TEL', $val, array('TYPE'=>'WORK'));
                break;

            case 'cellPhone':
                $vcard->setAttribute('TEL', $val, array('TYPE'=>'CELL'));
                break;

            case 'fax':
                $vcard->setAttribute('TEL', $val, array('TYPE'=>'FAX'));
                break;

            case 'email':
                $vcard->setAttribute('EMAIL', Horde_iCalendar_vcard::getBareEmail($val));
                break;

            case 'title':
                $vcard->setAttribute('TITLE', $val);
                break;

            case 'company':
                $vcard->setAttribute('ORG', $val);
                break;

            case 'notes':
                $vcard->setAttribute('NOTE', $val);
                break;

            case 'website':
                $vcard->setAttribute('URL', $val);
                break;
            }
        }

        if (!empty($hash['lastname']) || !empty($hash['firstname'])) {
            $a = array(
                VCARD_N_FAMILY      => isset($hash['lastname']) ? $hash['lastname'] : '',
                VCARD_N_GIVEN       => isset($hash['firstname']) ? $hash['firstname'] : '',
                VCARD_N_ADDL        => '',
                VCARD_N_PREFIX      => '',
                VCARD_N_SUFFIX      => '',
            );
            $vcard->setAttribute('N', implode(';', $a), array(), false, $a);
        }

        $a = array(
            VCARD_ADR_POB           => '',
            VCARD_ADR_EXTEND        => '',
            VCARD_ADR_STREET        => isset($hash['homeAddress']) ? $hash['homeAddress'] : '',
            VCARD_ADR_LOCALITY      => isset($hash['homeCity']) ? $hash['homeCity'] : '',
            VCARD_ADR_REGION        => isset($hash['homeProvince']) ? $hash['homeProvince'] : '',
            VCARD_ADR_POSTCODE      => isset($hash['homePostalCode']) ? $hash['homePostalCode'] : '',
            VCARD_ADR_COUNTRY       => isset($hash['homeCountry']) ? $hash['homeCountry'] : '',
        );
        $vcard->setAttribute('ADR', implode(';', $a), array('TYPE' => 'HOME' ), true, $a);

        $a = array(
            VCARD_ADR_POB           => '',
            VCARD_ADR_EXTEND        => '',
            VCARD_ADR_STREET        => isset($hash['workAddress']) ? $hash['workAddress'] : '',
            VCARD_ADR_LOCALITY      => isset($hash['workCity']) ? $hash['workCity'] : '',
            VCARD_ADR_REGION        => isset($hash['workProvince']) ? $hash['workProvince'] : '',
            VCARD_ADR_POSTCODE      => isset($hash['workPostalCode']) ? $hash['workPostalCode'] : '',
            VCARD_ADR_COUNTRY       => isset($hash['workCountry']) ? $hash['workCountry'] : '',
        );
        $vcard->setAttribute('ADR', implode(';', $a), array('TYPE' => 'WORK' ), true, $a);

        return $vcard;
    }

    /**
     * Static function to convert a Horde_iCalendar_vcard object into
     * a Turba Object Hash with Turba attributes suitable as a parameter
     * for add().
     *
     * @see add()
     *
     * @param Horde_iCalendar_vcard $vcard  The Horde_iCalendar_vcard object to parse.
     *
     * @return array  A Turba attribute hash.
     */
    function toHash($vcard)
    {
        if (!is_a($vcard, 'Horde_iCalendar_vcard')) {
            return PEAR::raiseError('Invalid parameter for Turba_Driver::toHash(), expected Horde_iCalendar_vcard object.');
        }

        $hash = array();
        $attr = $vcard->getAllAttributes();
        foreach ($attr as $item) {
            switch ($item['name']) {
            case 'FN':
                $hash['name'] = $item['value'];
                break;

            case 'N':
                $name = $item['values'];
                $hash['lastname'] = $name[VCARD_N_FAMILY];
                $hash['firstname'] = $name[VCARD_N_GIVEN];
                break;

            case 'NICKNAME':
                $hash['nickname'] = $item['value'];
                break;

            // We use LABEL but also support ADR.
            case 'LABEL':
                if (isset($item['params']['HOME'])) {
                    $hash['homeAddress'] = $item['value'];
                } elseif (isset($item['params']['WORK'])) {
                    $hash['workAddress'] = $item['value'];
                } else {
                    $hash['workAddress'] = $item['value'];
                }
                break;

            // For vCard 3.0.
            case 'ADR':
                if (isset($item['params']['TYPE'])) {
                    if (!is_array($item['params']['TYPE'])) {
                        $item['params']['TYPE'] = array($item['params']['TYPE']);
                    }
                } else {
                    $item['params']['TYPE'] = array();
                    if (isset($item['params']['WORK'])) {
                        $item['params']['TYPE'][] = 'WORK';
                    }
                    if (isset($item['params']['HOME'])) {
                        $item['params']['TYPE'][] = 'HOME';
                    }
                }

                $address = $item['values'];
                foreach ($item['params']['TYPE'] as $adr) {
                    switch (String::upper($adr)) {
                    case 'HOME':
                        $prefix = 'home';
                        break;

                    case 'WORK':
                        $prefix = 'work';
                        break;

                    default:
                        $prefix = null;
                    }

                    if ($prefix) {
                        $hash[$prefix . 'Street'] = isset($address[VCARD_ADR_STREET]) ? $address[VCARD_ADR_STREET] : null;
                        $hash[$prefix . 'City'] = isset($address[VCARD_ADR_LOCALITY]) ? $address[VCARD_ADR_LOCALITY] : null;
                        $hash[$prefix . 'Province'] = isset($address[VCARD_ADR_REGION]) ? $address[VCARD_ADR_REGION] : null;
                        $hash[$prefix . 'PostalCode'] = isset($address[VCARD_ADR_POSTCODE]) ? $address[VCARD_ADR_POSTCODE] : null;
                        $hash[$prefix . 'Country'] = isset($address[VCARD_ADR_COUNTRY]) ? $address[VCARD_ADR_COUNTRY] : null;

                        // Do our best to build a composite address
                        // entry as well.
                        $hash[$prefix . 'Address'] = trim($hash[$prefix . 'Street'] . "\n" .
                                                          $hash[$prefix . 'City'] . ', ' . $hash[$prefix . 'Province'] . ' ' . $hash[$prefix . 'PostalCode'] . "\n" .
                                                          $hash[$prefix . 'Country']);
                    }
                }
                break;

            case 'TEL':
                if (isset($item['params']['FAX'])) {
                    $hash['fax'] = $item['value'];
                } elseif (isset($item['params']['TYPE'])) {
                    if (!is_array($item['params']['TYPE'])) {
                        $item['params']['TYPE'] = array($item['params']['TYPE']);
                    }
                    // For vCard 3.0.
                    foreach ($item['params']['TYPE'] as $tel) {
                        if (String::upper($tel) == 'WORK') {
                            $hash['workPhone'] = $item['value'];
                        } elseif (String::upper($tel) == 'HOME') {
                            $hash['homePhone'] = $item['value'];
                        } elseif (String::upper($tel) == 'CELL') {
                            $hash['cellPhone'] = $item['value'];
                        } elseif (String::upper($tel) == 'FAX') {
                            $hash['fax'] = $item['value'];
                        }
                    }
                } else {
                    if (isset($item['params']['HOME'])) {
                        $hash['homePhone'] = $item['value'];
                    } elseif (isset($item['params']['WORK'])) {
                        $hash['workPhone'] = $item['value'];
                    } elseif (isset($item['params']['CELL'])) {
                        $hash['cellPhone'] = $item['value'];
                    } else {
                        $hash['homePhone'] = $item['value'];
                    }
                }
                break;

            case 'EMAIL':
                if (isset($item['params']['PREF']) || !isset($hash['email'])) {
                    $hash['email'] = Horde_iCalendar_vcard::getBareEmail($item['value']);
                }
                break;

            case 'TITLE':
                $hash['title'] = $item['value'];
                break;

            case 'ORG':
                $hash['company'] = $item['value'];
                break;

            case 'NOTE':
                $hash['notes'] = $item['value'];
                break;

            case 'URL':
                $hash['website'] = $item['value'];
                break;
            }
        }

        return $hash;
    }

    /**
     * Static method to construct Turba_Driver objects. Use this so
     * that we can return PEAR_Error objects if anything goes wrong.
     *
     * Should only be called by Turba_Driver::singleton().
     *
     * @see Turba_Driver::singleton()
     * @access private
     *
     * @param string $name    String containing the internal name of this source.
     * @param array  $config  Array containing the configuration information for this source.
     */
    function &factory($name, $config)
    {
        $class = basename($config['type']);
        include_once dirname(__FILE__) . '/Driver/' . $class . '.php';
        $class = 'Turba_Driver_' . $class;
        if (class_exists($class)) {
            $driver = &new $class($config['params']);
        } else {
            return PEAR::raiseError(sprintf(_("Unable to load the definition of %s."), $class));
        }

        $result = $driver->_init();
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        /* Store name and title. */
        $driver->name = $name;
        $driver->title = $config['title'];

        /* Store and translate the map at the Source level. */
        $driver->map = $config['map'];
        foreach ($driver->map as $key => $val) {
            if (!is_array($val)) {
                $driver->fields[$key] = $val;
            }
        }

        /* Store tabs. */
        if (isset($config['tabs'])) {
            $driver->tabs = $config['tabs'];
        }

        /* Store strict fields. */
        if (isset($config['strict'])) {
            $driver->strict = $config['strict'];
        }

        /* Store admins. */
        if (isset($config['admin'])) {
            $driver->admin = $config['admin'];
        }

        /* Set flags. */
        if (isset($config['public'])) {
            $driver->public = $config['public'];
        }
        if (isset($config['readonly'])) {
            $driver->readonly = $config['readonly'] &&
                (!isset($config['admin']) || !in_array(Auth::getAuth(), $config['admin']));
        }

        return $driver;
    }

}