forked from cfinke/OSX-Messages-Exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessages-exporter.php
executable file
·1307 lines (1084 loc) · 49.9 KB
/
messages-exporter.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
#!/usr/bin/env php
<?php
# Export Messages conversations to HTML files.
# Enhanced by Garvin Hicking @supergarv https://garv.in
# Based on https://github.com/PeterKaminski09/baskup, which was
# based on https://github.com/kyro38/MiscStuff/blob/master/OSXStuff/iMessageBackup.sh
#
# Basic Usage (see -h output for more):
# $ messages-exporter.php [-o|--output_directory output_directory]
# The path to the directory where the messages should be saved. Save files in the current directory by default.
# [-f|--flush]
# Flushes the existing backup DB.
# [-r|--rebuild]
# Rebuild the HTML files from the existing DB.
define( 'VERSION', 2 );
$options = getopt(
"o:fhrd:t:",
array(
"output_directory:",
"flush",
"help",
"rebuild",
"database:",
"date-start:",
"date-stop:",
"timezone:",
"date-format:",
"no-video-preload",
"summary",
"html-head-template:",
"safe-filenames",
"contact-csv:",
"skip-attachments:",
"progress",
"html-toc-template:",
"html-toc-loop-template:",
"max-messages:"
)
);
if ( isset( $options['h'] ) || isset( $options['help'] ) ) {
echo "Usage: messages-exporter.php [-o|--output_directory /path/to/output/directory] [-f|--flush] [-r|--rebuild] [-d|--database /path/to/chat/database]\n\n"
. " OPTIONS:\n"
. "\n"
. " [-o|--output_directory]\n"
. " A path to the directory where the messages should be saved. Save files in the current directory by default.\n"
. "\n"
. " [-f|--flush]\n"
. " Flushes the existing backup database, essentially starting over from scratch.\n"
. "\n"
. " [-r|--rebuild]\n"
. " Rebuild the HTML files from the existing database.\n"
. "\n"
. " [-d|--database /path/to/chat/database]\n"
. " You can specify an alternate database file if, for example, you're running this script on a backup of chat.db from another machine.\n"
. "\n"
. " [--date-start YYYY-MM-DD]\n"
. " Optionally, specify the first date that should be queried from the Messages database.\n"
. "\n"
. " [--date-stop YYYY-MM-DD]\n"
. " Optionally, specify the last date that should be queried from the Messages database.\n"
. "\n"
. " [-t|--timezone \"America/Los_Angeles\"]\n"
. " Optionally, supply a timezone to use for any dates and times that are displayed. If none is supplied, times will be in UTC. For a list of valid timezones, see https://www.php.net/manual/en/timezones.php\n"
. "\n"
. " [--date-format \"n/j/Y, g:i A\"]\n"
. " Optionally, supply a output dateformat to use. If none is supplied, a date will be shown like \"" . date("n/j/Y, g:i A", time()) . "\". For a list of valid timezones, see https://www.php.net/manual/en/datetime.format.php\n"
. "\n"
. " [--no-video-preload]\n"
. " If set, the HTML markup will include a 'preload=\"none\"' attribute so on larger chats not all video files will be preloaded in a browser\n"
. "\n"
. " [--summary]\n"
. " If set, the script will return a small summary with number of exported messages/chats and possible errors (missing attachments)\n"
. "\n"
. " [--html-head-template /path/to/template/file.html]\n"
. " If set, the script will use the specified filename inside the HTML <head> section. Variable substitution with {{CHAT_TITLE}} is available. Use this to use custom CSS rules or inject i.e. JavaScript\n"
. "\n"
. " [--html-toc-template /path/to/template/file.html]\n"
. " If set, the script will use the specified filename inside the HTML <head> section for the TOC. Variable substitution is available: {{TOC}} for the TOC loop (see below)\n"
. "\n"
. " [--html-toc-loop-template /path/to/template/file.html]\n"
. " If set, the script will use the specified filename inside the HTML TOC. Variable substitution is available: {{FILE}}, {{TITLE}}, {{DATE_FROM}}, {{DATE_TO}}, {{MESSAGE_FROM_BODY}}, {{MESSAGE_TO_BODY}} and {{STATS.xxx}}.\n"
. "\n"
. " [--safe-filenames]\n"
. " If set, directory and filenames will only contain characters from A-Z, no special characters, no spaces.\n"
. "\n"
. " [--contact-csv /path/to/contacts.csv]\n"
. " By default, contacts are matched by several lookup to system files, however a lookup may fail. In this case you can provide a CSV file with two columns \"Number,Name\" (Number can be an eMail address, too) that resolves a iMessage ID to a readable name. The CSV will take precedence over other address books, so you can use it to even override specific contact names that exist. Ensure the CSV file matches your local charset, use comma as separator, UNIX newlines and no enclosing quotes.\n"
. "\n"
. " [--skip-attachments \"all|a,i,v,d\"]\n"
. " When set to \"all\", all attachments will be replaced by a simple placeholder. Can be used if you just care about plaintexts. If no parameters to this is specified, all attachments are skipped. Else you can specify a comma-separated list of characters to each attachment type to skip (a=audio, v=video, i=image, d=document)\n"
. "\n"
. " [--progress]\n"
. " When set, you will get a (simple) progress report while compiling data and output.\n"
. "\n"
. " [--max-messages XX]\n"
. " Debugging: When set, you can specify the maximum of messages to write for each chat; allows easier debugging.\n"
. "\n"
. "";
echo "\n";
die();
}
if ( ! isset( $options['o'] ) && empty( $options['output_directory'] ) ) {
$options['o'] = getcwd();
}
else if ( ! empty( $options['output_directory'] ) ) {
$options['o'] = $options['output_directory'];
}
if ( ! empty( $options['database'] ) ) {
$options['d'] = $options['database'];
}
if ( ! isset( $options['f'] ) && isset( $options['flush'] ) ) {
$options['f'] = true;
}
if ( ! isset( $options['r'] ) && isset( $options['rebuild'] ) ) {
$options['r'] = true;
}
if ( isset( $options['timezone'] ) ) {
$options['t'] = $options['timezone'];
}
if ( isset( $options['o'] ) ) {
$options['o'] = preg_replace( '/^~/', $_SERVER['HOME'], $options['o'] );
}
if ( isset( $options['d'] ) ) {
$options['d'] = preg_replace( '/^~/', $_SERVER['HOME'], $options['d'] );
}
if ( ! isset( $options['date-format'] ) ) {
$options['date-format'] = "n/j/Y, g:i A";
}
if ( ! isset( $options['html-head-template'] ) ) {
$options['html-head-template'] = '
<meta charset="UTF-8">
<title>Conversation: {{CHAT_TITLE}}</title>
<style type="text/css">
body { font-family: "Helvetica Neue", sans-serif; font-size: 10pt; margin: 5px }
p { margin: 0; clear: both; }
.timestamp { text-align: center; color: #8e8e93; font-variant: small-caps; font-weight: bold; font-size: 9pt; }
.byline { text-align: left; color: #8e8e93; font-size: 9pt; padding-left: 1ex; padding-top: 1ex; margin-bottom: 2px; }
img { max-width: 100%; max-height: 50vh}
.message { text-align: left; color: black; border-radius: 8px; background-color: #e1e1e1; padding: 6px; display: inline-block; max-width: 75%; margin-bottom: 5px; float: left; }
.message[data-from="self"] { text-align: right; background-color: #007aff; color: white; float: right;}
.skipped-attachment { background-color: red; padding: 5px }
</style>
';
}
else {
if ( ! file_exists( $options['html-head-template'] ) ) {
die( "Error: The specified HTML head template file does not exist" );
}
$options['html-head-template'] = file_get_contents( $options['html-head-template'] );
}
if ( ! isset( $options['html-toc-template'] ) ) {
$options['html-toc-template'] = '<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>TOC</title>
<style type="text/css">
body { font-family: "Helvetica Neue", sans-serif; font-size: 10pt;}
p { margin: 0; clear: both; }
ul.toc { list-style-type: none; margin: 0; padding: 0}
ul.toc li { border: 1px solid #e1e1e1; margin: 5px; padding: 1ex}
.date_from, .date_to { color: #8e8e93; font-variant: small-caps; font-weight: bold; font-size: 9pt; }
.message_from, .message_to { margin-left: 5px; }
.date_range { display: none }
ul.toc li:hover { background-color: #e1e1e1; }
.stats { color: #8e8e93; font-variant: small-caps; font-style: italic; font-size: 9pt; }
</style>
</head>
<body>
<ul class="toc">
{{TOC}}
</ul>
</body>
</html>';
}
else {
if ( ! file_exists( $options['html-toc-template'] ) ) {
die( "Error: The specified HTML TOC template file does not exist" );
}
$options['html-toc-template'] = file_get_contents( $options['html-toc-template'] );
}
if ( ! isset( $options['html-toc-loop-template'] ) ) {
$options['html-toc-loop-template'] = '
<li>
<div class="toc_link">
<a class="toc_link" href="{{FILE}}" target="chat">{{TITLE}}</a>
</div>
<div class="toc_meta">
<div class="date_from">{{DATE_FROM}}</div>
<div class="message_from">{{MESSAGE_FROM_BODY}}</div>
<div class="date_range">-</div>
<div class="date_to">{{DATE_TO}}</div>
<div class="message_to">{{MESSAGE_TO_BODY}}</div>
<div class="stats">{{STATS.IMAGES}} images, {{STATS.VIDEOS}} videos, {{STATS.AUDIO}} audio, {{STATS.DOCUMENTS}} files</div>
</div>
</li>
';
}
else {
if ( ! file_exists( $options['html-toc-loop-template'] ) ) {
die( "Error: The specified HTML TOC loop template file does not exist" );
}
$options['html-toc-loop-template'] = file_get_contents( $options['html-toc-loop-template'] );
}
$customContactLookup = array();
if ( isset( $options['contact-csv'] ) ) {
if ( ! file_exists( $options['contact-csv'] ) ) {
die( "Error: The specified CSV file does not exist" );
}
$fp = fopen( $options['contact-csv'], 'rb');
ini_set("auto_detect_line_endings", true);
while ($line = fgetcsv( $fp, 0, ',' ) ) {
if ( ! isset( $line[1] ) ) {
die( "Error: The CSV format is invalid. Please check using comma as separator.\n" );
}
$customContactLookup[$line[0]] = $line[1];
}
if ( count( $customContactLookup ) == 0 ) {
die( "Error: The specified CSV file does not seem to contain any data. Please check newlines and proper format.\n" );
}
if ( isset( $options['summary'] ) ) {
echo count($customContactLookup) . " CSV contacts imported.\n";
}
}
$skip_attachments = array(
'audio' => false,
'images' => false,
'videos' => false,
'documents' => false
);
if ( isset ( $options['skip-attachments'] ) ) {
if ( strlen( $options['skip-attachments'] ) === 0 || $options['skip-attachments'] === 'all' ) {
$skip_attachments['audio'] = true;
$skip_attachments['images'] = true;
$skip_attachments['videos'] = true;
$skip_attachments['documents'] = true;
} else {
$parts = explode(',', $options['skip-attachments']);
foreach( $parts AS $part ) {
$part = trim( $part );
switch( strtolower( $part )) {
case 'a':
$skip_attachments['audio'] = true;
break;
case 'i':
$skip_attachments['images'] = true;
break;
case 'v':
$skip_attachments['videos'] = true;
break;
case 'd':
$skip_attachments['documents'] = true;
break;
}
}
}
if ( isset ( $options['summary'] ) ) {
echo "Skipping: \n";
if ( $skip_attachments['audio'] ) {
echo " * Audio attachments\n";
}
if ( $skip_attachments['videos'] ) {
echo " * Video attachments\n";
}
if ( $skip_attachments['images'] ) {
echo " * Images\n";
}
if ( $skip_attachments['documents'] ) {
echo " * Files / Documents\n";
}
}
}
// Regular expression that may be used (when enabled) to transform directories and filenames to ASCII names.
// Anything NON-ASCII will be changed to the safe_filename_replacement (you can use "" to get shorter filenames; multi-char replacements at your own risk
$safe_filename_pattern = '@[^a-zA-Z0-9\.\-_]@';
$safe_filename_replacement = '-';
// Number of characters of messages shown in the TOC index
$index_preview_length = 120;
# Ensure a trailing slash on the output directory.
$options['o'] = rtrim( $options['o'], '/' ) . '/';
if ( ! empty( $options['t'] ) ) {
try {
new DateTimeZone( $options['t'] );
} catch ( Exception $e ) {
file_put_contents('php://stderr', "Invalid timezone identifier: " . $options['t'] . "\n" );
die;
}
date_default_timezone_set( $options['t'] );
$timezone = new DateTimeZone( $options['t'] );
$time_right_now = new DateTime( 'now', $timezone );
$timezone_offset = $timezone->getOffset( $time_right_now );
}
else {
$timezone_offset = 0;
}
# Create the output directory if it doesn't exist.
if ( ! file_exists( $options['o'] ) ) {
mkdir( $options['o'] );
}
$summary = array(
'messages' => 0,
'chats' => 0,
'attachments' => 0,
'images' => 0,
'videos' => 0,
'audio' => 0,
'documents' => 0,
'warnings' => array(
'groupChats' => array(),
'emptyAttachmentFilenames' => array(),
'unknownDates' => 0,
'unknownMessages' => 0,
'filesNotFound' => 0
),
'notices' => array(
'URLPreviews' => 0
),
'start' => microtime(true),
'skipped' => array(
'videos' => 0,
'images' => 0,
'audio' => 0,
'documents' => 0,
'total' => 0
)
);
$progress_total = 0;
$database_file = $options['o'] . 'messages-exporter.db';
if ( ! isset( $options['r'] ) ) {
if ( isset( $options['f'] ) && file_exists( $database_file ) ) {
unlink( $database_file );
}
}
$temporary_db = $database_file;
$temp_db = new SQLite3( $temporary_db );
$temp_db->exec( "CREATE TABLE IF NOT EXISTS messages ( message_id INTEGER PRIMARY KEY, chat_title TEXT, is_attachment INT, attachment_mime_type TEXT, contact TEXT, is_from_me INT, timestamp TEXT, content TEXT, UNIQUE (chat_title, contact, timestamp, content, is_from_me) ON CONFLICT REPLACE )" );
$temp_db->exec( "CREATE INDEX IF NOT EXISTS chat_title_index ON messages (chat_title)" );
$temp_db->exec( "CREATE INDEX IF NOT EXISTS contact_index ON messages (contact)" );
$temp_db->exec( "CREATE INDEX IF NOT EXISTS timestamp_index ON messages (timestamp)" );
$temp_db->exec( "CREATE TABLE IF NOT EXISTS meta ( meta_id INTEGER PRIMARY KEY, meta_key TEXT, meta_value TEXT, UNIQUE (meta_key) ON CONFLICT REPLACE )" );
$previous_version = $temp_db->querySingle( "SELECT meta_value FROM meta WHERE meta_key='version'" );
if ( ! $previous_version ) {
$previous_version = 1;
}
if ( $previous_version < 2 ) {
// In version 2, we switched to timestamp-based attachment filenames. Update all existing attachments that are referenced in a message.
$attachments_statement = $temp_db->prepare( "SELECT * FROM messages WHERE is_attachment=1" );
$attachments = $attachments_statement->execute();
while ( $attachment = $attachments->fetchArray() ) {
$chat_title = $attachment['chat_title'];
$old_attachment_filename = basename( $attachment['content'] );
if ( ! $old_attachment_filename ) {
continue;
}
$new_attachment_filename = date( 'Y-m-d H i s', strtotime( $attachment['timestamp'] ) ) . ' - ' . $old_attachment_filename;
$chat_title_for_filesystem = get_chat_title_for_filesystem( $chat_title );
$attachments_directory = get_attachments_directory( $chat_title_for_filesystem );
if ( file_exists( $attachments_directory . $old_attachment_filename ) && ! file_exists( $attachments_directory . $new_attachment_filename ) ) {
rename( $attachments_directory . $old_attachment_filename, $attachments_directory . $new_attachment_filename );
}
}
}
$version_statement = $temp_db->prepare( "INSERT INTO meta (meta_key, meta_value) VALUES ('version', :meta_value)" );
$version_statement->bindValue( ':meta_value', VERSION, SQLITE3_TEXT );
$version_statement->execute();
$updated_contacts_memo = array();
if ( isset( $options['summary'] ) && isset ( $options['max-messages'] ) && $options['max-messages'] ) {
echo "DEBUGGING: Limiting export amount to max " . $options['max-messages'] . " messages.\n";
}
if ( ! isset( $options['r'] ) ) {
$chat_db_path = $_SERVER['HOME'] . "/Library/Messages/chat.db";
if ( isset( $options['d'] ) ) {
$chat_db_path = $options['d'];
}
if ( ! file_exists( $chat_db_path ) ) {
die( "Error: The file " . $chat_db_path . " does not exist.\n" );
}
if ( isset( $options['summary'] ) ) {
echo "Using database: " . $chat_db_path . "\n";
}
$db = new SQLite3( $chat_db_path, SQLITE3_OPEN_READONLY );
$chats = $db->query( "SELECT * FROM chat" );
if ( isset( $options['progress'] ) ) {
echo "Reading native iMessages...\n";
$total_chats_query = $db->query( "SELECT COUNT(*) AS count FROM chat" );
$total_chats_row = $total_chats_query->fetchArray( SQLITE3_ASSOC );
$progress_total = $total_chats_row['count'];
}
$chat_index = 0;
while ( $row = $chats->fetchArray( SQLITE3_ASSOC ) ) {
$chat_index++;
if ( isset( $options['progress'] ) ) {
progress_output( $chat_index, $progress_total);
}
$guid = $row['guid'];
$chat_id = $row['ROWID'];
$contactArray = explode( ';', $guid );
$contactNumber = array_pop( $contactArray );
$participant_identifiers = array();
$chat_participants_statement = $db->prepare(
"SELECT id FROM handle WHERE ROWID IN (SELECT handle_id FROM chat_handle_join WHERE chat_id=:chat_id)"
);
$chat_participants_statement->bindValue( ':chat_id', $chat_id );
$chat_participants = $chat_participants_statement->execute();
while ( $participant = $chat_participants->fetchArray( SQLITE3_ASSOC ) ) {
$participant_identifiers[] = get_contact_nicename( $participant['id'] );
}
sort( $participant_identifiers );
$chat_title = implode( ", ", $participant_identifiers );
if ( empty( $chat_title ) ) {
$chat_title = $contactNumber;
}
$statement = $db->prepare(
"SELECT
*,
message.ROWID,
message.is_from_me,
message.text,
handle.id as contact,
message.cache_has_attachments,
datetime(message.date/1000000000 + strftime('%s', '2001-01-01 00:00:00'), 'unixepoch', 'localtime') AS date_from_nanoseconds,
datetime(message.date + strftime('%s', '2001-01-01 00:00:00'), 'unixepoch', 'localtime') date_from_seconds
FROM message LEFT JOIN handle ON message.handle_id=handle.ROWID
WHERE message.ROWID IN (SELECT message_id FROM chat_message_join WHERE chat_id=:rowid)" );
$statement->bindValue( ':rowid', $row['ROWID'] );
$messages = $statement->execute();
$message_index = 0;
while ( $message = $messages->fetchArray( SQLITE3_ASSOC ) ) {
$message_index++;
// Debugging: Skip further compilation.
if ( isset ( $options['max-messages'] ) && $options['max-messages'] > 0 && $message_index > $options['max-messages'] ) {
break 1;
}
if ( isset( $options['progress'] ) ) {
progress_output( $chat_index, $progress_total, $message_index);
}
if ( strpos( $chat_title, ', ' ) === false && ! isset( $updated_contacts_memo[ $message['contact'] ] ) ) {
// Get all existing chat names for this contact ID.
// If the contact name has changed, update it for old messages and update the folder and filenames.
$stored_messages_statement = $temp_db->prepare( "SELECT chat_title FROM messages WHERE contact=:contact GROUP BY chat_title" );
$stored_messages_statement->bindValue( ":contact", $message['contact'] );
$stored_messages = $stored_messages_statement->execute();
while ( $stored_message = $stored_messages->fetchArray( SQLITE3_ASSOC ) ) {
if ( $stored_message['chat_title'] === $chat_title ) {
continue;
}
if ( strpos( $stored_message['chat_title'], ', ' ) !== false ) {
// Group chats are tricky. @todo
$summary['warnings']['groupChats'][] = $stored_message['chat_title'];
continue;
}
// If the contact name has changed, update it in old stored messages.
$update_statement = $temp_db->prepare( "UPDATE messages SET chat_title=:new_chat_title WHERE contact=:contact AND chat_title=:old_chat_title" );
$update_statement->bindValue( ":new_chat_title", $chat_title, SQLITE3_TEXT );
$update_statement->bindValue( ":contact", $message['contact'] );
$update_statement->bindValue( ":old_chat_title", $stored_message['chat_title'], SQLITE3_TEXT );
$update_statement->execute();
// Update the folder and filenames.
// For the HTML, we can just delete it, since it gets regenerated.
$old_html_file = get_html_file( get_chat_title_for_filesystem( $stored_message['chat_title'] ) );
if ( file_exists( $old_html_file ) ) {
unlink( $old_html_file );
}
// For the attachments directory, we need to create the new one and move everything from the old one.
$old_attachments_directory = get_attachments_directory( get_chat_title_for_filesystem( $stored_message['chat_title'] ) );
if ( file_exists( $old_attachments_directory ) ) {
$new_attachments_directory = get_attachments_directory( get_chat_title_for_filesystem( $chat_title ) );
if ( ! file_exists( $new_attachments_directory ) ) {
mkdir( $new_attachments_directory );
}
shell_exec( "mv -n " . escapeshellarg( $old_attachments_directory ) . "* " . escapeshellarg( $new_attachments_directory ) );
if ( empty( glob( $old_attachments_directory . "/*" ) ) ) {
// If there were two files with the same filename, keep the one in the old directory.
rmdir( $old_attachments_directory );
}
}
}
$updated_contacts_memo[ $message['contact'] ] = true;
}
// 0xfffc is the Object Replacement Character. Messages uses it as a placeholder for the image attachment, but we can strip it out because we process attachments separately.
$message['text'] = trim( str_replace( '', '', $message['text'] ) );
// Apple switched to storing a nanosecond value in the date field at some point.
// Due to SQLite not being able to handle converting huge timestamp values to dates,
// all dates would have been stored as some time on -1413-03-01, with no way to retrieve
// the original date.
//
// What we can do is check if we've improperly stored the date for this message, and then
// delete the bad record and insert a new record. The "ON CONFLICT REPLACE" clause won't
// do this automatically, because the timestamp is part of the unique index.
//
// Depending on the current environment, date_from_seconds might be right or date_from_nanoseconds might be right.
// If date_from_seconds is right, then this DB shouldn't have been affected by the bug.
// If date_from_nanoseconds is right, then we need to delete any records that used date_from_seconds.
// Or, we can just delete any records that used date_from_seconds anyway, since it'll just be re-inserted in a moment.
//
// If dates are still being stored as seconds (and not nanoseconds), then date_from_nanoseconds will be very close to 978307200 (January 1, 2001).
if ( strtotime( $message['date_from_nanoseconds'] ) - 978307200 < 1000 ) {
$correct_date = $message['date_from_seconds'];
}
else {
$correct_date = $message['date_from_nanoseconds'];
}
if ( ! empty( $options['date-start'] ) && $correct_date < $options['date-start'] . " 00:00:00" ) {
continue;
}
if ( ! empty( $options['date-stop'] ) && $correct_date > $options['date-stop'] . " 23:59:59" ) {
continue;
}
if ( ! empty( $message['text'] ) ) {
if ( $correct_date != $message['date_from_seconds'] ) {
$delete_old_date_statement = $temp_db->prepare(
"DELETE FROM messages
WHERE
chat_title=:chat_title AND "
. ( $message['is_from_me'] ? " is_from_me=1 AND " : " contact=:contact AND is_from_me=0 AND " )
. "timestamp=:timestamp AND
content=:content" );
$delete_old_date_statement->bindValue( ':chat_title', $chat_title, SQLITE3_TEXT );
if ( ! $message['is_from_me'] ) {
$delete_old_date_statement->bindValue( ':contact', $message['contact'], SQLITE3_TEXT );
}
$delete_old_date_statement->bindValue( ':timestamp', $message['date_from_seconds'], SQLITE3_TEXT );
$delete_old_date_statement->bindValue( ':content', $message['text'], SQLITE3_TEXT );
$delete_old_date_statement->execute();
}
$insert_statement = $temp_db->prepare( "INSERT INTO messages (chat_title, contact, is_from_me, timestamp, content) VALUES (:chat_title, :contact, :is_from_me, :timestamp, :content)" );
$insert_statement->bindValue( ':chat_title', $chat_title, SQLITE3_TEXT );
$insert_statement->bindValue( ':contact', $message['contact'], SQLITE3_TEXT );
$insert_statement->bindValue( ':is_from_me', $message['is_from_me'] );
$insert_statement->bindValue( ':timestamp', $correct_date, SQLITE3_TEXT );
$insert_statement->bindValue( ':content', $message['text'], SQLITE3_TEXT );
$insert_statement->execute();
}
// Handle any attachments.
if ( isset( $message['balloon_bundle_id'] ) && 'com.apple.messages.URLBalloonProvider' === $message['balloon_bundle_id'] ) {
// The attachment would just be a URL preview.
$summary['notices']['URLPreviews']++;
continue;
}
if ( $message['cache_has_attachments'] ) {
$attachmentStatement = $db->prepare(
"SELECT
attachment.filename,
attachment.mime_type,
*
FROM message_attachment_join LEFT JOIN attachment ON message_attachment_join.attachment_id=attachment.ROWID
WHERE message_attachment_join.message_id=:message_id"
);
$attachmentStatement->bindValue( ':message_id', $message['ROWID'] );
$attachmentResults = $attachmentStatement->execute();
while ( $attachmentResult = $attachmentResults->fetchArray( SQLITE3_ASSOC ) ) {
if ( $correct_date != $message['date_from_seconds'] ) {
// See the comment above for why we do this DELETE.
$delete_old_date_statement = $temp_db->prepare(
"DELETE FROM messages
WHERE
chat_title=:chat_title AND "
. ( $message['is_from_me'] ? " is_from_me=1 AND " : " contact=:contact AND is_from_me=0 AND " )
. "timestamp=:timestamp AND
content=:content" );
$delete_old_date_statement->bindValue( ':chat_title', $chat_title, SQLITE3_TEXT );
if ( ! $message['is_from_me'] ) {
$delete_old_date_statement->bindValue( ':contact', $message['contact'], SQLITE3_TEXT );
}
$delete_old_date_statement->bindValue( ':timestamp', $message['date_from_seconds'], SQLITE3_TEXT );
$delete_old_date_statement->bindValue( ':content', $attachmentResult['filename'], SQLITE3_TEXT );
$delete_old_date_statement->execute();
}
if ( empty( $attachmentResult['filename'] ) ) {
// Could be something like an Apple Pay request.
// $attachmentResult['attribution_info'] has a hint: bplist00?TnameYbundle-idiApple?Pay_vcom.apple.messages.MSMessageExtensionBalloonPlugin:0000000000:com.apple.PassbookUIService.PeerPaymentMessage...
// @todo
$summary['warnings']['emptyAttachmentFilenames'][] = '#' . $attachmentResult['ROWID'] . ': ' . $attachmentResult['attribution_info'];
}
if ( ! empty( $options['d'] ) ) {
// If we're running on a database that is not the default system DB, the attachments are likely not available,
// and even if there's a filename match, it may not be the correct file. Simply note that there was an attachment
// that is now unavailable.
$insert_statement = $temp_db->prepare( "INSERT INTO messages (chat_title, contact, is_from_me, timestamp, content) VALUES (:chat_title, :contact, :is_from_me, :timestamp, :content)" );
$insert_statement->bindValue( ':chat_title', $chat_title, SQLITE3_TEXT );
$insert_statement->bindValue( ':contact', $message['contact'], SQLITE3_TEXT );
$insert_statement->bindValue( ':is_from_me', $message['is_from_me'] );
$insert_statement->bindValue( ':timestamp', $correct_date, SQLITE3_TEXT );
$insert_statement->bindValue( ':content', '[File unavailable: ' . $attachmentResult['filename'] . ']', SQLITE3_TEXT );
$insert_statement->execute();
}
else {
$insert_statement = $temp_db->prepare( "INSERT INTO messages (chat_title, contact, is_attachment, is_from_me, timestamp, content, attachment_mime_type) VALUES (:chat_title, :contact, 1, :is_from_me, :timestamp, :content, :attachment_mime_type)" );
$insert_statement->bindValue( ':chat_title', $chat_title, SQLITE3_TEXT );
$insert_statement->bindValue( ':contact', $message['contact'], SQLITE3_TEXT );
$insert_statement->bindValue( ':is_from_me', $message['is_from_me'] );
$insert_statement->bindValue( ':timestamp', $correct_date, SQLITE3_TEXT );
$insert_statement->bindValue( ':attachment_mime_type', $attachmentResult['mime_type'], SQLITE3_TEXT );
$insert_statement->bindValue( ':content', $attachmentResult['filename'], SQLITE3_TEXT );
$insert_statement->execute();
}
}
}
}
}
}
if ( isset( $options['progress'] ) ) {
echo "\nNative iMessages prepared, compiling output...\n";
$total_chats_query = $temp_db->query( "SELECT COUNT(*) AS count FROM messages" );
$total_chats_row = $total_chats_query->fetchArray( SQLITE3_ASSOC );
$progress_total = $total_chats_row['count'];
}
$contacts = $temp_db->query( "SELECT chat_title FROM messages GROUP BY chat_title ORDER BY chat_title ASC" );
if ( isset( $options['summary'] ) ) {
echo "Using HTML output directory: " . $options['o'] . "\n";
}
$chat_index = array();
$progress_message_index = 0;
while ( $row = $contacts->fetchArray() ) {
$chat_title = $row['chat_title'];
$chat_title_for_filesystem = get_chat_title_for_filesystem( $chat_title );
$html_file = get_html_file( $chat_title_for_filesystem );
$attachments_directory = get_attachments_directory( $chat_title_for_filesystem );
$conversation_participant_count = substr_count( $chat_title, "," ) + 2;
if ( ! file_exists( $html_file ) ) {
touch( $html_file );
}
$messages_statement = $temp_db->prepare( "SELECT * FROM messages WHERE chat_title=:chat_title ORDER BY timestamp ASC" );
$messages_statement->bindValue( ':chat_title', $chat_title, SQLITE3_TEXT );
$messages = $messages_statement->execute();
$htmlHeadTemplate = $options['html-head-template'];
$summary['chats']++;
// Variable substitution. Supports future enhancements, for now only a single variable
$htmlHeadTemplate = str_replace(
array(
'{{CHAT_TITLE}}',
),
array(
$chat_title
),
$htmlHeadTemplate
);
file_put_contents(
$html_file,
'<!doctype html>
<html>
<head>
' . $htmlHeadTemplate . '
</head>
<body>
' );
$last_time = 0;
$last_participant = null;
$first_message = $last_message = null;
$chat_stats = array(
'videos' => 0,
'images' => 0,
'audio' => 0,
'documents' => 0,
);
while ( $message = $messages->fetchArray() ) {
$progress_message_index++;
if ( isset( $options['progress'] ) ) {
progress_output( $progress_message_index, $progress_total );
}
$summary['messages']++;
$message['this_time'] = strtotime( $message['timestamp'] );
if ( $message['this_time'] < 0 ) {
// There was a bug present from when Apple started storing timestamps as nanoseconds instead of seconds, so the stored
// timestamps were all from the year -1413. There's no way to fix it without re-importing the messages. Sorry.
$message['this_time'] = 0;
$message['timestamp'] = "Unknown Date";
$summary['warnings']['unknownDates']++;
}
if ( $message['this_time'] - $last_time > ( 60 * 60 ) ) {
$last_participant = null;
file_put_contents(
$html_file,
"\t\t\t" . '<p class="timestamp" data-timestamp="' . $message['timestamp'] . '">' . date( $options['date-format'], $message['this_time'] + $timezone_offset ) . '</p><br />' . "\n",
FILE_APPEND
);
}
$last_time = $message['this_time'];
if ( $conversation_participant_count > 2 && ! $message['is_from_me'] && $message['contact'] != $last_participant ) {
$last_participant = $message['contact'];
file_put_contents(
$html_file,
"\t\t\t" . '<p class="byline">' . htmlspecialchars( get_contact_nicename( $message['contact'] ) ) .'</p>' . "\n",
FILE_APPEND
);
}
if ( $message['is_attachment'] ) {
if ( ! file_exists( $attachments_directory ) ) {
mkdir( $attachments_directory );
}
if ( empty( $message['content'] ) ) {
$html_embed = '[Unknown Message]';
$summary['warnings']['unknownMessages']++;
}
else {
// Give the attachment filename a date-based prefix to avoid filename collisions if this backup is ever migrated to another machine.
if ( isset ( $GLOBALS['options']['safe-filenames'] ) ) {
$basename = get_safe_filename( basename( $message['content'] ) );
$attachment_filename = date( 'Y-m-d_H-i-s', strtotime( $message['timestamp'] ) ) . '-' . $basename;
}
else {
$attachment_filename = date( 'Y-m-d H i s', strtotime( $message['timestamp'] ) ) . ' - ' . basename( $message['content'] );
}
$file_to_copy = preg_replace( '/^~/', $_SERVER['HOME'], $message['content'] );
// If the file is no longer available and we didn't previously save it, show "File Not Found".
if ( ! file_exists( $file_to_copy ) && ! file_exists( $attachments_directory . $attachment_filename ) ) {
$html_embed = '[File Not Found: ' . $attachment_filename . ']';
$summary['warnings']['filesNotFound']++;
}
else {
if ( strpos( $message['content'], '.' ) !== false ) {
list( $extension, $filename_base ) = array_map( 'strrev', explode( '.', strrev( basename( $message['content'] ) ), 2 ) );
}
else {
$extension = null;
$filename_base = basename( $message['content'] );
}
$is_skipped_attachment = false;
if (
// We previously saved the attachment but it's no longer available.
( ! file_exists( $file_to_copy ) && file_exists( $attachments_directory . $attachment_filename ) )
||
( file_exists( $attachments_directory . $attachment_filename )
&& sha1_file( $attachments_directory . $attachment_filename ) == sha1_file( $file_to_copy )
&& filesize( $attachments_directory . $attachment_filename ) == filesize( $file_to_copy )
)
) {
// They're the same file. We've probably already run this script on the message that includes this file.
}
else {
$suffix = 1;
// If a file already exists where we want to save this attachment, add a suffix like -1, -2, -3, etc. until we get a unique filename.
// But don't copy the file if the destination file is the same as the one we're copying.
// GH: Bugfix. Sadly there's a problem, because multiple identically named attachments (if an image got resized)
// can exist for the SAME timestamp (if those files were sent at the same time).
// So instead of renaming to a filename like "FullSizeRender-X.jpg" we now also use
// "2021-03-03_22-00-30-FullSizeRender-X.jpg" instead. By keeping the timestamp, the uniqueness
// will be applied on a next run. Before, a file would be renamed to FullSizeRender-X.jpg and then
// everytime the rebuild was executed, a new -X would be created.
$performCopy = true;
while ( file_exists( $attachments_directory . $attachment_filename ) ) {
++$suffix;
if ( isset ( $GLOBALS['options']['safe-filenames'] ) ) {
$basename = get_safe_filename( $filename_base );
$attachment_filename = date( 'Y-m-d_H-i-s', strtotime( $message['timestamp'] ) ) . '-' . $basename . '-' . $suffix;
}
else {
$attachment_filename = date( 'Y-m-d H i s', strtotime( $message['timestamp'] ) ) . ' - ' . $filename_base . '-' . $suffix;
}
if ( $extension ) {
$attachment_filename .= '.' . $extension;
}
// Now perform the same identity check
if (
file_exists( $attachments_directory . $attachment_filename )
&& sha1_file( $attachments_directory . $attachment_filename ) == sha1_file( $file_to_copy )
&& filesize( $attachments_directory . $attachment_filename ) == filesize( $file_to_copy )
) {
// They're the same file. We've probably already run this script on the message that includes this file.
$performCopy = false;
// Abort the while statement; the file exists, but is identical.
break 1;
}
}
if ($performCopy) {
if ( $skip_attachments['images'] && strpos( $message['attachment_mime_type'], 'image' ) === 0 ) {
$summary['skipped']['images']++;
$summary['skipped']['total']++;
$is_skipped_attachment = true;
} else if ( $skip_attachments['videos'] && strpos( $message['attachment_mime_type'], 'video' ) === 0 ) {
$summary['skipped']['videos']++;
$summary['skipped']['total']++;
$is_skipped_attachment = true;
} else if ( $skip_attachments['audio'] && strpos( $message['attachment_mime_type'], 'audio' ) === 0 ) {
$summary['skipped']['audio']++;
$summary['skipped']['total']++;
$is_skipped_attachment = true;
} else if ( $skip_attachments['documents'] ) {
$summary['skipped']['documents']++;
$summary['skipped']['total']++;
$is_skipped_attachment = true;
} else {
copy( $file_to_copy, $attachments_directory . $attachment_filename );
}
$summary['attachments']++;
}
}
$html_embed = '';
if ( strpos( $message['attachment_mime_type'], 'image' ) === 0 ) {
if ( ! $is_skipped_attachment ) {
$html_embed = '<a class="imagelink" href="' . $chat_title_for_filesystem . '/' . $attachment_filename . '" target="_blank"><img loading="lazy" alt="Image" src="' . $chat_title_for_filesystem . '/' . $attachment_filename . '" /></a>';
} else {
$html_embed = '<div class="skipped-attachment">[' . $chat_title_for_filesystem . '/' . $attachment_filename . ']</div>' . "\n";
}
$summary['images']++;
$chat_stats['images']++;
}
else {
if ( strpos( $message['attachment_mime_type'], 'video' ) === 0 ) {
if ( ! $is_skipped_attachment ) {
$html_embed = '<video controls' . ( isset( $options['no-video-preload'] ) ? ' preload="none"' : '') . '><source src="' . $chat_title_for_filesystem . '/' . $attachment_filename . '" type="' . $message['attachment_mime_type'] . '"></video><br />';
}
$summary['videos']++;
$chat_stats['videos']++;
}
else if ( strpos( $message['attachment_mime_type'], 'audio' ) === 0 ) {
if ( ! $is_skipped_attachment ) {
$html_embed = '<audio controls' . ( isset( $options['no-video-preload'] ) ? ' preload="none"' : '') . '><source src="' . $chat_title_for_filesystem . '/' . $attachment_filename . '" type="' . $message['attachment_mime_type'] . '"></audio><br />';
}
$summary['audio']++;
$chat_stats['audio']++;
}
else {
$summary['documents']++;
$chat_stats['documents']++;
}
if ( $is_skipped_attachment ) {
$html_embed .= '<div class="skipped-attachment">[' . $chat_title_for_filesystem . '/' . $attachment_filename . ']</div>' . "\n";
} else {
$html_embed .= '<a class="attachmentlink" href="' . $chat_title_for_filesystem . '/' . $attachment_filename . '" target="_blank">' . htmlspecialchars( $attachment_filename ) . '</a>';
}
}
}
}
file_put_contents(
$html_file,
"\t\t\t" . '<p class="message" data-from="' . ( $message['is_from_me'] ? 'self' : $message['contact'] ) . '" data-timestamp="' . $message['timestamp'] . '" title="' . date( $options['date-format'], $message['this_time'] + $timezone_offset ) . '">' . $html_embed . '</p>',
FILE_APPEND
);
}
else {
file_put_contents(