File: Sync.php

package info (click to toggle)
horde3 3.1.3-4etch7
  • links: PTS
  • area: main
  • in suites: etch
  • size: 22,876 kB
  • ctags: 18,071
  • sloc: php: 75,151; xml: 2,979; sql: 1,069; makefile: 79; sh: 64
file content (400 lines) | stat: -rw-r--r-- 16,803 bytes parent folder | download | duplicates (2)
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
<?php
/**
 * $Horde: framework/SyncML/SyncML/Sync.php,v 1.8.4.9 2006/05/01 12:05:14 jan Exp $
 *
 * Copyright 2003-2006 Anthony Mills <amills@pyramid6.com>
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
 *
 * @author  Anthony Mills <amills@pyramid6.com>
 * @since   Horde 3.0
 * @package SyncML
 */
class SyncML_Sync {

    /**
     * Target: contacts, notes, calendar, tasks,
     */
    var $_targetLocURI; // target means server here

    var $_sourceLocURI; // source means client here

    var $_alert;

    /**
     * True indicates that there are still sync elements that have not been
     * sent yet due to message size limitations and have to be sent in the next
     * message.
     *
     * @var boolean
     */
    var $_pendingElements;

    /**
     * Remember entries we have handled already: once we send a delete for an
     * entry, we don't want to send an add afterwards. This array is also used
     * if a sync is sent in multiple messages due to message size restrictions.
     *
     * @var array
     */
    var $_done;

    function SyncML_Sync($alert, $serverURI, $clientURI)
    {
        $this->_alert = $alert;
        $this->_pendingElements = false;
        $this->_done = array();
        $this->_targetLocURI = basename($serverURI);
        $this->_sourceLocURI = $clientURI;
        global $backend;
        $backend->logMessage("create for syncType=$serverURI", __FILE__, __LINE__, PEAR_LOG_DEBUG);
    }

    /**
     * Here's where the actual processing of a client-sent Sync
     * Item takes place. Entries are added, deleted or replaced
     * from the server database by using Horde API (Registry) calls.
     */
    function handleSyncItem($item)
    {
        global $backend;

        $state = &$_SESSION['SyncML.state'];
        $device = &$state->getDevice();
        $syncIdentifier = $state->getSyncIdentifier();

        $hordeType = $type = $this->_targetLocURI;

        // Use contentType explicitly specified in this sync command.
        $contentType = $item->getContentType();

        // If not provided, use default from device info.
        if (!$contentType) {
            $contentType = $device->getPreferredContentType($type);
        }

        list($content, $contentType) =
            $device->convertClient2Server($item->getContent(),
                                          $contentType);
        $cuid = $item->getCuid();
        $suid = false;

        // Handle client add requests.
        if ($item->getElementType() =='Add') {
            $suid = $backend->importEntry($syncIdentifier, $hordeType,
                                          $content, $contentType, $cuid);
            if (!is_a($suid, 'PEAR_Error')) {
                $state->log("Client-Add");
                $backend->logMessage('added client entry as ' . $suid,
                                     __FILE__, __LINE__, PEAR_LOG_DEBUG);
            } else {
                $state->log("Client-AddFailure");
                $backend->logMessage('Error in adding client entry:' . $suid->message, __FILE__, __LINE__, PEAR_LOG_ERR);
            }

        // Handle client delete requests.
        } elseif ($item->getElementType() =='Delete') {
            $suid = $backend->deleteEntry($syncIdentifier, $type, $cuid);
            if ($type == 'calendar'
                && $device->handleTasksInCalendar()) {
                // deleteEntry does not need to return an error on
                // deletion of nonexistent entries. So just to be sure
                // we have to delete from the tasks database as well:
                $backend->logMessage('special tasks delete ' . $suid . ' due to client request', __FILE__, __LINE__, PEAR_LOG_DEBUG);
                $suid = $backend->deleteEntry($syncIdentifier, 'tasks', $cuid);
            }
            if (!is_a($suid, 'PEAR_Error')) {
                $state->log("Client-Delete");
                $backend->logMessage('deleted entry ' . $suid . ' due to client request', __FILE__, __LINE__, PEAR_LOG_DEBUG);
            } else {
                $state->log("Client-DeleteFailure");
                $this->logMessage('Failure deleting client entry, maybe gone already on server. msg:'. $suid->message, __FILE__, __LINE__, PEAR_LOG_ERR);
            }

        // Handle client replace requests.
        } elseif ($item->getElementType() == 'Replace') {
            $suid = $backend->replaceEntry($syncIdentifier, $hordeType,
                                           $content, $contentType, $cuid);

            if (!is_a($suid, 'PEAR_Error')) {
                $state->log("Client-Replace");
                $backend->logMessage('replaced entry ' . $suid . ' due to client request', __FILE__, __LINE__, PEAR_LOG_DEBUG);
            } else {
                $backend->logMessage($suid->message, __FILE__, __LINE__, PEAR_LOG_DEBUG);
                $backend->logMessage($suid, __FILE__, __LINE__, PEAR_LOG_DEBUG);

                // Entry may have been deleted; try adding it.
                $suid = $backend->importEntry($syncIdentifier, $hordeType,
                                              $content, $contentType, $cuid);
                if (!is_a($suid, 'PEAR_Error')) {
                    $state->log("Client-AddReplace");
                    $backend->logMessage('added client entry due to replace request as ' . $suid, __FILE__, __LINE__, PEAR_LOG_DEBUG);
                } else {
                    $state->log("Client-AddFailure");
                    $backend->logMessage('Error in adding client entry due to replace request:' . $suid->message, __FILE__, __LINE__, PEAR_LOG_ERR);
                }
            }
        } else {
            $backend->logMessage('Unexpected elementType: ' . $item->getElementType(),
                                 __FILE__, __LINE__, PEAR_LOG_ERR);
        }

        return $suid;
    }

    /**
     * Creates a &lt;Sync&gt; output.
     */
    function createSyncOutput($currentCmdID, &$output)
    {
        $state = &$_SESSION['SyncML.state'];
        $attrs = array();

        $output->startElement($state->getURI(), 'Sync', $attrs);
        $output->startElement($state->getURI(), 'CmdID', $attrs);
        $output->characters($currentCmdID);
        $currentCmdID++;
        $output->endElement($state->getURI(), 'CmdID');

        $output->startElement($state->getURI(), 'Target', $attrs);
        $output->startElement($state->getURI(), 'LocURI', $attrs);
        $output->characters($this->_sourceLocURI);
        $output->endElement($state->getURI(), 'LocURI');
        $output->endElement($state->getURI(), 'Target');

        $output->startElement($state->getURI(), 'Source', $attrs);
        $output->startElement($state->getURI(), 'LocURI', $attrs);
        $output->characters($this->_targetLocURI);
        $output->endElement($state->getURI(), 'LocURI');
        $output->endElement($state->getURI(), 'Source');

        $syncType = $this->_targetLocURI;

        global $backend;
        $backend->logMessage("handleSync for syncType=$syncType", __FILE__, __LINE__, PEAR_LOG_DEBUG);

        // Here's where server modifications are sent to the client:
        $refts = $state->getServerAnchorLast($syncType);
        $currentCmdID = $this->handleSync($currentCmdID, $syncType,
                                          $output, $refts);

        $output->endElement($state->getURI(), 'Sync');

        return $currentCmdID;
    }

    /**
     * Sends server changes to the client.
     */
    function handleSync($currentCmdID, $syncType, &$output, $refts, $end_ts = 0)
    {
        global $backend;
        global $messageFull;

        /* $messageFull will be set to true to indicate that there's no room
         * for other data in this message. If it's false (empty) and there
         * are pending Sync data, the final command will sent the pending data.
         * This global data should be moved to a global object, together
         * with currentCmdID and $output. */
        $messageFull = false;

        $state = &$_SESSION['SyncML.state'];
        $device = &$state->getDevice();
        $syncIdentifier = $state->getSyncIdentifier();
        $contentType = $device->getPreferredContentTypeClient($syncType, $this->_sourceLocURI);

        /* We faithfully expect to deal with all remaining elements. Will be
         * set to true if we run out of space for message creation. */
        $this->setPendingElements(false);

        // Handle deletions.
        $deletions = $backend->getServerDeletions($syncIdentifier, $syncType, $refts, $end_ts);

        if ($refts > 0) {
            // Don't send deletes on SlowSync.
            foreach ($deletions as $suid => $cuid) {
                $this->_done[$suid] = true;
                $backend->logMessage("delete: cuid=$cuid suid=$suid refts: $refts", __FILE__, __LINE__, PEAR_LOG_DEBUG);
                // Create a Delete request for client.
                $currentCmdID = $this->outputCommand($currentCmdID, $output, 'Delete',
                                                     null, null, $cuid, null);
                $state->log('Server-Delete');
            }
        }
        // Handle additions.
        $adds = $backend->getServerAdditions($syncIdentifier, $syncType, $refts, $end_ts);
        foreach ($adds as $suid => $cuid) {
            if (!empty($this->_done[$suid])) {
                // Already sent delete, no need to add.
                continue;
            }
            $backend->logMessage("add: $suid", __FILE__, __LINE__, PEAR_LOG_DEBUG);

            $c = $backend->retrieveEntry($syncType, $suid, $contentType);
            if (!is_a($c, 'PEAR_Error')) {
                // Item in history but not in database. Strange, but can happen.
                list($clientContent, $clientContentType) =
                    $device->convertServer2Client($c, $contentType);
                // Check if we have space left in the message.
                if (($state->getMaxMsgSize()
                    - $output->getOutputSize()
                    - strlen($clientContent)) < 50) {
                    $backend->logMessage('max message size reached cursize='
                                         . $output->getOutputSize(),
                                         __FILE__, __LINE__, PEAR_LOG_DEBUG);
                    $messageFull = true;
                    $this->setPendingElements(true);
                    return $currentCmdID;
                }
                $this->_done[$suid] = true;
                $currentCmdID = $this->outputCommand($currentCmdID, $output,
                                                     'Add',
                                                     $clientContent,
                                                     $clientContentType,
                                                     null,
                                                     $suid);
                $state->log('Server-Add');
            } else {
                $backend->logMessage('api export call for ' . $suid . ' failed:  ' . $c->getMessage(),
                                     __FILE__, __LINE__, PEAR_LOG_DEBUG);
            }
        }

        // Handle changes.
        if ($refts != 0) {
            // Don't send changes for SlowSync, confuses some clients.
            $end_ts = time();
            $changes = $backend->getServerModifications($syncIdentifier,
                                                        $syncType,
                                                        $refts, $end_ts);
            if (is_a($changes, 'PEAR_Error')) {
                $backend->logMessage($changes, __FILE__, __LINE__, PEAR_LOG_ERR);
                return $changes;
            }

            foreach ($changes as $suid => $cuid) {
                if (!empty($this->_done[$suid])) {
                    // Already sent delete or add, no need to modify.
                    continue;
                }

                if (!$cuid) {
                    // TODO: create an "add" here instead?
                    continue;
                }

                $c = $backend->retrieveEntry($syncType, $suid, $contentType);
                if (!is_a($c, 'PEAR_Error')) {
                    $backend->logMessage("change: $suid",
                                         __FILE__, __LINE__, PEAR_LOG_DEBUG);
                    list($clientContent, $clientContentType) =
                        $device->convertServer2Client($c, $contentType);
                    // Check if we have space left in the message.
                    if (($state->getMaxMsgSize()
                         - $output->getOutputSize()
                         - strlen($clientContent)) < 50) {
                        $backend->logMessage('max message size reached cursize='
                                             . $output->getOutputSize(),
                                             __FILE__, __LINE__, PEAR_LOG_DEBUG);
                        $messageFull = true;
                        $this->setPendingElements(true);
                        return $currentCmdID;
                    }
                    $this->_done[$suid] = true;
                    $currentCmdID = $this->outputCommand($currentCmdID, $output,
                                                         'Replace',
                                                         $clientContent,
                                                         $clientContentType,
                                                         $cuid,
                                                         null);
                    $state->log('Server-Replace');
                } else {
                    // Item in history but not in database. Strange, but
                    // can happen.
                }
            }
        }

        // If tasks are handled inside calendar, do the same again for
        // tasks.
        if ($syncType == 'calendar' && $device->handleTasksInCalendar()) {
            $backend->logMessage("handling tasks in calendar sync",
                                 __FILE__, __LINE__, PEAR_LOG_DEBUG);

            $currentCmdID = $this->handleSync($currentCmdID, 'tasks',
                                              $output, $refts, $end_ts);
        }

        return $currentCmdID;
    }

    /**
     * Output a single Sync command (Add, Delete, Replace).
     */
    function outputCommand($currentCmdID, &$output, $command,
                           $content, $contentType = null,
                           $cuid = null, $suid = null)
    {
        $state = &$_SESSION['SyncML.state'];

        $attrs = array();
        $output->startElement($state->getURI(), $command, $attrs);

        $output->startElement($state->getURI(), 'CmdID', $attrs);
        $chars = $currentCmdID;
        $output->characters($chars);
        $output->endElement($state->getURI(), 'CmdID');

        if (isset($contentType)) {
            $output->startElement($state->getURI(), 'Meta', $attrs);
            $output->startElement($state->getURIMeta(), 'Type', $attrs);
            $output->characters($contentType);
            $output->endElement($state->getURIMeta(), 'Type');
            $output->endElement($state->getURI(), 'Meta');
        }

        if (isset($content)
            || isset($cuid) || isset($suid)) {
            $output->startElement($state->getURI(), 'Item', $attrs);
            if ($suid != null) {
                $output->startElement($state->getURI(), 'Source', $attrs);
                $output->startElement($state->getURI(), 'LocURI', $attrs);
                $output->characters($suid);
                $output->endElement($state->getURI(), 'LocURI');
                $output->endElement($state->getURI(), 'Source');
            }

            if ($cuid != null) {
                $output->startElement($state->getURI(), 'Target', $attrs);
                $output->startElement($state->getURI(), 'LocURI', $attrs);
                $output->characters($cuid);
                $output->endElement($state->getURI(), 'LocURI');
                $output->endElement($state->getURI(), 'Target');
            }
            if (isset($content)) {
                $output->startElement($state->getURI(), 'Data', $attrs);
                $output->characters($content);
                $output->endElement($state->getURI(), 'Data');
            }
            $output->endElement($state->getURI(), 'Item');
        }

        $output->endElement($state->getURI(), $command);

        $currentCmdID++;

        return $currentCmdID;
    }

    function setPendingElements($e)
    {
        $this->_pendingElements = $e;
    }

    function hasPendingElements()
    {
        return $this->_pendingElements;
    }

}