forked from Kazanir/zendesk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zendesk.module
807 lines (724 loc) · 22.8 KB
/
zendesk.module
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
<?php
/**
* @file
* The Zendesk module helps you to interact with zendesk using Drupal.
*
* authors:
* Tom Deryckere ([email protected])
* Mark Koester (https://github.com/markwk/zendesk)
*/
/**
* Implements hook_permission().
*/
function zendesk_permission() {
return array(
'configure zendesk' => array(
'title' => t('Configure Zendesk'),
'description' => t('Configure Drupal settings to communicate with Zendesk.'),
),
);
}
/**
* Implements hook_entity_info().
*
* Used to give us a basic load/filter controller for tickets and ticket field definitions.
*/
function zendesk_entity_info() {
$info['zendesk_ticket'] = [
'controller class' => 'DrupalDefaultEntityController',
'base table' => 'zendesk_tickets',
'label' => t('Zendesk ticket'),
'entity keys' => [
'id' => 'id',
'label' => 'title',
],
];
$info['zendesk_ticket_field'] = [
'controller class' => 'DrupalDefaultEntityController',
'base table' => 'zendesk_ticket_fields',
'label' => t('Zendesk ticket field'),
'entity keys' => [
'id' => 'id',
'label' => 'title',
],
];
return $info;
}
/**
* Implements zendesk_ticket_field_load().
*/
function zendesk_zendesk_ticket_field_load($ticket_fields) {
$schema = drupal_get_schema('zendesk_ticket_fields');
foreach ($schema['fields'] as $name => $info) {
if (!empty($info['serialize'])) {
$unserialize[] = $name;
}
}
foreach ($ticket_fields as $field) {
foreach ($unserialize as $property) {
if (!empty($field->{$property})) {
$field->{$property . "_raw"} = $field->{$property};
$field->{$property} = unserialize($field->{$property});
}
}
}
}
/**
* Implements zendesk_ticket_load().
*/
function zendesk_zendesk_ticket_load($tickets) {
$schema = drupal_get_schema('zendesk_tickets');
foreach ($schema['fields'] as $name => $info) {
if (!empty($info['serialize'])) {
$unserialize[] = $name;
}
}
foreach ($tickets as $ticket) {
foreach ($unserialize as $property) {
if (!empty($ticket->{$property})) {
$ticket->{$property . "_raw"} = $ticket->{$property};
$ticket->{$property} = unserialize($ticket->{$property});
}
}
}
}
/**
* Implements hook_menu().
*/
function zendesk_menu() {
// Callback use by zendesk for remote authentication.
$items['services/zendesk'] = array(
'title' => 'Zendesk remote authentication',
'page callback' => 'zendesk_remote_authentication',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['admin/config/people/zendesk'] = array(
'title' => 'Zendesk settings',
'access arguments' => array('configure zendesk'),
'page callback' => 'drupal_get_form',
'page arguments' => array('zendesk_configuration_form'),
'type' => MENU_NORMAL_ITEM,
'description' => 'Configure Drupal settings to communicate with Zendesk',
'file' => 'zendesk.admin.inc',
);
return $items;
}
/**
* Implements hook_views_api().
*/
function zendesk_views_api($module = NULL, $api = NULL) {
return array("api" => "3.0");
}
/**
* Initialization of the zendesk library.
*/
function zendesk_initialize_library() {
$api_key = variable_get('zendesk_api_token', '');
$user = variable_get('zendesk_api_mail', '');
$subdomain = variable_get('zendesk_api_group', '');
$zd = new zendesk($api_key, $user, $subdomain);
return $zd;
}
/**
* Helper function to retrieve zendesk id of the user.
*/
function _zendesk_get_user($uid) {
$query = db_select('zendesk_users', 'zu')
->fields('zu', array('uid', 'zid'))->condition('zu.uid', $uid, '=');
$result = $query->execute();
if ($result->rowCount() <> 0) {
foreach ($result as $user) {
return $user->zid;
}
}
else {
return FALSE;
}
}
/**
* Implements hook_user_insert().
*/
function zendesk_user_insert(&$edit, $account, $category) {
if (variable_get('zendesk_api_sync_users', 0)) {
zendesk_create_user($account);
}
}
/**
* Implements hook_user_update().
*/
function zendesk_user_update(&$edit, $account, $category) {
if (variable_get('zendesk_api_sync_users', 0)) {
if ($user_id = _zendesk_get_user($account->uid)) {
$zd = zendesk_initialize_library();
$data = array(
'user' => array(
'id' => $user_id,
'name' => format_username($account),
'email' => $account->mail,
'role' => 'end-user',
),
);
// Invoke a alter call to allow other modules to pass data to ZenDesk.
drupal_alter(array('zendesk_user', 'zendesk_user_update'), $data, $account);
$data = drupal_json_encode($data);
$result = $zd->call('/users/' . $user_id, $data, 'PUT');
}
}
}
/**
* Implements hook_user_delete().
*/
function zendesk_user_delete($account) {
if (variable_get('zendesk_api_sync_users', 0)) {
if ($user_id = _zendesk_get_user($account->uid)) {
$zd = zendesk_initialize_library();
$data = drupal_json_encode(array(
'user' => array(
'id' => $user_id,
'name' => format_username($account),
'email' => $account->mail,
'suspended' => TRUE,
),
));
// Alter call to omitted since we are destroying the User object.
$result = $zd->call('/users/' . $user_id, $data, 'PUT');
}
}
}
/**
* Create a user on Zendesk's side.
*
* @param object $account
* The Drupal user object that we want to create on zendesk.
*
* @return mixed
* The zendesk's user id if succeeded, FALSE otherwise.
*/
function zendesk_create_user($account) {
$zd = zendesk_initialize_library();
$data = array(
'user' => array(
'name' => format_username($account),
'email' => $account->mail,
'role' => 'end-user',
),
);
if (variable_get('zendesk_authed_user', FALSE)) {
$data['user'] += array('verified' => TRUE);
}
// Invoke a alter call to allow other modules to pass data to ZenDesk.
drupal_alter(array('zendesk_user', 'zendesk_user_create'), $data, $account);
$data = drupal_json_encode($data);
$result = $zd->call("/users", $data, 'POST');
if (!empty($result->error)) {
// Try to handle special case where a user can be on zendesk's side, but
// not recorded on our table.
if ($result->error == 'RecordInvalid' && $result->details->email[0]->description == 'Email: ' . $account->mail . ' is already being used by another user') {
return zendesk_sync_user_back($account);
}
watchdog('zendesk', '%description: %error', array(
'%description' => $result->description,
'%error' => print_r($result->details, 1),
), WATCHDOG_ERROR);
return FALSE;
}
else {
db_insert('zendesk_users')
->fields(array(
'uid' => $account->uid,
'zid' => $result->user->id,
))
->execute();
return $result->user->id;
}
}
/**
* Try to sync user from zendesk on drupal side.
*
* If a user already exist on zendesk's side but not our the drupal side, add
* it in our database.
*
* @param object $account
* An object containing the user account.
*
* @return mixed
* Zendesk's user ID if succeeded, FALSE otherwise.
*/
function zendesk_sync_user_back($account) {
// Look for the user.
$zd = zendesk_initialize_library();
$result = $zd->call('/users/search.json?query=' . $account->mail, '', 'GET');
if (isset($result->users[0]->id)) {
db_merge('zendesk_users')
->fields(array(
'uid' => $account->uid,
'zid' => $result->users[0]->id,
))
// On the off-chance that something is wrong and the user has a Zendesk
// ID already, update it.
->key(array('uid' => $account->uid))
->execute();
return $result->users[0]->id;
}
else {
return FALSE;
}
}
/**
* Remote authentication script.
*
* @see http://developer.zendesk.com/documentation/sso
* @see https://support.zendesk.com/entries/23675367
*/
function zendesk_remote_authentication() {
global $user;
// Check if anonymous, if so redirect to login with destination the path where
// he comes from.
if ($user->uid) {
// Check if user role is allowed to be authenticated.
if (zendesk_user_has_access($user)) {
zendesk_authenticate_user();
}
else {
drupal_goto(variable_get('zendesk_no_permission_page', ''));
}
}
else {
// Make sure we pass along additional info from Zendesk as we goto.
drupal_goto('user', array('query' => drupal_get_destination()));
}
}
/**
* Check if the user may be be authenticated or synced with zendesk.
*/
function zendesk_user_has_access($user) {
$zendesk_roles = variable_get('zendesk_roles', array());
if (!array_sum($zendesk_roles)) {
// No roles are set, give access.
return TRUE;
}
else {
$keys = array_keys($user->roles);
foreach ($keys as $key) {
if ($zendesk_roles[$key] > 0) {
return TRUE;
}
}
}
return FALSE;
}
/**
* Authentication of the user after the user is logged in.
*/
function zendesk_authenticate_user() {
global $user;
$token = array(
'jti' => sha1($user->uid . REQUEST_TIME . rand()),
'iat' => REQUEST_TIME,
'name' => format_username($user),
'email' => $user->mail,
'external_id' => $user->uid,
);
$key = variable_get('zendesk_secret_key', '');
// Start the query params.
$query = array();
$jwt = zendesk_jwt_encode($token, $key);
$query['jwt'] = $jwt;
// Add in the passed-along return_to param, if any.
$current_params = drupal_get_query_parameters();
if(isset($current_params['return_to'])) {
$query['return_to'] = $current_params['return_to'];
}
// Redirect with attached GET params
$url = variable_get('zendesk_url', '') . '/access/jwt';
drupal_goto($url, array('query' => $query));
}
/**
* Converts and signs a PHP object or array into a JWT string.
*
* Taken from PEAR::JWT.
*
* @param $payload
* PHP object or array.
* @param $key
* The secret key.
*
* @return
* A signed JWT.
*/
function zendesk_jwt_encode($payload, $key) {
$header = array(
'typ' => 'JWT',
'alg' => 'HS256'
);
$segments = array();
$segments[] = zendesk_urlsafeb64_encode(json_encode($header));
$segments[] = zendesk_urlsafeb64_encode(json_encode($payload));
$signing_input = implode('.', $segments);
$signature = hash_hmac('sha256', $signing_input, $key, true);
$segments[] = zendesk_urlsafeb64_encode($signature);
return implode('.', $segments);
}
/**
* Encodes the given data with urlsafe base64.
*
* A base64 encoded string is made urlsafe by replacing '+' with '-',
* '/' with '_', and removing '='.
*
* Taken from PEAR::JWT.
*
* @param $data
* The data to encode.
*
* @return
* The encoded string.
*/
function zendesk_urlsafeb64_encode($data) {
$b64 = base64_encode($data);
return str_replace(array('+', '/', '\r', '\n', '='), array('-', '_'), $b64);
}
/**
* Implements hook_advanced_queue_info().
*/
function zendesk_advanced_queue_info() {
$items['zendesk_incremental_tickets'] = array(
'label' => t('Zendesk Incremental Tickets Pull'),
'worker callback' => 'zendesk_incremental_tickets_worker',
'delete when completed' => TRUE,
);
$items['zendesk_jira_links'] = array(
'label' => t('Zendesk Jira Links Pull'),
'worker callback' => 'zendesk_jira_links_worker',
'delete when completed' => TRUE,
);
return $items;
}
/**
* Implements hook_cron().
*/
function zendesk_cron() {
// @todo: Update ticket fields definition.
$zd = zendesk_initialize_library();
$response = $zd->call('/ticket_fields', '', 'GET');
if ($response) {
foreach ($response->ticket_fields as $tf) {
zendesk_ticket_field_write_record($tf);
}
}
// Make sure that the ticket incremental worker is queued in some non-failed state.
$result = db_query("SELECT COUNT(*) FROM advancedqueue WHERE name = 'zendesk_incremental_tickets' AND status != 2;")->fetchColumn(0);
if (!$result) {
$last_success = db_query("SELECT * FROM advancedqueue WHERE name = 'zendesk_incremental_tickets' AND status = 1 ORDER BY item_id DESC;")->fetchObject();
$start_time = ($last_success ? unserialize($last_success->data)['start_time'] : 0);
$data = array(
'title' => t('Zendesk incremental tickets pull'),
'start_time' => $start_time,
);
$queue = DrupalQueue::get('zendesk_incremental_tickets');
$queue->createItem($data);
}
// Make sure that the links worker is queued in some non-failed state.
if (variable_get('zendesk_jira_links_active', FALSE)) {
$result = db_query("SELECT COUNT(*) FROM advancedqueue WHERE name = 'zendesk_jira_links' AND status != 2;")->fetchColumn(0);
if (!$result) {
$data = array(
'title' => t('Zendesk/Jira links pull'),
);
$queue = DrupalQueue::get('zendesk_jira_links');
$queue->createItem($data);
}
}
}
/**
* Write a Zendesk field definition to the database.
*/
function zendesk_ticket_field_write_record($field_def) {
// Convert values.
$schema = drupal_get_schema('zendesk_ticket_fields');
foreach ($schema['fields'] as $field => $info) {
// Skip the ID field, it does not need to be updated.
if ($field == 'id') {
continue;
}
if (!property_exists($field_def, $field)) {
// Skip fields that are missing for any reason.
continue;
}
// Build array of fields to update or insert.
if (empty($info['serialize'])) {
$fields[$field] = $field_def->$field;
}
else {
$fields[$field] = serialize($field_def->$field);
}
// Type cast to proper datatypes.
if (isset($field_def->$field) || !empty($info['not null'])) {
if ($info['type'] == 'int' || $info['type'] == 'serial') {
$fields[$field] = (int) $fields[$field];
}
elseif ($info['type'] == 'float') {
$fields[$field] = (float) $fields[$field];
}
else {
$fields[$field] = (string) $fields[$field];
}
}
}
// Assemble merge.
$query = db_merge('zendesk_ticket_fields')->fields($fields)->key(array('id' => $field_def->id))->execute();
if (!$query) {
throw new Exception(t('Failed to insert Zendesk ticket field ID: ' . $field_def->id));
} // @todo: This thing
}
/**
* Write a ticket record from JSON to the database.
*/
function zendesk_ticket_write_record($ticket) {
// @todo: This thing
// Convert values.
$schema = drupal_get_schema('zendesk_tickets');
foreach ($schema['fields'] as $field => $info) {
// Skip the ticket ID field, it does not need to be updated.
if ($field == 'id') {
continue;
}
if (!property_exists($ticket, $field)) {
// Skip fields that are missing for any reason.
continue;
}
// Build array of fields to update or insert.
if ($field == 'created_at' || $field == 'updated_at') {
$fields[$field] = strtotime($ticket->$field);
}
elseif (empty($info['serialize'])) {
$fields[$field] = $ticket->$field;
}
else {
$fields[$field] = serialize($ticket->$field);
}
// Type cast to proper datatypes.
if (isset($ticket->$field) || !empty($info['not null'])) {
if ($info['type'] == 'int' || $info['type'] == 'serial') {
$fields[$field] = (int) $fields[$field];
}
elseif ($info['type'] == 'float') {
$fields[$field] = (float) $fields[$field];
}
else {
$fields[$field] = (string) $fields[$field];
}
}
}
// Assemble merge.
$query = db_merge('zendesk_tickets')->fields($fields)->key(array('id' => $ticket->id))->execute();
if (!$query) {
throw new Exception(t('Failed to insert Zendesk ticket ID: ' . $ticket->id));
}
// Write custom field values.
foreach ($ticket->fields as $field_value) {
$field_value->field_id = $field_value->id;
$field_value->ticket_id = $ticket->id;
zendesk_ticket_field_value_write_record($field_value, $ticket);
}
return $query;
}
function zendesk_ticket_field_value_write_record($field_value, $ticket) {
// Convert values.
$schema = drupal_get_schema('zendesk_ticket_field_values');
foreach ($schema['fields'] as $field => $info) {
// Skip the ID fields, it does not need to be updated.
if ($field == 'id') {
continue;
}
if (!property_exists($field_value, $field)) {
// Skip fields that are missing for any reason.
continue;
}
// Build array of fields to update or insert.
if (empty($info['serialize'])) {
$fields[$field] = $field_value->$field;
}
else {
$fields[$field] = serialize($field_value->$field);
}
// Type cast to proper datatypes.
if (isset($field_value->$field) || !empty($info['not null'])) {
if ($info['type'] == 'int' || $info['type'] == 'serial') {
$fields[$field] = (int) $fields[$field];
}
elseif ($info['type'] == 'float') {
$fields[$field] = (float) $fields[$field];
}
else {
$fields[$field] = (string) $fields[$field];
}
}
}
// Assemble merge.
$query = db_merge('zendesk_ticket_field_values')->fields($fields)->key(array('field_id' => $field_value->id, 'ticket_id' => $ticket->id))->execute();
if (!$query) {
throw new Exception(t('Failed to insert field value ' . $field_value->id . ' for Zendesk ticket ID: ' . $ticket->id));
}
}
/**
* Get the options from a dropdown field added on zendesk.
*
* @param int $field_id
* The field ID taken from zendesk.
*
* @return array|bool
*/
function zendesk_get_options_from_field($field_id) {
if (empty($field_id)) {
return FALSE;
}
// Try to load the field from the database.
$field_def = entity_object_load($field_id, 'zendesk_ticket_field');
if (!$field_def) {
// Not in the DB for some reason. Find it.
$zd = zendesk_initialize_library();
$data = $zd->call('/ticket_fields/' . $field_id, '', 'GET');
$options = array();
if (!empty($data->ticket_field)) {
// Yay, the API has it. Save it as if it had come in on cron.
$field_def = $data->ticket_field;
zendesk_ticket_field_write_record($field_def);
}
}
$options = [];
if ($field_def) {
if (!empty($field_def->custom_field_options)) {
foreach ($field_def->custom_field_options as $field_option) {
$options[$field_option->value] = $field_option->name;
}
}
else {
foreach ($field_def->system_field_options as $field_option) {
$options[$field_option->value] = $field_option->name;
}
}
}
return $options;
}
/**
* Options callback for the priority field.
*
* @return string[string]
*/
function zendesk_ticket_priority_options() {
return [
'' => t('None'),
'low' => t('Low'),
'normal' => t('Normal'),
'high' => t('High'),
'urgent' => t('Urgent'),
];
}
/**
* Options callback for the status field.
*
* @return string[string]
*/
function zendesk_ticket_status_options() {
return [
'deleted' => t('Deleted'),
'closed' => t('Closed'),
'hold' => t('On Hold'),
'pending' => t('Pending'),
'open' => t('Open'),
'solved' => t('Solved'),
'new' => t('New'),
];
}
function zendesk_incremental_tickets_worker($item) {
$success_count = 0;
$failure_count = 0;
$start_time = (!empty($item->data['start_time']) ? $item->data['start_time'] : 0);
$start_time = $start_time ?: _zendesk_start_time();
$zd = zendesk_initialize_library();
$url = '/incremental/tickets.json?start_time=' . $start_time;
do {
$response = $zd->call($url, '', 'GET');
if (!is_object($response)) {
watchdog("zendesk", "Zendesk error response: @response", ["@response" => var_export($response, TRUE)], WATCHDOG_WARNING);
break;
}
$count = $response->count;
$success_count += $count;
$url = str_replace($zd->base, '', $response->next_page);
if (is_array($response->tickets)) {
foreach ($response->tickets as $ticket) {
try {
zendesk_ticket_write_record($ticket);
}
catch (Exception $e) {
$failure_count++;
$success_count--;
advancedqueue_log_message(format_string('Invalid ticket exception for ticket ID @id: @message', ['@id' => $ticket->id, '@message' => $e->getMessage()]));
}
}
}
} while ($count >= 1000);
$queue = DrupalQueue::get('zendesk_incremental_tickets');
$item->data['start_time'] = (!empty($response->end_time) ? $response->end_time : time());
// We want to let the queue item do this, but failures causing a full re-run sucks.
variable_set('zendesk_incremental_ticket_last_time', $item->data['start_time']);
$item->created = time() + variable_get('zendesk_incremental_ticket_refresh_timer', 600);
// We tell the queue processor to not delete this item normally since we are
// requeueing it. This causes the success to not be logged.
$item->skip_deletion = TRUE;
// We requeue ourselves here with a +10 minute go-time and an updated
// Zendesk increment time.
$queue->requeueItem($item);
$params = [
'@success' => $success_count,
'@failure' => $failure_count,
];
// We log a message here because the normal operations won't record a message
// like this on the item status due to our requeueing shenanigans.
advancedqueue_log_message(format_string("Successfully finished incremental ticket processing run. Logged @success tickets updated successfully and @failure failures.", $params));
// This causes the success to be logged normally even though the details
// aren't recorded on the requeued item.
return ADVANCEDQUEUE_STATUS_SUCCESS;
}
/**
* If our worker doesn't have a start time, we will sync all tickets created after the last ticket's creation.
* And only if this fails for any reason whatsoever, we will fallback to the zendesk_last_incremental_pull
* variable.
*
* @return int
*/
function _zendesk_start_time() {
try {
return db_query("SELECT created_at FROM {zendesk_tickets} WHERE 1 ORDER BY id DESC LIMIT 0,1;")->fetchColumn(0) + 1;
}
catch (Exception $e) {
return variable_get('zendesk_last_incremental_pull', 0);
}
}
/**
* Pull in new Jira links.
*/
function zendesk_jira_links_worker($item) {
$latest_link = db_query("SELECT MAX(id) FROM zendesk_jira_links;")->fetchColumn() ?: 0;
$zd = zendesk_initialize_library();
$zd->base = substr($zd->base, 0, -3);
do {
$response = $zd->call("/services/jira/links.json?since_id=$latest_link", "", "GET");
foreach ($response->links as $l) {
$l->created_at = strtotime($l->created_at);
$l->updated_at = strtotime($l->updated_at);
drupal_write_record('zendesk_jira_links', $l);
$latest_link = max($latest_link, $l->id);
}
} while ($response->total > count($response->links));
$queue = DrupalQueue::get('zendesk_jira_links');
$item->created = time() + variable_get('zendesk_incremental_ticket_refresh_timer', 600);
// We tell the queue processor to not delete this item normally since we are
// requeueing it. This causes the success to not be logged.
$item->skip_deletion = TRUE;
// We requeue ourselves here with a +10 minute go-time.
$queue->requeueItem($item);
return ADVANCEDQUEUE_STATUS_SUCCESS;
}