summaryrefslogtreecommitdiff
path: root/lib/kolab_sync_backend_common.php
blob: 13fdf2309d0b4662d3298278b4c5bfcda251d0f6 (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
<?php

/**
 +--------------------------------------------------------------------------+
 | Kolab Sync (ActiveSync for Kolab)                                        |
 |                                                                          |
 | Copyright (C) 2011-2012, Kolab Systems AG <contact@kolabsys.com>         |
 |                                                                          |
 | 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>                      |
 +--------------------------------------------------------------------------+
*/

/**
 * Parent backend class for kolab backends
 */
class kolab_sync_backend_common implements Syncroton_Backend_IBackend
{
    /**
     * Table name
     *
     * @var string
     */
    protected $table_name;

    /**
     * Model interface name
     *
     * @var string
     */
    protected $interface_name;

    /**
     * Backend interface name
     *
     * @var string
     */
    protected $class_name;

    /**
     * SQL Database engine
     *
     * @var rcube_db
     */
    protected $db;

    /**
     * Internal cache (in-memory)
     *
     * @var array
     */
    protected $cache = array();


    /**
     * Constructor
     */
    function __construct()
    {
        $this->db = rcube::get_instance()->get_dbh();

        if (empty($this->class_name)) {
            $this->class_name = str_replace('Model_I', 'Model_', $this->interface_name);
        }
    }

    /**
     * Creates new Syncroton object in database
     *
     * @param Syncroton_Model_* $object Object
     *
     * @throws InvalidArgumentException
     * @return Syncroton_Model_* Object
     */
    public function create($object)
    {
        if (! $object instanceof $this->interface_name) {
            throw new InvalidArgumentException('$object must be instanace of ' . $this->interface_name);
        }

        $data = $this->object_to_array($object);
        $cols = array();

        $data['id'] = $object->id = sha1(mt_rand(). microtime());

        foreach (array_keys($data) as $key) {
            $cols[] = $this->db->quote_identifier($key);
        }

        $this->db->query('INSERT INTO `' . $this->table_name . '`' . ' (' . implode(', ', $cols) . ')'
            . ' VALUES(' . implode(', ', array_fill(0, count($cols), '?')) . ')',
            array_values($data)
        );

        if (!$this->db->insert_id($this->table_name)) {
            // @TODO: throw exception
        }

        return $object;
    }

    /**
     * Returns Syncroton data object
     *
     * @param string  $id
     * @throws Syncroton_Exception_NotFound
     * @return Syncroton_Model_*
     */
    public function get($id)
    {
        $id = $id instanceof $this->interface_name ? $id->id : $id;

        if ($id) {
            $select = $this->db->query('SELECT * FROM `' . $this->table_name . '` WHERE `id` = ?', array($id));
            $data   = $this->db->fetch_assoc($select);
        }

        if (empty($data)) {
            throw new Syncroton_Exception_NotFound('Object not found');
        }

        return $this->get_object($data);
    }

    /**
     * Deletes Syncroton data object
     *
     * @param string|Syncroton_Model_* $id Object or identifier
     *
     * @return bool True on success, False on failure
     */
    public function delete($id)
    {
        $id = $id instanceof $this->interface_name ? $id->id : $id;

        if (!$id) {
            return false;
        }

        $result = $this->db->query('DELETE FROM `' . $this->table_name .'` WHERE `id` = ?', array($id));

        return (bool) $this->db->affected_rows($result);
    }

    /**
     * Updates Syncroton data object
     *
     * @param Syncroton_Model_* $object
     *
     * @throws InvalidArgumentException
     * @return Syncroton_Model_* Object
     */
    public function update($object)
    {
        if (! $object instanceof $this->interface_name) {
            throw new InvalidArgumentException('$object must be instanace of ' . $this->interface_name);
        }

        $data = $this->object_to_array($object);
        $set  = array();

        foreach (array_keys($data) as $key) {
            $set[] = $this->db->quote_identifier($key) . ' = ?';
        }

        $this->db->query('UPDATE `' . $this->table_name . '` SET ' . implode(', ', $set)
            . ' WHERE `id` = ' . $this->db->quote($object->id), array_values($data));

        return $object;
    }

    /**
     * Returns list of user accounts
     *
     * @param Syncroton_Model_Device $device The current device
     *
     * @return array List of Syncroton_Model_Account objects
     */
    public function userAccounts($device)
    {
        // this method is overwritten by kolab_sync_backend class
    }

    /**
     * Convert array into model object
     */
    protected function get_object($data)
    {
        foreach ($data as $key => $value) {
            unset($data[$key]);

            if (!empty($value) && preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/', $value)) { // 2012-08-12 07:43:26
                $value = new DateTime($value, new DateTimeZone('utc'));
            }

            $data[$this->to_camelcase($key, false)] = $value;
        }

        return new $this->class_name($data);
    }

    /**
     * Converts model object into array
     */
    protected function object_to_array($object)
    {
        $data = array();

        foreach ($object as $key => $value) {
            if ($value instanceof DateTime) {
                $value = $value->format('Y-m-d H:i:s');
            } elseif (is_object($value) && isset($value->id)) {
                $value = $value->id;
            }

            $data[$this->from_camelcase($key)] = $value;
        }

        return $data;
    }

    /**
     * Convert property name from camel-case to lower-case-with-underscore
     */
    protected function from_camelcase($string)
    {
        $string = lcfirst($string);

        return preg_replace_callback('/([A-Z])/', function ($string) { return '_' . strtolower($string[0]); }, $string);
    }

    /**
     * Convert property name from lower-case-with-underscore to camel-case
     */
    protected function to_camelcase($string, $ucFirst = true)
    {
        if ($ucFirst) {
            $string = ucfirst($string);
        }

        return preg_replace_callback('/_([a-z])/', function ($string) { return strtoupper($string[1]); }, $string);
    }
}