/
Subs-SimpleDesk.php
2017 lines (1821 loc) · 70.5 KB
/
Subs-SimpleDesk.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
###############################################################
# Simple Desk Project - www.simpledesk.net #
###############################################################
# An advanced help desk modifcation built on SMF #
###############################################################
# #
# * Copyright 2010 - SimpleDesk.net #
# #
# This file and its contents are subject to the license #
# included with this distribution, license.txt, which #
# states that this software is New BSD Licensed. #
# Any questions, please contact SimpleDesk.net #
# #
###############################################################
# SimpleDesk Version: 2.0 Anatidae #
# File Info: Subs-SimpleDesk.php / 2.0 Anatidae #
###############################################################
/**
* This file handles key functions for SimpleDesk that can be called on every page load, such as the
* custom query function to handle ticket visibility, the counter for active tickets in the menu header, or the action log.
*
* @package subs
* @since 1.0
*/
if (!defined('SMF'))
die('Hacking attempt...');
/**
* Initialises key values for SimpleDesk.
*
* This function initialises certain key constructs for SimpleDesk, such as constants, that are used throughout
* SimpleDesk. It should be called first right up in Load.php anyway.
*
* Calling multiple times is not significantly detrimental to performance; the function is aware if it has been
* called previously.
*
* @since 2.0
*/
function shd_init()
{
global $modSettings, $sourcedir, $user_info, $context, $smcFunc;
static $called = null;
if (!empty($called))
return;
$called = true;
$context['shd_home'] = 'action=helpdesk;sa=main';
// What SD version are we on? It's now here!
define('SHD_VERSION', 'SimpleDesk 2.0 Anatidae');
// This isn't the SMF way. But for something like this, it's way way more logical and readable.
define('TICKET_STATUS_NEW', 0);
define('TICKET_STATUS_PENDING_STAFF', 1);
define('TICKET_STATUS_PENDING_USER', 2);
define('TICKET_STATUS_CLOSED', 3);
define('TICKET_STATUS_WITH_SUPERVISOR', 4);
define('TICKET_STATUS_ESCALATED', 5);
define('TICKET_STATUS_DELETED', 6);
define('TICKET_URGENCY_LOW', 0);
define('TICKET_URGENCY_MEDIUM', 1);
define('TICKET_URGENCY_HIGH', 2);
define('TICKET_URGENCY_VHIGH', 3);
define('TICKET_URGENCY_SEVERE', 4);
define('TICKET_URGENCY_CRITICAL', 5);
define('MSG_STATUS_NORMAL', 0);
define('MSG_STATUS_DELETED', 1);
// Relationship types
define('RELATIONSHIP_LINKED', 0);
define('RELATIONSHIP_DUPLICATED', 1);
define('RELATIONSHIP_ISPARENT', 2);
define('RELATIONSHIP_ISCHILD', 3);
// Custom fields, their types, positions, content type
define('CFIELD_TICKET', 1);
define('CFIELD_REPLY', 2);
define('CFIELD_PLACE_DETAILS', 1);
define('CFIELD_PLACE_INFO', 2);
define('CFIELD_PLACE_PREFIX', 3);
define('CFIELD_PLACE_PREFIXFILTER', 4);
define('CFIELD_TYPE_TEXT', 1);
define('CFIELD_TYPE_LARGETEXT', 2);
define('CFIELD_TYPE_INT', 3);
define('CFIELD_TYPE_FLOAT', 4);
define('CFIELD_TYPE_SELECT', 5);
define('CFIELD_TYPE_CHECKBOX', 6);
define('CFIELD_TYPE_RADIO', 7);
define('CFIELD_TYPE_MULTI', 8);
// Ticket notification options
define('NOTIFY_PREFS', 0);
define('NOTIFY_ALWAYS', 1);
define('NOTIFY_NEVER', 2);
// Roles and permissions
define('ROLE_USER', 1);
define('ROLE_STAFF', 2);
//define('ROLE_SUPERVISOR', 3);
define('ROLE_ADMIN', 4);
define('ROLEPERM_DISALLOW', 0);
define('ROLEPERM_ALLOW', 1);
define('ROLEPERM_DENY', 2);
// How many digits should we show for ticket numbers? Normally we pad to 5 digits, e.g. 00001 - this is how we set that width.
if (empty($modSettings['shd_zerofill']) || $modSettings['shd_zerofill'] < 0)
$modSettings['shd_zerofill'] = 0;
// Load some stuff
shd_load_language('sd_language/SimpleDesk');
require_once($sourcedir . '/sd_source/Subs-SimpleDeskPermissions.php');
// Set up defaults
$defaults = array(
'shd_attachments_mode' => 'ticket',
'shd_ticketnav_style' => 'sd',
'shd_staff_badge' => 'nobadge',
'shd_privacy_display' => 'smart',
);
foreach ($defaults as $var => $val)
{
if (empty($modSettings[$var]))
$modSettings[$var] = $val;
}
$modSettings['helpdesk_active'] = isset($modSettings['admin_features']) ? in_array('shd', explode(',', $modSettings['admin_features'])) : false;
if ($modSettings['helpdesk_active'])
{
shd_load_plugin_files('init');
shd_load_plugin_langfiles('init');
}
shd_load_user_perms();
if (!empty($modSettings['shd_maintenance_mode']))
{
if (!empty($modSettings['shd_helpdesk_only']) && !$user_info['is_admin'] && !shd_allowed_to('admin_helpdesk', 0))
{
// You can only login.... otherwise, you're getting the "maintenance mode" display. Except we have to boot up a decent amount of SMF.
if (empty($_REQUEST['action']) || ($_REQUEST['action'] != 'login2' && $_REQUEST['action'] != 'logout'))
{
$_GET['action'] = '';
$_REQUEST['action'] = '';
$context['shd_maintenance_mode'] = true;
loadBoard();
loadPermissions();
loadTheme();
is_not_banned();
require_once($sourcedir . '/Subs-Auth.php');
InMaintenance();
obExit(null, null, false);
}
}
else
$modSettings['helpdesk_active'] &= ($user_info['is_admin'] || shd_allowed_to('admin_helpdesk', 0));
}
// Last minute stuff
if ($modSettings['helpdesk_active'])
{
// Are they actually going into the helpdesk? If they are, do we need to deal with their theme?
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'helpdesk')
{
// First figure out what department they're in.
$this_dept = 0;
$depts = shd_allowed_to('access_helpdesk', false);
// Do they only have one dept? If so, that's the one.
if (count($depts) == 1)
$this_dept = $depts[0];
// They might explicitly say it on the request.
elseif (isset($_REQUEST['dept']))
{
$_REQUEST['dept'] = (int) $_REQUEST['dept'];
if (in_array($_REQUEST['dept'], $depts))
$this_dept = $_REQUEST['dept'];
}
// They might explicitly be posting into a dept from nowhere-land
elseif (isset($_REQUEST['newdept']))
{
$_REQUEST['newdept'] = (int) $_REQUEST['newdept'];
if (in_array($_REQUEST['newdept'], $depts))
$this_dept = $_REQUEST['newdept'];
}
// They might specify a ticket, see if we can get the dept from that. Validate we can see it and get the dept from there.
elseif (isset($_REQUEST['ticket']))
{
$ticket = (int) $_REQUEST['ticket'];
if (!empty($ticket))
{
$query = shd_db_query('', '
SELECT hdt.id_dept, dept_name, dept_theme
FROM {db_prefix}helpdesk_tickets AS hdt
INNER JOIN {db_prefix}helpdesk_depts AS hdd ON (hdt.id_dept = hdd.id_dept)
WHERE id_ticket = {int:ticket}
AND {query_see_ticket}',
array(
'ticket' => $ticket,
)
);
if ($row = $smcFunc['db_fetch_row']($query))
if (in_array($row[0], $depts))
list($this_dept, $context['shd_dept_name'], $theme) = $row;
$smcFunc['db_free_result']($query);
}
}
if (!empty($this_dept) && !isset($theme))
{
$context['queried_dept'] = $this_dept;
$query = $smcFunc['db_query']('', '
SELECT dept_theme
FROM {db_prefix}helpdesk_depts
WHERE id_dept = {int:dept}',
array(
'dept' => $this_dept,
)
);
if ($row = $smcFunc['db_fetch_row']($query))
$theme = $row[0];
$smcFunc['db_free_result']($query);
}
// If for whatever reason we didn't establish a theme, see if there's a forum default one.
if (empty($theme) && !empty($modSettings['shd_theme']))
$theme = $modSettings['shd_theme'];
// Action.
if (!empty($theme))
{
// This is ever so slightly hacky. But as this function is called sufficiently early we can get away with it.
unset($_REQUEST['theme'], $modSettings['theme_allow']);
$modSettings['theme_guests'] = $theme;
}
}
}
$context['shd_plugins'] = empty($modSettings['shd_enabled_plugins']) || empty($modSettings['helpdesk_active']) ? array() : explode(',', $modSettings['shd_enabled_plugins']);
call_integration_hook('shd_hook_init');
}
/**
* Query wrapper around $smcFunc['db_query'] for helpdesk specific operations.
*
* This function provides a basic wrapper around SMF's internal $smcFunc['db_query'] function, adding the parameter {query_see_ticket}
* to it, specifically so that ticket visibility can be enforced in a query without being aware of the specific rules for the user.
*
* If not previously loaded, user permissions are loaded with {@link shd_load_user_perms()}.
*
* @param string $identifier SMF-style query identifier for database backend-specific replacements
* @param string $db_string Standard SMF 2.0 style database query, including {query_see_ticket} if appropriate
* @param array $db_values Standard SMF 2.0 style hash map of parameters to inject into the query
* @param resource $connection A database connection variable, if supplied, to override the one used by SMF by default
* @return resource Standard database query resource, suitable for processing with other $smcFunc['db_*'] functions
*
* @see shd_load_user_perms()
* @since 1.0
*/
function shd_db_query($identifier, $db_string, $db_values = array(), $connection = null)
{
global $user_info, $smcFunc;
$replacements = array(
'{query_see_ticket}' => $user_info['query_see_ticket'],
);
$db_string = str_replace(array_keys($replacements), array_values($replacements), $db_string);
$db_values['user_info_id'] = $user_info['id'];
return $smcFunc['db_query']($identifier, $db_string, $db_values, $connection);
}
/**
* Defines the helpdesk menu item, including the number of active tickets to be displayed to the user.
*
* Identifies the number of tickets that a user might be interested in, and generates the menu text for the main menu
* to include this; note that the value should be cached through SMF's functions. The cache is also clearable, through
* the {@link shd_clear_active_tickets()} function.
*
* @return string A formatted string containing the language-specific version of "Helpdesk [x]" menu item with the x in bold
* @see shd_clear_active_tickets()
* @since 1.0
*/
function shd_get_active_tickets()
{
global $modSettings, $user_info, $smcFunc, $context, $txt;
if (empty($txt['shd_helpdesk'])) // provide a last-ditch fallback in the event we can't even find the file; SimpleDesk.{language}.php should be loaded by now (falling back to english if lang-specific doesn't exist)
$txt['shd_helpdesk'] = 'Helpdesk';
if (!$modSettings['helpdesk_active'] || $context['user']['is_guest'] || !empty($context['shd_maintenance_mode']) || !empty($modSettings['shd_hidemenuitem']))
return $txt['shd_helpdesk'];
// Have we already run on this page? If so we already have the answer.
if (!empty($context['active_tickets']))
return $txt['shd_helpdesk'] . $context['active_tickets'];
// Can we get it from the cache?
$temp = cache_get_data('shd_active_tickets_' . $user_info['id'], 180);
if ($temp !== null)
{
list($context['active_tickets'], $context['active_tickets_raw']) = $temp;
$context['menu_buttons']['helpdesk']['alttitle'] = $txt['shd_helpdesk'] . !empty($context['active_tickets_raw']) ? (' [' . $context['active_tickets_raw'] . ']') : '';
return $txt['shd_helpdesk'] . $context['active_tickets'];
}
shd_init();
// Figure out the status(es) that the ticket could be.
if (shd_allowed_to('shd_staff', 0))
$status = array(TICKET_STATUS_NEW, TICKET_STATUS_PENDING_STAFF); // staff actually need to deal with these
else
$status = array(TICKET_STATUS_PENDING_USER); // user actually needs to deal with this
$query = shd_db_query('', '
SELECT COUNT(id_ticket)
FROM {db_prefix}helpdesk_tickets AS hdt
WHERE {query_see_ticket} AND status IN ({array_int:status})',
array(
'status' => $status,
)
);
$context['active_tickets_raw'] = 0;
$row = $smcFunc['db_fetch_row']($query);
if (!empty($row[0]))
{
$context['menu_buttons']['helpdesk']['alttitle'] = $txt['shd_helpdesk'] . ' [' . $row[0] . ']';
$context['active_tickets'] = ' [<strong>' . $row[0] . '</strong>]';
$context['active_tickets_raw'] = $row[0]; // in case you want to do something funky in the theme later?
}
else
$context['active_tickets'] = '';
cache_put_data('shd_active_tickets_' . $user_info['id'], array($context['active_tickets'], $context['active_tickets_raw']), 120);
return $txt['shd_helpdesk'] . $context['active_tickets'];
}
/**
* Clears the cache of active tickets for the menu item.
*
* {@link shd_get_active_tickets()} generates the number of active tickets for the user display, and caches it for 180 seconds
* normally. This function clears the cache and should be called whenever any operation modifies the state of a ticket.
*
* @param int $dept The department that is being affected by this change. Users who cannot see this department will not be affected.
* @see shd_get_active_tickets()
* @since 1.0
*/
function shd_clear_active_tickets($dept = 0)
{
global $modSettings;
static $done_all = false;
// This isn't very nice, unfortunately. But it's the only way to ensure that caches are flushed as necessary and to prevent us having to query so much more on every page.
// Firstly, the active ticket count. Needs to be for every person that can see this department.
$members = shd_members_allowed_to('access_helpdesk', $dept);
if (!$done_all)
{
foreach ($members as $member)
{
cache_put_data('shd_active_tickets_' . $member, null, 120);
cache_put_data('shd_ticket_count_' . $member, null, 120);
}
$done_all = true;
}
// This is going to hurt.
if ($dept == 0)
{
$depts = shd_allowed_to('access_helpdesk', false);
foreach ($depts as $dept)
foreach ($members as $member)
cache_put_data('shd_ticket_count_dept' . $dept . '_' . $member, null, 120);
}
// Not so much?
else
{
foreach ($members as $member)
cache_put_data('shd_ticket_count_dept' . $dept . '_' . $member, null, 120);
}
// If we've updated this count, and the menu's cached, which it will be under the following conditions, update the 'settings'.
if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
updateSettings(
array('settings_updated' => time())
);
}
/**
* Adds an action to the helpdesk internal action log.
*
* This function deals with adding items to the action log maintained by the helpdesk.
*
* @param string $action Specifies the name of the action to log, which implies the image and language string (log_$action is the name of the image, and $txt['shd_log_$action'] is the string used to express the action, as listed in {@link SimpleDeskLogAction.english.php}.
* Note that since 1.1, the list of actions is looked up against the options in Admin / Helpdesk / Options / Action Log Options as to whether they should be logged or not
* @param array $params This is a list of named parameters in a hash array to be used in the language string later.
*
* @see shd_load_action_log_entries()
* @since 1.0
*/
function shd_log_action($action, $params, $do_last_update = true)
{
global $smcFunc, $context, $user_info, $modSettings;
static $last_cache;
// Before we go any further, we use this function to globally update tickets' last updated time (since every ticket action should potentially
// be logged) - but we don't do the query *every* time if we don't need to. Allows a two second leeway.
if ($do_last_update && isset($params['ticket']) && ((int) $params['ticket'] != 0) && (empty($last_cache[$params['ticket']]) || $last_cache[$params['ticket']] < time() - 2))
{
$last_cache[$params['ticket']] = time();
$smcFunc['db_query']('', '
UPDATE {db_prefix}helpdesk_tickets
SET last_updated = {int:new_time}
WHERE id_ticket = {int:ticket}',
array(
'new_time' => $last_cache[$params['ticket']],
'ticket' => $params['ticket'],
)
);
}
if (!empty($modSettings['shd_disable_action_log']))
return;
// Check to see if we should actually log this action or not.
$logopt = array(
'newticket' => 'shd_logopt_newposts',
'newticketproxy' => 'shd_logopt_newposts',
'editticket' => 'shd_logopt_editposts',
'newreply' => 'shd_logopt_newposts',
'editreply' => 'shd_logopt_editposts',
'resolve' => 'shd_logopt_resolve',
'unresolve' => 'shd_logopt_resolve',
'assign' => 'shd_logopt_assign',
'unassign' => 'shd_logopt_assign',
'markprivate' => 'shd_logopt_privacy',
'marknotprivate' => 'shd_logopt_privacy',
'urgency_increase' => 'shd_logopt_urgency',
'urgency_decrease' => 'shd_logopt_urgency',
'tickettotopic' => 'shd_logopt_tickettopicmove',
'topictoticket' => 'shd_logopt_tickettopicmove',
'delete' => 'shd_logopt_delete',
'delete_reply' => 'shd_logopt_delete',
'restore' => 'shd_logopt_restore',
'restore_reply' => 'shd_logopt_restore',
'permadelete' => 'shd_logopt_permadelete',
'permadelete_reply' => 'shd_logopt_permadelete',
'rel_linked' => 'shd_logopt_relationships',
'rel_duplicated' => 'shd_logopt_relationships',
'rel_parent' => 'shd_logopt_relationships',
'rel_child' => 'shd_logopt_relationships',
'rel_re_linked' => 'shd_logopt_relationships',
'rel_re_duplicated' => 'shd_logopt_relationships',
'rel_re_parent' => 'shd_logopt_relationships',
'rel_re_child' => 'shd_logopt_relationships',
'rel_delete' => 'shd_logopt_relationships',
'cf_tktchange_admin' => 'shd_logopt_cfchanges',
'cf_tktchange_staffadmin' => 'shd_logopt_cfchanges',
'cf_tktchange_useradmin' => 'shd_logopt_cfchanges',
'cf_tktchange_userstaffadmin' => 'shd_logopt_cfchanges',
'cf_rplchange_admin' => 'shd_logopt_cfchanges',
'cf_rplchange_staffadmin' => 'shd_logopt_cfchanges',
'cf_rplchange_useradmin' => 'shd_logopt_cfchanges',
'cf_rplchange_userstaffadmin' => 'shd_logopt_cfchanges',
'cf_tktchgdef_admin' => 'shd_logopt_cfchanges',
'cf_tktchgdef_staffadmin' => 'shd_logopt_cfchanges',
'cf_tktchgdef_useradmin' => 'shd_logopt_cfchanges',
'cf_tktchgdef_userstaffadmin' => 'shd_logopt_cfchanges',
'cf_rplchgdef_admin' => 'shd_logopt_cfchanges',
'cf_rplchgdef_staffadmin' => 'shd_logopt_cfchanges',
'cf_rplchgdef_useradmin' => 'shd_logopt_cfchanges',
'cf_rplchgdef_userstaffadmin' => 'shd_logopt_cfchanges',
'move_dept' => 'shd_logopt_move_dept',
'monitor' => 'shd_logopt_monitor',
'unmonitor' => 'shd_logopt_monitor',
'ignore' => 'shd_logopt_monitor',
'unignore' => 'shd_logopt_monitor',
);
if (empty($logopt[$action]) || empty($modSettings[$logopt[$action]]))
return;
// Some parts of $params we will want in the main row for sorting + lookups later. Let's see if they're here.
if (!empty($params['ticket']))
{
$ticket_id = (int) $params['ticket'];
if ($ticket_id == 0)
trigger_error('log_action(): received data with non-numeric ticket', E_USER_NOTICE);
else
unset($params['ticket']);
}
else
$ticket_id = 0;
if (!empty($params['msg']))
{
$msg_id = (int) $params['msg'];
if ($msg_id == 0)
trigger_error('log_action(): received data with non-numeric msg', E_USER_NOTICE);
else
unset($params['msg']);
}
else
$msg_id = 0;
$smcFunc['db_insert']('',
'{db_prefix}helpdesk_log_action',
array(
'log_time' => 'int', 'id_member' => 'int', 'ip' => 'string-16', 'action' => 'string', 'id_ticket' => 'int', 'id_msg' => 'int', 'extra' => 'string-65534',
),
array(
time(), $user_info['id'], $user_info['ip'], $action, $ticket_id, $msg_id, serialize($params),
),
array('id_action')
);
}
/**
* Determines if the current user can raise/lower the urgency of a ticket.
*
* This function identifies whether the current user can raise or lower the urgency of a ticket based on the current urgency
* of the ticket and whether it is their ticket; this is used in the ticket display as well as the actions linked directly to
* modifying urgency (both AJAXively and non AJAXively)
*
* @param int $urgency The current urgency of a ticket as an integer
* @param bool $ticket_starter Whether the user in question is the starter of the ticket (instead of querying to establish that,
* that detail should already be known to the calling function)
* @param bool $closed Whether the ticket is currently closed or not
* @param bool $deleted Whether the ticket is currently closed or not
*
* @see shd_urgency_change_noajax()
* @since 1.0
*/
function shd_can_alter_urgency($urgency, $ticket_starter, $closed, $deleted, $dept)
{
global $user_info;
$can_urgency = array(
'increase' => false,
'decrease' => false,
);
if ($closed || $deleted)
return $can_urgency;
if (shd_allowed_to('shd_alter_urgency_any', $dept))
{
if (shd_allowed_to('shd_alter_urgency_higher_any', $dept) || (shd_allowed_to('shd_alter_urgency_higher_own', $dept) && $ticket_starter == $user_info['id']))
$can_urgency = array( // can alter any urgency and can alter this one's higher urgency too
'increase' => ($urgency < TICKET_URGENCY_CRITICAL),
'decrease' => ($urgency > TICKET_URGENCY_LOW),
);
else
$can_urgency = array( // can alter any base urgency - just not this one's higher urgency
'increase' => ($urgency < TICKET_URGENCY_HIGH),
'decrease' => ($urgency > TICKET_URGENCY_LOW && $urgency < TICKET_URGENCY_VHIGH),
);
}
elseif (shd_allowed_to('shd_alter_urgency_own', $dept) && $ticket_starter == $user_info['id'])
$can_urgency = array( // ok, so this is our ticket and we can change it
'increase' => ($urgency < (shd_allowed_to('shd_alter_urgency_higher_own', $dept) ? TICKET_URGENCY_CRITICAL : TICKET_URGENCY_HIGH)),
'decrease' => ($urgency > TICKET_URGENCY_LOW && $urgency <= (shd_allowed_to('shd_alter_urgency_higher_own', $dept) ? TICKET_URGENCY_CRITICAL : TICKET_URGENCY_VHIGH)),
);
return $can_urgency;
}
/**
* Queries the database to find the number of applicable tickets
*
* This function collects counts for the different states of tickets (new, with staff, with user, etc) of all the tickets
* visible to the user, and returns a selection of that dataset based on the values provided to $status and $is_staff.
*
* @param string $status The relevant count of tickets to return:
* <ul>
* <li>'open': All tickets currently open that the user can see</li>
* <li>'assigned': All tickets assigned to the current user</li>
* <li>'new': All the new tickets that the user can see</li>
* <li>'staff': All the tickets currently with staff (varies for staff vs user; user count here includes 'new' tickets)</li>
* <li>'with_user': All the tickets pending user comment</li>
* <li>'closed': All the tickets the user can see that are resolved</li>
* <li>'recycled': All the tickets the user can see that are currently in the recycle bin</li>
* <li>'withdeleted': All the tickets that have at least one deleted reply</li>
* <li>'' or unspecified: Return the total of all tickets in the helpdesk (subject to visibility)</li>
* </ul>
* @param bool $is_staff If the user in question is staff or not.
*
* @return int Number of applicable tickets.
* @since 1.0
*/
function shd_count_helpdesk_tickets($status = '', $is_staff = false)
{
global $smcFunc, $context, $user_info;
if (empty($context['ticket_count']))
{
$context['ticket_count'] = array();
for ($i = 0; $i <= 6; $i++)
$context['ticket_count'][$i] = 0; // set the count to zero for all known states
$cache_id = 'shd_ticket_count_' . (!empty($context['shd_department']) ? 'dept' . $context['shd_department'] . '_' : '') . $user_info['id'];
$temp = cache_get_data($cache_id, 180);
if ($temp !== null)
{
$context['ticket_count'] = $temp;
}
else
{
$query = shd_db_query('', '
SELECT status, COUNT(status) AS tickets
FROM {db_prefix}helpdesk_tickets AS hdt
WHERE {query_see_ticket}' . (!empty($context['shd_department']) ? '
AND id_dept = ' . $context['shd_department'] : '') . '
GROUP BY status
ORDER BY null',
array()
);
while ($row = $smcFunc['db_fetch_assoc']($query))
$context['ticket_count'][$row['status']] = $row['tickets'];
$smcFunc['db_free_result']($query);
$context['ticket_count']['assigned'] = 0;
if (shd_allowed_to('shd_staff', 0))
{
$query = shd_db_query('', '
SELECT status, COUNT(status) AS tickets
FROM {db_prefix}helpdesk_tickets AS hdt
WHERE {query_see_ticket}
AND id_member_assigned = {int:user}' . (!empty($context['shd_department']) ? '
AND id_dept = ' . $context['shd_department'] : '') . '
GROUP BY status
ORDER BY null',
array(
'user' => $context['user']['id'],
)
);
while ($row = $smcFunc['db_fetch_assoc']($query))
{
if (!in_array($row['status'], array(TICKET_STATUS_CLOSED, TICKET_STATUS_DELETED)))
{
$context['ticket_count']['assigned'] += $row['tickets'];
$context['ticket_count'][$row['status']] -= $row['tickets'];
}
}
$smcFunc['db_free_result']($query);
}
if (shd_allowed_to('shd_access_recyclebin'))
{
$query = shd_db_query('', '
SELECT COUNT(id_ticket) AS tickets
FROM {db_prefix}helpdesk_tickets AS hdt
WHERE {query_see_ticket}' . (!empty($context['shd_department']) ? '
AND id_dept = ' . $context['shd_department'] : '') . '
AND hdt.withdeleted = {int:has_deleted}
AND hdt.status != {int:ticket_deleted}',
array(
'has_deleted' => MSG_STATUS_DELETED,
'ticket_deleted' => TICKET_STATUS_DELETED, // we want all non deleted tickets with deleted replies
)
);
list($count) = $smcFunc['db_fetch_row']($query);
$smcFunc['db_free_result']($query);
$context['ticket_count']['withdeleted'] = $count;
}
else
$context['ticket_count']['withdeleted'] = 0;
cache_put_data($cache_id, $context['ticket_count'], 180);
}
}
switch($status)
{
case 'open':
return (
$context['ticket_count'][TICKET_STATUS_NEW] +
$context['ticket_count'][TICKET_STATUS_PENDING_STAFF] +
$context['ticket_count'][TICKET_STATUS_PENDING_USER] +
$context['ticket_count'][TICKET_STATUS_WITH_SUPERVISOR] +
$context['ticket_count'][TICKET_STATUS_ESCALATED] +
$context['ticket_count']['assigned']
);
case 'assigned':
return $context['ticket_count']['assigned'];
case 'new':
return $context['ticket_count'][TICKET_STATUS_NEW];
case 'staff':
return $is_staff ? $context['ticket_count'][TICKET_STATUS_PENDING_STAFF] : ($context['ticket_count'][TICKET_STATUS_NEW] + $context['ticket_count'][TICKET_STATUS_PENDING_STAFF]); // both "new" and "with staff" should appear as 'with staff' to non staff
case 'with_user':
return $context['ticket_count'][TICKET_STATUS_PENDING_USER];
case 'closed':
return $context['ticket_count'][TICKET_STATUS_CLOSED];
case 'recycled':
return $context['ticket_count'][TICKET_STATUS_DELETED];
case 'withdeleted':
return $context['ticket_count']['withdeleted'];
default:
return array_sum($context['ticket_count']) - $context['ticket_count']['withdeleted']; // since withdeleted is the only duplicate information, all the rest is naturally self-exclusive
}
}
/**
* Attempts to load a given ticket's data.
*
* This function permission-checks, and throws appropriate errors if no ticket is specified either directly or through URL,
* or if the ticket is not accessible either through deletion or lack of permissions.
*
* @param int $ticket The ticket to use; if none is specified, use the one from $_REQUEST['ticket'], which will have been processed
* into $context['ticket_id'] if it is available.
*
* @return array A large hash map stating many ticket details
* @since 1.0
*/
function shd_load_ticket($ticket = 0)
{
global $context, $smcFunc, $scripturl;
// Make sure they set a ticket ID.
if ($ticket == 0 && empty($context['ticket_id']))
fatal_lang_error('shd_no_ticket', false);
// Get the ticket data. Note this implicitly checks perms too.
$query = shd_db_query('', '
SELECT hdt.id_first_msg, hdt.id_last_msg, hdt.id_member_started, hdt.subject, hdt.urgency, hdt.status,
hdt.num_replies, hdt.deleted_replies, hdt.private, hdtr.body, hdtr.id_member, hdtr.poster_time,
hdtr.modified_time, hdtr.smileys_enabled, hdt.id_dept AS dept, hdd.dept_name,
IFNULL(mem.real_name, hdtr.poster_name) AS starter_name, IFNULL(mem.id_member, 0) AS starter_id, hdtr.poster_ip AS starter_ip,
IFNULL(ma.real_name, 0) AS assigned_name, IFNULL(ma.id_member, 0) AS assigned_id,
IFNULL(mm.real_name, hdtr.modified_name) AS modified_name, IFNULL(mm.id_member, 0) AS modified_id
FROM {db_prefix}helpdesk_tickets AS hdt
INNER JOIN {db_prefix}helpdesk_ticket_replies AS hdtr ON (hdt.id_first_msg = hdtr.id_msg)
INNER JOIN {db_prefix}helpdesk_depts AS hdd ON (hdt.id_dept = hdd.id_dept)
LEFT JOIN {db_prefix}members AS mem ON (hdt.id_member_started = mem.id_member)
LEFT JOIN {db_prefix}members AS ma ON (hdt.id_member_assigned = ma.id_member)
LEFT JOIN {db_prefix}members AS mm ON (hdtr.modified_member = mm.id_member)
WHERE {query_see_ticket} AND hdt.id_ticket = {int:ticket}',
array(
'ticket' => $ticket == 0 ? $context['ticket_id'] : $ticket,
)
);
if ($smcFunc['db_num_rows']($query) == 0)
{
$smcFunc['db_free_result']($query);
fatal_lang_error('shd_no_ticket', false);
}
$ticketinfo = $smcFunc['db_fetch_assoc']($query);
$smcFunc['db_free_result']($query);
// Anything else we'll use a lot?
$ticketinfo['is_own'] = ($context['user']['id'] == $ticketinfo['starter_id']);
$ticketinfo['closed'] = $ticketinfo['status'] == TICKET_STATUS_CLOSED;
$ticketinfo['deleted'] = $ticketinfo['status'] == TICKET_STATUS_DELETED;
return $ticketinfo;
}
/**
* Formats a string for bbcode and/or smileys.
*
* Formatting is done according to the supplied settings and the master administration settings.
*
* @param string $text Raw text with optional bbcode formatting
* @param bool $smileys Whether smileys should be used; this is not an override to the master administration setting of
* whether to use smileys or not, and that takes precedence.
* @param string $cache If specified, this will provide the cache'd id that SMF should use to cache the output if it is suitably large.
*
* @return string Will return $text as processed for bbcode (if $modSettings['shd_allow_ticket_bbc'] permits) and smileys (if
* $modSettings['shd_allow_ticket_smileys'] and $smileys permits)
* @since 1.0
*/
function shd_format_text($text, $smileys = true, $cache = '')
{
global $modSettings, $scripturl, $smcFunc;
static $smf_disabled = false, $shd_disabled = false;
if (empty($modSettings['shd_allow_ticket_bbc']))
{
if (!empty($modSettings['shd_allow_wikilinks']))
shd_parse_wikilinks($text);
if (!empty($modSettings['shd_allow_ticket_smileys']) && $smileys)
parsesmileys($text);
}
else
{
// Figure out what's disabled, if anything, and do a bait'n'switch
if ($smf_disabled === false)
{
$original_tags = parse_bbc(false);
$tags = array();
foreach ($original_tags as $smf_tag)
{
if (!isset($tags[$smf_tag['tag']]))
$tags[$smf_tag['tag']] = true;
}
// See what tagz we can haz.
if (!empty($modSettings['shd_enabled_bbc']))
$enabled_tags = explode(',', $modSettings['shd_enabled_bbc']);
else
$enabled_tags = array(false);
$disabled_tags = array_diff(array_keys($tags), $enabled_tags); // this gets us what's present in SMF but not enabled by SD
$disabled_tags[] = '_SHD_DUMMY_TAG';
$smf_disabled = isset($modSettings['disabledBBC']) ? $modSettings['disabledBBC'] . ',_SHD_DUMMY_TAG' : '_SHD_DUMMY_TAG';
$shd_disabled = implode(',', $disabled_tags);
}
// wecanhazbbc
if ($shd_disabled == $smf_disabled)
{
// What SMF and SD have is the same, yay
$text = parse_bbc($text, (!empty($modSettings['shd_allow_ticket_smileys']) ? $smileys : false), $cache);
}
else
{
// first override SMF's disabled set with ours
$modSettings['disabledBBC'] = $shd_disabled;
parse_bbc(false);
$text = parse_bbc($text, (!empty($modSettings['shd_allow_ticket_smileys']) ? $smileys : false), $cache);
// Now put it back
$modSettings['disabledBBC'] = $smf_disabled;
parse_bbc(false);
}
}
return $text;
}
/**
* Processes the incoming message for wiki-links.
*
* @param string &$message The message to be parsed.
* @since 2.0
*/
function shd_parse_wikilinks(&$message)
{
global $modSettings, $smcFunc, $scripturl;
static $wikilinks = array();
// We need to check we're not coming from the convert-to-WYSIWYG context. If we are, we must not parse wikilinks.
// If we're doing the WYSIWYG thing, bbc_to_html() will be in the backtrace somewhere.
$backtrace = debug_backtrace();
for ($i = 0, $n = count($backtrace); $i < $n; $i++)
if (isset($backtrace[$i]['function']) && $backtrace[$i]['function'] == 'bbc_to_html')
return;
unset($backtrace); // This might be quite heavy so get rid of it if we're still here.
if (preg_match_all('~\[\[ticket\:([0-9]+)\]\]~iU', $message, $matches, PREG_SET_ORDER))
{
// Step through the matches, check if it's one we already had in $wikilinks (where persists through the life of this page)
$ticketlist = array();
$ticketcount = count($matches);
for ($i = 0; $i < $ticketcount; $i++)
{
$id = (int) $matches[$i][1];
if (!isset($wikilinks[$id]))
$ticketlist[$id] = false;
}
// Anything we didn't get from $wikilinks we now need to look up
if (!empty($ticketlist))
{
$query = shd_db_query('', '
SELECT id_ticket, subject
FROM {db_prefix}helpdesk_tickets AS hdt
WHERE {query_see_ticket}
AND id_ticket IN ({array_int:tickets})',
array(
'tickets' => array_keys($ticketlist),
)
);
while ($row = $smcFunc['db_fetch_assoc']($query))
{
$row['id_ticket'] = (int) $row['id_ticket'];
$ticketlist[$row['id_ticket']] = $row['subject'];
}
// Attach the list we've just made to the master list.
$wikilinks += $ticketlist;
}
// Now, go back through the list of matches again, this time we've got all the tickets we can actually display, so build the final replacement list
$replacements = array();
for ($i = 0; $i < $ticketcount; $i++)
{
$id = (int) $matches[$i][1];
if (!empty($wikilinks[$id]))
$replacements[$matches[$i][0]] = '<a href="' . $scripturl . '?action=helpdesk;sa=ticket;ticket=' . $id . '.0">[' . str_pad($id, $modSettings['shd_zerofill'], '0', STR_PAD_LEFT) . '] ' . $wikilinks[$id] . '</a>';
}
$message = str_replace(array_keys($replacements), array_values($replacements), $message);
}
}
/**
* Generates a profile link given user id and name.
*
* SMF itself has loadMemberData() and loadMemberContext to perform this act, however those two functions are much larger and more
* complex than we need more often than not, especially when all we want/need is member name (and subsequently profile link)
*
* Since profile links should be based on the view profile permission, we will need to establish that.
*
* @param string $name The name to display. This should be a standard SMF type name, which means already sanitised for HTML.
* @param int $id The numeric id of the user we are linking to.
*
* @return string Returns an HTML link to user profile if sufficient permission and both a name and id are supplied. Otherwise just the name is.
* @since 1.0
*/
function shd_profile_link($name, $id = 0)
{
global $user_info, $scripturl;
static $any = null;
static $own = null;
if ($any === null)
{
$any = allowedTo('profile_view_any') || shd_allowed_to('shd_view_profile_any', 0); // profile is visible either on SMF or SD permission.
$own = allowedTo('profile_view_own') || shd_allowed_to('shd_view_profile_own', 0);
}
if (empty($id))
return $name;
elseif ($any || ($own && $id == $user_info['id']))
return '<a href="' . $scripturl . '?action=profile;u=' . $id . '">' . $name . '</a>';
else
return $name;
}
/**
* Generate an image URL given the base filename.
*
* As of 2.0, images can live either in the main Themes/default/images/simpledesk folder, or additionally in Themes/default/images/sd_plugins,
* the latter of which is intended for plugins (the former is removed on SD uninstall, the latter is not)
*
* It should only be used in cases where there is ambiguity over where the image may live, e.g. preferences, permissions UIs. If there is no
* ambiguity (e.g. SD core, or plugins themselves, where they know where the image will be referenced from), it is recommended to avoid this function.
*
* @param string $filename An image filename, e.g. image.png
* @return string A full URL to the image in question, e.g. http://www.example.com/Themes/default/images/sd_plugins/image.png
*/
function shd_image_url($filename)
{
global $settings;
if (file_exists($settings['default_theme_dir'] . '/images/sd_plugins/' . $filename))
return $settings['default_theme_url'] . '/images/sd_plugins/' . $filename;
else
return $settings['default_theme_url'] . '/images/simpledesk/' . $filename;
}
/**
* Establishes the next change of status of a ticket.
*
* Tickets invariably have multiple changes of status during their life. All actions that could change
* a ticket's status should call here, even if it is a straight forward, one-route-only change of status
* since it is possible we could end up giving the user a choice one day over how statuses work, so
* we should route everything through here all the time.
*
* @param string $action (required), represents the action carried out by the calling function
* Known values: new, resolve, unresolve, deleteticket, restoreticket, deletereply, restorereply, reply, topictoticket (new is default)
* @param int $starter_id Numeric id of the ticket's starter (should be provided)
* @param int $replier_id Numeric id of the ticket's last reply author (should be provided)
* @param int $replies Number of replies in the ticket (should be provided)
*
* @return int Returns an integer value that corresponds to the ticket's status, relating to one of the TICKET_STATUS states.
* @since 1.0
*/
function shd_determine_status($action, $starter_id = 0, $replier_id = 0, $replies = -1, $dept = -1)
{
global $context;
static $staff = null;
if (!isset($staff[$dept]))
$staff[$dept] = shd_members_allowed_to('shd_staff', $dept);
$known_states = array(
'new',
'resolve',
'unresolve',