-
Notifications
You must be signed in to change notification settings - Fork 21
/
cwslack.php
1034 lines (937 loc) · 39.5 KB
/
cwslack.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
/*
CWSlack-SlashCommands
Copyright (C) 2018 jundis
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
ini_set('display_errors', 1); //Display errors in case something occurs
header('Content-Type: application/json'); //Set the header to return JSON, required by Slack
require_once 'config.php';
require_once 'functions.php';
// Authorization array. Auto encodes API key for auhtorization above.
$header_data = authHeader($companyname, $apipublickey, $apiprivatekey);
// Authorization array, with extra json content-type used in patch commands to change tickets.
$header_data2 = postHeader($companyname, $apipublickey, $apiprivatekey);
if(empty($_REQUEST['token']) || ($_REQUEST['token'] != $slacktoken)) die("Slack token invalid."); //If Slack token is not correct, kill the connection. This allows only Slack to access the page for security purposes.
if(empty($_REQUEST['text'])) die("No text provided."); //If there is no text added, kill the connection.
$exploded = explode(" ",$_REQUEST['text']); //Explode the string attached to the slash command for use in variables.
//This section checks if the ticket number is not equal to 6 digits (our tickets are in the hundreds of thousands but not near a million yet) and kills the connection if it's not.
if(!is_numeric($exploded[0])) {
//Check to see if the first command in the text array is actually help, if so redirect to help webpage detailing slash command use.
if ($exploded[0]=="help") {
die(json_encode(array("parse" => "full", "response_type" => "in_channel","text" => "Please visit " . $helpurl . " for more help information","mrkdwn"=>true)));
}
if ($exploded[0]=="new")
{
// Do nothing
}
else //Else close the connection.
{
die("Unknown entry for ticket number.");
}
}
//Timeout Fix Block
if($timeoutfix == true)
{
ob_end_clean();
header("Connection: close");
ob_start();
echo ('{"response_type": "in_channel"}');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
session_write_close();
if($sendtimeoutwait==true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral", "text" => "Please wait..."));
}
}
//End timeout fix block
$ticketnumber = $exploded[0]; //Set the ticket number to the first string
$command=NULL; //Create a command variable and set it to Null
$option3=NULL; //Create a option variable and set it to Null
if (array_key_exists(1,$exploded)) //If a second string exists in the slash command array, make it the command.
{
$command = $exploded[1];
}
if (array_key_exists(2,$exploded)) //If a third string exists in the slash command array, make it the option for the command.
{
$option3 = $exploded[2];
}
//Set URLs
$urlticketdata = $connectwise . "/$connectwisebranch/apis/3.0/service/tickets/" . $ticketnumber; //Set ticket API url
$ticketurl = $connectwise . "/$connectwisebranch/services/system_io/Service/fv_sr100_request.rails?service_recid="; //Ticket URL for connectwise.
$timeurl = $connectwise . "/$connectwisebranch/apis/3.0/time/entries?conditions=chargeToId=" . $ticketnumber . "&chargeToType=%27ServiceTicket%27&orderBy=dateEntered%20desc"; //Set the URL required for cURL requests to the time entry API.
if($command == "initial" || $command == "first" || $command == "note") //Set noteurl to use ascending if an initial note command is passed, else use descending.
{
$noteurl = $connectwise . "/$connectwisebranch/apis/3.0/service/tickets/" . $ticketnumber . "/notes?orderBy=id%20asc";
}
else
{
$noteurl = $connectwise . "/$connectwisebranch/apis/3.0/service/tickets/" . $ticketnumber . "/notes?orderBy=id%20desc";
}
//Need to create 3 arrays before hand to ensure no errors occur.
$dataTNotes = array();
$dataTData = array();
$dataTCmd = array();
if (strpos(strtolower($exploded[0]), "new") !== false)
{
unset($exploded[0]);
$exploded = implode(" ", $exploded);
$ticketstuff = explode("|",$exploded);
if($useboards == 1)
{
if(!array_key_exists(2, $ticketstuff)) {
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "Not enough values specified. Please use /t new board|company|summary"));
} else {
die("Not enough values specified. Please use /t new board|company|summary"); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
$companyurl = $connectwise . "/$connectwisebranch/apis/3.0/company/companies?conditions=name%20contains%20%27" . urlencode($ticketstuff[1]) . "%27";
$companydata = cURL($companyurl, $header_data);
if(is_null($companydata))
{
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "No company found with the name " . $ticketstuff[0]));
} else {
die("No company found with the name " . $ticketstuff[0]); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
$boardurl = $connectwise . "/$connectwisebranch/apis/3.0/service/boards?conditions=name%20contains%20%27" .$ticketstuff[0]. "%27";
$boarddata = cURL($boardurl, $header_data);
$postarray = array(
"summary" => $ticketstuff[2],
"company" => array(
"id" => $companydata[0]->id
),
"board" => array(
"id" => $boarddata[0]->id
));
}
else
{
if(!array_key_exists(1, $ticketstuff)) {
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "Not enough values specified. Please use /t new company|summary"));
} else {
die("Not enough values specified. Please use /t new company|summary"); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
$companyurl = $connectwise . "/$connectwisebranch/apis/3.0/company/companies?conditions=name%20contains%20%27" . urlencode($ticketstuff[0]) . "%27";
$companydata = cURL($companyurl, $header_data);
if(is_null($companydata))
{
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "No company found with the name " . $ticketstuff[0]));
} else {
die("No company found with the name " . $ticketstuff[0]); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
$postarray = array(
"summary" => $ticketstuff[1],
"company" => array(
"id" => $companydata[0]->id
));
}
//Username mapping code
if($usedatabase==1)
{
$mysql = mysqli_connect($dbhost, $dbusername, $dbpassword, $dbdatabase); //Connect MySQL
if (!$mysql) //Check for errors
{
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "Connection Error: " . mysqli_connect_error()));
} else {
die("Connection Error: " . mysqli_connect_error()); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
$val1 = mysqli_real_escape_string($mysql,$_REQUEST["user_name"]);
$sql = "SELECT * FROM `usermap` WHERE `slackuser`=\"" . $val1 . "\""; //SQL Query to select all ticket number entries
$result = mysqli_query($mysql, $sql); //Run result
$rowcount = mysqli_num_rows($result);
if($rowcount > 1) //If there were too many rows matching query
{
die("Error: too many users somehow?"); //This should NEVER happen.
}
else if ($rowcount == 1) //If exactly 1 row is found.
{
$row = mysqli_fetch_assoc($result); //Row association.
$postarray["enteredBy"] = $row["cwname"]; //Return the connectwise name of the row found as the CW member name.
$postarray["owner"] = array("identifier"=>$row["cwname"]); //Return the connectwise name of the row found as the CW member name.
}
else //If no rows are found
{
if($usecwname==1) //If variable enabled
{
$postarray["enteredBy"] = $_REQUEST['user_name'];
$postarray["owner"] = array("identifier"=>$_REQUEST['user_name']); //Return the slack username as the user for the ticket note. If the user does not exist in CW, it will use the API username.
}
}
}
else
{
if($usecwname==1)
{
$postarray["enteredBy"] = $_REQUEST['user_name'];
$postarray["owner"] = array("identifier"=>$_REQUEST['user_name']);
}
}
$dataTCmd = cURLPost( //Function for POST requests in cURL
$connectwise . "/$connectwisebranch/apis/3.0/service/tickets", //URL
$header_data2, //Header
"POST", //Request type
$postarray
);
if($timeoutfix == true)
{
cURLPost($_REQUEST["response_url"],array("Content-Type: application/json"),"POST",array("parse" => "full", "response_type" => "ephemeral","text" => "New ticket #<" . $connectwise . "/$connectwisebranch/services/system_io/Service/fv_sr100_request.rails?service_recid=" . $dataTCmd->id . "|" . $dataTCmd->id . "> has been created.","mrkdwn"=>true));
}
else
{
die("New ticket #<" . $connectwise . "/$connectwisebranch/services/system_io/Service/fv_sr100_request.rails?service_recid=" . $dataTCmd->id . "|" . $dataTCmd->id . "> has been created.");
}
die();
}
//-
//Ticket data section
//-
$dataTData = cURL($urlticketdata, $header_data); //Decode the JSON returned by the CW API.
if($dataTData==NULL)
{
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "Array not returned in line 195. Please check your connectwise URL variable in config.php and ensure it is accessible via the web at " . $urlticketdata));
} else {
die("Array not returned in line 195. Please check your connectwise URL variable in config.php and ensure it is accessible via the web at " . $urlticketdata); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
//-
//Priority command
//-
if($command=="priority") { //Check if the second string in the text array from the slash command is priority
$priority = "0"; //Set priority = 0.
$priorityname = "";
$priorityurl = $connectwise . "/$connectwisebranch/apis/3.0/service/priorities?conditions=name%20like%20%27%2A" . $option3 . "%2A%27";
$dataTCmd = cURL($priorityurl, $header_data);
if(array_key_exists(0,$dataTCmd))
{
$priority = $dataTCmd[0]->id;
$priorityname = $dataTCmd[0]->name;
}
//Check what $option3 was set to, the third string in the text array from the slash command.
if ($priority==0)
{
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "Failed to get priority code: " . $option3));
} else {
die("Failed to get priority code: " . $option3); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
$dataTCmd = cURLPost( //Function for POST requests in cURL
$urlticketdata, //URL
$header_data2, //Header
"PATCH", //Request type
array(array("op" => "replace", "path" => "/priority/id", "value" => $priority)) //POST Body
);
$return =array(
"parse" => "full", //Parse all text.
"response_type" => "ephemeral", //Send the response to the user only
"attachments"=>array(array(
"fallback" => "Info on Ticket #" . $dataTData->id, //Fallback for notifications
"title" => "Ticket Summary: " . $dataTData->summary, //Set bolded title text
"pretext" => "Ticket #" . $dataTData->id . "'s priority has been set to " . $priorityname, //Set pretext
"text" => "Click <" . $ticketurl . $dataTData -> id . "&companyName" . $companyname . "|here> to open the ticket.", //Set text to be returned
"mrkdwn_in" => array( //Set markdown values
"text",
"pretext"
)
))
);
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", $return);
} else {
die(json_encode($return, JSON_PRETTY_PRINT)); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
//-
//Ticket Status change command.
//-
if($command=="status") {
$status = "0";
$statusname = "";
$statusurl = $dataTData->board->_info->board_href . "/statuses?conditions=name%20contains%20%27" . $option3 . "%27";
$dataTCmd = cURL($statusurl, $header_data);
if(array_key_exists(0,$dataTCmd))
{
$status = $dataTCmd[0]->id;
$statusname = $dataTCmd[0]->name;
}
if ($status == 0)
{
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "Failed to get status code: " . $status));
} else {
die("Failed to get status code: " . $status); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
$dataTCmd = cURLPost(
$urlticketdata,
$header_data2,
"PATCH",
array(array("op" => "replace", "path" => "/status/id", "value" => $status))
);
$return = array(
"parse" => "full",
"response_type" => "ephemeral", //Send the response to the user only
"attachments" => array(array(
"fallback" => "Info on Ticket #" . $dataTData->id, //Fallback for notifications
"title" => "Ticket Summary: " . $dataTData->summary,
"pretext" => "Ticket #" . $dataTData->id . "'s status has been set to " . $statusname,
"text" => "Click <" . $ticketurl . $dataTData->id . "&companyName" . $companyname . "|here> to open the ticket.",
"mrkdwn_in" => array(
"text",
"pretext"
)
))
);
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", $return);
} else {
die(json_encode($return, JSON_PRETTY_PRINT)); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
if($command=="scheduleme")
{
$cwuser = NULL;
//Username mapping code
if($usedatabase==1)
{
$mysql = mysqli_connect($dbhost, $dbusername, $dbpassword, $dbdatabase); //Connect MySQL
if (!$mysql) //Check for errors
{
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "Connection Error: " . mysqli_connect_error()));
} else {
die("Connection Error: " . mysqli_connect_error()); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
$val1 = mysqli_real_escape_string($mysql,$_REQUEST["user_name"]);
$sql = "SELECT * FROM `usermap` WHERE `slackuser`=\"" . $val1 . "\""; //SQL Query to select all ticket number entries
$result = mysqli_query($mysql, $sql); //Run result
$rowcount = mysqli_num_rows($result);
if($rowcount > 1) //If there were too many rows matching query
{
die("Error: too many users somehow?"); //This should NEVER happen.
}
else if ($rowcount == 1) //If exactly 1 row is found.
{
$row = mysqli_fetch_assoc($result); //Row association.
$cwuser = $row["cwname"]; //Return the connectwise name of the row found as the CW member name.
}
else //If no rows are found
{
if($usecwname==1) //If variable enabled
{
$cwuser = $_REQUEST['user_name'];
}
}
}
else
{
if($usecwname==1)
{
$cwuser = $_REQUEST['user_name'];
}
else
{
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "Error: Name " . $_REQUEST['user_name'] . " not found"));
} else {
die("Error: Name " . $_REQUEST['user_name'] . " not found"); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
}
unset($exploded[0]);
unset($exploded[1]);
$removal = implode(" ", $exploded);
if($removal==NULL)
{
$datestart = gmdate("Y-m-d\TH:i:s\Z", strtotime("12:00AM"));
$timingdate = explode("T", $datestart);
$datestart = $timingdate[0] . "T00:00:00Z";
}
else
{
$datestart = gmdate("Y-m-d\TH:i:s\Z", strtotime($removal));
$dateend = gmdate("Y-m-d\TH:i:s\Z", strtotime($removal. " +30 minutes"));
}
if(strpos($datestart, 'T06:00:00Z') !== false)
{
$timingdate = explode("T", $datestart);
$datestart = $timingdate[0] . "T00:00:00Z";
}
if(strpos($datestart, 'T00:00:00Z') !== false)
{
$dateend = $datestart;
}
if(!empty($schedulestatus))
{
$status = "0";
$statusname = "";
$statusurl = $dataTData->board->_info->board_href . "/statuses?conditions=name%20like%20%27" . $schedulestatus . "%27";
$dataStatus = cURL($statusurl, $header_data);
if(array_key_exists(0,$dataStatus))
{
$status = $dataStatus[0]->id;
$statusname = $dataStatus[0]->name;
}
if ($status == 0)
{
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "Failed to get status code: " . $status));
} else {
die("Failed to get status code: " . $status); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
$dataStatus = cURLPost(
$urlticketdata,
$header_data2,
"PATCH",
array(array("op" => "replace", "path" => "/status/id", "value" => $status))
);
$postarray = array("objectId" => $ticketnumber, "member" => array("identifier" => $cwuser), "type" => array("id" => 4), "dateStart" => $datestart, "dateEnd" => $dateend, "allowScheduleConflictsFlag" => true);
$dataTCmd = cURLPost(
$connectwise . "/$connectwisebranch/apis/3.0/schedule/entries",
$header_data2,
"POST",
$postarray
);
}
else
{
$postarray = array("objectId" => $ticketnumber, "member" => array("identifier" => $cwuser), "type" => array("id" => 4), "dateStart" => $datestart, "dateEnd" => $dateend, "allowScheduleConflictsFlag" => true);
$dataTCmd = cURLPost(
$connectwise . "/$connectwisebranch/apis/3.0/schedule/entries",
$header_data2,
"POST",
$postarray
);
}
if($removal==NULL)
{
$timingdate = explode("T", $datestart);
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "You have been properly scheduled for ticket #" . $dataTCmd->objectId . " for $timingdate[0]","mrkdwn"=>true));
} else {
die("You have been properly scheduled for ticket #" . $dataTCmd->objectId . " for $timingdate[0]"); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
else
{
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "You have been properly scheduled for ticket #" . $dataTCmd->objectId . " at " . $removal,"mrkdwn"=>true));
} else {
die("You have been properly scheduled for ticket #" . $dataTCmd->objectId . " at " . $removal); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
}
if($command=="schedule")
{
$cwuser = NULL;
if($option3 == NULL)
{
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "No user specified."));
} else {
die("No user specified."); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
$username = $option3;
//Username mapping code
if($usedatabase==1)
{
$mysql = mysqli_connect($dbhost, $dbusername, $dbpassword, $dbdatabase); //Connect MySQL
if (!$mysql) //Check for errors
{
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "Connection Error: " . mysqli_connect_error()));
} else {
die("Connection Error: " . mysqli_connect_error()); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
$val1 = mysqli_real_escape_string($mysql,$username);
$sql = "SELECT * FROM `usermap` WHERE `slackuser`=\"" . $val1 . "\""; //SQL Query to select all ticket number entries
$result = mysqli_query($mysql, $sql); //Run result
$rowcount = mysqli_num_rows($result);
if($rowcount > 1) //If there were too many rows matching query
{
die("Error: too many users somehow?"); //This should NEVER happen.
}
else if ($rowcount == 1) //If exactly 1 row is found.
{
$row = mysqli_fetch_assoc($result); //Row association.
$cwuser = $row["cwname"]; //Return the connectwise name of the row found as the CW member name.
}
else //If no rows are found
{
if($usecwname==1) //If variable enabled
{
$cwuser = $username;
}
}
}
else
{
if($usecwname==1)
{
$cwuser = $username;
}
else
{
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "Error: Name " . $username . " not found"));
} else {
die("Error: Name " . $username . " not found"); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
}
unset($exploded[0]);
unset($exploded[1]);
unset($exploded[2]);
$removal = implode(" ", $exploded);
if($removal==NULL)
{
$datestart = gmdate("Y-m-d\TH:i:s\Z", strtotime("12:00AM"));
$timingdate = explode("T", $datestart);
$datestart = $timingdate[0] . "T00:00:00Z";
}
else
{
$datestart = gmdate("Y-m-d\TH:i:s\Z", strtotime($removal));
$dateend = gmdate("Y-m-d\TH:i:s\Z", strtotime($removal. " +30 minutes"));
}
if(strpos($datestart, 'T06:00:00Z') !== false)
{
$timingdate = explode("T", $datestart);
$datestart = $timingdate[0] . "T00:00:00Z";
}
if(strpos($datestart, 'T00:00:00Z') !== false)
{
$dateend = $datestart;
}
if(!empty($schedulestatus))
{
$status = "0";
$statusname = "";
$statusurl = $dataTData->board->_info->board_href . "/statuses?conditions=name%20like%20%27" . $schedulestatus . "%27";
$dataStatus = cURL($statusurl, $header_data);
if(array_key_exists(0,$dataStatus))
{
$status = $dataStatus[0]->id;
$statusname = $dataStatus[0]->name;
}
if ($status == 0)
{
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "Failed to get status code: " . $status));
} else {
die("Failed to get status code: " . $status); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
$dataStatus = cURLPost(
$urlticketdata,
$header_data2,
"PATCH",
array(array("op" => "replace", "path" => "/status/id", "value" => $status))
);
$postarray = array("objectId" => $ticketnumber, "member" => array("identifier" => $cwuser), "type" => array("id" => 4), "dateStart" => $datestart, "dateEnd" => $dateend, "allowScheduleConflictsFlag" => true);
$dataTCmd = cURLPost(
$connectwise . "/$connectwisebranch/apis/3.0/schedule/entries",
$header_data2,
"POST",
$postarray
);
}
else
{
$postarray = array("objectId" => $ticketnumber, "member" => array("identifier" => $cwuser), "type" => array("id" => 4), "dateStart" => $datestart, "dateEnd" => $dateend, "allowScheduleConflictsFlag" => true);
$dataTCmd = cURLPost(
$connectwise . "/$connectwisebranch/apis/3.0/schedule/entries",
$header_data2,
"POST",
$postarray
);
}
if($removal==NULL)
{
$timingdate = explode("T", $datestart);
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "$username has been properly scheduled for ticket #" . $dataTCmd->objectId . " for $timingdate[0]","mrkdwn"=>true));
} else {
die("$username has been properly scheduled for ticket #" . $dataTCmd->objectId . " for $timingdate[0]"); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
else
{
if ($timeoutfix == true) {
cURLPost($_REQUEST["response_url"], array("Content-Type: application/json"), "POST", array("parse" => "full", "response_type" => "ephemeral","text" => "$username has been properly scheduled for ticket #" . $dataTCmd->objectId . " at " . $removal,"mrkdwn"=>true));
} else {
die("$username has been properly scheduled for ticket #" . $dataTCmd->objectId . " at " . $removal); //Return properly encoded arrays in JSON for Slack parsing.
}
die();
}
}
if($posttext==1) //Block for curl to get latest note
{
$createdby = "Error"; //Create with error just in case.
$notetext = "Error"; //Create with error just in case.
$dataTNotes = cURL($noteurl, $header_data); // Get the JSON returned by the CW API for $noteurl.
$dataTimeData = cURL($timeurl, $header_data); // Get the JSON returned by the CW API for $timeurl.
if($command == "full" || $command == "notes" || $command == "all")
{
$dataTNotes2 = cURL($connectwise . "/$connectwisebranch/apis/3.0/service/tickets/" . $ticketnumber . "/notes?orderBy=id%20asc", $header_data); // Get the JSON returned by the CW API for ticket notes.
}
if(!array_key_exists(0, $dataTNotes))
{
if(array_key_exists(0, $dataTimeData))
{
$createdby = $dataTimeData[0]->enteredBy; //Set $createdby to the time entry creator.
$text = $dataTimeData[0]->notes; //Set $text to the time entry text.
$notedate = $dataTimeData[0]->dateEntered;
$date2 = strtotime($notedate);
$date2format = date('m-d-Y g:i:sa', $date2);
$internalflag = $dataTimeData[0]->addToInternalAnalysisFlag;
}
else
{
$posttext=0;
}
}
else if($dataTNotes[0]->text != NULL || $dataTimeData[0]->text != NULL) //Makes sure that if both text values == null, then there is no text to post.
{
if($dataTNotes[0]->text != NULL) {
$createdby = $dataTNotes[0]->createdBy; //Set $createdby to the ticket note creator.
$notetime = new DateTime($dataTNotes[0]->dateCreated); //Create new datetime object based on ticketnote note.
$notedate = $dataTNotes[0]->dateCreated;
$internalflag = $dataTNotes[0]->internalAnalysisFlag;
$text = $dataTNotes[0]->text; //Set $text to the ticket text.
if (array_key_exists(0, $dataTNotes) && array_key_exists(0, $dataTimeData) && $command != "initial" && $command != "first" && $command != "note") //Check if arrays exist properly.
{
$timetime = new DateTime($dataTimeData[0]->dateEntered); //Create new time object based on time entry note.
if ($timetime > $notetime) //If the time entry is newer than latest ticket note.
{
$createdby = $dataTimeData[0]->enteredBy; //Set $createdby to the time entry creator.
$text = $dataTimeData[0]->notes; //Set $text to the time entry text.
$notedate = $dataTimeData[0]->dateEntered;
$internalflag = $dataTimeData[0]->addToInternalAnalysisFlag;
}
}
$date2 = strtotime($notedate);
$date2format = date('m-d-Y g:i:sa', $date2);
}
else
{
$createdby = $dataTimeData[0]->enteredBy; //Set $createdby to the time entry creator.
$text = $dataTimeData[0]->notes; //Set $text to the time entry text.
$notedate = $dataTimeData[0]->dateEntered;
$date2 = strtotime($notedate);
$date2format = date('m-d-Y g:i:sa', $date2);
$internalflag = $dataTimeData[0]->addToInternalAnalysisFlag;
}
}
else
{
$posttext=0;
}
}
//Scheduled resource block
$scheduleurl = str_replace(' ', '%20', $dataTData->_info->scheduleentries_href);
$resourceset = cURL($scheduleurl,$header_data); //Get URL and send that to curl function, retrieve response.
if($resourceset == NULL)
{
$resourceline = false;
}
else
{
$latestsched = end($resourceset);
if(!array_key_exists("dateStart",$latestsched) || $latestsched->dateStart==NULL)
{
$resourceline = false;
}
else
{
$scheddate = date("m-d-y",strtotime($latestsched->dateStart));
$schedstart = date("g:iA",strtotime($latestsched->dateStart));
$schedend = date("g:iA",strtotime($latestsched->dateEnd));
$resourceline = "\nNext: " . $latestsched->member->identifier . " at " . $scheddate . " " . $schedstart . "-" . $schedend;
}
}
$lastupdate = "\nUpdated: " . $dataTData->_info->updatedBy . " at " . date("m-d-y g:iA", strtotime($dataTData->lastUpdated));
$date=strtotime($dataTData->dateEntered); //Convert date entered JSON result to time.
$dateformat=date('m-d-Y g:i:sa',$date); //Convert previously converted time to a better time string.
$return="Nothing!"; //Create return value and set to a basic message just in case.
$contact="None"; //Set None for contact in case no contact exists for "Catch All" tickets.
$resources="No resources"; //Just in case resources are null, have something to return.
$hours="No time entered."; //Just in case time is null, have something to return.
if(array_key_exists("actualHours",$dataTData) && $dataTData->actualHours != NULL) //If time is not NULL
{
$hours="Time: ". $dataTData->actualHours . " Hours"; //Set $hours to a formatted time line.
}
if(array_key_exists("resources",$dataTData) && $dataTData->resources != NULL)
{
$resources=$dataTData->resources;
}
if(array_key_exists("contact",$dataTData) && !$dataTData->contact==NULL) { //Check if contact name exists in array.
$contact = $dataTData->contact->name; //Set contact variable to contact name.
}
if($command == "initial" || $command == "first" || $command == "note")
{
if($posttext==0)
{
$return =array(
"parse" => "full",
"response_type" => "in_channel",
"attachments"=>array(array(
"fallback" => "Info on Ticket #" . $dataTData->id, //Fallback for notifications
"title" => "<" . $ticketurl . $dataTData -> id . "&companyName=" . $companyname . "|#" . $dataTData->id . ">: " . $dataTData->summary, //Return clickable link to ticket with ticket summary.
"pretext" => "Info on Ticket #" . $dataTData->id, //Return info string with ticket number.
"text" => $dataTData->company->identifier . " / " . $contact . //Return "Company / Contact" string
"\n" . $dateformat . " | " . $dataTData->status->name . //Return "Date Entered / Status" string
"\n" . $resources . " | " . $hours . //Return assigned resources
(!$resourceline ? "" : $resourceline) . //Return next resource
$lastupdate,
"mrkdwn_in" => array(
"text",
"pretext"
)
))
);
}
else
{
$return =array(
"parse" => "full",
"response_type" => "ephemeral",
"attachments"=>array(array(
"fallback" => "Info on Ticket #" . $dataTData->id, //Fallback for notifications
"title" => "<" . $ticketurl . $dataTData -> id . "&companyName=" . $companyname . "|#" . $dataTData->id . ">: " . $dataTData->summary, //Return clickable link to ticket with ticket summary.
"pretext" => "Info on Ticket #" . $dataTData->id, //Return info string with ticket number.
"text" => $dataTData->company->identifier . " / " . $contact . //Return "Company / Contact" string
"\n" . $dateformat . " | " . $dataTData->status->name . //Return "Date Entered / Status" string
"\n" . $resources . " | " . $hours . //Return assigned resources
(!$resourceline ? "" : $resourceline) . //Return next resource
$lastupdate,
"mrkdwn_in" => array(
"text",
"pretext"
)
),
array(
"pretext" => "Initial " . ($internalflag == "true" ? "Internal" : "External") . " ticket note (" . $date2format . ") from: " . $createdby,
"text" => $text,
"mrkdwn_in" => array(
"text",
"pretext",
"title"
)
))
);
}
}
else if($command == "full" || $command == "notes" || $command == "all")
{
if($posttext==0)
{
$return =array(
"parse" => "full",
"response_type" => "in_channel",
"attachments"=>array(array(
"fallback" => "Info on Ticket #" . $dataTData->id, //Fallback for notifications
"title" => "<" . $ticketurl . $dataTData -> id . "&companyName=" . $companyname . "|#" . $dataTData->id . ">: " . $dataTData->summary, //Return clickable link to ticket with ticket summary.
"pretext" => "Info on Ticket #" . $dataTData->id, //Return info string with ticket number.
"text" => $dataTData->company->identifier . " / " . $contact . //Return "Company / Contact" string
"\n" . $dateformat . " | " . $dataTData->status->name . //Return "Date Entered / Status" string
"\n" . $resources . " | " . $hours . //Return assigned resources
(!$resourceline ? "" : $resourceline) . //Return next resource
$lastupdate,
"mrkdwn_in" => array(
"text",
"pretext"
)
))
);
}
else
{
$date3=strtotime($dataTNotes2[0]->dateCreated);
$date3format=date('m-d-Y g:i:sa',$date3);
if(array_key_exists("internalAnalysisFlag", $dataTNotes2))
{
$internalflag2 = $dataTNotes2[0]->internalAnalysisFlag;
}
else if(array_key_exists("addToInternalAnalysisFlag", $dataTNotes2))
{
$internalflag2 = $dataTNotes2[0]->addToInternalAnalysisFlag;
}
else if(array_key_exists("internalFlag", $dataTNotes2))
{
$internalflag2 = $dataTNotes2[0]->internalFlag;
}
else
{
$internalflag2 = "";
}
$initialinfoarray = array(
array(
"fallback" => "Info on Ticket #" . $dataTData->id, //Fallback for notifications
"title" => "<" . $ticketurl . $dataTData -> id . "&companyName=" . $companyname . "|#" . $dataTData->id . ">: " . $dataTData->summary, //Return clickable link to ticket with ticket summary.
"pretext" => "Info on Ticket #" . $dataTData->id, //Return info string with ticket number.
"text" => $dataTData->company->identifier . " / " . $contact . //Return "Company / Contact" string
"\n" . $dateformat . " | " . $dataTData->status->name . //Return "Date Entered / Status" string
"\n" . $resources . " | " . $hours . //Return assigned resources
(!$resourceline ? "" : $resourceline) . //Return next resource
$lastupdate,
"mrkdwn_in" => array(
"text",
"pretext"
)
));
$temparray = array();
if(array_key_exists(0, $dataTNotes)) {
foreach ($dataTNotes as $singlenote) {
$createdby = $singlenote->createdBy; //Set $createdby to the ticket note creator.
$notetime = new DateTime($singlenote->dateCreated); //Create new datetime object based on ticketnote note.
$notedate = $singlenote->dateCreated;
$internalflag = $singlenote->internalAnalysisFlag;
$text = $singlenote->text; //Set $text to the ticket text.
$date2 = strtotime($notedate);
$date2format = date('m-d-Y g:i:sa', $date2);
$temparray[$date2] = array(
"pretext" => ($internalflag == "true" ? "Internal" : "External") . " Note (" . $date2format . ") from: " . $createdby,
"text" => $text,
"mrkdwn_in" => array(
"text",
"pretext",
"title"
));
}
}
if(array_key_exists(0, $dataTimeData))
{
foreach($dataTimeData as $singletime)
{
$createdby = $singletime->enteredBy; //Set $createdby to the time entry creator.
$notedate = $singletime->dateEntered;
$internalflag = $singletime->addToInternalAnalysisFlag;
$text = $singletime->notes; //Set $text to the time entry text.
$date2 = strtotime($notedate);
$date2format = date('m-d-Y g:i:sa', $date2);
$temparray[$date2] = array(
"pretext" => ($internalflag == "true" ? "Internal" : "External") . " Time Entry (" . $date2format . ") from: " . $createdby,
"text" => $text,
"mrkdwn_in" => array(
"text",
"pretext",
"title"
));
}
}
ksort($temparray);
$notesandtimes = array_merge($initialinfoarray, $temparray);
$return =array(
"parse" => "full",
"response_type" => "ephemeral",
"attachments"=>$notesandtimes
);
}
}
else //If no command is set, or if it's just random gibberish after ticket number.
{
if($posttext==0)
{
$return =array(
"parse" => "full",
"response_type" => "in_channel",
"attachments"=>array(array(
"fallback" => "Info on Ticket #" . $dataTData->id, //Fallback for notifications
"title" => "<" . $ticketurl . $dataTData -> id . "&companyName=" . $companyname . "|#" . $dataTData->id . ">: " . $dataTData->summary, //Return clickable link to ticket with ticket summary.
"pretext" => "Info on Ticket #" . $dataTData->id, //Return info string with ticket number.
"text" => $dataTData->company->identifier . " / " . $contact . //Return "Company / Contact" string
"\n" . $dateformat . " | " . $dataTData->status->name . //Return "Date Entered / Status" string
"\n" . $resources . " | " . $hours . //Return assigned resources
(!$resourceline ? "" : $resourceline) . //Return next resource
$lastupdate,
"mrkdwn_in" => array(
"text",
"pretext"
)
))
);
}
else
{
$return =array(
"parse" => "full",
"response_type" => "in_channel",
"attachments"=>array(array(
"fallback" => "Info on Ticket #" . $dataTData->id, //Fallback for notifications