-
Notifications
You must be signed in to change notification settings - Fork 0
/
HqSync.inc.php
1479 lines (1311 loc) · 43.6 KB
/
HqSync.inc.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
/**
* Cause all errors to throw exceptions
*/
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
/**
* Used to replace ugly characters in table names.
*/
function replaceUglyCharacters($subject) {
return str_replace(array('#','|','.'), '', $subject);
}
/**
* CURL constants for HqSyncFactory::fetchExportFromServer()
*/
define('HQSYNC_CURL_SUCCESS', 1);
/**
* Constants for the outcome of a sync operation
*/
define('HQSYNC_STATUS_SUCCESSFUL_IMPORT', 100);
define('HQSYNC_STATUS_EMPTY_EXPORT', 200);
define('HQSYNC_STATUS_ERROR', -100);
/**
* Return values for HqSyncFactory::getExportDiff()
*/
define('HQSYNC_DIFF_NONE', 0); // no difference between csv columns and db columns
define('HQSYNC_DIFF_COLUMN_MISMATCH', 1); // column names in csv do not match column names in db
define('HQSYNC_DIFF_TABLE_MISSING', 2); // db table does not exist
/**
* Command line argument states.
*/
define('HQSYNC_ARGS_VALUE_REQUIRED', 1);
define('HQSYNC_ARGS_VALUE_OPTIONAL', 2);
define('HQSYNC_ARGS_VALUE_NOT_ALLOWED', 3);
/**
* Zip error constant. For some reason, these have to be defined manually.
*/
define('ZIP_ER_NOZIP', 19);
/**
* class HqSyncTable
*
* @author Jonathan Payne <[email protected]>
* @updated 31-Aug-2011
* @version 1.0
*/
class HqSyncTable
{
public $hqsync_table_id;
public $hqsync_id;
public $filename;
public $tablename;
public $include_in_import;
private $arr_field = array();
/**
* Constructor
*/
public function __construct($hqsync_table_id=null, $hqsync_id=null,
$filename='', $tablename='', $include_in_import=null)
{
$this->hqsync_table_id = $hqsync_table_id;
$this->hqsync_id = $hqsync_id;
$this->filename = $filename;
$this->tablename = $tablename;
$this->include_in_import = $include_in_import;
}
/**
* Set the array of fields names stored in this CSV file
*
* @param array Array of field names
* @return none
*/
public function setFields(array $arr_field) {
$this->arr_field = $arr_field;
}
/**
* Get array of field names stored in this CSV file
*
* @return array Array of field names
*/
public function getFields() {
return $this->arr_field;
}
}
/**
* class HqSyncCsvFile
*
* @author Jonathan Payne <[email protected]>
* @updated 31-Aug-2011
* @version 1.0
*/
class HqSyncCsvFile
{
/**
* Full pathname of the csv file
* @type string
*/
public $pathname;
/**
* Filename of the csv file
* @type string
*/
public $filename;
/**
* Array of field names extracted from the first line of the csv file.
* @type array
*/
private $arr_field = array();
/**
* Constructor
*
* @param string $pathname
* @param string $filename
*/
public function __construct($pathname, $filename) {
$this->pathname = $pathname;
$this->filename = $filename;
}
/**
* Set the array of fields names stored in this CSV file
*
* @param array Array of field names
* @return none
*/
public function setFields(array $arr_field) {
$this->arr_field = $arr_field;
}
/**
* Get array of field names stored in this CSV file
*
* @return array Array of field names
*/
public function getFields() {
return $this->arr_field;
}
}
/**
* class HqSync
*
* @author Jonathan Payne <[email protected]>
* @updated 31-Aug-2011
* @version 1.0
*/
class HqSync
{
/**
* Variables that correspond with database fields in HqSync
*/
public $hqsync_id;
public $domain;
public $dbname;
public $url;
public $form_name;
public $curl_uid;
public $curl_pwd;
public $use_token;
/**
* If true, all database tables related to the HQSync object are truncated before doing the import.
* This is useful for pulling report data rather than sequential submissions.
*/
public $purge_before_import;
/**
* The token of the most import. Retrieved from the hqsync_log table. Not loaded and
* not applicable if HqSync::use_token set to false. If HqSync::ignore_input_token is
* true, then the input token is still loaded. See description for
* HqSync::ignore_input_token for details.
* @type string
*/
public $input_token;
/**
* Whether the input token should be used during a fetch operation. Turning this off
* causes HqSyncFactory to fetch the entire dataset, instead of just new submissions.
* This is used when the underlying data model has changed and the table is dropped and
* rebuilt.
* @type bool
*/
public $ignore_input_token = false;
public $curl_url;
public $curl_result;
public $output_token;
public $header;
public $filename_data;
public $filename_header;
public $curl_info;
/**
* Indicates whether the zip file retrieved from the server is empty. Null if no file retrieved.
* False if retrieved file contains records. True if retrieved file is empty.
*/
private $is_empty_export = null;
private $arr_hqsync_table = array();
private $arr_csv_file = array();
/**
* Array of textstrings that describe events that have taken place on this object.
* @type array
*/
private $arr_log = array();
/**
* Constructor
*/
public function __construct($hqsync_id, $root_path, $domain, $dbname,
$url, $form_name, $curl_uid, $curl_pwd, $use_token, $purge_before_import,
$input_token='')
{
$this->hqsync_id = $hqsync_id;
$this->root_path = $root_path;
$this->domain = $domain;
$this->dbname = $dbname;
$this->url = $url;
$this->form_name = $form_name;
$this->curl_uid = $curl_uid;
$this->curl_pwd = $curl_pwd;
$this->use_token = $use_token;
$this->input_token = $input_token;
$this->purge_before_import = $purge_before_import;
$this->generateFilename();
}
/**
* Generates the filenames for this object based on root_path, domain, and form_name. This is
* called automatically in the constructor, but should be called again if any of the above
* variables are updated.
*
* @return none
*/
public function generateFilename()
{
$this->filename_data = $this->root_path . $this->domain . '/' . $this->domain . '.' .
$this->form_name . '.data.zip';
$this->filename_header = $this->root_path . $this->domain . '/' . $this->domain . '.' .
$this->form_name . '.header.txt';
}
/**
* Returns the client url to use to fetch data from CommCare HQ. If an input_token is set and
* ignore_input_token is false (default), then the token will be used in the request
* parameters to limit the data retrieved to submissions received after the token.
*
* @return string Client url used to fetch data from CommCare HQ
*/
public function getCurlUrl() {
$curl_url = $this->url;
if ($this->use_token && $this->input_token && !$this->ignore_input_token) {
$curl_url .= '&previous_export=' . $this->input_token;
}
return $curl_url;
}
/**
* True if this is a new import, false if a previous import has occurred for this form. If
* a previous import has occurred, HqObject::input_token will have a value.
*
* @return bool
*/
public function isNewImport() {
if ($this->input_token) return false;
return true;
}
/**
* Adds the HqSyncTable to this HqSync object
*
* @param HqSyncTable $hqs_table
* @return none
*/
public function addHqSyncTable(HqSyncTable $hqs_table) {
$this->arr_hqsync_table[$hqs_table->hqsync_table_id] = $hqs_table;
}
/**
* Returns an array of HqSyncTable objects associated with this HqSync object.
*
* @param bool $include_excluded_files (Optional) Whether to include in the return array
* files that have been explicitly excluded at the
* database level (hqsync_table.include_in_import == 0).
* @return array
*/
public function getHqSyncTableArray($include_excluded_files = false)
{
/*
* If excluded files should also be returned, just return the entire array.
*/
if ($include_excluded_files) {
return $this->arr_hqsync_table;
}
/*
* Else, create a new array without the excluded files first and return.
*/
else {
$arr_return = array();
foreach ($this->arr_hqsync_table as $hqs_table) {
if ($hqs_table->include_in_import == 1) {
$arr_return[] = $hqs_table;
}
}
return $arr_return;
}
}
/**
* Clears the HqSyncTable objects from this HqSync object.
*
* @return none
*/
public function clearHqSyncTables() {
$this->arr_hqsync_table = array();
}
/**
* Returns the HqSyncTable object that matches the specified filename or null if it does
* not exist. Set include_excluded_files to true to match tables that have been explicitly
* excluded at the database level (hqsync_table.include_in_import == 0).
*
* @param string $filename The filename to match
* @param bool $include_excluded_files (Optional) Whether to include in the return array
* files that have been explicitly excluded at the
* database level (hqsync_table.include_in_import == 0).
* @return HqSyncTable
*/
public function getHqSyncTableByFilename($filename, $include_excluded_files = false)
{
foreach ($this->arr_hqsync_table as $hqs_table) {
if ($hqs_table->filename == $filename &&
($hqs_table->include_in_import || $include_excluded_files))
{
return $hqs_table;
}
}
return null;
}
/**
* Returns the HqSyncTable object that matches the specified tablename or null if it does
* not exist. Set include_excluded_files to true to match tables that have been explicitly
* excluded at the database level (hqsync_table.include_in_import == 0).
*
* @param string $tablename The table name to match
* @param bool $include_excluded_files (Optional) Whether to include in the return array
* files that have been explicitly excluded at the
* database level (hqsync_table.include_in_import == 0).
* @return HqSyncTable
*/
public function getHqSyncTableByTablename($tablename, $include_excluded_files = false)
{
foreach ($this->arr_hqsync_table as $hqs_table) {
if ($hqs_table->tablename == $tablename &&
($hqs_table->include_in_import || $include_excluded_files))
{
return $hqs_table;
}
}
return null;
}
/**
* Add the HqSyncCsvFile to this object.
*
* @param HqSyncCsvFile $hqs_csv HqSyncCsvFile to add
* @return none
*/
public function addCsvFile(HqSyncCsvFile $hqs_csv) {
$this->arr_csv_file[$hqs_csv->filename] = $hqs_csv;
}
/**
* Get array of HqSyncCsvFile objects
*
* @return array
*/
public function getCsvFileArray() {
return $this->arr_csv_file;
}
/**
* Get the count of HqSyncCsvFile objects
*
* @return int
*/
public function getCsvFileCount() {
return count($this->arr_csv_file);
}
/**
* Get the HqSyncCsvFile object that matches the specified filename or null if it does not exist.
*
* @param string $filename
* @return HqSyncCsvFile
*/
public function getCsvFileByFilename($filename) {
foreach ($this->arr_csv_file as $hqs_csv) {
if ($hqs_csv->filename == $filename) return $hqs_csv;
}
return null;
}
/**
* Returns true if zip file retrieved from the server contains no records.
*
* @return bool
*/
public function isEmptyExport() {
return (bool)$this->is_empty_export;
}
/**
* Sets the is_empty_export flag to the value of is_empty (default=true).
*
* @param bool $is_empty
*/
public function setEmptyExport($is_empty = true) {
$this->is_empty_export = $is_empty;
}
/**
* Add text describing an event that took place on this HqSync object to the log.
*/
public function log($event_desc) {
$this->arr_log[] = $event_desc;
}
/**
* Returns array of strings of logged events that took place on this HqSync object.
* @return array
*/
public function getLogs() {
return $this->arr_log;
}
}
/**
* class HqSyncFactory
*
* Scripts [current_directory]
* Data zip & header [root_path/][domain]/
* Unzipped CSV files [root_path/][domain]/[form_name]/
* Logs ???
*
* @author Jonathan Payne <[email protected]>
* @updated 31-Aug-2011
* @version 1.0
*/
class HqSyncFactory
{
/**
* Name of the primary hqsync database (location of hqsync tables).
* @type string
*/
private $hqsync_dbname;
/**
* Pathname to prepend to all other filenames and pathnames used by methods in this class.
* Must be empty or end in a forward slash.
* @type string
*/
private $root_path;
/**
* Database connection resource
* @type resource
*/
private $conn = null;
/**
* Whether to display debug info
* @type bool
*/
public $debug = false;
/**
* Array of csv filenames to ignore
* @type array
*/
private $arr_csv_ignore_list = array();
/**
* Constructor
*
* @param resource $conn Database connection object
* @param string $hqsync_dbname Name of the database that contains the HQSync database tables
* @param string $root_path Pathname that is prepended to all other filenames and pathnames
* used by methods in this class. Must be empty or end in a forward slash.
*/
public function __construct($conn, $hqsync_dbname, $root_path)
{
$this->conn = $conn;
$this->hqsync_dbname = $hqsync_dbname;
$this->root_path = $root_path;
}
/**
* Set the connection object
*
* @pararm resource $conn
* @return none
*/
public function setConnection($conn) {
$this->conn = $conn;
}
/**
* Get the connection object
*
* @return resource Connection resource
*/
public function getConnection() {
return $this->conn;
}
/**
* Clears the connection object
*
* @return none
*/
public function clearConnection() {
$this->conn = null;
}
/**
* Set the list of CSV filenames to ignore during import.
*
* @param array $arr_csv_ignore_list
* @return none
*/
public function setCsvIgnoreList(array $arr_csv_ignore_list) {
$this->arr_csv_ignore_list = $arr_csv_ignore_list;
}
/**
* Returns list of files to sync from the database using the connection set in this object.
*
* @return array
*/
public function loadHqSyncList($domain = null, $form_name = null)
{
if ($this->debug) echo "\nLoading sync list...\n";
/*
* Load hqsync and token from most recent import
*/
$sql =
'select s.*, ' .
'(' .
'select output_token ' .
'from "' . mysql_escape_string($this->hqsync_dbname) . '".hqsync_log l ' .
'where l.hqsync_id = s.hqsync_id ' .
'and sync_status = ' . HQSYNC_STATUS_SUCCESSFUL_IMPORT .
' order by sync_time desc limit 1' .
') last_success_token, ' .
'(' .
'select sync_time ' .
'from "' . mysql_escape_string($this->hqsync_dbname) . '".hqsync_log l ' .
'where l.hqsync_id = s.hqsync_id ' .
'and sync_status = ' . HQSYNC_STATUS_SUCCESSFUL_IMPORT .
' order by sync_time desc limit 1' .
') last_success_date, ' .
'(' .
'select output_token ' .
'from "' . mysql_escape_string($this->hqsync_dbname) . '".hqsync_log l ' .
'where l.hqsync_id = s.hqsync_id ' .
'and sync_status = ' . HQSYNC_STATUS_EMPTY_EXPORT .
' order by sync_time desc limit 1' .
') last_empty_token, ' .
'(' .
'select sync_time ' .
'from "' . mysql_escape_string($this->hqsync_dbname) . '".hqsync_log l ' .
'where l.hqsync_id = s.hqsync_id ' .
'and sync_status = ' . HQSYNC_STATUS_EMPTY_EXPORT .
' order by sync_time desc limit 1' .
') last_empty_date ' .
'from "' . mysql_escape_string($this->hqsync_dbname) . '".hqsync s ' .
'where s.active = 1';
if ($domain) $sql .= " and domain='" . mysql_escape_string($domain) . "'";
if ($form_name) $sql .= " and form_name='" . mysql_escape_string($form_name) . "'";
if (!($rsc_hqsync = $this->execute_query($sql))) {
trigger_error('Could not query db: ' . mysql_error($this->conn), E_USER_ERROR);
}
$arr_hqs = array();
$hqs = null;
$str_hqsync_id = '';
while ($s = mysql_fetch_assoc($rsc_hqsync))
{
// Determine which token to use
$token = null;
if ($s['last_success_date'] && $s['last_success_token'] &&
$s['last_empty_date' ] && $s['last_empty_token' ])
{
if (strtotime($s['last_success_date']) > strtotime($s['last_empty_date'])) {
$token = $s['last_success_token'];
} else {
$token = $s['last_empty_token'];
}
} elseif ($s['last_success_token']) {
$token = $s['last_success_token'];
} elseif ($s['last_empty_token']) {
$token = $s['last_empty_token'];
}
// Create the hqsync object
$hqs = new HqSync($s['hqsync_id'], $this->root_path, $s['domain'], $s['dbname'],
$s['url'], $s['form_name'], $s['uid'], $s['pwd'], $s['use_token'],
$s['purge_before_import'], $token);
$arr_hqs[$s['hqsync_id']] = $hqs;
if ($str_hqsync_id) $str_hqsync_id .= ',';
$str_hqsync_id .= $s['hqsync_id'];
}
/*
* Load hqsync_table, create HqSyncTable objects, and add to HqSync objects
*/
if ($arr_hqs) {
$sql = 'select * ' .
'from "' . mysql_escape_string($this->hqsync_dbname) . '".hqsync_table ' .
'where hqsync_id in (' . $str_hqsync_id . ')';
if (!($rsc_hqsync_table = $this->execute_query($sql))) {
trigger_error('Could not query db: ' . mysql_error($this->conn), E_USER_ERROR);
}
while ($row = mysql_fetch_assoc($rsc_hqsync_table))
{
if (!isset($arr_hqs[$row['hqsync_id']])) continue;
$hqs = $arr_hqs[$row['hqsync_id']];
// Create the object
$hqs_table = new HqSyncTable($row['hqsync_table_id'], $row['hqsync_id'],
$row['filename'], $row['tablename'], $row['include_in_import']);
// Load field names for this table from the db and store in the HqSyncTable object
// NOTE: It is possible that this table does not exist, so the field list is empty. This
// should be caught by HqSyncFactory::getExportDiff
$sql_fields = 'select column_name from information_schema.columns ' .
'where table_schema=\'' . mysql_escape_string($hqs->dbname) . '\' ' .
'and table_name=\'' . mysql_escape_string($hqs_table->tablename) . '\'';
$rsc_fields = $this->execute_query($sql_fields);
$arr_db_field = array();
while ($row = mysql_fetch_row($rsc_fields)) {
$arr_db_field[] = $row[0];
}
$hqs_table->setFields($arr_db_field);
// Add HqSyncTable to the HqSync object
$hqs->addHqSyncTable($hqs_table);
}
}
return $arr_hqs;
}
/**
* Setups and executes the curl statement to retrieve the export file from CommCareHQ.
* Saves the results of the data download and the header in separate files (filenames are
* automatically set in the HqSync object). The output token is extracted from the
* header and saved in the HqSync object.
*
* @param HqSync $hqs
* @param bool $decompress If true (default), the data file is unzipped
* @param bool $use_input_token If true (default), the input token is used to limit
* the data that is exported from the server. If false,
* all data is exported.
* @return bool TRUE on success; FALSE if an error occurs
*/
public function fetchExportFromServer(HqSync $hqs, $process_export_files = true)
{
if ($this->debug) echo "\nFetching export from server...\n";
/*
* Create domain directory in local file system if not exists
* TODO: Should CSV target directory be set here or in the HqSync object?
*/
$csv_target_directory = $this->root_path . $hqs->domain . '/' . $hqs->form_name;
if (!is_dir($csv_target_directory)) {
if (!mkdir($csv_target_directory, 0777, true)) {
trigger_error('Unable to create directory: \'' . $csv_target_directory . '\'', E_USER_ERROR);
}
}
/*
* Initialize file handlers
*/
$fp_data = fopen($hqs->filename_data, 'w');
$fp_header = fopen($hqs->filename_header, 'w');
if (!$fp_data || !$fp_header) {
trigger_error('Unable to create header and data files. Exiting...', E_USER_ERROR);
}
/*
* Initialize curl
*/
$hqs->curl_url = $hqs->getCurlUrl();
$ch = curl_init($hqs->curl_url);
curl_setopt($ch, CURLOPT_FILE, $fp_data);
curl_setopt($ch, CURLOPT_WRITEHEADER, $fp_header);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($ch, CURLOPT_USERPWD, $hqs->curl_uid . ':' . $hqs->curl_pwd);
if ($this->debug) {
echo "\nInput token: " . $hqs->input_token . "\n";
echo "Curl url: " . $hqs->curl_url . "\n";
}
/*
* Execute curl and get additional info.
*/
$hqs->curl_result = curl_exec($ch);
if (!$hqs->curl_result) {
trigger_error('Unable to query server', E_USER_ERROR);
}
$hqs->curl_info = curl_getinfo($ch);
/*
* Cleanup
*/
curl_close($ch);
fclose($fp_data);
fclose($fp_header);
/*
* Extract token from the header and decompress the data zip file.
*/
if ($process_export_files) {
$this->processExportFiles($hqs);
}
return $hqs->curl_result;
}
/**
* Processes the export files after they have been downloaded. This includes extracting the
* token from the header text file and unzipping the csv files.
*
* @param HqSync $hqs
* @return none
*/
public function processExportFiles(HqSync $hqs)
{
/*
* Extract the token from the header file. The token represents the last record that
* was retrieved from the server so that we only need to fetch new data in the next export.
*/
if ($hqs->use_token) {
$hqs->output_token = $this->extractOutputTokenFromHeader($hqs);
}
/*
* Unzip data file
*/
$this->unzipHqDataExport($hqs);
}
/**
* Extracts the token from the header output of the curl request.
*
* @param HqSync $hqs
* @return none
*/
public function extractOutputTokenFromHeader(HqSync $hqs)
{
$matches = array();
if (!($hqs->header = file_get_contents($hqs->filename_header))) {
trigger_error('Could not read from file \'' . $hqs->filename_header . '\'', E_USER_ERROR);
}
if (preg_match('/X-CommCareHQ-Export-Token: (\w+)/', $hqs->header, $matches)) {
return $matches[1];
}
return '';
}
/**
* Unzips the data file created by HqSyncFactory::performCurl() and adds the corresponding
* HqSyncCsvFile objects to the HqSync object.
*
* TODO: Assumes that there are no directories in the zip file, and will not find files in
* subdirectories if they exist. Need error checking and logging of results for each file
* that is unzipped.
*
* @param HqSync $hqs
* @param none
*/
public function unzipHqDataExport(HqSync &$hqs)
{
if ($this->debug) echo "\nDecompressing export files...\n";
$csv_target_directory = $this->root_path . $hqs->domain . '/' . $hqs->form_name;
$zip = zip_open($hqs->filename_data);
if (is_resource($zip))
{
while ($zip_entry = zip_read($zip))
{
/*
* Get current filename in zip
*/
$current_filename_in_zip = zip_entry_name($zip_entry);
/*
* Skip file if in the ignore list
*/
if (array_search($current_filename_in_zip, $this->arr_csv_ignore_list) !== false) {
if ($this->debug) {
echo "Skipping '$current_filename_in_zip' for " . $hqs->domain .
"." . $hqs->form_name . "\n";
}
continue;
}
/*
* Unzip the file
*/
$csv_target_pathname = $csv_target_directory . '/' . $current_filename_in_zip;
$fp_extract = fopen($csv_target_pathname, 'w');
if ($is_file_unzip_success = zip_entry_open($zip, $zip_entry, 'r')) {
// Do the extraction
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
$is_file_unzip_success = (bool)fwrite($fp_extract, "$buf");
zip_entry_close($zip_entry);
fclose($fp_extract);
}
if (!$is_file_unzip_success) {
trigger_error('Unable to unzip file \'' . $current_filename_in_zip . '\' from zip file \'' .
$hqs->filename_data . '\'', E_USER_ERROR);
}
/*
* Load column names from the csv file
*/
$fp_csv = fopen($csv_target_pathname, 'r');
if (!$fp_csv) {
trigger_error('Could not open CSV file \'' . $pathname . '\'', E_USER_ERROR);
}
$arr_csv_field = fgetcsv($fp_csv);
fclose($fp_csv);
/*
* Create the HqSyncCsvFile object and add to HqSync
*/
$hqs_csv = new HqSyncCsvFile($csv_target_pathname, $current_filename_in_zip);
$hqs_csv->setFields($arr_csv_field);
$hqs->addCsvFile($hqs_csv);
}
zip_close($zip);
return $hqs->getCsvFileCount();
}
/*
* Could not open zip file, so handle the error here. ZIP_ER_NOZIP usually means
* empty file. Anything else, then throw an error.
*/
else {
if ($zip == ZIP_ER_NOZIP) {
$hqs->setEmptyExport();
$hqs->log('Empty export');
if ($this->debug) echo "Empty zip file. No results returned from HQ.\n";
} else {
trigger_error('Zip error #' . $zip . ' occurred. Look at the documentation for details.', E_USER_ERROR);
}
}
return 0;
}
/**
* Returns whether the columns in the csv file match the columns in the corresponding
* database table. Checks both field names and order.
*
* @param HqSyncCsvFile $hqs_csv
* @param HqSyncTable $hqs_table
* @param bool TRUE if columns in csv file match columns in database
* table; FALSE if they do not match.
*/
public function doColumnsMatch(HqSyncCsvFile &$hqs_csv, HqSyncTable &$hqs_table)
{
/*
* Compare the 2 lists (must be exact, including the order); return FALSE if not identical.
* NOTE: array_diff_assoc returns an empty array if array1 and array2 are identical
*/
if (array_diff_assoc($hqs_csv->getFields(), $hqs_table->getFields())) {
return false;
}
return true;
}
/**
* Returns an array of differences between each CSV file returned
* in the HQ export and the corresponding existing database structure for the given HqSync
* object. Possible return values for each csv file are:
* HQSYNC_DIFF_NONE - no difference between csv structure and the existing db structure
* HQSYNC_DIFF_COLUMN_MISMATCH - columns in the csv file do not match columns in the
* corresponding database table
* HQSYNC_DIFF_TABLE_MISSING - there is no corresponding database table for this csv file
*
* @access public
* @param HqSync $hqs
* @return array
*/
public function getExportDiff(HqSync &$hqs)
{
$arr_diff = array();
// Iterate through csv files in the zip file
foreach ($hqs->getCsvFileArray() as $hqs_csv)
{
// Skip the file if in the ignore list
if (array_search($hqs_csv->filename, $this->arr_csv_ignore_list) !== false) {
if ($this->debug) echo "Filename '" . $hqs_csv->filename . "' in the ignore list. Skipping...\n";
continue;
}
// If CSV file has matching entry in hqsync_table
if ($hqs_table = $hqs->getHqSyncTableByFilename($hqs_csv->filename))
{
// If columns in csv file match columns in db
if ($this->doColumnsMatch($hqs_csv, $hqs_table))
{
// indicate in changeset that this file is a complete match
$arr_diff[$hqs_csv->filename] = HQSYNC_DIFF_NONE;
}
// else if columns in csv file do NOT match columns in db
else
{
// indicate in changeset that purge is required
$arr_diff[$hqs_csv->filename] = HQSYNC_DIFF_COLUMN_MISMATCH;
}
}
// Else CSV file does NOT have matching entry in hqsync_table, so create the table
else {
// indicate in changeset to create new table
$arr_diff[$hqs_csv->filename] = HQSYNC_DIFF_TABLE_MISSING;
}
}
return $arr_diff;
}
/**
* Return whether the specified database exists in this connection (for the hqsync user)
*
* @param string $db Database name
* @return bool Whether db exists
*/