forked from cfinke/OSX-Messages-Exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessages-exporter.php
executable file
·768 lines (619 loc) · 31 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
#!/usr/bin/env php
<?php
# Export Messages conversations to HTML files.
# 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:p:",
array(
"output_directory:",
"flush",
"help",
"rebuild",
"database:",
"date-start:",
"date-stop:",
"timezone:",
"path-template:",
)
);
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"
. " [-p|--path-template \"%Y-%m-%d - _CHAT_TITLE_\"]\n"
. " Optionally, supply a strftime-style format string to use for the exported chat files. **Use _CHAT_TITLE_ for the name of the chat.** For example, you can separate your chats into yearly files by using `--path-template \"%Y - _CHAT_TITLE_\"` or monthly files by using `--path-template \"%Y-%m - _CHAT_TITLE_\"`. You may also wish to use the date as a suffix so that chats from the same person are all organized together in Finder, in which case you might use `--path-template \"_CHAT_TITLE_ - %Y-%m-%d\"`"
. "\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['path-template'] ) ) {
$options['p'] = $options['path-template'];
}
if ( empty( $options['p'] ) ) {
$options['p'] = '_CHAT_TITLE_';
}
# 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'] );
}
$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['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" );
}
$db = new SQLite3( $chat_db_path, SQLITE3_OPEN_READONLY );
$chats = $db->query( "SELECT * FROM chat" );
while ( $row = $chats->fetchArray( SQLITE3_ASSOC ) ) {
$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();
while ( $message = $messages->fetchArray( SQLITE3_ASSOC ) ) {
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
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();
}
if ( ! $message['contact'] && $message['is_from_me'] ) {
// The ON CONFLICT REPLACE doesn't work in these conditions (at least not for me). Maybe has something to do with the contact column being null...
// So let's manually remove any duplicate rows. This will also clean up any duplicates that have stacked up from previous runs of the script.
$delete_statement = $temp_db->prepare( "DELETE FROM messages WHERE chat_title=:chat_title AND contact IS NULL AND is_from_me=1 AND timestamp=:timestamp AND content=:content" );
$delete_statement->bindValue( ':chat_title', $chat_title, SQLITE3_TEXT );
$delete_statement->bindValue( ':timestamp', $correct_date, SQLITE3_TEXT );
$delete_statement->bindValue( ':content', $message['text'], SQLITE3_TEXT );
$delete_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.
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
}
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();
}
}
}
}
}
}
$messages_statement = $temp_db->prepare( "SELECT * FROM messages ORDER BY timestamp ASC" );
$messages = $messages_statement->execute();
$files_started = array();
while ( $message = $messages->fetchArray() ) {
$conversation_participant_count = substr_count( $message['chat_title'], "," ) + 2;
$chat_title = str_replace(
'_CHAT_TITLE_',
$message['chat_title'],
strftime( $options['p'], strtotime( $message['timestamp'] ) )
);
$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 );
if ( ! isset( $files_started[ $html_file ] ) ) {
touch( $html_file );
file_put_contents(
$html_file,
'<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Conversation: ' . $chat_title . '</title>
<style type="text/css">
body { font-family: "Helvetica Neue", sans-serif; font-size: 10pt; }
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%; }
.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;}
</style>
</head>
<body>
' );
$files_started[ $html_file ]['last_time'] = 0;
$files_started[ $html_file ]['last_participant'] = null;
}
$this_time = strtotime( $message['timestamp'] );
if ( $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.
$this_time = 0;
$message['timestamp'] = "Unknown Date";
}
if ( $this_time - $files_started[ $html_file ]['last_time'] > ( 60 * 60 ) ) {
$files_started[ $html_file ]['last_participant'] = null;
file_put_contents(
$html_file,
"\t\t\t" . '<p class="timestamp" data-timestamp="' . $message['timestamp'] . '">' . date( "n/j/Y, g:i A", $this_time + $timezone_offset ) . '</p><br />' . "\n",
FILE_APPEND
);
}
$files_started[ $html_file ]['last_time'] = $this_time;
if ( $conversation_participant_count > 2 && ! $message['is_from_me'] && $message['contact'] != $files_started[ $html_file ]['last_participant'] ) {
$files_started[ $html_file ]['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]';
}
else {
// Give the attachment filename a date-based prefix to avoid filename collisions if this backup is ever migrated to another machine.
$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 . ']';
}
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'] );
}
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.
while ( file_exists( $attachments_directory . $attachment_filename ) ) {
++$suffix;
$attachment_filename = $filename_base . '-' . $suffix;
if ( $extension ) {
$attachment_filename .= '.' . $extension;
}
}
copy( $file_to_copy, $attachments_directory . $attachment_filename );
}
$html_embed = '';
if ( strpos( $message['attachment_mime_type'], 'image' ) === 0 ) {
$html_embed = '<img src="' . $chat_title_for_filesystem . '/' . $attachment_filename . '" />';
}
else {
if ( strpos( $message['attachment_mime_type'], 'video' ) === 0 ) {
$html_embed = '<video controls><source src="' . $chat_title_for_filesystem . '/' . $attachment_filename . '" type="' . $message['attachment_mime_type'] . '"></video><br />';
}
else if ( strpos( $message['attachment_mime_type'], 'audio' ) === 0 ) {
$html_embed = '<audio controls><source src="' . $chat_title_for_filesystem . '/' . $attachment_filename . '" type="' . $message['attachment_mime_type'] . '"></audio><br />';
}
$html_embed .= '<a href="' . $chat_title_for_filesystem . '/' . $attachment_filename . '">' . 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( "n/j/Y, g:i A", $this_time + $timezone_offset ) . '">' . $html_embed . '</p>',
FILE_APPEND
);
}
else {
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( "n/j/Y, g:i A", $this_time + $timezone_offset ) . '">' . nl2br( htmlspecialchars( trim( $message['content'] ) ) ) . '</p>',
FILE_APPEND
);
}
file_put_contents(
$html_file,
"<br />\n",
FILE_APPEND
);
}
foreach ( $files_started as $html_file => $meta ) {
file_put_contents( $html_file, "\t</body>\n</html>", FILE_APPEND );
}
function get_contact_nicename( $contact_notnice_name ) {
static $contact_nicename_map = array();
if ( ! $contact_notnice_name ) {
return $contact_notnice_name;
}
if ( isset( $contact_nicename_map[ $contact_notnice_name ] ) ) {
return $contact_nicename_map[ $contact_notnice_name ];
}
$contact_nicename_map[ $contact_notnice_name ] = $contact_notnice_name;
// These are SQLite files that are synced with iCloud, I think.
$possible_address_book_db_files = glob( $_SERVER['HOME'] . "/Library/Application Support/AddressBook/Sources/*/AddressBook-v22.abcddb" );
// But check the local contacts DB first.
array_unshift( $possible_address_book_db_files, $_SERVER['HOME'] . "/Library/Application Support/AddressBook/AddressBook-v22.abcddb" );
foreach ( $possible_address_book_db_files as $address_book_db_file ) {
if ( ! file_exists( $address_book_db_file ) ) {
echo $address_book_db_file . " does not exist.\n";
continue;
}
$contacts_db = new SQLite3( $address_book_db_file, SQLITE3_OPEN_READONLY );
if ( strpos( $contact_notnice_name, '@' ) !== false ) {
// Assume an email address.
$nameStatement = $contacts_db->prepare(
"SELECT
ZABCDRECORD.ZFIRSTNAME,
ZABCDRECORD.ZLASTNAME
FROM ZABCDEMAILADDRESS
LEFT JOIN ZABCDRECORD ON ZABCDEMAILADDRESS.ZOWNER=ZABCDRECORD.Z_PK
WHERE
ZABCDEMAILADDRESS.ZADDRESS=:address"
);
$nameStatement->bindValue( ':address', $contact_notnice_name );
$nameResults = $nameStatement->execute();
while ( $nameResult = $nameResults->fetchArray( SQLITE3_ASSOC ) ) {
$name = trim( $nameResult['ZFIRSTNAME'] . ' ' . $nameResult['ZLASTNAME'] );
if ( $name ) {
$contact_nicename_map[ $contact_notnice_name ] = $name;
break 2;
}
}
}
else {
// Assume a phone number.
$forms = array();
$forms[] = $contact_notnice_name;
$forms[] = preg_replace( '/[^0-9]/', '', $contact_notnice_name );
$forms[] = preg_replace( '/[^0-9]/', '', preg_replace( '/^\+1/', '', $contact_notnice_name ) );
$forms = array_unique( $forms );
$phoneNumberStatement = $contacts_db->prepare( "SELECT ZOWNER, ZFULLNUMBER FROM ZABCDPHONENUMBER" );
$phoneNumberResults = $phoneNumberStatement->execute();
while ( $phoneNumberResult = $phoneNumberResults->fetchArray( SQLITE3_ASSOC ) ) {
if (
in_array( $phoneNumberResult['ZFULLNUMBER'], $forms )
|| in_array( preg_replace( '/[^0-9]/', '', $phoneNumberResult['ZFULLNUMBER'] ), $forms )
|| in_array( preg_replace( '/^\+1/', '', preg_replace( '/[^0-9]/', '', $phoneNumberResult['ZFULLNUMBER'] ) ), $forms )
) {
$nameStatement = $contacts_db->prepare(
"SELECT ZABCDRECORD.ZFIRSTNAME, ZABCDRECORD.ZLASTNAME, ZABCDRECORD.ZORGANIZATION FROM ZABCDRECORD WHERE Z_PK = :zowner"
);
$nameStatement->bindValue( ':zowner', $phoneNumberResult['ZOWNER'] );
$nameResults = $nameStatement->execute();
while ( $nameResult = $nameResults->fetchArray( SQLITE3_ASSOC ) ) {
$name = trim( $nameResult['ZFIRSTNAME'] . ' ' . $nameResult['ZLASTNAME'] );
if ( $nameResult['ZORGANIZATION'] ) {
if ( ! $name ) {
$name = $nameResult['ZORGANIZATION'];
}
else {
$name .= ' (' . $nameResult['ZORGANIZATION'] . ')';
}
}
if ( $name ) {
$contact_nicename_map[ $contact_notnice_name ] = $name;
break 3;
}
}
}
}
}
}
return $contact_nicename_map[ $contact_notnice_name ];
}
function get_chat_title_for_filesystem( $chat_title ) {
$chat_title_for_filesystem = $chat_title;
// Mac OSX has a 255-char filename limit, so if the number of contacts in a chat
// would push the filenames past 255 chars, truncate the filename and add an identifier
// to ensure that another chat with the same initial list of contacts doesn't overlap
// with it.
// Colon and slash are prohibited in filenames on Mac.
$chat_title_for_filesystem = str_replace( array( ":", "/" ), "-", $chat_title_for_filesystem );
if ( strlen( $chat_title_for_filesystem . ".html" ) > 255 ) {
$unique_chat_hash = "{" . md5( $chat_title ) . "}";
// Shorten the filename until there's enough room for the identifying hash and a space.
while ( strlen( $chat_title_for_filesystem . ".html" ) > 255 - 1 - strlen( $unique_chat_hash ) ) {
$chat_title_for_filesystem = explode( " ", $chat_title_for_filesystem );
array_pop( $chat_title_for_filesystem );
$chat_title_for_filesystem = join( " ", $chat_title_for_filesystem );
}
$chat_title_for_filesystem .= " " . $unique_chat_hash;
}
return $chat_title_for_filesystem;
}
function get_html_file( $chat_title_for_filesystem ) {
global $options;
return $options['o'] . $chat_title_for_filesystem . '.html';
}
function get_attachments_directory( $chat_title_for_filesystem ) {
global $options;
return $options['o'] . $chat_title_for_filesystem . '/';
}