-
Notifications
You must be signed in to change notification settings - Fork 2
/
rcube_dbmail.php
8287 lines (6865 loc) · 282 KB
/
rcube_dbmail.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
/**
* Description of rcube_dbmail
*
* @author Schema31 S.P.A.
*
* TO ENABLE 'rcube_dbmail' PLUGIN:
* 1. drop rcube_dbmail.php to '../program/lib/Roundcube'
* 2. add the following lines to roundcube/config/config.inc.php
* $config['storage_driver'] = 'dbmail';
* $config['dbmail_dsn'] = 'mysql://user:pass@host/db'; # dsn connection string
* $config['dbmail_hash'] = 'sha1'; # hashing method to use, must coincide with dbmail.conf - sha1, md5, sha256, sha512, whirlpool. sha1 is the default
* $config['dbmail_fixed_headername_cache'] = FALSE; # add new headernames (if not exists) in 'dbmail_headername' when saving messages
* $config['dbmail_cache'] = 'db'; # Generic cache switch. FALSE (to disable cache) / 'db' / 'memcache' / 'apc'
* $config['dbmail_cache_ttl'] = '10d'; # Cache default expire value
* $config['dbmail_sql_debug'] = FALSE; # log executed queries to 'logs/sql'?
*
* !!! IMPORTANT !!!
* Use the official PEAR Mail_mimeDecode library, changing following line in 'composer.json'
* change "pear/mail_mime-decode": ">=1.5.5",
* to "pear-pear.php.net/Mail_mimeDecode": ">=1.5.5",
*
* ----------------------------
*
* Notes:
*
* 1. DBMAIL nightly cleanup every cached data (envelope / headers) for deleted
* messages, so we don't need to manually delete those records
*/
class rcube_dbmail extends rcube_storage {
private $rc;
private $debug = FALSE; ## Not really useful, we use it just to track internally the debug status
private $user_idnr = null;
private $namespace = null;
private $delimiter = null;
private $dbmail = null;
private $rcubeInstance = null;
private $err_no = 0;
private $err_str = '';
private $response_code = null;
/**
* Supported IMAP capabilities
*/
private $imap_capabilities = array(
'ACL' => TRUE,
'ANNOTATE-EXPERIMENT-1' => TRUE,
'AUTH' => TRUE,
'BINARY' => TRUE,
'CATENATE' => TRUE,
'CHILDREN' => TRUE,
'COMPRESS' => array('DEFLATE'),
'CONDSTORE' => TRUE,
'CONTEXT' => array('SEARCH', 'SORT'),
'CONVERT' => TRUE,
'CREATE-SPECIAL-USE' => TRUE,
'ENABLE' => TRUE,
'ESEARCH' => TRUE,
'ESORT' => TRUE,
'FILTERS' => TRUE,
'I18NLEVEL' => array('1', '2'),
'ID' => TRUE,
'IDLE' => TRUE,
'IMAPSIEVE' => TRUE,
'LANGUAGE' => TRUE,
'LIST-EXTENDED' => TRUE,
'LIST-STATUS' => TRUE,
'LITERAL+' => TRUE,
'LOGIN-REFERRALS' => TRUE,
'LOGINDISABLED' => TRUE,
'MAILBOX-REFERRALS' => TRUE,
'METADATA' => TRUE,
'METADATA-SERVER' => TRUE,
'MOVE' => TRUE,
'MULTIAPPEND' => TRUE,
'MULTISEARCH' => TRUE,
'NAMESPACE' => TRUE,
'NOTIFY' => TRUE,
'QRESYNC' => TRUE,
'QUOTA' => TRUE,
'RIGHTS' => TRUE,
'SASL-IR' => TRUE,
'SEARCH' => array('FUZZY'),
'SEARCHRES' => TRUE,
'SORT' => array('DISPLAY'),
'SPECIAL-USE' => TRUE,
'STARTTLS' => TRUE,
// 'THREAD' => array('ORDEREDSUBJECT'),
'UIDPLUS' => TRUE,
'UNSELECT' => TRUE,
'URLFETCH' => array('BINARY'),
'URL-PARTIAL' => TRUE,
'URLAUTH' => TRUE,
'UTF8' => array('ACCEPT', 'ALL', 'APPEND', 'ONLY', 'USER'),
'WITHIN' => TRUE,
);
/**
* Cache configuration
*/
protected $cache = null; // cache handler instance
protected $caching = null; // cache type (db /memcache/...)
/**
* Message status flags
*/
const MESSAGE_STATUS_NEW = 0;
const MESSAGE_STATUS_SEEN = 1;
const MESSAGE_STATUS_DELETE = 2;
const MESSAGE_STATUS_PURGE = 3;
const MESSAGE_STATUS_UNUSED = 4;
const MESSAGE_STATUS_INSERT = 5;
const MESSAGE_STATUS_ERROR = 6;
/**
* Keyword tokens
*/
const KEYWORD_FORWARDED = '$Forwarded';
/**
* ACLs mapping flags
*/
const ACL_CACHE_TTL = 300;
const ACL_LOOKUP_FLAG = 'l';
const ACL_READ_FLAG = 'r';
const ACL_SEEN_FLAG = 's';
const ACL_WRITE_FLAG = 'w';
const ACL_INSERT_FLAG = 'i';
const ACL_POST_FLAG = 'p';
const ACL_CREATE_FLAG = 'k';
const ACL_DELETE_FLAG = 'x';
const ACL_DELETED_FLAG = 't';
const ACL_EXPUNGE_FLAG = 'e';
const ACL_ADMINISTER_FLAG = 'a';
/**
* Public userId
*/
const PUBLIC_FOLDER_USER = '__public__';
/**
* Temporary items time to live (seconds)
*/
const TEMP_TTL = 300;
public function __construct() {
// get main roundcube instance
$this->rcubeInstance = rcube::get_instance();
$this->rc = rcmail::get_instance();
// set namespaces
if (is_null($this->namespace)) {
$this->namespace = array(
'personal' => array(
array(
"",
"/")
),
'other' => array(
array(
"#Users",
"/"
)
),
'shared' => array(
array(
"#Public",
"/"
)
),
'prefix' => ""
);
$_SESSION['imap_namespace'] = $this->namespace;
}
// set common delimiter
if (is_null($this->delimiter)) {
$this->delimiter = "/";
$_SESSION['imap_delimiter'] = $this->delimiter;
}
// connect to dbmail database
if (!$this->dbmail_connect()) {
die("Error during connection to Dbmail database: " . $this->dbmail->is_error());
}
// set dbmail user_idnr (retrieve it if empty)
if (!isset($_SESSION['user_idnr']) || !$_SESSION['user_idnr'] || strlen($_SESSION['user_idnr']) == 0) {
$_SESSION['user_idnr'] = $this->get_dbmail_user_idnr($_SESSION['username']);
}
$this->user_idnr = $this->get_dbmail_user_idnr($_SESSION['username']);
}
/**
* This is the function that fakes the connection to the IMAP Server
* Don't get confused by the name - it's not the function to connect to the DB Engine.
*
* @param string $host Host to connect
* @param string $user Username for IMAP account
* @param string $pass Password for IMAP account
* @param integer $port Port to connect to
* @param string $use_ssl SSL schema (either ssl or tls) or null if plain connection
*
* @return boolean TRUE on success, FALSE on failure
*/
public function connect($host, $user, $pass, $port = 143, $use_ssl = null) {
// connected?
if (!$this->dbmail->is_connected()) {
return FALSE;
}
$valid_user = FALSE;
// validate supplied login details
$user_sql = "SELECT user_idnr, passwd, encryption_type "
. " FROM dbmail_users "
. " WHERE userid = '{$this->dbmail->escape($user)}' ";
$res = $this->dbmail->query($user_sql);
if ($this->dbmail->num_rows($res) == 0) {
// usename not found
return FALSE;
}
$row = $this->dbmail->fetch_assoc($res);
// supplied password match?
switch ($row['encryption_type']) {
case 'md5':
$salt = substr($row['passwd'], 0, (strrpos($row['passwd'], '$') + 1));
$valid_user = (crypt($pass, $salt) == $row['passwd']);
break;
case 'md5sum':
$valid_user = (md5($pass) == $row['passwd']);
break;
case 'sha1':
case 'sha256':
case 'sha512':
case 'whirlpool':
$valid_user = (hash($row['encryption_type'], $pass) == $row['passwd']);
break;
default :
// plain text:
$valid_user = ($pass == $row['passwd']);
break;
}
// authenticated user?
if (!$valid_user) {
return FALSE;
}
// Update last login
$current_datetime = new DateTime();
$last_login_sql = "UPDATE dbmail_users "
. "SET last_login = '{$this->dbmail->escape($current_datetime->format('Y-m-d H:i:s'))}' "
. "WHERE user_idnr = '{$this->dbmail->escape($row['user_idnr'])}' ";
if (!$this->dbmail->query($last_login_sql)) {
return FALSE;
}
//Loggare autenticazione in dbmail_authlog
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
list($remoteAddr) = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
} else {
$remoteAddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'N/D';
}
$remotePort = isset($_SERVER['REMOTE_PORT']) ? $_SERVER['REMOTE_PORT'] : null;
$serverAddr = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : 'N/D';
$serverPort = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : null;
$now = new DateTime();
/*
* Create insert into dbmail_authlog
*/
$query = "INSERT INTO dbmail_authlog "
. " ( "
. " userid, "
. " service, "
. " login_time, "
. " src_ip, "
. " src_port, "
. " dst_ip, "
. " dst_port, "
. " status"
. ""
. " ) "
. " VALUES "
. " ( "
. " '{$user}', "
. " 'auth', "
. " '{$now->format('Y-m-d H:i:s')}',"
. " '{$remoteAddr}',"
. " '{$remotePort}',"
. " '{$serverAddr}',"
. " '{$serverPort}',"
. " 'authOK'"
. " ) ";
if (!$this->dbmail->query($query)) {
return FALSE;
}
// Retrieve inserted ID
//$dbmail_authlog_id = $this->dbmail->insert_id('dbmail_authlog');
// OK - store user identity within session data
$this->user_idnr = $row['user_idnr'];
$_SESSION['user_idnr'] = $this->user_idnr;
// subscribe INBOX when needed
$mailbox_idnr = $this->get_mail_box_id('INBOX', $this->user_idnr);
if ($mailbox_idnr && !$this->folder_subscription_exists($mailbox_idnr)) {
// subsribe INBOX
$this->subscribe(array('INBOX'));
}
return TRUE;
}
/**
* Close connection. Usually done on script shutdown
*/
public function close() {
// DO NOTHING!!!!
}
/**
* Delete all the expunged messages in all the mailboxes
* @return boolean
*/
public function expungeAll($mailbox_idnr) {
// ACLs check ('expunge' grant required )
$ACLs = $this->_get_acl(NULL, $mailbox_idnr);
if (!is_array($ACLs) || !in_array(self::ACL_EXPUNGE_FLAG, $ACLs)) {
// Unauthorized!
return FALSE;
}
// set message flag
$expungeAllSQL = "UPDATE dbmail_mailboxes "
. "INNER JOIN dbmail_messages ON dbmail_messages.mailbox_idnr = dbmail_mailboxes.mailbox_idnr "
. "SET dbmail_messages.status = 2, "
. "dbmail_mailboxes.seq = dbmail_mailboxes.seq + 1 "
. "WHERE dbmail_messages.deleted_flag = 1 "
. "AND dbmail_mailboxes.mailbox_idnr = {$this->dbmail->escape($mailbox_idnr)} "
. "AND dbmail_messages.status < {$this->dbmail->escape(self::MESSAGE_STATUS_DELETE)} "
. "AND dbmail_mailboxes.owner_idnr = {$this->dbmail->escape($this->user_idnr)} ";
return ($this->dbmail->query($expungeAllSQL) ? TRUE : FALSE);
}
/**
* Checks connection state.
*
* @return boolean TRUE on success, FALSE on failure
*/
public function is_connected() {
return $this->dbmail->is_connected();
}
/**
* Check connection state, connect if not connected.
*
* @return bool Connection state.
*/
public function check_connection() {
return $this->dbmail->is_connected();
}
/**
* Returns code of last error
*
* @return int Error code
*/
public function get_error_code() {
return $this->err_no;
}
/**
* Returns message of last error
*
* @return string Error message
*/
public function get_error_str() {
return $this->err_str;
}
/**
* Returns code of last command response
*
* @return int Response code (class constant)
*/
public function get_response_code() {
return $this->response_code;
}
/**
* Set connection and class options
*
* @param array $opt Options array
*/
public function set_options($opt) {
$this->options = array_merge($this->options, (array) $opt);
}
/**
* Get connection/class option
*
* @param string $name Option name
*
* @param mixed Option value
*/
public function get_option($name) {
return $this->options[$name];
}
/**
* Activate/deactivate debug mode.
*
* @param boolean $dbg True if conversation with the server should be logged
*/
public function set_debug($dbg = true) {
/** Enable Query Logging * */
$this->debug($dbg);
$this->dbmail->set_debug($dbg);
}
/**
* Set default message charset.
*
* This will be used for message decoding if a charset specification is not available
*
* @param string $cs Charset string
*/
public function set_charset($cs) {
$this->default_charset = $cs;
}
/**
* Set internal folder reference.
* All operations will be perfomed on this folder.
*
* @param string $folder Folder name
*/
public function set_folder($folder) {
if ($this->folder === $folder) {
return;
}
$this->folder = $folder;
}
/**
* Backward compatibility with IMAP stuff
*
* set_mailbox == set_folder
*/
public function set_mailbox($folder) {
$this->set_folder($folder);
}
/**
* Returns the currently used folder name
*
* @return string Name of the folder
*/
public function get_folder() {
return $this->folder;
}
/**
* Set internal list page number.
*
* @param int $page Page number to list
*/
public function set_page($page) {
$this->list_page = (int) $page;
}
/**
* Gets internal list page number.
*
* @return int Page number
*/
public function get_page() {
return $this->list_page;
}
/**
* Set internal page size
*
* @param int $size Number of messages to display on one page
*/
public function set_pagesize($size) {
$this->page_size = (int) $size;
}
/**
* Get internal page size
*
* @return int Number of messages to display on one page
*/
public function get_pagesize() {
return $this->page_size;
}
/**
* Save a search result for future message listing methods.
*
* @param mixed $set Search set in driver specific format
*/
public function set_search_set($set) {
// $this->search_set = $set;
$set = (array) $set;
$this->search_string = $set[0];
$this->search_set = $set[1];
$this->search_charset = $set[2];
$this->search_sort_field = $set[3];
$this->search_sorted = $set[4];
$this->search_threads = is_a($this->search_set, 'rcube_result_thread');
if (is_a($this->search_set, 'rcube_result_multifolder')) {
$this->set_threading(false);
}
}
/**
* Return the saved search set.
*
* @return array Search set in driver specific format, NULL if search wasn't initialized
*/
public function get_search_set() {
if (empty($this->search_set)) {
return null;
}
return array(
$this->search_string,
$this->search_set,
$this->search_charset,
$this->search_sort_field,
$this->search_sorted,
);
}
/**
* Returns the storage server's (IMAP) capability
*
* @param string $cap Capability name
*
* @return mixed Capability value or TRUE if supported, FALSE if not
*/
public function get_capability($cap) {
$cap = strtoupper($cap);
/*
* Supported capability?
*/
if (!in_array($cap, $this->imap_capabilities)) {
/*
* Not found!
*/
return FALSE;
} elseif (is_array($this->imap_capabilities[$cap]) && count($this->imap_capabilities[$cap]) > 0) {
/*
* Key / value pairs found: return supported capability properties
*/
return $this->imap_capabilities[$cap];
} else {
/*
* Supported
*/
return TRUE;
}
}
/**
* Sets threading flag to the best supported THREAD algorithm.
* Enable/Disable threaded mode.
*
* @param boolean $enable TRUE to enable and FALSE
*
* @return mixed Threading algorithm or False if THREAD is not supported
*/
public function set_threading($enable = false) {
$this->threading = false;
if (!$enable) {
return $this->threading;
}
$caps = $this->get_capability('THREAD');
if (!$caps || !is_array($caps)) {
return $this->threading;
}
$methods = array_intersect(array('REFS', 'REFERENCES', 'ORDEREDSUBJECT'), $caps);
if (!is_array($methods) || count($methods) == 0) {
return $this->threading;
}
$this->threading = array_shift($methods);
return $this->threading;
}
/**
* Get current threading flag.
*
* @return mixed Threading algorithm or False if THREAD is not supported or disabled
*/
public function get_threading() {
return $this->threading;
}
/**
* Checks the PERMANENTFLAGS capability of the current folder
* and returns true if the given flag is supported by the server.
*
* @param string $flag Permanentflag name
*
* @return boolean True if this flag is supported
*/
public function check_permflag($flag) {
// TO DO!!!!!!
}
/**
* Returns the delimiter that is used by the server
* for folder hierarchy separation.
*
* @return string Delimiter string
*/
public function get_hierarchy_delimiter() {
return $this->delimiter;
}
/**
* Get namespace
*
* @param string $name Namespace array index: personal, other, shared, prefix
*
* @return array Namespace data
*/
public function get_namespace($name = null) {
$ns = $this->namespace;
if ($name) {
return (array_key_exists($name, $ns) ? $ns[$name] : null);
}
unset($ns['prefix']);
return $ns;
}
/**
* Get messages count for a specific folder.
*
* @param mixed $folder Folders list
* @param string $mode Mode for count [ALL|THREADS|UNSEEN|RECENT|EXISTS]
* @param boolean $force Force reading from server and update cache
* @param boolean $status Enables storing folder status info (max UID/count),
* required for folder_status()
*
* @return int Number of messages
*/
public function count($folder = null, $mode = 'ALL', $force = false, $status = true) {
/**
* Some actions (eg. roundcube/program/steps/mail/move_del.inc) call this
* method twice to retrieve messages count before and after doing stuff:
*
* $old_count = $RCMAIL->storage->count(NULL, $threading ? 'THREADS' : 'ALL');
* $msg_count = $RCMAIL->storage->count(NULL, $threading ? 'THREADS' : 'ALL');
*
* So we can't cache results or the second call will not get fresh data ('$force' flag is not supplied)
*/
if (is_array($folder) && count($folder) > 0) {
// mailboxes list supplied
$target = $folder;
} elseif (is_string($folder) && strlen($folder) > 0) {
// single mailbox supplied
$target = array($folder);
} elseif (array_key_exists('search_scope', $_SESSION) && $_SESSION['search_scope'] == 'all') {
// no mailbox supplied, search within all mailboxes
$target = $this->list_folders_subscribed('', '*', 'mail', null, true);
} else if (array_key_exists('search_scope', $_SESSION) && $_SESSION['search_scope'] == 'sub') {
// no mailbox supplied, search within current mailbox and nested ones
$target = $this->list_folders_subscribed($this->folder, '*', 'mail');
} elseif (strlen($this->folder) > 0) {
$target = array($this->folder);
}
if (!is_array($target) || count($target) == 0) {
// empty set!!!
return 0;
}
$folders = $this->_format_folders_list($target);
// map mailboxes ID
$mailboxes = array();
foreach ($folders as $folder_name) {
// Retrieve mailbox ID
$mail_box_idnr = $this->get_mail_box_id($folder_name);
if (!$mail_box_idnr) {
// Not found - Skip!
return FALSE;
}
// ACLs check ('lookup' and 'read' grants required )
$ACLs = $this->_get_acl(NULL, $mail_box_idnr);
if (!is_array($ACLs) || !in_array(self::ACL_LOOKUP_FLAG, $ACLs) || !in_array(self::ACL_READ_FLAG, $ACLs)) {
// Unauthorized - Skip!
return FALSE;
}
// Add mailbox ID to mailboxes list
$mailboxes[$mail_box_idnr] = $folder_name;
}
/*
* Init $additional_joins list
*/
$additional_joins = '';
/*
* Retrieve search string
*/
$search_str = NULL;
if (is_array($this->search_set) && array_key_exists(0, $this->search_set)) {
$tmp = $this->format_search_parameters($this->search_set[0]);
$search_str = $tmp->search;
}
$search_conditions = $this->_translate_search_parameters($search_str);
if (!$search_conditions) {
return FALSE;
}
/*
* set additional join tables according to supplied search / filter conditions
*/
if (is_object($search_conditions) && property_exists($search_conditions, 'additional_join_tables')) {
$additional_joins .= " {$search_conditions->additional_join_tables} ";
}
/*
* Set base 'where' conditions
*/
$where_conditions = " WHERE dbmail_messages.mailbox_idnr IN (" . implode(",", array_keys($mailboxes)) . ")";
$where_conditions .= " AND dbmail_messages.status < " . self::MESSAGE_STATUS_DELETE . " ";
/*
* Apply search criteria
*/
if (isset($search_conditions->additional_where_conditions) && strlen($search_conditions->additional_where_conditions) > 0) {
$where_conditions .= " AND {$search_conditions->additional_where_conditions}";
$additional_joins .= implode(PHP_EOL, $search_conditions->additional_joins);
}
/*
* add 'where' conditions according to supplied search / filter conditions
*/
if (is_object($search_conditions) && property_exists($search_conditions, 'formatted_filter_str') && strlen($search_conditions->formatted_filter_str) > 0) {
$where_conditions .= " AND ( {$search_conditions->formatted_filter_str} ) ";
}
if (is_object($search_conditions) && property_exists($search_conditions, 'formatted_search_str') && strlen($search_conditions->formatted_search_str) > 0) {
$where_conditions .= " AND ( {$search_conditions->formatted_search_str} ) ";
}
if ($mode == 'UNSEEN') {
$where_conditions .= " AND dbmail_messages.seen_flag = 0 ";
}
/*
* Prepare base query
*/
$query = " SELECT mailbox_idnr, dbmail_messages.message_idnr "
. " FROM dbmail_messages ";
/*
* Join to dbmail_physmessage when needed
*/
if (isset($search_conditions->needs_physmessages) && $search_conditions->needs_physmessages) {
$query .= " INNER JOIN dbmail_physmessage ON dbmail_messages.physmessage_id = dbmail_physmessage.id ";
}
$query .= " {$additional_joins} ";
$query .= " {$where_conditions} ";
if ($this->rcubeInstance->config->get('dbmail_messages_disable_cache')){
$query .= " group by dbmail_messages.message_idnr "; //patched cc'
}
/*
* Execute query
*/
$res = $this->dbmail->query($query);
if ($this->rcubeInstance->config->get('dbmail_messages_disable_cache')){
return $res->rowCount();
}
/*
* Retrieve full messages count and folder specific messages count
*/
$total_messages = 0;
$mailbox_messages = array();
while ($row = $this->dbmail->fetch_assoc($res)) {
$mailbox_name = $mailboxes[$row['mailbox_idnr']];
$message_idnr = $row['message_idnr'];
if (!array_key_exists($mailbox_name, $mailbox_messages)) {
$mailbox_messages[$mailbox_name] = array();
}
if (!in_array($message_idnr, $mailbox_messages[$mailbox_name])) {
$total_messages++;
$mailbox_messages[$mailbox_name][] = $message_idnr;
}
}
/*
* Cache messages count and latest message id
*/
if ($mode == 'ALL' && $status) {
foreach ($mailbox_messages as $mailbox_name => $messages) {
$mailbox_messages_count = count($messages);
$this->set_folder_stats($mailbox_name, 'cnt', $mailbox_messages_count);
$this->set_folder_stats($mailbox_name, 'maxuid', ($mailbox_messages_count ? $this->get_latest_message_idnr($mailbox_name) : 0));
}
}
return $total_messages;
}
/**
* Get latest message ID within specific folder.
*
* @param string $folder Folder name
* @return int message_idnr
*/
public function get_latest_message_idnr($folder = null) {
if (strlen($folder) == 0) {
$folder = $this->folder;
}
// mailbox exists?
$mailbox_idnr = $this->get_mail_box_id($folder);
if (!$mailbox_idnr) {
return FALSE;
}
// ACLs check ('lookup' and 'read' grants required )
$ACLs = $this->_get_acl(NULL, $mailbox_idnr);
if (!is_array($ACLs) || !in_array(self::ACL_LOOKUP_FLAG, $ACLs) || !in_array(self::ACL_READ_FLAG, $ACLs)) {
// Unauthorized!
return FALSE;
}
// prepare base query
$query = " SELECT MAX(message_idnr) AS latest_message_idnr "
. " FROM dbmail_messages "
. " WHERE dbmail_messages.mailbox_idnr = {$this->dbmail->escape($mailbox_idnr)} "
. " AND dbmail_messages.status < " . self::MESSAGE_STATUS_DELETE;
$res = $this->dbmail->query($query);
$row = $this->dbmail->fetch_assoc($res);
return ($row['latest_message_idnr'] > 0 ? $row['latest_message_idnr'] : FALSE);
}
/**
* Public method for listing message flags
*
* @param string $folder Folder name
* @param array $uids Message UIDs
* @param int $mod_seq Optional MODSEQ value
*
* @return array Indexed array with message flags
*/
public function list_flags($folder, $uids, $mod_seq = null) {
if (strlen($folder) == 0) {
$folder = $this->folder;
}
$mailbox_idnr = $this->get_mail_box_id($folder);
/*
* Filter by:
* 1 - $mailbox_idnr
* 2 - $message_idnrs
* 3 - $mailbox_idnr + $message_idnrs
*/
$filters = array();
if (strlen($mailbox_idnr) > 0) {
$filters[] = "mailbox_idnr = {$this->dbmail->escape($mailbox_idnr)}";
}
if (is_array($uids) && count($uids) > 0) {
foreach ($uids as &$uid) {
/*
* escape arguments
*/
$uid = $this->dbmail->escape($uid);
}
$filters[] = "message_idnr in (" . implode(',', $uids) . ")";
}
if (count($filters) == 0) {
/*
* No filters supplied!
*/
return array();
}
$query = " SELECT message_idnr, seen_flag, answered_flag, deleted_flag, flagged_flag, recent_flag, draft_flag "
. " FROM dbmail_messages "
. " WHERE " . implode(" AND ", $filters);
$res = $this->dbmail->query($query);
$result = array();
while ($row = $this->dbmail->fetch_assoc($res)) {
$result[$row['message_idnr']] = array(
'seen' => ($row['seen_flag'] ? TRUE : FALSE),
'answered' => ($row['answered_flag'] ? TRUE : FALSE),
'deleted' => ($row['deleted_flag'] ? TRUE : FALSE),
'flagged' => ($row['flagged_flag'] ? TRUE : FALSE),
'recent' => ($row['recent_flag'] ? TRUE : FALSE),
'draft' => ($row['draft_flag'] ? TRUE : FALSE)
);
}
return $result;
}
/**
* Public method for listing headers.
*
* @param mixed $folder Folders list
* @param int $page Current page to list
* @param string $sort_field Header field to sort by
* @param string $sort_order Sort order [ASC|DESC]
* @param int $slice Number of slice items to extract from result array
*
* @return array Indexed array with message header objects
*/
public function list_messages($folder = null, $page = null, $sort_field = null, $sort_order = null, $slice = 0) {
$target = array();
if (is_array($folder) && count($folder) > 0) {
// mailboxes list supplied
$target = $folder;
} elseif (is_string($folder) && strlen($folder) > 0) {
// single mailbox supplied
$target = array($folder);
} elseif (array_key_exists('search_scope', $_SESSION) && $_SESSION['search_scope'] == 'all') {
// no mailbox supplied, search within all mailboxes
$target = $this->list_folders_subscribed('', '*', 'mail', null, true);
} else if (array_key_exists('search_scope', $_SESSION) && $_SESSION['search_scope'] == 'sub') {
// no mailbox supplied, search within current mailbox and nested ones
$target = $this->list_folders_subscribed($this->folder, '*', 'mail');
}