forked from osTicket/osTicket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
class.search.php
executable file
·1657 lines (1368 loc) · 52.1 KB
/
class.search.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
/*********************************************************************
module.search.php
Search Engine for osTicket
This module defines the pieces for a search engine for osTicket.
Searching can be performed by various search engine backends which can
make use of the features of various search providers.
A reference search engine backend is provided which uses MySQL MyISAM
tables. This default backend should not be used on Galera clusters.
Jared Hancock <[email protected]>
Peter Rotich <[email protected]>
Copyright (c) 2006-2013 osTicket
http://www.osticket.com
Released under the GNU General Public License WITHOUT ANY WARRANTY.
See LICENSE.TXT for details.
vim: expandtab sw=4 ts=4 sts=4:
**********************************************************************/
require_once INCLUDE_DIR . 'class.role.php';
require_once INCLUDE_DIR . 'class.list.php';
require_once INCLUDE_DIR . 'class.queue.php';
abstract class SearchBackend {
static $id = false;
static $registry = array();
const SORT_RELEVANCE = 1;
const SORT_RECENT = 2;
const SORT_OLDEST = 3;
const PERM_EVERYTHING = 'search.all';
static protected $perms = array(
self::PERM_EVERYTHING => array(
'title' => /* @trans */ 'Search',
'desc' => /* @trans */ 'See all tickets in search results, regardless of access',
'primary' => true,
),
);
abstract function update($model, $id, $content, $new=false, $attrs=array());
abstract function find($query, QuerySet $criteria, $addRelevance=true);
static function register($backend=false) {
$backend = $backend ?: get_called_class();
if ($backend::$id == false)
throw new Exception('SearchBackend must define an ID');
static::$registry[$backend::$id] = $backend;
}
function getInstance($id) {
if (!isset(self::$registry[$id]))
return null;
return new self::$registry[$id]();
}
static function getPermissions() {
return self::$perms;
}
}
RolePermission::register(/* @trans */ 'Miscellaneous', SearchBackend::getPermissions());
// Register signals to intercept saving of various content throughout the
// system
class SearchInterface {
var $backend;
function __construct() {
$this->bootstrap();
}
function find($query, QuerySet $criteria, $addRelevance=true) {
$query = Format::searchable($query);
return $this->backend->find($query, $criteria, $addRelevance);
}
function update($model, $id, $content, $new=false, $attrs=array()) {
if ($this->backend)
$this->backend->update($model, $id, $content, $new, $attrs);
}
function createModel($model) {
return $this->updateModel($model, true);
}
function deleteModel($model) {
if ($this->backend)
$this->backend->delete($model);
}
function updateModel($model, $new=false) {
// The MySQL backend does not need to index attributes of the
// various models, because those other attributes are available in
// the local database in other tables.
switch (true) {
case $model instanceof ThreadEntry:
// Only index an entry for threads if a human created the
// content
if (!$model->getUserId() && !$model->getStaffId())
break;
$this->update($model, $model->getId(),
$model->getBody()->getSearchable(),
$new === true,
array(
'title' => $model->getTitle(),
'created' => $model->getCreateDate(),
)
);
break;
case $model instanceof Ticket:
$cdata = array();
foreach ($model->loadDynamicData() as $a)
if ($v = $a->getSearchable())
$cdata[] = $v;
$this->update($model, $model->getId(),
trim(implode("\n", $cdata)),
$new === true,
array(
'title'=> Format::searchable($model->getSubject()),
'number'=> $model->getNumber(),
'status'=> $model->getStatus(),
'topic_id'=> $model->getTopicId(),
'priority_id'=> $model->getPriorityId(),
// Stats (comments, attachments)
// Access constraints
'dept_id'=> $model->getDeptId(),
'staff_id'=> $model->getStaffId(),
'team_id'=> $model->getTeamId(),
// Sorting and ranging preferences
'created'=> $model->getCreateDate(),
// Add last-updated timestamp
)
);
break;
case $model instanceof User:
$cdata = array();
foreach ($model->getDynamicData($false) as $e)
foreach ($e->getAnswers() as $tag=>$a)
if ($tag != 'subject' && ($v = $a->getSearchable()))
$cdata[] = $v;
$this->update($model, $model->getId(),
trim(implode("\n", $cdata)),
$new === true,
array(
'title'=> Format::searchable($model->getFullName()),
'emails'=> $model->emails->asArray(),
'org_id'=> $model->getOrgId(),
'created'=> $model->getCreateDate(),
)
);
break;
case $model instanceof Organization:
$cdata = array();
foreach ($model->getDynamicData(false) as $e)
foreach ($e->getAnswers() as $a)
if ($v = $a->getSearchable())
$cdata[] = $v;
$this->update($model, $model->getId(),
trim(implode("\n", $cdata)),
$new === true,
array(
'title'=> Format::searchable($model->getName()),
'created'=> $model->getCreateDate(),
)
);
break;
case $model instanceof FAQ:
$this->update($model, $model->getId(),
$model->getSearchableAnswer(),
$new === true,
array(
'title'=> Format::searchable($model->getQuestion()),
'keywords'=> $model->getKeywords(),
'topics'=> $model->getHelpTopicsIds(),
'category_id'=> $model->getCategoryId(),
'created'=> $model->getCreateDate(),
)
);
break;
default:
// Not indexed
break;
}
}
function bootstrap() {
// Determine the backend
if (defined('SEARCH_BACKEND'))
$bk = SearchBackend::getInstance(SEARCH_BACKEND);
if (!$bk && !($bk = SearchBackend::getInstance('mysql')))
// No backend registered or defined
return false;
$this->backend = $bk;
$this->backend->bootstrap();
$self = $this;
// Thread entries
// Tickets, which can be edited as well
// Knowledgebase articles (FAQ and canned responses)
// Users, organizations
Signal::connect('threadentry.created', array($this, 'createModel'));
Signal::connect('ticket.created', array($this, 'createModel'));
Signal::connect('user.created', array($this, 'createModel'));
Signal::connect('organization.created', array($this, 'createModel'));
Signal::connect('model.created', array($this, 'createModel'), 'FAQ');
Signal::connect('model.updated', array($this, 'updateModel'));
Signal::connect('model.deleted', array($this, 'deleteModel'));
}
}
require_once(INCLUDE_DIR.'class.config.php');
class MySqlSearchConfig extends Config {
var $table = CONFIG_TABLE;
function __construct() {
parent::__construct("mysqlsearch");
}
}
class MysqlSearchBackend extends SearchBackend {
static $id = 'mysql';
static $BATCH_SIZE = 30;
// Only index 20 batches per cron run
var $max_batches = 60;
var $_reindexed = 0;
var $SEARCH_TABLE;
function __construct() {
$this->SEARCH_TABLE = TABLE_PREFIX . '_search';
}
function getConfig() {
if (!isset($this->config))
$this->config = new MySqlSearchConfig();
return $this->config;
}
function bootstrap() {
if ($this->getConfig()->get('reindex', true))
Signal::connect('cron', array($this, 'IndexOldStuff'));
}
function update($model, $id, $content, $new=false, $attrs=array()) {
if (!($type=ObjectModel::getType($model)))
return;
if ($model instanceof Ticket)
$attrs['title'] = $attrs['number'].' '.$attrs['title'];
elseif ($model instanceof User)
$content .=' '.implode("\n", $attrs['emails']);
$title = $attrs['title'] ?: '';
if (!$content && !$title)
return;
if (!$id)
return;
$sql = 'REPLACE INTO '.$this->SEARCH_TABLE
. ' SET object_type='.db_input($type)
. ', object_id='.db_input($id)
. ', content='.db_input($content)
. ', title='.db_input($title);
return db_query($sql, false);
}
function delete($model) {
switch (true) {
case $model instanceof Thread:
$sql = 'DELETE s.* FROM '.$this->SEARCH_TABLE
. " s JOIN ".THREAD_ENTRY_TABLE." h ON (h.id = s.object_id) "
. " WHERE s.object_type='H'"
. ' AND h.thread_id='.db_input($model->getId());
return db_query($sql);
default:
if (!($type = ObjectModel::getType($model)))
return;
$sql = 'DELETE FROM '.$this->SEARCH_TABLE
. ' WHERE object_type='.db_input($type)
. ' AND object_id='.db_input($model->getId());
return db_query($sql);
}
}
// Quote things like email addresses
function quote($query) {
$parts = array();
if (!preg_match_all('`(?:([^\s"\']+)|"[^"]*"|\'[^\']*\')(\s*)`', $query, $parts,
PREG_SET_ORDER))
return $query;
$results = array();
foreach ($parts as $m) {
// Check for quoting
if ($m[1] // Already quoted?
&& preg_match('`@`u', $m[0])
) {
$char = strpos($m[1], '"') ? "'" : '"';
$m[0] = $char . $m[0] . $char;
}
$results[] = $m[0].$m[2];
}
return implode('', $results);
}
function find($query, QuerySet $criteria, $addRelevance=true) {
global $thisstaff;
// MySQL usually doesn't handle words shorter than three letters
// (except with special configuration)
if (strlen($query) < 3)
return $criteria;
$criteria = clone $criteria;
$mode = ' IN NATURAL LANGUAGE MODE';
// According to the MySQL full text boolean mode, this grammar is
// assumed:
// see http://dev.mysql.com/doc/refman/5.6/en/fulltext-boolean.html
//
// PREOP = [<>~+-]
// POSTOP = [*]
// WORD = [\w][\w-]*
// TERM = PREOP? WORD POSTOP?
// QWORD = " [^"]+ "
// PARENS = \( { { TERM | QWORD } { \s+ { TERM | QWORD } }+ } \)
// EXPR = { PREOP? PARENS | TERM | QWORD }
// BOOLEAN = EXPR { \s+ EXPR }*
//
// Changing '{' for (?: and '}' for ')', collapsing whitespace, we
// have this regular expression
$BOOLEAN = '(?:[<>~+-]?\((?:(?:[<>~+-]?[\w][\w-]*[*]?|"[^"]+")(?:\s+(?:[<>~+-]?[\w][\w-]*[*]?|"[^"]+"))+)\)|[<>~+-]?[\w][\w-]*[*]?|"[^"]+")(?:\s+(?:[<>~+-]?\((?:(?:[<>~+-]?[\w][\w-]*[*]?|"[^"]+")(?:\s+(?:[<>~+-]?[\w][\w-]*[*]?|"[^"]+"))+)\)|[<>~+-]?[\w][\w-]*[*]?|"[^"]+"))*';
// Require the use of at least one operator and conform to the
// boolean mode grammar
if (preg_match('`(^|\s)["()<>~+-]`u', $query, $T = array())
&& preg_match("`^{$BOOLEAN}$`u", $query, $T = array())
) {
// If using boolean operators, search in boolean mode. This regex
// will ensure proper placement of operators, whitespace, and quotes
// in an effort to avoid crashing the query at MySQL
$query = $this->quote($query);
$mode = ' IN BOOLEAN MODE';
}
#elseif (count(explode(' ', $query)) == 1)
# $mode = ' WITH QUERY EXPANSION';
$search = 'MATCH (Z1.title, Z1.content) AGAINST ('.db_input($query).$mode.')';
switch ($criteria->model) {
case false:
case 'Ticket':
if ($addRelevance) {
$criteria = $criteria->extra(array(
'select' => array(
'__relevance__' => 'Z1.`relevance`',
),
));
}
$criteria->extra(array(
'tables' => array(
str_replace(array(':', '{}'), array(TABLE_PREFIX, $search),
"(SELECT COALESCE(Z3.`object_id`, Z5.`ticket_id`, Z8.`ticket_id`) as `ticket_id`, Z1.relevance FROM (SELECT Z1.`object_id`, Z1.`object_type`, {} AS `relevance` FROM `:_search` Z1 WHERE {} ORDER BY relevance DESC) Z1 LEFT JOIN `:thread_entry` Z2 ON (Z1.`object_type` = 'H' AND Z1.`object_id` = Z2.`id`) LEFT JOIN `:thread` Z3 ON (Z2.`thread_id` = Z3.`id` AND Z3.`object_type` = 'T') LEFT JOIN `:ticket` Z5 ON (Z1.`object_type` = 'T' AND Z1.`object_id` = Z5.`ticket_id`) LEFT JOIN `:user` Z6 ON (Z6.`id` = Z1.`object_id` and Z1.`object_type` = 'U') LEFT JOIN `:organization` Z7 ON (Z7.`id` = Z1.`object_id` AND Z7.`id` = Z6.`org_id` AND Z1.`object_type` = 'O') LEFT JOIN `:ticket` Z8 ON (Z8.`user_id` = Z6.`id`)) Z1"),
),
));
$criteria->extra(array('order_by' => array(array(new SqlCode('Z1.relevance', 'DESC')))));
$criteria->filter(array('ticket_id'=>new SqlCode('Z1.`ticket_id`')));
break;
case 'User':
$criteria->extra(array(
'select' => array(
'__relevance__' => 'Z1.`relevance`',
),
'tables' => array(
str_replace(array(':', '{}'), array(TABLE_PREFIX, $search),
"(SELECT Z6.`id` as `user_id`, {} AS `relevance` FROM `:_search` Z1 LEFT JOIN `:user` Z6 ON (Z6.`id` = Z1.`object_id` and Z1.`object_type` = 'U') LEFT JOIN `:organization` Z7 ON (Z7.`id` = Z1.`object_id` AND Z7.`id` = Z6.`org_id` AND Z1.`object_type` = 'O') WHERE {}) Z1"),
)
));
$criteria->filter(array('id'=>new SqlCode('Z1.`user_id`')));
break;
case 'Organization':
$criteria->extra(array(
'select' => array(
'__relevance__' => 'Z1.`relevance`',
),
'tables' => array(
str_replace(array(':', '{}'), array(TABLE_PREFIX, $search),
"(SELECT Z2.`id` as `org_id`, {} AS `relevance` FROM `:_search` Z1 LEFT JOIN `:organization` Z2 ON (Z2.`id` = Z1.`object_id` AND Z1.`object_type` = 'O') WHERE {}) Z1"),
)
));
$criteria->filter(array('id'=>new SqlCode('Z1.`org_id`')));
break;
}
// TODO: Ensure search table exists;
if (false) {
// TODO: Create the search table automatically
// $class::createSearchTable();
}
return $criteria;
}
static function createSearchTable() {
// Use InnoDB with Galera, MyISAM with v5.5, and the database
// default otherwise
$sql = "select count(*) from information_schema.tables where
table_schema='information_schema' and table_name =
'INNODB_FT_CONFIG'";
$mysql56 = db_result(db_query($sql));
$sql = "show status like 'wsrep_local_state'";
$galera = db_result(db_query($sql));
if ($galera && !$mysql56)
throw new Exception('Galera cannot be used with MyISAM tables. Upgrade to MariaDB 10 / MySQL 5.6 is required');
$engine = $galera ? 'InnodB' : ($mysql56 ? '' : 'MyISAM');
if ($engine)
$engine = 'ENGINE='.$engine;
$sql = 'CREATE TABLE IF NOT EXISTS '.TABLE_PREFIX."_search (
`object_type` varchar(8) not null,
`object_id` int(11) unsigned not null,
`title` text collate utf8_general_ci,
`content` text collate utf8_general_ci,
primary key `object` (`object_type`, `object_id`),
fulltext key `search` (`title`, `content`)
) $engine CHARSET=utf8";
if (!db_query($sql))
return false;
// Start rebuilding the index
$config = new MySqlSearchConfig();
$config->set('reindex', 1);
return true;
}
/**
* Cooperates with the cron system to automatically find content that is
* not indexed in the _search table and add it to the index.
*/
function IndexOldStuff() {
$class = get_class();
$auto_create = function($db_error) use ($class) {
if ($db_error != 1146)
// Perform the standard error handling
return true;
// Create the search table automatically
$class::__init();
};
// THREADS ----------------------------------
$sql = "SELECT A1.`id`, A1.`title`, A1.`body`, A1.`format` FROM `".THREAD_ENTRY_TABLE."` A1
LEFT JOIN `".TABLE_PREFIX."_search` A2 ON (A1.`id` = A2.`object_id` AND A2.`object_type`='H')
WHERE A2.`object_id` IS NULL AND (A1.poster <> 'SYSTEM')
AND (IFNULL(LENGTH(A1.`title`), 0) + IFNULL(LENGTH(A1.`body`), 0) > 0)
ORDER BY A1.`id` DESC LIMIT 500";
if (!($res = db_query_unbuffered($sql, $auto_create)))
return false;
while ($row = db_fetch_row($res)) {
$body = ThreadEntryBody::fromFormattedText($row[2], $row[3]);
$body = $body->getSearchable();
$title = Format::searchable($row[1]);
if (!$body && !$title)
continue;
$record = array('H', $row[0], $title, $body);
if (!$this->__index($record))
return;
}
// TICKETS ----------------------------------
$sql = "SELECT A1.`ticket_id` FROM `".TICKET_TABLE."` A1
LEFT JOIN `".TABLE_PREFIX."_search` A2 ON (A1.`ticket_id` = A2.`object_id` AND A2.`object_type`='T')
WHERE A2.`object_id` IS NULL
ORDER BY A1.`ticket_id` DESC LIMIT 300";
if (!($res = db_query_unbuffered($sql, $auto_create)))
return false;
while ($row = db_fetch_row($res)) {
if (!($ticket = Ticket::lookup($row[0])))
continue;
$cdata = $ticket->loadDynamicData();
$content = array();
foreach ($cdata as $k=>$a)
if ($k != 'subject' && ($v = $a->getSearchable()))
$content[] = $v;
$record = array('T', $ticket->getId(),
Format::searchable($ticket->getNumber().' '.$ticket->getSubject()),
implode("\n", $content));
if (!$this->__index($record))
return;
}
// USERS ------------------------------------
$sql = "SELECT A1.`id` FROM `".USER_TABLE."` A1
LEFT JOIN `".TABLE_PREFIX."_search` A2 ON (A1.`id` = A2.`object_id` AND A2.`object_type`='U')
WHERE A2.`object_id` IS NULL";
if (!($res = db_query_unbuffered($sql, $auto_create)))
return false;
while ($row = db_fetch_row($res)) {
$user = User::lookup($row[0]);
$cdata = $user->getDynamicData();
$content = array();
foreach ($user->emails as $e)
$content[] = $e->address;
foreach ($cdata as $e)
foreach ($e->getAnswers() as $a)
if ($c = $a->getSearchable())
$content[] = $c;
$record = array('U', $user->getId(),
Format::searchable($user->getFullName()),
trim(implode("\n", $content)));
if (!$this->__index($record))
return;
}
// ORGANIZATIONS ----------------------------
$sql = "SELECT A1.`id` FROM `".ORGANIZATION_TABLE."` A1
LEFT JOIN `".TABLE_PREFIX."_search` A2 ON (A1.`id` = A2.`object_id` AND A2.`object_type`='O')
WHERE A2.`object_id` IS NULL";
if (!($res = db_query_unbuffered($sql, $auto_create)))
return false;
while ($row = db_fetch_row($res)) {
$org = Organization::lookup($row[0]);
$cdata = $org->getDynamicData();
$content = array();
foreach ($cdata as $e)
foreach ($e->getAnswers() as $a)
if ($c = $a->getSearchable())
$content[] = $c;
$record = array('O', $org->getId(),
Format::searchable($org->getName()),
trim(implode("\n", $content)));
if (!$this->__index($record))
return null;
}
// KNOWLEDGEBASE ----------------------------
require_once INCLUDE_DIR . 'class.faq.php';
$sql = "SELECT A1.`faq_id` FROM `".FAQ_TABLE."` A1
LEFT JOIN `".TABLE_PREFIX."_search` A2 ON (A1.`faq_id` = A2.`object_id` AND A2.`object_type`='K')
WHERE A2.`object_id` IS NULL";
if (!($res = db_query_unbuffered($sql, $auto_create)))
return false;
while ($row = db_fetch_row($res)) {
$faq = FAQ::lookup($row[0]);
$q = $faq->getQuestion();
if ($k = $faq->getKeywords())
$q = $k.' '.$q;
$record = array('K', $faq->getId(),
Format::searchable($q),
$faq->getSearchableAnswer());
if (!$this->__index($record))
return;
}
// FILES ------------------------------------
// Flush non-full batch of records
$this->__index(null, true);
if (!$this->_reindexed) {
// Stop rebuilding the index
$this->getConfig()->set('reindex', 0);
}
}
function __index($record, $force_flush=false) {
static $queue = array();
if ($record)
$queue[] = $record;
elseif (!$queue)
return;
if (!$force_flush && count($queue) < $this::$BATCH_SIZE)
return true;
foreach ($queue as &$r)
$r = sprintf('(%s)', implode(',', db_input($r)));
unset($r);
$sql = 'INSERT INTO `'.TABLE_PREFIX.'_search` (`object_type`, `object_id`, `title`, `content`)
VALUES '.implode(',', $queue);
if (!db_query($sql, false) || count($queue) != db_affected_rows())
throw new Exception('Unable to index content');
$this->_reindexed += count($queue);
$queue = array();
if (!--$this->max_batches)
return null;
return true;
}
static function __init() {
self::createSearchTable();
}
}
Signal::connect('system.install',
array('MysqlSearchBackend', '__init'));
MysqlSearchBackend::register();
// Saved search system
/**
* Custom Queue truly represent a saved advanced search.
*/
class SavedQueue extends CustomQueue {
// Override the ORM relationship to force no children
private $children = false;
private $_config;
private $_criteria;
private $_columns;
private $_settings;
private $_form;
function __onload() {
global $thisstaff;
// Load custom settings for this staff
if ($thisstaff) {
$this->_config = QueueConfig::lookup(array(
'queue_id' => $this->getId(),
'staff_id' => $thisstaff->getId())
);
}
}
static function forStaff(Staff $agent) {
return static::objects()->filter(Q::any(array(
'staff_id' => $agent->getId(),
'flags__hasbit' => self::FLAG_PUBLIC,
)))
->exclude(array('flags__hasbit'=>self::FLAG_QUEUE));
}
private function getSettings() {
if (!isset($this->_settings)) {
$this->_settings = array();
if ($this->_config)
$this->_settings = $this->_config->getSettings();
}
return $this->_settings;
}
private function getCustomColumns() {
if (!isset($this->_columns)) {
$this->_columns = array();
if ($this->_config
&& $this->_config->columns->count())
$this->_columns = $this->_config->columns;
}
return $this->_columns;
}
static function getHierarchicalQueues(Staff $staff, $pid=0,
$primary=true) {
return CustomQueue::getHierarchicalQueues($staff, 0, false);
}
/**
* Fetch an AdvancedSearchForm instance for use in displaying or
* configuring this search in the user interface.
*
*/
function getForm($source=null, $searchable=array()) {
$searchable = null;
if ($this->isAQueue())
// Only allow supplemental matches.
$searchable = array_intersect_key($this->getCurrentSearchFields($source),
$this->getSupplementalMatches());
return parent::getForm($source, $searchable);
}
/**
* Get get supplemental matches for public queues.
*
*/
function getSupplementalMatches() {
// Target flags
$flags = array('isoverdue', 'isassigned', 'isreopened', 'isanswered');
$current = array();
// Check for closed state - whih disables above flags
foreach (parent::getCriteria() as $c) {
if (!strcasecmp($c[0], 'status__state')
&& isset($c[2]['closed']))
return array();
$current[] = $c[0];
}
// Filter out fields already in criteria
$matches = array_intersect_key($this->getSupportedMatches(),
array_flip(array_diff($flags, $current)));
return $matches;
}
function criteriaRequired() {
return !$this->isAQueue();
}
function describeCriteria($criteria=false){
$criteria = $criteria ?: parent::getCriteria();
return parent::describeCriteria($criteria);
}
function getCriteria($include_parent=true) {
if (!isset($this->_criteria)) {
$this->getSettings();
$this->_criteria = $this->_settings['criteria'] ?: array();
}
$criteria = $this->_criteria;
if ($include_parent)
$criteria = array_merge($criteria,
parent::getCriteria($include_parent));
return $criteria;
}
function getSupplementalCriteria() {
return $this->getCriteria(false);
}
function useStandardColumns() {
$this->getSettings();
if ($this->getCustomColumns()
&& isset($this->_settings['inherit-columns']))
return $this->_settings['inherit-columns'];
// owner?? edit away.
if ($this->_config
&& $this->_config->staff_id == $this->staff_id)
return false;
return parent::useStandardColumns();
}
function getStandardColumns() {
return parent::getColumns(is_null($this->parent));
}
function getColumns($use_template=false) {
if (!$this->useStandardColumns() && ($columns=$this->getCustomColumns()))
return $columns;
return parent::getColumns($use_template);
}
function update($vars, &$errors=array()) {
global $thisstaff;
if (!$this->checkAccess($thisstaff))
return false;
if ($this->checkOwnership($thisstaff)) {
// Owner of the queue - can update everything
if (!parent::update($vars, $errors))
return false;
// Personal queues _always_ inherit from their parent
$this->setFlag(self::FLAG_INHERIT_CRITERIA, $this->parent_id >
0);
return true;
}
// Agent's config for public queue.
if (!$this->_config)
$this->_config = QueueConfig::create(array(
'queue_id' => $this->getId(),
'staff_id' => $thisstaff->getId()));
// Validate & isolate supplemental criteria (if any)
$vars['criteria'] = array();
if (isset($vars['fields'])) {
$form = $this->getForm($vars, $thisstaff);
if ($form->isValid()) {
$criteria = self::isolateCriteria($form->getClean(),
$this->getRoot());
$allowed = $this->getSupplementalMatches();
foreach ($criteria as $k => $c)
if (!isset($allowed[$c[0]]))
unset($criteria[$k]);
$vars['criteria'] = $criteria ?: array();
} else {
$errors['criteria'] = __('Validation errors exist on supplimental criteria');
}
}
if (!$errors && $this->_config->update($vars, $errors))
$this->_settings = $this->_criteria = null;
return (!$errors);
}
function getTotal($agent=null) {
$query = $this->getQuery();
if ($agent)
$query = $agent->applyVisibility($query);
$query->limit(false)->offset(false)->order_by(false);
try {
return $query->count();
} catch (Exception $e) {
return null;
}
}
function getCount($agent, $cached=true) {
$count = null;
if ($cached && ($counts = self::counts($agent, $cached)))
$count = $counts["q{$this->getId()}"];
if ($count == null)
$count = $this->getTotal($agent);
return $count;
}
// Get ticket counts for queues the agent has acces to.
static function counts($agent, $cached=true, $criteria=array()) {
if (!$agent instanceof Staff)
return null;
// Cache TLS in seconds
$ttl = 5*60;
// Cache key based on agent and salt of the installation
$key = "counts.queues.{$agent->getId()}.".SECRET_SALT;
if ($criteria && is_array($criteria)) // Consider additional criteria.
$key .= '.'.md5(serialize($criteria));
// only consider cache if requesed
if ($cached && ($counts=self::getCounts($key, $ttl)))
return $counts;
$queues = static::objects()
->filter(Q::any(array(
'flags__hasbit' => CustomQueue::FLAG_QUEUE,
'staff_id' => $agent->getId(),
)));
if ($criteria && is_array($criteria))
$queues->filter($criteria);
$counts = array();
$query = Ticket::objects();
// Apply tickets visibility for the agent
$query = $agent->applyVisibility($query, true);
// Aggregate constraints
foreach ($queues as $queue) {
$Q = $queue->getBasicQuery();
if ($Q->constraints) {
$empty = false;
if (count($Q->constraints) > 1) {
foreach ($Q->constraints as $value) {
if (!$value->constraints)
$empty = true;
}
}
if (!$empty) {
$expr = SqlCase::N()->when(new SqlExpr(new Q($Q->constraints)), new SqlField('ticket_id'));
$query->aggregate(array(
"q{$queue->id}" => SqlAggregate::COUNT($expr, true)
));
}
}
// Add extra tables joins (if any)
if ($Q->extra && isset($Q->extra['tables'])) {
$counts['q'.$queue->getId()] = 500;
continue;
$contraints = array();
if ($Q->constraints)
$constraints = new Q($Q->constraints);
foreach ($Q->extra['tables'] as $T)
$query->addExtraJoin(array($T, $constraints, ''));
}
}
try {
$counts = array_merge($counts, $query->values()->one());
} catch (Exception $ex) {
foreach ($queues as $q)
$counts['q'.$q->getId()] = $q->getTotal();
}
// Always cache the results
self::storeCounts($key, $counts, $ttl);
return $counts;
}
static function getCounts($key, $ttl) {
if (!$key) {
return array();
} elseif (function_exists('apcu_store')) {
$found = false;
$counts = apcu_fetch($key, $found);
if ($found === true)
return $counts;
} elseif (isset($_SESSION['qcounts'][$key])
&& (time() - $_SESSION['qcounts'][$key]['time']) < $ttl) {
return $_SESSION['qcounts'][$key]['counts'];
} else {
// Auto clear missed session cache (if any)
unset($_SESSION['qcounts'][$key]);
}
}
static function storeCounts($key, $counts, $ttl) {
if (function_exists('apcu_store')) {
apcu_store($key, $counts, $ttl);
} else {
// Poor man's cache
$_SESSION['qcounts'][$key]['counts'] = $counts;
$_SESSION['qcounts'][$key]['time'] = time();
}
}
static function clearCounts() {
if (function_exists('apcu_store')) {
if (class_exists('APCUIterator')) {
$regex = '/^counts.queues.\d+.' . preg_quote(SECRET_SALT, '/') . '$/';
foreach (new APCUIterator($regex, APC_ITER_KEY) as $key) {
apcu_delete($key);
}
}
// Also clear rough counts
apcu_delete("rough.counts.".SECRET_SALT);
}
}
static function lookup($criteria) {
$queue = parent::lookup($criteria);
// Annoted cusom settings (if any)
if (($c=$queue->_config)) {
$queue->_settings = $c->getSettings() ?: array();
$queue = AnnotatedModel::wrap($queue,
array_intersect_key($queue->_settings,
array_flip(array('sort_id', 'filter'))));
$queue->_config = $c;
}