forked from jstanden/cerb
/
Application.class.php
1798 lines (1517 loc) · 56.2 KB
/
Application.class.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
/***********************************************************************
| Cerb(tm) developed by WebGroup Media, LLC.
|-----------------------------------------------------------------------
| All source code & content (c) Copyright 2012, WebGroup Media LLC
| unless specifically noted otherwise.
|
| This source code is released under the Devblocks Public License.
| The latest version of this license can be found here:
| http://cerberusweb.com/license
|
| By using this software, you acknowledge having read this license
| and agree to be bound thereby.
| ______________________________________________________________________
| http://www.cerberusweb.com http://www.webgroupmedia.com/
***********************************************************************/
/*
* IMPORTANT LICENSING NOTE from your friends on the Cerberus Helpdesk Team
*
* Sure, it would be so easy to just cheat and edit this file to use the
* software without paying for it. But we trust you anyway. In fact, we're
* writing this software for you!
*
* Quality software backed by a dedicated team takes money to develop. We
* don't want to be out of the office bagging groceries when you call up
* needing a helping hand. We'd rather spend our free time coding your
* feature requests than mowing the neighbors' lawns for rent money.
*
* We've never believed in hiding our source code out of paranoia over not
* getting paid. We want you to have the full source code and be able to
* make the tweaks your organization requires to get more done -- despite
* having less of everything than you might need (time, people, money,
* energy). We shouldn't be your bottleneck.
*
* We've been building our expertise with this project since January 2002. We
* promise spending a couple bucks [Euro, Yuan, Rupees, Galactic Credits] to
* let us take over your shared e-mail headache is a worthwhile investment.
* It will give you a sense of control over your inbox that you probably
* haven't had since spammers found you in a game of 'E-mail Battleship'.
* Miss. Miss. You sunk my inbox!
*
* A legitimate license entitles you to support from the developers,
* and the warm fuzzy feeling of feeding a couple of obsessed developers
* who want to help you get more done.
*
* - Jeff Standen, Darren Sugita, Dan Hildebrandt, Scott Luther
* WEBGROUP MEDIA LLC. - Developers of Cerberus Helpdesk
*/
define("APP_BUILD", 2013022701);
define("APP_VERSION", '6.2.5');
define("APP_MAIL_PATH", APP_STORAGE_PATH . '/mail/');
require_once(APP_PATH . "/api/Model.class.php");
require_once(APP_PATH . "/api/Extension.class.php");
// App Scope ClassLoading
$path = APP_PATH . '/api/app/';
DevblocksPlatform::registerClasses($path . 'Mail.php', array(
'CerberusMail',
));
DevblocksPlatform::registerClasses($path . 'Parser.php', array(
'CerberusParser',
'CerberusParserMessage',
'CerberusParserModel',
'ParserFile',
'ParserFileBuffer',
));
DevblocksPlatform::registerClasses($path . 'Update.php', array(
'ChUpdateController',
));
DevblocksPlatform::registerClasses($path . 'Utils.php', array(
'CerberusUtils',
));
/**
* Application-level Facade
*/
class CerberusApplication extends DevblocksApplication {
/**
* @return CerberusVisit
*/
static function getVisit() {
$session = DevblocksPlatform::getSessionService();
return $session->getVisit();
}
/**
* @return Model_Worker
*/
static function getActiveWorker() {
$visit = self::getVisit();
return (null != $visit)
? $visit->getWorker()
: null
;
}
/**
*
* @param string $uri
* @return DevblocksExtensionManifest or NULL
*/
static function getPageManifestByUri($uri) {
$pages = DevblocksPlatform::getExtensions('cerberusweb.page', false);
foreach($pages as $manifest) { /* @var $manifest DevblocksExtensionManifest */
if(0 == strcasecmp($uri,$manifest->params['uri'])) {
return $manifest;
}
}
return NULL;
}
static function processRequest(DevblocksHttpRequest $request, $is_ajax=false) {
/**
* Override the 'update' URI since we can't count on the database
* being populated from XML beforehand when /update loads it.
*/
if(!$is_ajax && isset($request->path[0]) && 0 == strcasecmp($request->path[0],'update')) {
if(null != ($update_controller = new ChUpdateController(null)))
$update_controller->handleRequest($request);
} else {
// Hand it off to the platform
DevblocksPlatform::processRequest($request, $is_ajax);
}
}
static function checkRequirements() {
$errors = array();
// Privileges
// Make sure the temporary directories of Devblocks are writeable.
if(!is_writeable(APP_TEMP_PATH)) {
$errors[] = APP_TEMP_PATH ." is not writeable by the webserver. Please adjust permissions and reload this page.";
}
if(!file_exists(APP_TEMP_PATH . "/templates_c")) {
@mkdir(APP_TEMP_PATH . "/templates_c");
}
if(!is_writeable(APP_TEMP_PATH . "/templates_c/")) {
$errors[] = APP_TEMP_PATH . "/templates_c/" . " is not writeable by the webserver. Please adjust permissions and reload this page.";
}
if(!file_exists(APP_TEMP_PATH . "/cache")) {
@mkdir(APP_TEMP_PATH . "/cache");
}
if(!is_writeable(APP_TEMP_PATH . "/cache/")) {
$errors[] = APP_TEMP_PATH . "/cache/" . " is not writeable by the webserver. Please adjust permissions and reload this page.";
}
if(!is_writeable(APP_STORAGE_PATH)) {
$errors[] = APP_STORAGE_PATH ." is not writeable by the webserver. Please adjust permissions and reload this page.";
}
if(!is_writeable(APP_STORAGE_PATH . "/import/fail")) {
$errors[] = APP_STORAGE_PATH . "/import/fail/" ." is not writeable by the webserver. Please adjust permissions and reload this page.";
}
if(!is_writeable(APP_STORAGE_PATH . "/import/new")) {
$errors[] = APP_STORAGE_PATH . "/import/new/" ." is not writeable by the webserver. Please adjust permissions and reload this page.";
}
if(!is_writeable(APP_STORAGE_PATH . "/mail/new/")) {
$errors[] = APP_STORAGE_PATH . "/mail/new/" ." is not writeable by the webserver. Please adjust permissions and reload this page.";
}
if(!is_writeable(APP_STORAGE_PATH . "/mail/fail/")) {
$errors[] = APP_STORAGE_PATH . "/mail/fail/" ." is not writeable by the webserver. Please adjust permissions and reload this page.";
}
// Requirements
// PHP Version
if(version_compare(PHP_VERSION,"5.3") >=0) {
} else {
$errors[] = sprintf("Cerb %s requires PHP 5.3 or later. Your server PHP version is %s",
APP_VERSION,
PHP_VERSION
);
}
// File Uploads
$ini_file_uploads = ini_get("file_uploads");
if($ini_file_uploads == 1 || strcasecmp($ini_file_uploads,"on")==0) {
} else {
$errors[] = 'file_uploads is disabled in your php.ini file. Please enable it.';
}
// Memory Limit
$memory_limit = ini_get("memory_limit");
if ($memory_limit == '') { // empty string means failure or not defined, assume no compiled memory limits
} else {
$ini_memory_limit = DevblocksPlatform::parseBytesString($memory_limit);
if($ini_memory_limit < 16777216) {
$errors[] = 'memory_limit must be 16M or larger (32M recommended) in your php.ini file. Please increase it.';
}
}
// Extension: MySQL
if(extension_loaded("mysql")) {
} else {
$errors[] = "The 'MySQL' PHP extension is required. Please enable it.";
}
// Extension: Sessions
if(extension_loaded("session")) {
} else {
$errors[] = "The 'Session' PHP extension is required. Please enable it.";
}
// Extension: cURL
if(extension_loaded("curl")) {
} else {
$errors[] = "The 'cURL' PHP extension is required. Please enable it.";
}
// Extension: PCRE
if(extension_loaded("pcre")) {
} else {
$errors[] = "The 'PCRE' PHP extension is required. Please enable it.";
}
// Extension: GD
if(extension_loaded("gd") && function_exists('imagettfbbox')) {
} else {
$errors[] = "The 'GD' PHP extension (with FreeType library support) is required. Please enable them.";
}
// Extension: IMAP
if(extension_loaded("imap")) {
} else {
$errors[] = "The 'IMAP' PHP extension is required. Please enable it.";
}
// Extension: MailParse
if(extension_loaded("mailparse")) {
} else {
$errors[] = "The 'MailParse' PHP extension is required. Please enable it.";
}
// Extension: mbstring
if(extension_loaded("mbstring")) {
} else {
$errors[] = "The 'mbstring' PHP extension is required. Please enable it.";
}
// Extension: XML
if(extension_loaded("xml")) {
} else {
$errors[] = "The 'XML' PHP extension is required. Please enable it.";
}
// Extension: SimpleXML
if(extension_loaded("simplexml")) {
} else {
$errors[] = "The 'SimpleXML' PHP extension is required. Please enable it.";
}
// Extension: DOM
if(extension_loaded("dom")) {
} else {
$errors[] = "The 'DOM' PHP extension is required. Please enable it.";
}
// Extension: SPL
if(extension_loaded("spl")) {
} else {
$errors[] = "The 'SPL' PHP extension is required. Please enable it.";
}
// Extension: ctype
if(extension_loaded("ctype")) {
} else {
$errors[] = "The 'ctype' PHP extension is required. Please enable it.";
}
// Extension: JSON
if(extension_loaded("json")) {
} else {
$errors[] = "The 'JSON' PHP extension is required. Please enable it.";
}
return $errors;
}
static function update() {
// Update the platform
if(!DevblocksPlatform::update())
throw new Exception("Couldn't update Devblocks.");
// Read in plugin information from the filesystem to the database
DevblocksPlatform::readPlugins();
// Clean up missing plugins
DAO_Platform::cleanupPluginTables();
DAO_Platform::maint();
// Registry
$plugins = DevblocksPlatform::getPluginRegistry();
// Update the application core (version by version)
if(!isset($plugins['cerberusweb.core']))
throw new Exception("Couldn't read application manifest.");
$plugin_patches = array();
// Load patches
foreach($plugins as $p) { /* @var $p DevblocksPluginManifest */
if('devblocks.core'==$p->id)
continue;
// Don't patch disabled plugins
if($p->enabled) {
// Ensure that the plugin requirements match, or disable
if(!$p->checkRequirements()) {
$p->setEnabled(false);
continue;
}
$plugin_patches[$p->id] = $p->getPatches();
}
}
$core_patches = $plugin_patches['cerberusweb.core'];
unset($plugin_patches['cerberusweb.core']);
/*
* For each core release, patch plugins in dependency order
*/
foreach($core_patches as $patch) { /* @var $patch DevblocksPatch */
if(!file_exists($patch->getFilename()))
throw new Exception("Missing application patch: ".$patch->getFilename());
$version = $patch->getVersion();
if(!$patch->run())
throw new Exception("Application patch failed to apply: ".$patch->getFilename());
// Patch this version and then patch plugins up to this version
foreach($plugin_patches as $plugin_id => $patches) {
$pass = true;
foreach($patches as $k => $plugin_patch) {
// Recursive patch up to _version_
if($pass && version_compare($plugin_patch->getVersion(), $version, "<=")) {
if($plugin_patch->run()) {
unset($plugin_patches[$plugin_id][$k]);
} else {
$plugins[$plugin_id]->setEnabled(false);
$pass = false;
}
}
}
}
}
return TRUE;
}
static function generatePassword($length=8) {
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ123456789';
$len = strlen($chars)-1;
$password = '';
for($x=0;$x<$length;$x++) {
$chars = str_shuffle($chars);
$password .= substr($chars,mt_rand(0,$len),1);
}
return $password;
}
/**
* @return a unique ticket mask as a string
*/
static function generateTicketMask($pattern = null) {
if(empty($pattern))
$pattern = DevblocksPlatform::getPluginSetting('cerberusweb.core', CerberusSettings::TICKET_MASK_FORMAT);
if(empty($pattern))
$pattern = CerberusSettingsDefaults::TICKET_MASK_FORMAT;
$letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ";
$numbers = "123456789";
do {
$mask = "";
$bytes = preg_split('//', $pattern, -1, PREG_SPLIT_NO_EMPTY);
$literal = false;
if(is_array($bytes))
foreach($bytes as $byte) {
$append = '';
switch(strtoupper($byte)) {
case '{':
$literal = true;
$byte = '';
break;
case '}':
$literal = false;
$append = '';
break;
case 'L':
$append .= substr($letters,mt_rand(0,strlen($letters)-1),1);
break;
case 'N':
$append .= substr($numbers,mt_rand(0,strlen($numbers)-1),1);
break;
case 'C': // L or N
if(mt_rand(0,100) >= 50) { // L
$append .= substr($letters,mt_rand(0,strlen($letters)-1),1);
} else { // N
$append .= substr($numbers,mt_rand(0,strlen($numbers)-1),1);
}
break;
case 'Y':
$append .= date('Y');
break;
case 'M':
$append .= date('m');
break;
case 'D':
$append .= date('d');
break;
default:
$append .= $byte;
break;
}
if($literal) {
$mask .= $byte;
} else {
$mask .= $append;
}
$mask = strtoupper(DevblocksPlatform::strAlphaNum($mask,'\-'));
}
} while(null != DAO_Ticket::getTicketIdByMask($mask));
return $mask;
}
static function generateTicketMaskCardinality($pattern = null) {
if(empty($pattern))
$pattern = DevblocksPlatform::getPluginSetting('cerberusweb.core', CerberusSettings::TICKET_MASK_FORMAT);
if(empty($pattern))
$pattern = CerberusSettingsDefaults::TICKET_MASK_FORMAT;
$combinations = 1;
$bytes = preg_split('//', $pattern, -1, PREG_SPLIT_NO_EMPTY);
$literal = false;
if(is_array($bytes))
foreach($bytes as $byte) {
$mul = 1;
switch(strtoupper($byte)) {
case '{':
$literal = true;
break;
case '}':
$literal = false;
break;
case 'L':
$mul *= 25;
break;
case 'N':
$mul *= 9;
break;
case 'C': // L or N
$mul *= 34;
break;
case 'Y':
$mul *= 1;
break;
case 'M':
$mul *= 12;
break;
case 'D':
$mul *= 30;
break;
default:
break;
}
if(!$literal)
$combinations = round($combinations*$mul,0);
}
return $combinations;
}
/**
* Generate an RFC-compliant Message-ID
*/
static function generateMessageId() {
$message_id = sprintf('<%s.%s@%s>', base_convert(time(), 10, 36), base_convert(mt_rand(), 10, 36), !empty($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME']);
return $message_id;
}
/**
* Translates the string version of a group/bucket combo into their
* respective IDs.
*
* @todo This needs a better name and home
*/
static function translateGroupBucketCode($code) {
$t_or_c = substr($code,0,1);
$t_or_c_id = intval(substr($code,1));
if($t_or_c=='c') {
$buckets = DAO_Bucket::getAll();
$group_id = $buckets[$t_or_c_id]->group_id;
$bucket_id = $t_or_c_id;
} else {
$group_id = $t_or_c_id;
$bucket_id = 0;
}
return array($group_id, $bucket_id);
}
/**
* Looks up an e-mail address using a revolving cache. This is helpful
* in situations where you may look up the same e-mail address multiple
* times (reports, audit log, views) and you don't want to waste code
* filtering out dupes.
*
* @param string $address The e-mail address to look up
* @param bool $create Should the address be created if not found?
* @return Model_Address The address object or NULL
*
* @todo [JAS]: Move this to a global cache/hash registry
*/
static public function hashLookupAddress($email, $create=false) {
static $hash_address_to_id = array();
static $hash_hits = array();
static $hash_size = 0;
if(isset($hash_address_to_id[$email])) {
$return = $hash_address_to_id[$email];
@$hash_hits[$email] = intval($hash_hits[$email]) + 1;
$hash_size++;
// [JAS]: if our hash grows past our limit, crop hits array + intersect keys
if($hash_size > 250) {
arsort($hash_hits);
$hash_hits = array_slice($hash_hits,0,100,true);
$hash_address_to_id = array_intersect_key($hash_address_to_id,$hash_hits);
$hash_size = count($hash_address_to_id);
}
return $return;
}
$address = DAO_Address::lookupAddress($email, $create);
if(!empty($address)) {
$hash_address_to_id[$email] = $address;
}
return $address;
}
/**
* Looks up a ticket ID by the provided mask using a revolving cache.
* This is useful if you need to translate several ticket masks into
* IDs where there may be a lot of redundancy (batches in the e-mail
* parser, etc.)
*
* @param string $mask The ticket mask to look up
* @return integer The ticket id, or NULL if not found
*
* @todo [JAS]: Move this to a global cache/hash registry
*/
static public function hashLookupTicketIdByMask($mask) {
static $hash_mask_to_id = array();
static $hash_hits = array();
static $hash_size = 0;
if(isset($hash_mask_to_id[$mask])) {
$return = $hash_mask_to_id[$mask];
@$hash_hits[$mask] = intval($hash_hits[$mask]) + 1;
$hash_size++;
// [JAS]: if our hash grows past our limit, crop hits array + intersect keys
if($hash_size > 250) {
arsort($hash_hits);
$hash_hits = array_slice($hash_hits,0,100,true);
$hash_mask_to_id = array_intersect_key($hash_mask_to_id,$hash_hits);
$hash_size = count($hash_mask_to_id);
}
return $return;
}
$ticket_id = DAO_Ticket::getTicketIdByMask($mask);
if(!empty($ticket_id)) {
$hash_mask_to_id[$mask] = $ticket_id;
}
return $ticket_id;
}
};
class CerbException extends DevblocksException {
};
interface IContextToken {
static function getValue($context, $context_values);
};
class CerberusContexts {
private static $_default_actor_context = null;
private static $_default_actor_context_id = null;
const CONTEXT_APPLICATION = 'cerberusweb.contexts.app';
const CONTEXT_ACTIVITY_LOG = 'cerberusweb.contexts.activity_log';
const CONTEXT_ADDRESS = 'cerberusweb.contexts.address';
const CONTEXT_ATTACHMENT = 'cerberusweb.contexts.attachment';
const CONTEXT_BUCKET = 'cerberusweb.contexts.bucket';
const CONTEXT_CALENDAR_EVENT = 'cerberusweb.contexts.calendar_event';
const CONTEXT_CALL = 'cerberusweb.contexts.call';
const CONTEXT_COMMENT = 'cerberusweb.contexts.comment';
const CONTEXT_CONTACT_PERSON = 'cerberusweb.contexts.contact_person';
const CONTEXT_DOMAIN = 'cerberusweb.contexts.datacenter.domain';
const CONTEXT_DRAFT = 'cerberusweb.contexts.mail.draft';
const CONTEXT_FEED = 'cerberusweb.contexts.feed';
const CONTEXT_FEED_ITEM = 'cerberusweb.contexts.feed.item';
const CONTEXT_FEEDBACK = 'cerberusweb.contexts.feedback';
const CONTEXT_GROUP = 'cerberusweb.contexts.group';
const CONTEXT_KB_ARTICLE = 'cerberusweb.contexts.kb_article';
const CONTEXT_KB_CATEGORY = 'cerberusweb.contexts.kb_category';
const CONTEXT_MESSAGE = 'cerberusweb.contexts.message';
const CONTEXT_NOTIFICATION= 'cerberusweb.contexts.notification';
const CONTEXT_OPPORTUNITY = 'cerberusweb.contexts.opportunity';
const CONTEXT_ORG = 'cerberusweb.contexts.org';
const CONTEXT_PORTAL = 'cerberusweb.contexts.portal';
const CONTEXT_PROJECT = 'cerberusweb.contexts.project';
const CONTEXT_ROLE = 'cerberusweb.contexts.role';
const CONTEXT_SENSOR = 'cerberusweb.contexts.datacenter.sensor';
const CONTEXT_SERVER = 'cerberusweb.contexts.datacenter.server';
const CONTEXT_SNIPPET = 'cerberusweb.contexts.snippet';
const CONTEXT_TASK = 'cerberusweb.contexts.task';
const CONTEXT_TICKET = 'cerberusweb.contexts.ticket';
const CONTEXT_TIMETRACKING = 'cerberusweb.contexts.timetracking';
const CONTEXT_WORKER = 'cerberusweb.contexts.worker';
public static function getContext($context, $context_object, &$labels, &$values, $prefix=null, $nested=false) {
switch($context) {
case 'cerberusweb.contexts.attachment':
self::_getAttachmentContext($context_object, $labels, $values, $prefix);
break;
default:
// Migrated
if(null != ($ctx = DevblocksPlatform::getExtension($context, true))
&& $ctx instanceof Extension_DevblocksContext) {
$ctx->getContext($context_object, $labels, $values, $prefix);
}
break;
}
if(!$nested) {
// Globals
CerberusContexts::merge(
'global_',
'(Global) ',
array(
'timestamp|date' => 'Current Date+Time',
),
array(
'timestamp' => time(),
),
$labels,
$values
);
// Current worker (Don't add to worker context)
if($context != CerberusContexts::CONTEXT_WORKER) {
$active_worker = CerberusApplication::getActiveWorker();
$merge_token_labels = array();
$merge_token_values = array();
self::getContext(self::CONTEXT_WORKER, $active_worker, $merge_token_labels, $merge_token_values, '', true);
CerberusContexts::merge(
'worker_',
'Current:Worker:',
$merge_token_labels,
$merge_token_values,
$labels,
$values
);
}
// Plugin-provided tokens
$token_extension_mfts = DevblocksPlatform::getExtensions('cerberusweb.snippet.token', false);
foreach($token_extension_mfts as $mft) { /* @var $mft DevblocksExtensionManifest */
@$token = $mft->params['token'];
@$label = $mft->params['label'];
@$contexts = $mft->params['contexts'][0];
if(empty($token) || empty($label) || !is_array($contexts))
continue;
if(!isset($contexts[$context]))
continue;
if(null != ($ext = $mft->createInstance()) && $ext instanceof IContextToken) {
/* @var $ext IContextToken */
$value = $ext->getValue($context, $values);
if(!empty($value)) {
$labels['plugin_'.$token] = '(Plugin) '.$label;
$values['plugin_'.$token] = $value;
}
}
}
}
// Rename labels
foreach($labels as $idx => $label) {
// [TODO] mb_*
$labels[$idx] = ucfirst(strtolower(strtr($label,':',' ')));
}
// Alphabetize
asort($labels);
return null;
}
public static function scrubTokensWithRegexp(&$labels, &$values, $patterns=array()) {
foreach($patterns as $pattern) {
foreach(array_keys($labels) as $token) {
if(preg_match($pattern, $token)) {
unset($labels[$token]);
}
}
foreach(array_keys($values) as $token) {
if(false !== ($pos = strpos($token,'|')))
$token = substr($token,0,$pos);
if(preg_match($pattern, $token)) {
unset($values[$token]);
}
}
}
return TRUE;
}
/**
*
* @param string $token_prefix
* @param array $label_replace
* @param array $src_labels
* @param array $dst_labels
* @param array $src_values
* @param array $dst_values
* @return void
*/
public static function merge($token_prefix, $label_prefix, $src_labels, $src_values, &$dst_labels, &$dst_values) {
foreach($src_labels as $token => $label) {
$dst_labels[$token_prefix.$token] = $label_prefix.$label;
}
foreach($src_values as $token => $value) {
$dst_values[$token_prefix.$token] = $src_values[$token];
}
return true;
}
static public function getWatchers($context, $context_id, $as_contexts=false) {
list($results, $null) = DAO_Worker::search(
array(
SearchFields_Worker::ID,
),
array(
new DevblocksSearchCriteria(SearchFields_Worker::CONTEXT_LINK,'=',$context),
new DevblocksSearchCriteria(SearchFields_Worker::CONTEXT_LINK_ID,'=',$context_id),
),
0,
0,
null,
null,
false
);
$workers = array();
// Does the caller want the watchers as context objects?
if($as_contexts) {
foreach(array_keys($results) as $watcher_id) {
$null_labels = array();
$watcher_values = array();
CerberusContexts::getContext(CerberusContexts::CONTEXT_WORKER, $watcher_id, $null_labels, $watcher_values, null, true);
$workers[$watcher_id] = $watcher_values;
}
// Or as Model_* objects?
} else {
if(!empty($results)) {
$workers = DAO_Worker::getWhere(sprintf("%s IN (%s)",
DAO_Worker::ID,
implode(',', array_keys($results))
));
}
}
return $workers;
}
static public function addWatchers($context, $context_id, $worker_ids) {
$workers = DAO_Worker::getAll();
if(!is_array($worker_ids))
$worker_ids = array($worker_ids);
foreach($worker_ids as $worker_id) {
if(null != ($worker = @$workers[$worker_id]) && $worker instanceof Model_Worker && !$worker->is_disabled) {
DAO_ContextLink::setLink($context, $context_id, CerberusContexts::CONTEXT_WORKER, $worker_id);
}
}
}
static public function removeWatchers($context, $context_id, $worker_ids) {
if(!is_array($worker_ids))
$worker_ids = array($worker_ids);
foreach($worker_ids as $worker_id)
DAO_ContextLink::deleteLink($context, $context_id, CerberusContexts::CONTEXT_WORKER, $worker_id);
}
static public function formatActivityLogEntry($entry, $format=null, $scrub_tokens=array()) {
$tpl_builder = DevblocksPlatform::getTemplateBuilder();
$url_writer = DevblocksPlatform::getUrlService();
$translate = DevblocksPlatform::getTranslationService();
// Load the translated version of the message
$entry['message'] = $translate->_($entry['message']);
// Scrub desired tokens
if(is_array($scrub_tokens) && !empty($scrub_tokens)) {
foreach($scrub_tokens as $token) {
// Scrub tokens and only preserve trailing whitespace
$entry['message'] = preg_replace('#\s*\{\{'.$token.'\}\}(\s*)#', '\1', $entry['message']);
}
}
// Variables
$vars = $entry['variables'];
switch($format) {
case 'html':
// HTML formatting and incorporating URLs
if(is_array($vars))
foreach($vars as $k => $v) {
$vars[$k] = htmlentities($v, ENT_QUOTES, LANG_CHARSET_CODE);
}
if(isset($entry['urls']))
foreach($entry['urls'] as $token => $url) {
if(0 == strcasecmp('ctx://',substr($url,0,6))) {
$url = self::parseContextUrl($url);
} elseif(0 != strcasecmp('http',substr($url,0,4))) {
$url = $url_writer->writeNoProxy($url, true);
}
$vars[$token] = '<a href="'.$url.'" style="font-weight:bold;">'.$vars[$token].'</a>';
}
break;
case 'markdown':
if(isset($entry['urls']))
foreach($entry['urls'] as $token => $url) {
if(0 == strcasecmp('ctx://',substr($url,0,6))) {
$url = self::parseContextUrl($url);
} elseif(0 != strcasecmp('http',substr($url,0,4))) {
$url = $url_writer->writeNoProxy($url, true);
}
$vars[$token] = '['.$vars[$token].']('.$url.')';
}
break;
case 'email':
@$url = reset($entry['urls']);
if(empty($url))
break;
if(0 == strcasecmp('ctx://',substr($url,0,6))) {
$url = self::parseContextUrl($url);
} elseif(0 != strcasecmp('http',substr($url,0,4))) {
$url = $url_writer->writeNoProxy($url, true);
}
$entry['message'] .= ' <' . $url . '>';
break;
default:
break;
}
if(!is_array($vars))
$vars = array();
return $tpl_builder->build($entry['message'], $vars);
}
static function parseContextUrl($url) {
if(0 != strcasecmp('ctx://',substr($url,0,6))) {
return false;
}
$context_parts = explode('/', substr($url,6));
$context_pair = explode(':', $context_parts[0], 2);
if(count($context_pair) != 2)
return false;
$context = $context_pair[0];
$context_id = $context_pair[1];
if(null == ($context_ext = Extension_DevblocksContext::get($context)))
return null;
if($context_ext instanceof IDevblocksContextProfile) {
$url = $context_ext->profileGetUrl($context_id);
} else {
$meta = $context_ext->getMeta($context_id);
if(is_array($meta) && isset($meta['permalink']))
$url = $meta['permalink'];
}
return $url;
}
static public function setActivityDefaultActor($context, $context_id=null) {
if(empty($context) || empty($context_id)) {
self::$_default_actor_context = null;
self::$_default_actor_context_id = null;
} else {
self::$_default_actor_context = $context;
self::$_default_actor_context_id = $context_id;
}
}
static public function logActivity($activity_point, $target_context, $target_context_id, $entry_array, $actor_context=null, $actor_context_id=null, $also_notify_worker_ids=array()) {
// Target meta
if(!isset($target_meta)) {
if(null != ($target_ctx = DevblocksPlatform::getExtension($target_context, true))
&& $target_ctx instanceof Extension_DevblocksContext) {
$target_meta = $target_ctx->getMeta($target_context_id);
}
}
// Forced actor
if(!empty($actor_context) && !empty($actor_context_id)) {
if(null != ($ctx = DevblocksPlatform::getExtension($actor_context, true))
&& $ctx instanceof Extension_DevblocksContext) {
$meta = $ctx->getMeta($actor_context_id);
$actor_name = $meta['name'];
$actor_url = $meta['permalink'];
}
}
// Auto-detect the actor
if(empty($actor_context)) {
$actor_name = null;
$actor_context = null;
$actor_context_id = 0;
$actor_url = null;
// See if we're inside of an attendant's running decision tree
$stack = EventListener_Triggers::getTriggerStack();
if(EventListener_Triggers::getDepth() > 0
&& null != ($trigger_id = end($stack))
&& !empty($trigger_id)
&& null != ($trigger = DAO_TriggerEvent::get($trigger_id))
) {
/* @var $trigger Model_TriggerEvent */
switch($trigger->owner_context) {