/
Collections.php
1273 lines (1153 loc) · 41.5 KB
/
Collections.php
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
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Horde_ActiveSync_Collections::
*
* @license http://www.horde.org/licenses/gpl GPLv2
* NOTE: According to sec. 8 of the GENERAL PUBLIC LICENSE (GPL),
* Version 2, the distribution of the Horde_ActiveSync module in or
* to the United States of America is excluded from the scope of this
* license.
* @copyright 2013-2014 Horde LLC (http://www.horde.org)
* @author Michael J Rubinsky <mrubinsk@horde.org>
* @package ActiveSync
*/
/**
* Horde_ActiveSync_Collections:: Responsible for all functionality related to
* collections and managing the sync cache.
*
* @license http://www.horde.org/licenses/gpl GPLv2
* NOTE: According to sec. 8 of the GENERAL PUBLIC LICENSE (GPL),
* Version 2, the distribution of the Horde_ActiveSync module in or
* to the United States of America is excluded from the scope of this
* license.
* @copyright 2010-2014 Horde LLC (http://www.horde.org)
* @author Michael J Rubinsky <mrubinsk@horde.org>
* @package ActiveSync
* @internal Not intended for use outside of the ActiveSync library.
*/
class Horde_ActiveSync_Collections implements IteratorAggregate
{
const COLLECTION_ERR_FOLDERSYNC_REQUIRED = -1;
const COLLECTION_ERR_SERVER = -2;
const COLLECTION_ERR_STALE = -3;
const COLLECTION_ERR_SYNC_REQUIRED = -4;
const COLLECTION_ERR_PING_NEED_FULL = -5;
/**
* The collection data
*
* @var array
*/
protected $_collections = array();
/**
* Cache a temporary syncCache.
*
* @var Horde_ActiveSync_SyncCache
*/
protected $_tempSyncCache;
/**
* The syncCache
*
* @var Horde_ActiveSync_SyncCache
*/
protected $_cache;
/**
* The logger
*
* @var Horde_Log_Logger
*/
protected $_logger;
/**
* Count of unchanged collections calculated for PARTIAL sync.
*
* @var integer
*/
protected $_unchangedCount = 0;
/**
* Count of available synckeys
*
* @var integer
*/
protected $_synckeyCount = 0;
/**
* Count of confirmed collections calculated for PARTIAL sync.
*
* @var integer
*/
protected $_confirmedCount = 0;
/**
* Global WINDOWSIZE
*
* @var integer
*/
protected $_globalWindowSize = 100;
/**
* Imported changes flag.
*
* @var boolean
*/
protected $_importedChanges = false;
/**
* Short sync request flag.
*
* @var boolean
*/
protected $_shortSyncRequest = false;
/**
* Cache of collections that have had changes detected.
*
* @var array
*/
protected $_changedCollections = array();
/**
* The ActiveSync server object.
*
* @var Horde_ActiveSync
*/
protected $_as;
/**
* Cache the process id for logging.
*
* @var integer
*/
protected $_procid;
/**
* Cache of changes.
*
* @var array
*/
protected $_changes;
/**
* Flag to indicate the client is requesting a hanging SYNC.
*
* @var boolean
*/
protected $_hangingSync = false;
/**
* Const'r
*
* @param Horde_ActiveSync_SyncCache $cache The SyncCache.
* @param Horde_ActiveSync $as The ActiveSync server object.
*/
public function __construct(
Horde_ActiveSync_SyncCache $cache,
Horde_ActiveSync $as)
{
$this->_cache = $cache;
$this->_as = $as;
$this->_logger = $as->logger;
$this->_procid = getmypid();
}
/**
* Load all the collections we know about from the cache.
*/
public function loadCollectionsFromCache()
{
foreach ($this->_cache->getCollections(false) as $collection) {
if (empty($collection['synckey']) && !empty($collection['lastsynckey'])) {
$collection['synckey'] = $collection['lastsynckey'];
}
// Load the class if needed for EAS >= 12.1
if (empty($collection['class'])) {
$collection['class'] = $this->getCollectionClass($collection['id']);
}
if (empty($collection['serverid'])) {
try {
$collection['serverid'] = $this->getBackendIdForFolderUid($collection['id']);
} catch (Horde_ActiveSync_Exception $e) {
$this->_logger->err($e->getMessage());
continue;
}
}
$this->_collections[$collection['id']] = $collection;
$this->_logger->info(sprintf(
'[%s] Loaded %s from the cache.',
$this->_procid,
$collection['serverid']));
}
}
/**
* Magic...
*/
public function __call($method, $parameters)
{
switch ($method) {
case 'hasPingChangeFlag':
case 'addConfirmedKey':
case 'updateCollection':
case 'collectionExists':
case 'updateWindowSize':
return call_user_func_array(array($this->_cache, $method), $parameters);
}
throw new BadMethodCallException('Unknown method: ' . $method);
}
/**
* Property getter
*/
public function __get($property)
{
switch ($property) {
case 'hbinterval':
case 'wait':
case 'confirmed_synckeys':
case 'lasthbsyncstarted':
case 'lastsyncendnormal':
return $this->_cache->$property;
case 'importedChanges':
case 'shortSyncRequest':
case 'hangingSync':
$p = '_' . $property;
return $this->$p;
}
throw new InvalidArgumentException('Unknown property: ' . $property);
}
/**
* Property setter.
*/
public function __set($property, $value)
{
switch ($property) {
case 'importedChanges':
case 'shortSyncRequest':
case 'hangingSync':
$p = '_' . $property;
$this->$p = $value;
return;
case 'lasthbsyncstarted':
case 'lastsyncendnormal':
case 'hbinterval':
case 'wait':
$this->_cache->$property = $value;
return;
case 'confirmed_synckeys':
throw new InvalidArgumentException($property . ' is READONLY.');
}
throw new InvalidArgumentException('Unknown property: ' . $property);
}
/**
* Get a new collection array, populated with default values.
*
* @return array
*/
public function getNewCollection()
{
return array(
'truncation' => Horde_ActiveSync::TRUNCATION_ALL,
'clientids' => array(),
'fetchids' => array(),
'windowsize' => 100,
'conflict' => Horde_ActiveSync::CONFLICT_OVERWRITE_PIM,
'bodyprefs' => array(),
'mimesupport' => Horde_ActiveSync::MIME_SUPPORT_NONE,
'mimetruncation' => Horde_ActiveSync::TRUNCATION_8,
);
}
/**
* Add a new populated collection array to the sync cache.
*
* @param array $collection The collection array.
* @param boolean $requireSyncKey Attempt to read missing synckey from
* cache if true. If not found, set to 0.
*/
public function addCollection(array $collection, $requireSyncKey = false)
{
if ($requireSyncKey && empty($collection['synckey'])) {
$cached_collections = $this->_cache->getCollections(false);
$collection['synckey'] = !empty($cached_collections[$collection['id']])
? $cached_collections[$collection['id']]['lastsynckey']
: 0;
if ($collection['synckey'] === 0) {
$this->_logger->err(sprintf('[%s] Attempting to add a collection
to the sync cache while requiring a synckey, but no
synckey could be found. Most likely a client error in
requesting a collection during PING before it has issued a
SYNC.', $this->_procid));
throw new Horde_ActiveSync_Exception_StateGone('Synckey required in Horde_ActiveSync_Collections::addCollection, but none was found.');
}
$this->_logger->info(sprintf(
'[%s] Obtained synckey for collection %s from cache: %s',
$this->_procid, $collection['id'], $collection['synckey']));
}
// Load the class if needed for EAS >= 12.1 and ensure we have the
// backend folder id.
if (empty($collection['class'])) {
$collection['class'] = $this->getCollectionClass($collection['id']);
}
try {
$collection['serverid'] = $this->getBackendIdForFolderUid($collection['id']);
} catch (Horde_ActiveSync_Exception $e) {
throw new Horde_ActiveSync_Exception_StateGone($e->getMessage());
}
$this->_collections[$collection['id']] = $collection;
$this->_logger->info(sprintf(
'[%s] Collection added to collection handler: collection: %s, synckey: %s.',
$this->_procid,
$collection['serverid'],
!empty($collection['synckey']) ? $collection['synckey'] : 'NONE'));
}
/**
* Translate an EAS folder uid into a backend serverid.
*
* @param $id The uid.
*
* @return string The backend server id.
* @throws Horde_ActiveSync_Exception
*/
public function getBackendIdForFolderUid($folderid)
{
// Always use RI for recipient cache.
if ($folderid == 'RI') {
return $folderid;
}
$folder = $this->_cache->getFolder($folderid);
if ($folder) {
return $folder['serverid'];
} else {
$this->_logger->err(
sprintf('[%s] Horde_ActiveSync_Collections::getBackendIdForFolderUid failed because folder was not found in cache.',
$this->_procid));
throw new Horde_ActiveSync_Exception('Folder not found in cache.');
}
}
/**
* Translate a backend id E.g., INBOX into an EAS folder uid.
*
* @param string $folderid The backend id.
*
* @return string The EAS uid.
*/
public function getFolderUidForBackendId($folderid)
{
// Always use 'RI' for Recipient cache.
if ($folderid == 'RI') {
return $folderid;
}
$map = $this->_as->state->getFolderUidToBackendIdMap();
if (empty($map[$folderid])) {
return false;
}
return $map[$folderid];
}
/**
* Return the count of available collections.
*
* @return integer
*/
public function collectionCount()
{
return count($this->_collections);
}
/**
* Return the count of collections in the cache only.
*
* @return integer
*/
public function cachedCollectionCount()
{
return $this->_cache->countCollections();
}
/**
* Set the getchanges flag on the specified collection.
*
* @param string $collection_id The collection id.
*
* @throws Horde_ActiveSync_Exception
*/
public function setGetChangesFlag($collection_id)
{
if (empty($this->_collections[$collection_id])) {
throw new Horde_ActiveSync_Exception('Missing collection data');
}
$this->_collections[$collection_id]['getchanges'] = true;
}
/**
* Get the getchanges flag on the specified collection.
*
* @param string $collection_id The collection id.
*
* @return boolean
* @throws Horde_ActiveSync_Exception
*/
public function getChangesFlag($collection_id)
{
if (empty($this->_collections[$collection_id])) {
throw new Horde_ActiveSync_Exception('Missing collection data');
}
return !empty($this->_collections[$collection_id]['getchanges']);
}
/**
* Sets the default WINDOWSIZE.
*
* Note that this is really a ceiling on the number of TOTAL responses
* that can be sent (including all collections). This method should be
* renamed for 3.0
*
* @param integer $window The windowsize
*/
public function setDefaultWindowSize($window)
{
$this->_globalWindowSize = $window;
}
public function getDefaultWindowSize()
{
return $this->_globalWindowSize;
}
/**
* Validates the collection data from the syncCache, filling in missing
* values from the folder cache.
*/
public function validateFromCache()
{
$this->_cache->validateCollectionsFromCache($this->_collections);
}
/**
* Updates data from the cache for collectons that are already loaded. Used
* to ensure looping SYNC and PING requests are operating on the most
* recent syncKey.
*/
public function updateCollectionsFromCache()
{
$this->_cache->refreshCollections();
$collections = $this->_cache->getCollections();
foreach (array_keys($this->_collections) as $id) {
if (!empty($collections[$id])) {
$this->_logger->info(sprintf(
'[%s] Refreshing %s from the cache.',
$this->_procid, $id));
$this->_collections[$id] = $collections[$id];
}
}
}
/**
* Return a collection class given the collection id.
*
* @param string $id The collection id.
*
* @return string|boolean The collection class or false if not found.
*/
public function getCollectionClass($id)
{
if ($id == 'RI') {
return $id;
}
if (isset($this->_cache->folders[$id]['class'])) {
$class = $this->_cache->folders[$id]['class'];
$this->_logger->info(sprintf(
'[%s] Obtaining collection class of %s for collection id %s',
$this->_procid, $class, $id));
return $class;
}
return false;
}
/**
* Determine if we have any syncable collections either locally or in the
* sync cache.
*
* @param long $version The EAS version
*
* @return boolean
*/
public function haveSyncableCollections($version)
{
// Ensure we have syncable collections, using the cache if needed.
if ($version >= Horde_ActiveSync::VERSION_TWELVEONE && empty($this->_collections)) {
$this->_logger->info('No collections - looking in sync_cache.');
$found = false;
foreach ($this->_cache->getCollections() as $value) {
if (isset($value['synckey'])) {
$this->_logger->info(sprintf(
'[%s] Found a syncable collection: %s : %s. Adding it to the collections object.',
$this->_procid, $value['serverid'], $value['synckey']));
$this->_collections[$value['id']] = $value;
$found = true;
}
}
return $found;
} elseif (empty($this->_collections)) {
return false;
}
$this->_logger->info('Have syncable collections');
return true;
}
/**
* Set the looping sync heartbeat values.
*
* @param array $hb An array containing one or both of: hbinterval, wait.
*/
public function setHeartbeat(array $hb)
{
if (isset($hb['wait'])) {
$this->_cache->wait = $hb['wait'];
}
if (isset($hb['hbinterval'])) {
$this->_cache->hbinterval = $hb['hbinterval'];
}
}
/**
* Return the heartbeat interval. Always returned as the heartbeat (seconds)
* not wait interval (minutes).
*
* @return integer|boolean The number of seconds in a heartbeat, or false
* if no heartbeat set.
*/
public function getHeartbeat()
{
return !empty($this->_cache->hbinterval)
? $this->_cache->hbinterval
: (!empty($this->_cache->wait)
? $this->_cache->wait * 60
: false);
}
/**
* Return whether or not we want a looping sync. We can do a looping sync
* if we have no imported changes AND we have either a hbinterval, wait,
* or a shortSync.
*
* @return boolean True if we want a looping sync, false otherwise.
*/
public function canDoLoopingSync()
{
return $this->_hangingSync && !$this->_importedChanges && ($this->_shortSyncRequest || $this->_cache->hbinterval !== false || $this->_cache->wait !== false);
}
/**
* Return if the current looping sync is stale. A stale looping sync is one
* which has begun earlier than the most recently running sync reported by
* the syncCache.
*
* @return boolean True if the current looping sync is stale. False
* otherwise.
*/
public function checkStaleRequest()
{
return !$this->_cache->validateCache(true);
}
/**
* Return if we have a current folder hierarchy.
*
* @return boolean
*/
public function haveHierarchy()
{
return isset($this->_cache->hierarchy);
}
/**
* Prepare for a hierarchy sync.
*
* @param string $synckey The current synckey from the client.
*
* @return array An array of known folders.
*/
public function initHierarchySync($synckey)
{
$this->_as->state->loadState(
array(),
$synckey,
Horde_ActiveSync::REQUEST_TYPE_FOLDERSYNC);
// Refresh the cache since it might have changed like e.g., if synckey
// was empty.
$this->_cache->loadCacheFromStorage();
return $this->_as->state->getKnownFolders();
}
/**
* Update/Add a folder in the hierarchy cache.
*
* @param Horde_ActiveSync_Message_Folder $folder The folder object.
* @param boolean $update Update the state objects? @since 2.4.0
*/
public function updateFolderinHierarchy(
Horde_ActiveSync_Message_Folder $folder, $update = false)
{
$this->_cache->updateFolder($folder);
$cols = $this->_cache->getCollections(false);
$cols[$folder->serverid]['serverid'] = $folder->_serverid;
$this->_cache->updateCollection($cols[$folder->serverid]);
if ($update) {
$this->_as->state->updateServerIdInState($folder->serverid, $folder->_serverid);
}
}
/**
* Delete a folder from the hierarchy cache.
*
* @param string $id The folder's uid.
*/
public function deleteFolderFromHierarchy($uid)
{
$this->_cache->deleteFolder($uid);
$this->_as->state->removeState(array(
'id' => $uid,
'devId' => $this->_as->device->id,
'user' => $this->_as->device->user));
}
/**
* Return all know hierarchy changes.
*
* @return array An array of changes.
*/
public function getHierarchyChanges()
{
return $this->_as->state->getChanges();
}
/**
* Validate and perform some sanity checks on the hierarchy changes before
* being sent to the client.
*
* @param Horde_ActiveSync_Connector_Exporter $exporter The exporter.
* @param array $seenFolders An array of folders.
*/
public function validateHierarchyChanges(Horde_ActiveSync_Connector_Exporter $exporter, array $seenFolders)
{
if ($this->_as->device->version < Horde_ActiveSync::VERSION_TWELVEONE ||
count($exporter->changed)) {
return;
}
// Remove unnecessary changes.
foreach ($exporter->changed as $key => $folder) {
if (isset($folder->serverid) &&
$syncFolder = $this->_cache->getFolder($folder->serverid) &&
in_array($folder->serverid, $seenfolders) &&
$syncFolder['parentid'] == $folder->parentid &&
$syncFolder['displayname'] == $folder->displayname &&
$syncFolder['type'] == $folder->type) {
$this->_logger->info(sprintf(
'[%s] Ignoring %s from changes because it contains no changes from device.',
$this->_procid,
$folder->serverid)
);
unset($exporter->changed[$key]);
$exporter->count--;
}
}
// Remove unnecessary deletions.
foreach ($exporter->deleted as $key => $folder) {
if (($sid = array_search($folder, $seenfolders)) === false) {
$this->_logger->info(sprintf(
'[%s] Ignoring %s from deleted list because the device does not know it',
$this->_procid,
$folder)
);
unset($exporter->deleted[$key]);
$exporter->count--;
}
}
}
/**
* Update the hierarchy synckey in the cache.
*
* @param string $key The new/existing synckey.
*/
public function updateHierarchyKey($key)
{
$this->_cache->hierarchy = $key;
}
/**
* Prepares the syncCache for a full sync request.
*/
public function initFullSync()
{
$this->_cache->confirmed_synckeys = array();
$this->_cache->clearCollectionKeys();
}
/**
* Prepares the syncCache for a partial sync request and checks that
* it is allowed.
*
* @return boolean True if parital sync is possible, false otherwise.
*/
public function initPartialSync()
{
if (empty($this->_collections)) {
$this->_logger->err('No collections in collection handler, no PARTIAL allowed.');
return false;
}
$this->_tempSyncCache = clone $this->_cache;
$c = $this->_tempSyncCache->getCollections();
foreach ($this->_collections as $key => $value) {
// Collections from cache might not all have synckeys.
if (!empty($c[$key])) {
$v1 = $value;
foreach ($v1 as $k => $o) {
if (is_null($o)) {
unset($v1[$k]);
}
}
unset($v1['id'], $v1['serverid'], $v1['clientids'], $v1['fetchids'],
$v1['getchanges'], $v1['changeids'], $v1['pingable'],
$v1['class'], $v1['synckey'], $v1['lastsynckey']);
$v2 = $c[$key];
foreach ($v2 as $k => $o) {
if (is_null($o)) {
unset($v2[$k]);
}
}
unset($v2['id'], $v2['serverid'], $v2['pingable'], $v2['class'], $v2['synckey'], $v2['lastsynckey']);
ksort($v1);
if (isset($v1['bodyprefs'])) {
ksort($v1['bodyprefs']);
foreach (array_keys($v1['bodyprefs']) as $k) {
if (is_array($v1['bodyprefs'][$k])) {
ksort($v1['bodyprefs'][$k]);
}
}
}
ksort($v2);
if (isset($v2['bodyprefs'])) {
ksort($v2['bodyprefs']);
foreach (array_keys($v2['bodyprefs']) as $k) {
if (is_array($v2['bodyprefs'][$k])) {
ksort($v2['bodyprefs'][$k]);
}
}
}
if (md5(serialize($v1)) == md5(serialize($v2))) {
$this->_unchangedCount++;
}
// Unset in tempSyncCache, since we have it from device.
// Afterwards, anything left in tempSyncCache needs to be
// added to _collections.
$this->_tempSyncCache->removeCollection($key);
// Remove keys from confirmed synckeys array and count them
if (isset($value['synckey'])) {
if (isset($this->_cache->confirmed_synckeys[$value['synckey']])) {
$this->_logger->info(sprintf(
'Removed %s from confirmed_synckeys',
$value['synckey'])
);
$this->_cache->removeConfirmedKey($value['synckey']);
$this->_confirmedCount++;
}
$this->_synckeyCount++;
}
}
}
$csk = $this->_cache->confirmed_synckeys;
if ($csk) {
$this->_logger->info(sprintf(
'[%s] Confirmed Synckeys contains %s',
$this->_procid,
serialize($csk))
);
$this->_logger->err('Some synckeys were not confirmed. Requesting full SYNC');
$this->save();
return false;
}
if ($this->_haveNoChangesInPartialSync()) {
$this->_logger->warn(sprintf(
'[%s] Partial Request with completely unchanged collections. Request a full SYNC',
$this->_procid));
return false;
}
return true;
}
/**
* Return if we can do an empty response
*
* @return boolean
*/
public function canSendEmptyResponse()
{
return !$this->_importedChanges &&
($this->_hangingSync && ($this->_cache->wait !== false || $this->_cache->hbinterval !== false));
}
/**
* Return if we have no changes, but have requested a partial sync. A
* partial sync must have either a wait, hbinterval, or some subset of
* collections to be valid.
*
* @return boolean
*/
protected function _haveNoChangesInPartialSync()
{
return $this->_synckeyCount > 0 &&
$this->_unchangedCount == $this->_synckeyCount &&
$this->_cache->wait == false && $this->_cache->hbinterval == false;
}
/**
* Populate the collections data with missing data from the syncCache.
*/
public function getMissingCollectionsFromCache()
{
if (empty($this->_tempSyncCache)) {
throw new Horde_ActiveSync_Exception('Did not initialize the PARTIAL sync.');
}
// Update _collections with all data that was not sent, but we
// have a synckey for in the sync_cache.
foreach ($this->_tempSyncCache->getCollections() as $value) {
// The collection might have been updated due to incoming
// changes. Some clients send COMMANDS in a PARTIAL sync and
// initializing the PARTIAL afterwards will overwrite the various
// flags stored in $collection['id'][]
if (!empty($this->_collections[$value['id']])) {
continue;
}
$this->_logger->info(sprintf(
'Using SyncCache State for %s',
$value['serverid']
));
if (empty($value['synckey'])) {
$value['synckey'] = $value['lastsynckey'];
}
$this->_collections[$value['id']] = $value;
}
}
/**
* Check for an update FILTERTYPE
*
* @param string $id The collection id to check
* @param string $filter The new filter value.
*
* @return boolean True if filtertype passed, false if it has changed.
*/
public function checkFilterType($id, $filter)
{
$cc = $this->_cache->getCollections();
if (!empty($cc[$id]['filtertype']) &&
!is_null($filter) &&
$cc[$id]['filtertype'] != $filter) {
$this->_cache->removeCollection($id, true);
$this->_cache->save();
$this->_logger->info('Invalidating SYNCKEY and removing collection - found updated filtertype');
return false;
}
return true;
}
/**
* Update the syncCache with current collection data.
*/
public function updateCache()
{
foreach ($this->_collections as $value) {
$this->_cache->updateCollection($value);
}
}
/**
* Save the syncCache to storage.
*/
public function save()
{
$this->_cache->save();
}
/**
* Attempt to initialize the sync state.
*
* @param array $collection The collection array.
* @param boolean $requireSyncKey Require collection to have a synckey and
* throw exception if it's not present.
*
* @throws Horde_ActiveSync_Exception_InvalidRequest
*/
public function initCollectionState(array $collection, $requireSyncKey = false)
{
// Clear the changes cache.
$this->_changes = null;
if (empty($collection['class'])) {
if (!empty($this->_collections[$collection['id']])) {
$collection['class'] = $this->_collections[$collection['id']]['class'];
} else {
throw new Horde_ActiveSync_Exception_FolderGone('Could not load collection class for ' . $collection['id']);
}
}
// Get the backend serverid.
if (empty($collection['serverid'])) {
$f = $this->_cache->getFolder($collection['id']);
$collection['serverid'] = $f['serverid'];
}
if ($requireSyncKey && empty($collection['synckey'])) {
throw new Horde_ActiveSync_Exception_InvalidRequest(sprintf(
'[%s] Empty synckey for %s.',
$this->_procid, $collection['id']));
}
// Initialize the state
$this->_logger->info(sprintf(
'[%s] Initializing state for collection: %s, synckey: %s',
$this->_procid,
$collection['serverid'],
$collection['synckey']));
$this->_as->state->loadState(
$collection,
$collection['synckey'],
Horde_ActiveSync::REQUEST_TYPE_SYNC,
$collection['id']);
}
/**
* Poll the backend for changes.
*
* @param integer $heartbeat The heartbeat lifetime to wait for changes.
* @param integer $interval The wait interval between poll iterations.
* @param array $options An options array containing any of:
* - pingable: (boolean) Only poll collections with the pingable flag set.
* DEFAULT: false
*
* @return boolean|integer True if changes were detected in any of the
* collections, false if no changes detected
* or a status code if failed.
*/
public function pollForChanges($heartbeat, $interval, array $options = array())
{
$dataavailable = false;
$started = time();
$until = $started + $heartbeat;
$this->_logger->info(sprintf(
'Waiting for changes for %s seconds',
$heartbeat)
);
// If pinging, make sure we have pingable collections. Note we can't
// filter on them here because the collections might change during the
// loop below.
if (!empty($options['pingable']) && !$this->havePingableCollections()) {
$this->_logger->err('No pingable collections.');
return self::COLLECTION_ERR_SERVER;
}
// Need to update AND SAVE the timestamp for race conditions to be
// detected.
$this->lasthbsyncstarted = $started;
$this->save();
while (($now = time()) < $until) {
// Try not to go over the heartbeat interval.
if ($until - $now < $interval) {
$interval = $until - $now;
}