forked from telabotanica/ezmlm-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEzmlm.php
2098 lines (1920 loc) · 65.5 KB
/
Ezmlm.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
require_once 'EzmlmInterface.php';
require_once 'auth/AuthAdapter.php';
// composer
require_once 'vendor/autoload.php';
/**
* Library for ezmlm discussion lists management
*/
class Ezmlm implements EzmlmInterface {
/** JSON config */
protected $config = array();
public static $CONFIG_PATH = "config/config.json";
/** ezmlm-idx tools path */
protected $ezmlmIdxPath;
/** Authentication management - must implement interface AuthAdapter */
protected $authAdapter;
/** absolute path of domains root (eg vpopmail's "domains" folder) */
protected $domainsPath;
/** current mailing list domain (eg "my-domain.org") */
protected $domainName;
/** absolute path of current domain @TODO rename not to confuse with $domainsPath ? */
protected $domainPath;
/** current mailing list (eg "my-list") */
protected $listName;
/** absolute path of current mailing list */
protected $listPath;
/** absolute path of cache folder */
protected $cachePath;
/** various settings read from config */
protected $settings;
/** grep binary - a recent version is needed */
protected $grepBinary;
/** "find" binary - might not be found by PHP's exec() shell */
protected $findBinary;
/** abbreviations used by ezmlm-archive */
protected $monthsNumbers = array(
"en" => array(
"jan" => "01",
"feb" => "02",
"mar" => "03",
"apr" => "04",
"may" => "05",
"jun" => "06",
"jul" => "07",
"aug" => "08",
"sep" => "09",
"oct" => "10",
"nov" => "11",
"dec" => "12"
),
"fr" => array(
"jan" => "01",
"fev" => "02",
"mar" => "03",
"avr" => "04",
"mai" => "05",
"jun" => "06",
"jul" => "07",
"aou" => "08",
"sep" => "09",
"oct" => "10",
"nov" => "11",
"dec" => "12"
)
);
public function __construct() {
// config
if (file_exists(self::$CONFIG_PATH)) {
$this->config = json_decode(file_get_contents(self::$CONFIG_PATH), true);
} else {
throw new Exception("file " . self::$CONFIG_PATH . " doesn't exist");
}
// ezmlm-idx tools path configuration
$this->ezmlmIdxPath = $this->config['ezmlm-idx']['binariesPath'];
// authentication adapter / rights management
$this->authAdapter = new AuthAdapter(); // default dummy adapter
// rights management is not mandatory
if (! empty($this->config['authAdapter'])) {
$authAdapterName = $this->config['authAdapter'];
$authAdapterDir = strtolower($authAdapterName);
$authAdapterPath = 'auth/' . $authAdapterDir . '/' . $authAdapterName . '.php';
if (strpos($authAdapterName, "..") != false || $authAdapterName == '' || ! file_exists($authAdapterPath)) {
throw new Exception ("auth adapter " . $authAdapterPath . " doesn't exist");
}
require $authAdapterPath;
// always passing self and config to the auth adapter
$this->authAdapter = new $authAdapterName($this, $this->config['adapters'][$authAdapterName]);
}
// domains path
$this->domainsPath = $this->config['ezmlm']['domainsPath'];
// default domain
$this->setDomain($this->config['ezmlm']['domain']);
// cache path
$this->cachePath = $this->config['cache']['path'];
// various settings
$this->settings = $this->config['settings'];
// binaries location (specific versions might be needed)
$this->grepBinary = "grep";
if (!empty($this->config['system']['grepBinary'])) {
$this->grepBinary = $this->config['system']['grepBinary'];
}
$this->findBinary = "find";
if (!empty($this->config['system']['findBinary'])) {
$this->findBinary = $this->config['system']['findBinary'];
}
}
protected function notImplemented() {
throw new Exception("Method not implemented yet");
}
// ------------------ SYSTEM METHODS --------------------------
/**
* Ensures that a user-given command or argument to a command does not
* threaten security
* @WARNING minimalistic
* @TODO improve !
*/
protected function checkAllowedArgument($arg) {
if (strpos($arg, "..") !== false || strpos($arg, "/") !== false) {
throw new Exception("forbidden command / argument: [$arg]");
}
}
/**
* Runs an ezmlm-idx binary, located in $this->ezmlmIdxPath
* Output parameters are optional to reduce memory consumption
*/
protected function runEzmlmTool($tool, $optionsString, &$stdout=false, &$stderr=false) {
$this->checkAllowedArgument($tool);
// prepare proces opening
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("pipe", "w")
);
// cautiousness
$cwd = '/tmp';
$process = proc_open($this->ezmlmIdxPath . '/' . $tool . ' ' . $optionsString, $descriptorspec, $pipes, $cwd);
if (is_resource($process)) {
// optionally write something to stdin
fclose($pipes[0]);
if ($stdout !== false) {
$stdout = stream_get_contents($pipes[1]);
}
fclose($pipes[1]);
if ($stderr !== false) {
$stderr = stream_get_contents($pipes[2]);
}
fclose($pipes[2]);
// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
$return_value = proc_close($process);
return $return_value;
} else {
throw new Exception('rt(): cound not create process');
}
}
/**
* Run ezmlm-idx tool; convenience method for runEzmlmTool()
* Throws an exception containing stderr if the command returns something
* else that 0; otherwise, returns true if $returnStdout is false (default)
* or returns stdout otherwise
*/
protected function rt($tool, $optionsString, $returnStdout=false) {
$ret = false;
$stdout = $returnStdout;
$stderr = null;
// "smart" call to reduce memory consumption
$ret = $this->runEzmlmTool($tool, $optionsString, $stdout, $stderr);
// catch command error
if ($ret !== 0) {
throw new Exception($stderr);
}
// mixed return
if ($returnStdout) {
return $stdout;
}
return true;
}
// ------------------ UTILITY METHODS -------------------------
/**
* Sets current directory to the current domain directory
*/
protected function chdirToDomain() {
if (! is_dir($this->domainPath)) {
throw new Exception("domain path: cannot access directory [" . $this->domainPath . "]");
}
chdir($this->domainPath);
}
/**
* Returns true if $fileName exists in directory $dir, false otherwise
* @TODO replace by a simple file_exists() provided by PHP ?!
*/
protected function fileExistsInDir($fileName, $dir) {
$dirP = opendir($dir);
$exists = false;
while (($file = readdir($dirP)) && ! $exists) {
$exists = ($exists || ($file == $fileName));
}
return $exists;
}
/*
* Returns true if list $name exists in $this->domainPath domain
*/
protected function listExists($name) {
return is_dir($this->domainPath . '/' . $name);
}
/**
* Throws an exception if $email is not valid, in the
* meaning of PHP's FILTER_VALIDATE_EMAIL
*/
protected function checkValidEmail($email) {
if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new Exception("invalid email address [$email]");
}
}
/**
* Throws an exception if $this->listName is not set
*/
protected function checkValidList() {
if (empty($this->listName)) {
throw new Exception("please set a valid list");
}
if (!is_dir($this->listPath)) {
throw new Exception("list [" . $this->listName . "] does not exist");
}
}
/**
* Throws an exception if $this->listName is not set
*/
protected function checkValidDomain() {
if (empty($this->domainName)) {
throw new Exception("please set a valid domain");
}
if (!is_dir($this->domainPath)) {
throw new Exception("domain [" . $this->domainName . "] does not exist");
}
}
/**
* Throws an exception if $this->cachePath is not set, or if the directory
* does not exist or is not writable
*/
protected function checkValidCache() {
if (empty($this->cachePath)) {
throw new Exception("please set a valid cache path");
}
if (!is_dir($this->cachePath)) {
throw new Exception("cache folder [" . $this->cachePath . "] does not exist");
}
if (!is_writable($this->cachePath)) {
throw new Exception("cache folder [" . $this->cachePath . "] is not writable");
}
}
/**
* Converts a string of letters (ex: "aBuD") to a command line switches
* string (ex: "-a -B -u -D") @WARNING only supports single letter switches !
*/
protected function getSwitches($options) {
$switches = '';
if (!empty($options)) {
$switchesArray = array();
$optionsArray = str_split($options);
// not twice the same switch
$optionsArray = array_unique($optionsArray);
foreach ($optionsArray as $opt) {
// only letters are allowed
if (preg_match('/[a-zA-Z]/', $opt)) {
$switchesArray[] = '-' . $opt;
}
}
$switches = implode(' ', $switchesArray);
}
return $switches;
}
/**
* Generates an author's hash using the included makehash program
* (i) copied from original lib
*/
protected function makehash($str) {
$str = preg_replace ('/>/', '', $str); // wtf ?
$hash = $this->rt("makehash", $str, true);
return $hash;
}
/**
* Checks if a string is valid UTF-8; if not, converts it from $fallbackCharset
* to UTF-8; returns the UTFized string
*/
protected function utfize($str, $fallbackCharset='ISO-8859-1') {
$result = $this->utfizeAndStats($str, $fallbackCharset);
return $result[0];
}
/**
* Checks if a string is valid UTF-8; if not, converts it from $fallbackCharset
* to UTF-8; returns an array containing the UTFized string, and a boolean
* telling if a conversion was performed
*/
protected function utfizeAndStats($str, $fallbackCharset='ISO-8859-1') {
$valid_utf8 = preg_match('//u', $str);
if (! $valid_utf8) {
$str = iconv($fallbackCharset, "UTF-8//TRANSLIT", $str);
}
return array($str, ($valid_utf8 !== false));
}
/**
* Comparison function for usort() returning threads having the greatest
* "last_message_id" first
*/
protected function sortMostRecentThreads($a, $b) {
return $b['last_message_id'] - $a['last_message_id'];
}
/**
* Comparison function for usort() returning threads having the lowest
* "last_message_id" first
* @TODO use first_message_id instead ?
*/
protected function sortLeastRecentThreads($a, $b) {
return $this->sortMostRecentThreads($b, $a);
}
/**
* Converts a "*" based pattern to a preg compatible regex pattern
*/
protected function convertPatternForPreg($pattern) {
if ($pattern == "*") {
$pattern = false; // micro-optimization
}
if ($pattern != false) {
$pattern = str_replace('*', '.*', $pattern);
$pattern = '/^' . $pattern . '$/is'; // case insensitive, multilines
}
return $pattern;
}
/**
* Converts a "*" based pattern to a grep compatible regex pattern
*/
protected function convertPatternForGrep($pattern) {
$pattern = str_replace('*', '.*', $pattern);
$pattern = '^' . $pattern . '$';
return $pattern;
}
/**
* If $silent is true, returns a message stub to represent a message not
* found in the archive; if $silent is false, throws an Exception
*/
protected function messageNotFound($silent=false) {
if ($silent) {
return array(
"message_id" => false,
"subject_hash" => false,
"subject" => false,
"message_date" => false,
"author_hash" => false,
"author_name" => false,
"author_email" => false
);
} else {
throw new Exception("message not found");
}
}
/**
* Returns the months numbers / names array for the current list's language,
* if it exists, or defaults to "en" numbers / names
*/
protected function getMonthsNumbersForLang($lang=null) {
$monthsNumbersForLang = $this->monthsNumbers["en"];
// months names depending on the list's language
if ($lang == null) {
$lang = $this->getListLanguage();
}
if (array_key_exists($lang, $this->monthsNumbers)) {
$monthsNumbersForLang = $this->monthsNumbers[$lang];
}
return $monthsNumbersForLang;
}
/**
* Returns a month number given a month name abreviation, dependnig on the
* current list's language; falls back to "en" if the abreviation doesn't
* exist in the localized array
*/
protected function getMonthNumber($monthAbr, $lang=null) {
$monthNumber = false;
$monthsNumbersForLang = $this->getMonthsNumbersForLang($lang);
// sometimes, a non-english list has archives mentioning english
// month abreviations; probably the language was en at first, then
// was changed at some point
if (array_key_exists($monthAbr, $monthsNumbersForLang)) {
$monthNumber = $monthsNumbersForLang[$monthAbr];
} else {
$monthNumber = $this->monthsNumbers['en'][$monthAbr];
}
return $monthNumber;
}
// ------------------ PARSING METHODS -------------------------
/**
* Sets an option in ezmlm config so that the "Reply-To:" header points
* to the list address and not the sender's
* @TODO find a proper way to know if it worked or not
* � copyleft David Delon 2005 - Tela Botanica / Outils R�seaux
*/
protected function setReplyToHeader() {
$this->checkValidDomain();
$this->checkValidList();
// files to be modified
$headerRemovePath = $this->listPath . '/headerremove';
$headerAddPath = $this->listPath . '/headeradd';
// commands
$hrCommand = "echo -e 'reply-to' >> " . $headerRemovePath;
$haCommand = "echo -e 'Reply-To: <#l#>@<#h#>' >> " . $headerAddPath;
//echo $haCommand; exit;
exec($hrCommand);
exec($haCommand);
}
protected function computeSubfolderAndId($id) {
// ezmlm archive format : http://www.mathematik.uni-ulm.de/help/qmail/ezmlm.5.html
$subfolder = intval($id / 100);
$messageId = $id - (100 * $subfolder);
if ($messageId < 10) {
$messageId = '0' . $messageId;
}
return array($subfolder, $messageId);
}
protected function extractMessageMetadata($line1, $line2) {
// Line 1 : get message number, subject hash and subject
preg_match('/^([0-9]+): ([a-z]+)( .*)?$/', $line1, $match1);
// Line 2 : get date, author hash and hash
preg_match('/^\t([0-9]+ [a-zA-Z][a-zA-Z][a-zA-Z] [0-9][0-9][0-9][0-9] [^;]+)?;([^ ]*) (.*)$/', $line2, $match2);
$message = null;
if ($match1[1] != '') {
//var_dump($match2);
$timestamp = strtotime($match2[1]);
$date = null;
if ($timestamp != false) {
$date = date('Y-m-d h:i:s', $timestamp);
}
$subject = "";
if (isset($match1[3])) {
$subject = $this->utfize(trim($match1[3]));
}
// formatted return
$message = array(
"message_id" => intval($match1[1]),
"subject_hash" => $match1[2],
"subject" => $subject,
"message_date" => $date, // @TODO include time zone ?
"author_hash" => $match2[2],
"author_name" => $this->utfize($match2[3]),
"author_email" => $this->readMessageAuthorEmail(intval($match1[1])) // doesn't seem to cost so much
);
}
return $message;
}
/**
* Reads "num" file in list dir to get total messages count
*/
protected function countMessagesFromArchive() {
$numFile = $this->listPath . '/num';
if (! file_exists($numFile)) { // should mean the list is brand new
return 0;
}
$num = file_get_contents($numFile);
$num = explode(':', $num);
return intval($num[0]);
}
/**
* Reads $limit messages from the list archive. Beware: setting $limit to 0 means no limit.
* If $includeMessages is true, returns the parsed message contents along with the metadata;
* if $includeMessages is "abstract", returns only the first characters of the message.
*/
protected function readMessagesFromArchive($includeMessages=false, $limit=false, $sort='desc', $offset=0) {
// check valid limit
if (! is_numeric($limit) || $limit <= 0) {
$limit = false;
}
// check valid sort order
if ($sort != 'asc') {
$sort = 'desc';
}
// check valid offset
if (!is_numeric($offset) || $offset < 0) {
$offset = 0;
}
// idiot-proof attempt
if ($includeMessages === true) { // unlimited abstracts are allowed
if (! empty($this->settings['maxMessagesWithContentsReadableAtOnce']) && ($this->settings['maxMessagesWithContentsReadableAtOnce']) < $limit) {
throw new Exception("cannot read more than " . $this->settings['maxMessagesWithContentsReadableAtOnce'] . " messages at once, if messages contents are included");
}
}
$archiveDir = $this->listPath . '/archive';
if (! is_dir($archiveDir)) {
throw new Exception('list is not archived'); // @TODO check if archive folder exists in case a list is archived but empty
}
$archiveD = opendir($archiveDir);
//echo "Reading $archiveDir \n";
// get all subfolders
$subfolders = array();
while (($d = readdir($archiveD)) !== false) {
if (preg_match('/[0-9]+/', $d)) {
$subfolders[] = $d;
}
}
// sort and reverse order if needed (last messages first)
sort($subfolders, SORT_NUMERIC);
if ($sort == 'desc') {
$subfolders = array_reverse($subfolders);
}
//var_dump($subfolders);
$messages = array();
// read index files for each folder
$idx = 0;
$read = 0;
$length = count($subfolders);
// number of index files to skip // @WARNING if sort=desc, needs to
// know how many messages there are in the last index file (<= 100)
/*$indexFilesToSkip = intval(floor(($offset + 1) / 100));
$idx += $indexFilesToSkip;*/
// go
while (($idx < $length) && ($limit == false || $limit > $read)) { // stop if enough messages are read
$sf = $subfolders[$idx];
// @WARNING setting limit to 0 means unlimited
$subMessages = $this->readMessagesFromArchiveSubfolder($sf, $includeMessages, $sort, ($limit - $read), $offset);
$messages = array_merge($messages, $subMessages);
$read += count($subMessages); // might be 0 if using an offset
$idx++;
}
// bye
closedir($archiveD);
return $messages;
}
/**
* Returns all messages whose date matches the given $datePortion, using
* "YYYY[-MM[-DD]]" format (ie. "2015", "2015-04" or "2015-04-23")
*/
protected function readMessagesByDate($datePortion, $contents=false, $limit=false, $sort='desc', $offset=0) {
// check valid limit
if (! is_numeric($limit) || $limit <= 0) {
$limit = false;
}
// check valid sort order
if ($sort != 'asc') {
$sort = 'desc';
}
// check valid offset
if (!is_numeric($offset) || $offset < 0) {
$offset = 0;
}
// idiot-proof attempt
if ($contents === true) { // unlimited abstracts are allowed
if (! empty($this->settings['maxMessagesWithContentsReadableAtOnce']) && ($this->settings['maxMessagesWithContentsReadableAtOnce']) < $limit) {
throw new Exception("cannot read more than " . $this->settings['maxMessagesWithContentsReadableAtOnce'] . " messages at once, if messages contents are included");
}
}
// date to search for
$year = substr($datePortion, 0, 4);
$month = substr($datePortion, 5, 2);
$day = substr($datePortion, 8, 2);
if (! is_numeric($year)) {
throw new Exception("invalid date [$year]");
}
// file(s) to read
$pattern = $year;
$monthsNumbersForLang = $this->getMonthsNumbersForLang();
$monthsNames = array_flip($monthsNumbersForLang);
if ($month != false) {
$pattern = $monthsNames[$month] . ' ' . $pattern;
}
if ($day != false) {
$pattern = '\t' . $day . ' ' . $pattern;
}
//var_dump($pattern); exit;
$archiveDir = $this->listPath . '/archive';
$command = $this->grepBinary . ' --no-group-separator -i -hP -B1 "' . $pattern . '" ' . $archiveDir . '/*/index';
exec($command, $output);
// sort (BASH "*" expansion is alphabetical)
if ($sort == 'desc') {
$output = array_reverse($output);
}
$count = floor(count($output) / 2);
//echo "<pre>"; var_dump($output); echo "</pre>"; exit;
$messages = $this->readMessagesPairsOfLines($output, $contents, $sort, $limit, $offset) ;
$msgs = array();
foreach ($messages as &$msg) {
$msgs[] = $msg;
}
//echo "<pre>"; var_dump($msgs); echo "</pre>"; exit;
return array(
"total" => $count,
"data" => $msgs
);
}
/**
* Comparison function for usort() returning oldest messages first : a lower
* message_id always means an older date
*/
protected function sortMessagesByIdAsc($a, $b) {
return $a['message_id'] - $b['message_id'];
}
/**
* Comparison function for usort() returning oldest messages first : a lower
* message_id always means an older date
*/
protected function sortMessagesByIdDesc($a, $b) {
return $this->sortMessagesByIdAsc($b, $a);
}
/**
* Reads $limit messages from an archive subfolder (ex: archive/0, archive/1) - this represents maximum
* 100 messages - then returns all metadata for each message, along with the messages contents if
* $includeMessages is true; limits the output to $limit messages, if $limit is a valid number > 0;
* beware: setting $limit to 0 means no limit !
* $offset will be used to skip messages while > 0 and updated for each message skipped
*/
protected function readMessagesFromArchiveSubfolder($subfolder, $includeMessages=false, $sort='desc', $limit=false, &$offset=0) {
// check valid limit
if (! is_numeric($limit) || $limit <= 0) {
$limit = false;
}
$index = file($this->listPath . '/archive/' . $subfolder . '/index');
// if $sort='desc', read file backwards
if ($sort == 'desc') {
$index = array_reverse($index);
}
$messages = $this->readMessagesPairsOfLines($index, $includeMessages, $sort, $limit, $offset);
return $messages;
}
/**
* Reads couples of lines from a message index file, to extract messages
*/
protected function readMessagesPairsOfLines($lines, $includeMessages=false, $sort='desc', $limit=false, &$offset=0) {
// read 2 lines at once - @WARNING considers number of lines in file is always even !
$length = count($lines);
$idx = 0;
$read = 0;
$messages = array();
while ($idx < $length && ($limit == false || $limit > $read)) {
if ($offset == 0) {
$lineA = $lines[$idx];
$lineB = $lines[$idx+1];
if ($sort == 'desc') { // file is read backwards
$lineA = $lines[$idx+1];
$lineB = $lines[$idx];
}
$message = $this->extractMessageMetadata($lineA, $lineB);
$messageId = $message['message_id'];
$messages[$messageId] = $message;
// read message contents on the fly
if ($includeMessages === true) {
$messageContents = $this->readMessageContents($messageId);
$messages[$messageId]["message_contents"] = $messageContents;
} elseif ($includeMessages === "abstract") {
$messageAbstract = $this->readMessageAbstract($messageId);
$messages[$messageId]["message_contents"] = $messageAbstract;
}
$read++;
} else {
$offset--;
}
$idx += 2;
}
return $messages;
}
protected function searchMessagesInArchive($pattern, $contents=false, $sort='desc', $offset=0, $limit=false) {
// ensure valid parameters
if (!is_numeric($offset) || $offset < 0) {
$offset = 0;
}
if (!is_numeric($limit) || $limit <= 0) {
$limit = null;
}
// find
$pregPattern = $this->convertPatternForPreg($pattern);
$grepPattern = $this->convertPatternForGrep($pattern);
if ($pregPattern === false) {
throw new Exception('Invalid search pattern');
}
$archiveDir = $this->listPath . '/archive';
// grep the pattern in message files only
$command = $this->findBinary . " $archiveDir -regextype sed -regex " . '"' . $archiveDir . '/[0-9]\+/[0-9]\+$" -exec ' . $this->grepBinary . ' -i -l -R "' . $grepPattern . '" {} +';
exec($command, $output);
// message header or attachments might have matched $pattern - extracting
// message text to ensure the match was not a false positive
$totalResults = count($output);
$messages = array();
foreach ($output as $line) {
$line = str_replace($archiveDir, '', $line); // strip folder path @TODO find a cleaner way to do this
$id = intval(str_replace('/', '', $line));
// message contents is required to check pattern matching
$message = $this->readMessage($id, true);
if (
isset($message["message_contents"]) &&
isset($message["message_contents"]["text"]) &&
preg_match($pregPattern, $message["message_contents"]["text"])
) {
// if contents was not asked, remove it from results @TODO manage contents=abstract
if ($contents == false) {
unset($message["message_contents"]);
} elseif ($contents == 'abstract') {
$message["message_contents"]["text"] = $this->abstractize($message["message_contents"]["text"]);
}
$messages[] = $message;
}
}
// sort
usort($messages, array($this, 'sortMessagesById' . ucfirst($sort)));
// paginate
$messages = array_slice($messages, $offset, $limit);
return array(
"total" => $totalResults,
"data" => $messages
);
}
/**
* Reads and returns metadata for the $id-th message in the current list's archive.
* If $contents is true, includes the message contents; if $contents is "abstract",
* includes only the first characters of the message; if $silent is false,
* will throw an Exception if the message is not found in the archive
*/
protected function readMessage($id, $contents=true, $silent=true) {
list($subfolder, $messageid) = $this->computeSubfolderAndId($id);
$indexPath = $this->listPath . '/archive/' . $subfolder . '/index';
// sioux trick to get the 2 lines concerning the message
$grep = $this->grepBinary . ' "^' . $id . ': " "' . $indexPath . '" --no-group-separator -A 1';
exec($grep, $lines);
// in case messge was not found in the archive (might happen)
if (count($lines) == 2) {
$ret = $this->extractMessageMetadata($lines[0], $lines[1]);
if ($contents === true) {
$messageContents = $this->readMessageContents($id);
$ret["message_contents"] = $messageContents;
} elseif ($contents === "abstract") {
$messageAbstract = $this->readMessageAbstract($id);
$ret["message_contents"] = $messageAbstract;
}
} else {
$ret = $this->messageNotFound($silent);
}
return $ret;
}
/**
* Returns the path of the file containing message n°$id
*/
protected function getMessageFileForId($id) {
// check valid id
if (! is_numeric($id) || $id <=0) {
throw new Exception("invalid message id [$id]");
}
list($subfolder, $messageId) = $this->computeSubfolderAndId($id);
$messageFile = $this->listPath . '/archive/' . $subfolder . '/' . $messageId;
if (! file_exists($messageFile)) {
throw new Exception("message of id [$id] does not exist");
}
return $messageFile;
}
protected function readMessageAbstract($id) {
return $this->readMessageContents($id, true);
}
/**
* Returns the email address of the author of message n°$id (needs message
* to be parsed, beware of resources usage)
*/
protected function readMessageAuthorEmail($id) {
$messageFile = $this->getMessageFileForId($id);
$parser = new PhpMimeMailParser\Parser();
$parser->setPath($messageFile);
$from = $this->extractEmailFromHeader($parser->getHeader('from'));
return $from;
}
/**
* Extracts the email address part (ie. "<[email protected]>") of an email "From:",
* "To:", or equivalent header, such as "John DOE <[email protected]>"
*/
protected function extractEmailFromHeader($authorHeader) {
if (preg_match('/.*<(.+@.+\..+)>/', $authorHeader, $matches)) {
return $matches[1];
}
return false;
}
/**
* Reads and returns the contents of the $id-th message in the current list's archive
* If $abstract is true, reads only the first $this-->settings['messageAbstractSize'] chars
* of the message (default 128)
*/
protected function readMessageContents($id, $abstract=false) {
$messageFile = $this->getMessageFileForId($id);
// read message
$parser = new PhpMimeMailParser\Parser();
$parser->setPath($messageFile);
$text = $parser->getMessageBody('text');
if ($text) {
$text = $this->utfize($text);
}
$attachments = $parser->getAttachments();
$attachmentsArray = array();
foreach ($attachments as $attachment) {
$attachmentsArray[] = array(
"filename" => $attachment->filename,
"content-type" => $attachment->contentType,
"content-transfer-encoding" => isset($attachment->headers["content-transfer-encoding"]) ? $attachment->headers["content-transfer-encoding"] : null
);
}
if ($abstract) {
$text = $this->abstractize($text);
}
$text = $this->cleanMessageText($text);
return array(
'text' => $text,
'attachments' => $attachmentsArray
);
}
/**
* Given a text, returns an abstract limited to 'config->messageAbstractSize'
* characters, or 128 if 'config->messageAbstractSize' is not set
*/
protected function abstractize($text) { // abstract is a reserved keyword
if ($text != "") {
$abstractSize = 128;
if (! empty($this->settings['messageAbstractSize']) && is_numeric($this->settings['messageAbstractSize']) && $this->settings['messageAbstractSize'] > 0) {
$abstractSize = $this->settings['messageAbstractSize'];
}
// mb_ prevents breaking UTF-8 characters, that cause json_encode to fail
$text = mb_substr($text, 0, $abstractSize);
}
return $text;
}
/**
* Attempts to remove quotations, headers, markups that could be interpreted
* as HTML, and all other sh*t clients send
* @TODO improve !
*/
protected function cleanMessageText($text) {
// basic job : remove markups
$text = str_replace(array('<','>'), array('<','>'), $text);
return $text;
}
/**
* Uses php-mime-mail-parser to extract and save attachments to message $id,
* into subfolder "attachments" of the associated cache folder; if subfolder
* "attachments" already exists and unless $force is true, does nothing.
*/
protected function saveMessageAttachments($id, $force=false) {
$messageCacheFolder = $this->getMessageCacheFolder($id);
$attachmentsFolder = $messageCacheFolder . '/attachments/';
$attachmentsFolderExists = is_dir($attachmentsFolder);
if ($force || ! $attachmentsFolderExists) {
if (! $attachmentsFolderExists) {
mkdir($attachmentsFolder);
}
$messageFile = $this->getMessageFileForId($id);
$parser = new PhpMimeMailParser\Parser();
$parser->setPath($messageFile);
$parser->saveAttachments($attachmentsFolder);
}
}
/**
* Saves the attachments of message $id in the cache if needed, then returns
* the path for attachment $attachmentName; throws an exception if the
* required attachment doesn't exist or could not be extracted / saved
*/
protected function getMessageAttachmentPath($messageId, $attachmentName) {
$this->checkValidCache();
$messageCacheFolder = $this->getMessageCacheFolder($messageId);
// extract and save attachments
$this->saveMessageAttachments($messageId);
$fileName = $messageCacheFolder . '/attachments/' . $attachmentName;
if (!file_exists($fileName)) {
throw new Exception("Attachment [$attachmentName] to message [$messageId] does not exist or could not be extracted");
}
return $fileName;
}
/**
* Returns the path of the cache folder for message $id, following
* ezmlm-archive's folders convention (ex. message 12743 => folder 127/43)
*/
protected function getMessageCacheFolder($id) {
$f1 = "0";
$f2 = $id;
if ($id >= 100) {
$f1 = floor($id / 100);
$f2 = $id - (100 * $f1);
}
$folderForId = $f1 . '/' . str_pad($f2, 2, "0",STR_PAD_LEFT);
$folderPath = $this->cachePath . '/' . $this->listName . '/' . $folderForId;
if (! is_dir($folderPath)) {
mkdir($folderPath, 0777, true);
}
return $folderPath;
}
/**
* Returns the number of threads existing in the current list's archive
* @WARNING assumes that "wc" executable is present in /usr/bin
* @WARNING raw counting, does not try to merge linked threads (eg "blah", "Re: blah", "Fwd: blah"...)
*/
protected function countThreadsFromArchive() {
$threadsFolder = $this->listPath . '/archive/threads';
$command = "cat $threadsFolder/* | /usr/bin/wc -l";
exec($command, $output);
//echo "CMD: $command\n";
return intval($output[0]);
}
/**
* Reads and returns all threads in the current list's archive, most recent activity first.
* If $pattern is set, only returns threads whose subject matches $pattern. Il $limit is set,
* only returns the $limit most recent (regarding activity ie. last message id) threads. If
* $flMessageDetails is set, returns details for first and last message (take a lot more time)
*/
protected function readThreadsFromArchive($pattern=false, $limit=false, $flMessageDetails=false, $sort='desc', $offset=0) {
$pattern = $this->convertPatternForPreg($pattern);
// read all threads files in chronological order
$threadsFolder = $this->listPath . '/archive/threads';
// in case a list has no messages yet
if (!file_exists($threadsFolder)) {
return array(
"total" => 0,