-
Notifications
You must be signed in to change notification settings - Fork 15
/
workbooks_api.php
2003 lines (1793 loc) · 74.1 KB
/
workbooks_api.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
/**
* A PHP wrapper for the Workbooks API documented at http://www.workbooks.com/api
*
* Last commit $Id: workbooks_api.php 56196 2022-10-20 13:44:51Z gbarlow $
* License: www.workbooks.com/mit_license
*
*
* Significant methods in the class Workbooks:
* new - create an API object, specifying various options
* login - authenticate
* logout - terminate logged-in session (automatic when object destroyed)
* get - get a list of objects, or show an object
* create - create objects
* update - update objects
* delete - delete objects
* batch - create, update, and delete objects together
* response - gather response from an asynchonous request
* getSessionId/setSessionId - use these to connect to an existing session
* condensedStatus - use this to quickly check the response
*
* NOTE: When this file is included, if certain values with names beginning '_workbooks_'
* exist in the array '$params' then those values are used to establish a connection
* back to the Workbooks service, putting a handle to it in the variable '$workbooks'.
* This technique is used by scripts running under the Workbooks Process Engine.
*
* Requirements: Uses CURL and JSON PHP extensions.
**/
if (!function_exists('curl_init')) {
throw new Exception('workbooks_api.php uses the CURL PHP extension');
}
if (!function_exists('json_decode')) {
throw new Exception('workbooks_api.php uses the JSON PHP extension');
}
/**
* Thrown when an API call returns an exception.
**/
class WorkbooksApiException extends Exception
{
/**
* The result from the API server that represents the exception information.
**/
protected $result;
/**
* Make a new API Exception with the given result.
*
* @param Array $result the result from the API server
**/
public function __construct($result) {
$msg = $result['error']['message'];
$code = isset($result['error_code']) ? $result['error_code'] : 0;
// If we have access to the Workbooks API object, log all that we can
if (isset($result['workbooks_api'])) {
$result['workbooks_api']->log('new WorkbooksApiException', array($msg, $code, $this));
}
parent::__construct($msg, $code);
}
}
class WorkbooksApi
{
const API_VERSION = 1; // Used to select the default Workbooks server-side behaviour
/**
* Instance variables
**/
protected $curl_multi_handle = NULL;
protected $curl_handle = NULL;
protected $curl_options = NULL;
protected $logger_callback = NULL;
protected $session_id = NULL;
protected $api_key = NULL;
protected $username = NULL;
protected $logical_database_id = NULL;
protected $database_instance_id = NULL;
protected $authenticity_token = NULL;
protected $api_version = WorkbooksApi::API_VERSION;
protected $api_logging_key = NULL; // when available requests server-side logging of API requests/responses
protected $api_logging_seq = 0; // used for server-side logging of API requests/responses
protected $login_state = false; // true => logged in
protected $auto_logout = true; // true => call logout() in destroy hook
protected $application_name = NULL;
protected $user_agent = NULL;
protected $connect_timeout = 120; // 2 minutes
protected $request_timeout = 120;
protected $verify_peer = true; // false is not correct for Production use.
protected $fast_login = true; // speed up the login by not returning my_queues and some other details during login.
protected $service = 'https://secure.workbooks.com';
protected $last_request_duration = NULL;
protected $user_queues = NULL; // when logged in contains an array of user queues
protected $login_response = NULL;
protected $async_running = array();// In-flight async requests
protected $async_queue = array(); // Async requests not sent yet (concurrency limit exceeded)
protected $audit_lifetime_days = NULL; // If set to a positive integer audit records expire and are automatically deleted
protected $process_start_time = NULL; // The time this object was created which should be when the script process started
/**
* Those HTTP status codes of particular significance to the API.
**/
const HTTP_STATUS_OK = 200;
const HTTP_STATUS_FOUND = 302;
const HTTP_STATUS_FORBIDDEN = 403;
/**
* The Workbooks session cookie
**/
const SESSION_COOKIE = 'Workbooks-Session';
/**
* The content_type governs the encoding used for data transfer to the Service. Two forms are supported in this binding; use
* FORM_DATA for file uploads.
**/
const FORM_URL_ENCODED = 'application/x-www-form-urlencoded';
const FORM_DATA = 'multipart/form-data';
/**
* Define a hard limit of 1 MegaByte to limit the size of a log message logged with the default logger.
**/
const HARD_LOG_LIMIT = 1048576;
const PARALLEL_CONCURRENCY_LIMIT = 5;
/**
* Initialise the Workbooks API
*
* The configuration:
* Mandatory settings
* - application_name: You should specify a descriptive name for your application such as 'Freedom Plugin' or 'Mactools Widget'
* - user_agent: A technical name for the application including version number e.g. 'Mactools/0.9.2' as defined in HTTP.
* Optional settings
* - service: The FQDN of the Workbooks service (defaults to secure.workbooks.com)
* - logger_callback: an array of (class, name of function) to pass debugging output to. The function takes two
* string arguments: msg and level. In the absence of a logger_callback, no logging is done by this library.
* WorkbooksApi::logAllToStdout() is provided as an example: pass
* array('Workbooks', 'logAllToStdout').
* - api_key or username: the user to login with
* - session_id: a sessionID to reconnect to
* - logical_database_id: the databaseID which the session_id is associated with
* - api_logging_key: if specified this is used to identify a Process Log to attach API logging records to
* - api_version: used to request a specific server-side behaviour. Normally this should be left as API_VERSION
* - connect_timeout: how long to wait for a connection to be established in seconds (default: 20)
* - request_timeout: how long to wait for a response in seconds (default: 20)
* - verify_peer: whether to verify the peer's SSL certificate. Set this to false for some test environments but do not
* do this in Production.
* - fast_login: whether to skip generating certain items (e.g. my_queues) during login
* @param Array $params the Workbooks connection configuration
**/
public function __construct($params) {
if (isset($params['logger_callback'])) {
$this->setLoggerCallback($params['logger_callback']);
}
// $this->log('new() called with params', $params);
if (isset($params['application_name'])) {
$this->setApplicationName($params['application_name']);
} else {
throw new Exception('An application name must be supplied');
}
if (isset($params['user_agent'])) {
$this->setUserAgent($params['user_agent']);
} else {
throw new Exception('A user agent must be supplied');
}
if (isset($params['service'])) {
$this->setService($params['service']);
}
if (isset($params['connect_timeout'])) {
$this->setConnectTimeout($params['connect_timeout']);
}
if (isset($params['request_timeout'])) {
$this->setRequestTimeout($params['request_timeout']);
}
if (isset($params['api_key'])) {
$this->setApiKey($params['api_key']);
}
if (isset($params['username'])) {
$this->setUsername($params['username']);
}
if (isset($params['session_id'])) {
$this->setSessionId($params['session_id']);
}
if (isset($params['logical_database_id'])) {
$this->setLogicalDatabaseId($params['logical_database_id']);
}
if (isset($params['api_logging_key'])) {
$this->setApiLoggingKey($params['api_logging_key']);
$this->resetApiLoggingSeq();
}
if (isset($params['api_version'])) {
$this->setApiVersion($params['api_version']);
}
if (isset($params['verify_peer'])) {
$this->setVerifyPeer($params['verify_peer']);
}
if (isset($params['fast_login'])) {
$this->setFastLogin($params['fast_login']);
}
// Set the process start time to now
$this->process_start_time = time();
$curl_handle = curl_init();
$this->setCurlHandle($curl_handle);
$this->curl_options = array(
CURLOPT_USERAGENT => $this->getUserAgent(),
CURLOPT_CONNECTTIMEOUT => $this->getConnectTimeout(),
CURLOPT_TIMEOUT => $this->getRequestTimeout(),
CURLOPT_SSL_VERIFYHOST => $this->getVerifyPeer() ? 2 : 0,
CURLOPT_SSL_VERIFYPEER => $this->getVerifyPeer(),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_POST => true,
//CURLOPT_VERBOSE => true, // Very noisy, logs to stderr
);
// $this->log('new() returns', $this);
return $this;
}
/**
* Get (and create if required) the Curl Multi handle.
*
* @return Resource $curl_multi_handle a Curl Multi handle as might be returned by curl_multi_init()
**/
private function getCurlMultiHandle() {
if (!isset($this->curl_multi_handle)) {
$this->curl_multi_handle = curl_multi_init();
if (function_exists('curl_multi_setopt')) { // More efficient if this is available; not an error if not.
if (defined('CURLPIPE_NOTHING')) { // from cURL 7.43.0
curl_multi_setopt($this->curl_multi_handle, CURLMOPT_PIPELINING, CURLPIPE_NOTHING);
} else {
curl_multi_setopt($this->curl_multi_handle, CURLMOPT_PIPELINING, true);
}
// when we are working with HTTP/2, we can think about CURLPIPE_MULTIPLEX
}
}
return $this->curl_multi_handle;
}
/**
* Clear down the Curl Multi handle, destroying it.
**/
private function destroyCurlMultiHandle() {
if (isset($this->curl_multi_handle)) {
curl_multi_close($this->curl_multi_handle);
unset($this->curl_multi_handle);
}
}
/**
* Set the Curl handle.
*
* @param Resource $curl_handle a Curl handle as might be returned by curl_init()
**/
private function setCurlHandle($curl_handle) {
$this->curl_handle = $curl_handle;
return $this;
}
/**
* Get the Curl handle.
*
* @return Resource $curl_handle a Curl handle as might be returned by curl_init()
**/
private function getCurlHandle() {
return $this->curl_handle;
}
/**
* Clear down the Curl handle, destroying it.
**/
private function destroyCurlHandle() {
if (isset($this->curl_handle)) {
curl_close($this->curl_handle);
unset($this->curl_handle);
}
}
/**
* Set the last request duration.
*
* @param Float $last_request_duration the duration of the last request, in seconds
**/
protected function setLastRequestDuration($last_request_duration) {
$this->last_request_duration = $last_request_duration;
return $this;
}
/**
* Get the last request duration.
*
* @return Float $last_request_duration the duration of the last request, in seconds
**/
public function getLastRequestDuration() {
return round($this->last_request_duration,6);
}
/**
* Set the user_queues list.
*
* @param Array $user_queues - an array of queues as returned at login time
**/
protected function setUserQueues(&$user_queues) {
$this->user_queues = $user_queues;
return $user_queues;
}
/**
* Get the user_queues list.
*
* @return Array $user_queues - an array of queues as returned at login time
**/
public function getUserQueues() {
$this->ensureLogin();
return $this->user_queues;
}
/**
* Set the application name.
*
* @param String $application_name the application name
**/
public function setApplicationName($application_name) {
$this->application_name = $application_name;
return $this;
}
/**
* Get the application name.
*
* @return String the application name
**/
public function getApplicationName() {
return $this->application_name;
}
/**
* Set the user agent string.
*
* @param String $user_agent the user agent string
**/
public function setUserAgent($user_agent) {
$this->user_agent = $user_agent;
return $this;
}
/**
* Get the user agent string.
*
* @return String the user agent string
**/
public function getUserAgent() {
return $this->user_agent;
}
/**
* Set the API Version.
*
* @param Integer $api_version the API Version to use
**/
public function setApiVersion($api_version) {
$this->api_version = $api_version;
return $this;
}
/**
* Get the API Version.
*
* @return Integer the API Version in use
**/
public function getApiVersion() {
return $this->api_version;
}
/**
* Set the connect timeout.
*
* @param Integer $connect_timeout the connect timeout
**/
public function setConnectTimeout($connect_timeout) {
$this->connect_timeout = $connect_timeout;
return $this;
}
/**
* Get the connect timeout.
*
* @return Integer the connect timeout
**/
public function getConnectTimeout() {
return $this->connect_timeout;
}
/**
* Set the request timeout.
*
* @param Integer $request_timeout the request timeout
**/
public function setRequestTimeout($request_timeout) {
$this->request_timeout = $request_timeout;
return $this;
}
/**
* Get the request timeout.
*
* @return Integer the request timeout
**/
public function getRequestTimeout() {
return $this->request_timeout;
}
/**
* Set the API Key used to login.
*
* @param String $api_key the API key
**/
public function setApiKey($api_key) {
$this->api_key = $api_key;
return $this;
}
/**
* Get the API Key used to login.
*
* @return String $api_key the API key
**/
public function getApiKey() {
return $this->api_key;
}
/**
* Set the user name used to login/reconnect.
*
* @param String $username the login name
**/
public function setUsername($username) {
$this->username = $username;
return $this;
}
/**
* Get the user name used to login/reconnect.
*
* @return String $username the login name
**/
public function getUsername() {
return $this->username;
}
/**
* Set the logical database ID used to login/reconnect.
*
* @param Integer $logical_database_id the ID of the logical database the session is associated with
**/
public function setLogicalDatabaseId($logical_database_id) {
$this->logical_database_id = $logical_database_id;
return $this;
}
/**
* Get the logical database ID used to login/reconnect.
*
* @return Integer $logical_database_id the ID of the logical database the session is associated with
**/
public function getLogicalDatabaseId() {
return $this->logical_database_id;
}
/**
* Set the active database ID.
*
* @param Integer $database_instance_id the ID of the database instance the session is associated with
**/
public function setDatabaseInstanceId($database_instance_id) {
$this->database_instance_id = $database_instance_id;
return $this;
}
/**
* Get the active database as a string to embed in a URL (useful for web processes).
*
* @return String $encoded_database_instance_id the database instance the session is associated with
**/
public function getDatabaseInstanceRef() {
$this->ensureLogin();
return strrev(base64_encode($this->database_instance_id + 17));
}
/**
* Set the API logging key: this is used to associate API request/response log
* records with the log for an invocation of a Process. Only useful when running
* within the Process Engine environment.
*
* @param String $api_logging_key the API logging key
**/
public function setApiLoggingKey($api_logging_key) {
$this->api_logging_key = $api_logging_key;
return $this;
}
/**
* Get the API logging key.
*
* @return String the API logging key
**/
public function getApiLoggingKey() {
return $this->api_logging_key;
}
/**
* Reset the API logging sequence number which is used in conjunction with API request/response
* log records. Only useful when running within the Process Engine environment. Each request
* gets a new sequence number.
**/
private function resetApiLoggingSeq() {
$this->api_logging_seq = 0;
return $this;
}
/**
* Get the next API logging sequence number.
*
* @return Integer the API logging sequence number
**/
public function nextApiLoggingSeq() {
$this->api_logging_seq++;
return $this->api_logging_seq;
}
/**
* Set the Audit Lifetime in days (which defaults to NULL, i.e. do not automatically delete)
*
* @param Integer $audit_lifetime_days the number of days after which audit records should be automatically deleted
**/
public function setAuditLifetime($audit_lifetime_days) {
$this->audit_lifetime_days = $audit_lifetime_days;
return $this;
}
/**
* Get the Audit Lifetime (in days)
*
* @return Integer the audit lifetime, or NULL (the default)
**/
public function getAuditLifetime() {
return $this->audit_lifetime_days;
}
/**
* Get the process start time in seconds since the Unix Epoch
*
* @return Integer the process start time in seconds
**/
protected function getProcessStartTime(){
return $this->process_start_time;
}
/**
* Get the elapsed time since the process started in seconds
*
* @return Integer the elapsed time in seconds
**/
protected function getElapsedProcessTime() {
return time() - $this->getProcessStartTime();
}
/**
* Get the process time allowed in seconds or NULL if not set
*
* @return Integer the process time allowed in seconds or NULL if not set
**/
protected function getProcessTimeout(){
return isset($_SERVER['TIMEOUT']) ? $_SERVER['TIMEOUT'] : NULL;
}
/**
* Get the process time remaining in seconds or NULL if no timeout is set
*
* @return Integer the time remaining in seconds or NULL
**/
public function getProcessTimeRemaining(){
if (!is_null($this->getProcessTimeout())){
$time_left = $this->getProcessTimeout() - $this->getElapsedProcessTime();
return $time_left < 0 ? 0 : $time_left;
}else{
return NULL;
}
}
/**
* Set the flag for verifying the peer's SSL certificate. When connecting to test servers
* you may need to turn peer verification off.
*
* @param Boolean $verify_peer whether to verify the peer's SSL certificate
**/
public function setVerifyPeer($verify_peer) {
$this->verify_peer = $verify_peer;
return $this;
}
/**
* Get the SSL verify certificate setting.
*
* @return Boolean whether to verify the peer's SSL certificate
**/
public function getVerifyPeer() {
return $this->verify_peer;
}
/**
* Set the flag for speeding up login by not generating my_queues etc
* @param Boolean $fast_login
**/
public function setFastLogin($fast_login) {
$this->fast_login = $fast_login;
return $this;
}
/**
* Get the flag for speeding up login by not generating my_queues etc
*
* @return Boolean
**/
public function getFastLogin() {
return $this->fast_login;
}
/**
* Set the service name.
*
* @param String $service the FQDN of the Workbooks service
**/
public function setService($service) {
$this->service = $service;
return $this;
}
/**
* Get the service name.
*
* @return String the service name
**/
public function getService() {
return $this->service;
}
/**
* Set the login_state.
*
* @param Boolean $login_state true if logged in, false otherwise
**/
public function setLoginState($login_state) {
$this->login_state = $login_state;
return $this;
}
/**
* Get the login_state.
*
* @return Boolean true if logged in, false otherwise
**/
public function getLoginState() {
return $this->login_state;
}
/**
* Store the Login response
* @param $login_response - the response returned after successful login
*/
public function setLoginResponse($login_response)
{
$this->login_response = $login_response;
}
/**
* @return the response after logging in
*/
public function getLoginResponse()
{
return $this->login_response;
}
/**
* Set the auto_logout flag.
* NOTE: Deprecated; this flag no longer has any effect. Call logout directly.
*
* @param Boolean $auto_logout true to logout automatically, false to leave the session
**/
public function setAutoLogout($auto_logout) {
$this->auto_logout = $auto_logout;
return $this;
}
/**
* Get the auto_logout flag.
* NOTE: Deprecated; this flag no longer has any effect. Call logout directly.
*
* @return Boolean $auto_logout true to logout automatically, false to leave the session
**/
public function getAutoLogout() {
return $this->auto_logout;
}
/**
* Set the Authenticity Token. This is unique to each session.
*
* @param String $authenticity_token the Authenticity Token.
**/
protected function setAuthenticityToken($authenticity_token) {
$this->authenticity_token = $authenticity_token;
return $this;
}
/**
* Get the Authenticity Token
*
* @return String the Authenticity Token
**/
public function getAuthenticityToken() {
return $this->authenticity_token;
}
/**
* Set the session ID which is sent in a cookie to the server.
*
* @param String $session_id the session ID received from Workbooks.
**/
public function setSessionId($session_id) {
$this->session_id = $session_id;
return $this;
}
/**
* Get the session ID
*
* @return String the session ID
**/
public function getSessionId() {
return $this->session_id;
}
/**
* Get the session cookie
*
* @return String the session cookie
**/
public function getSessionCookie() {
$session_cookie = NULL;
if (!empty($this->session_id)) {
$session_cookie = WorkbooksApi::SESSION_COOKIE . '=' . $this->session_id;
}
return $session_cookie;
}
/**
* Set the logger callback. In the absence of this, no log output is generated.
*
* @param Array $logger_callback a class and function to pass (level, msg) to
* e.g. setLoggerCallback(array('WorkbooksApi', 'logAllToStdout'))
**/
public function setLoggerCallback($logger_callback) {
$this->logger_callback = $logger_callback;
return $this;
}
/**
* Call the logger function, if any.
*
* @param String $msg a string to be logged
* @param Mixed $expression optional, any values to output with the message
* @param String $level optional: one of 'error', 'warning', 'notice', 'info', 'debug' (the default), or 'output'
* @param Integer $log_size_limit the maximum size msg that will be logged.
**/
public function log($msg, $expression=NULL, $level='debug', $log_size_limit=4096) {
if (isset($this->logger_callback)) {
if ($expression !== NULL && $expression != 'nil') {
$msg .= ' «' . var_export($expression, true) . '»';
}
call_user_func($this->logger_callback, $msg, $level, $log_size_limit);
}
}
/**
* A sample logger, this one passes all messages to stdout.
* @param String $msg a string to be logged
* @param String $level one of 'error', 'warning', 'notice', 'info', 'debug', 'output'
* @param Integer $log_size_limit the maximum size msg that will be logged.
* Logs the first and last parts of longer msgs and indicates the number of bytes that have not been logged.
**/
public function logAllToStdout($msg, $level, $log_size_limit) {
// Use isset on every msg for performance and only use strlen() when the msg is over the limit.
if (isset($msg[$log_size_limit])){
$msg_size = strlen($msg);
// Apply a hard limit to limit the load on the Workbooks service.
$log_size_limit = ($log_size_limit > WorkbooksApi::HARD_LOG_LIMIT ? WorkbooksApi::HARD_LOG_LIMIT : $log_size_limit);
$msg = substr($msg, 0, $log_size_limit / 2) . "... (" . ($msg_size - $log_size_limit) . " bytes) ..." . substr($msg, $msg_size - $log_size_limit / 2);
}
echo "\n\n[" . $level .'] ' . $msg . "\n\n";
}
/**
* A sample logger, this one passes all messages to stdout and flushes the buffer
* @param String $msg a string to be logged
* @param String $level one of 'error', 'warning', 'notice', 'info', 'debug', 'output'
* @param Integer $log_size_limit the maximum size msg that will be logged.
**/
public function logAllToStdoutAndFlush($msg, $level, $log_size_limit) {
self::logAllToStdout(preg_replace('/\n\n+/m', "\n", $msg), $level, $log_size_limit);
// Now flush the output buffer
ob_flush();
}
/**
* Helper function to send headers when running as a Web Process.
**/
public function header($str) {
echo "\n\n[header] {$str}\n\n";
}
/**
* Helper function to send output when running as a Web Process.
**/
public function output($str) {
echo "\n\n[outbin] " . chunk_split(base64_encode($str), 1024*1024, "\n\n[outbin] ") . "\n\n";
}
/**
* Internal function to send commands back to the desktop when running as a Button Process or On Save Process.
**/
protected function desktopAction($action_and_parameters) {
$json = json_encode($action_and_parameters);
echo "\n\n[desktop_action] $json\n\n";
}
/**
* Helper function to open a window in the desktop when running as a Button Process or On Save Process.
**/
public function desktopOpenWindow($url) {
self::desktopAction(array('open' => $url));
}
/**
* Helper function to close the current window in the desktop when running as a Button Process or On Save Process.
**/
public function desktopCloseCurrentWindow() {
self::desktopAction(array('close' => ''));
}
/**
* Helper function to open a record in the desktop when running as a Button Process or On Save Process.
**/
public function desktopOpenRecordByObjectRef($object_ref) {
self::desktopAction(array('open_record_by_object_ref' => $object_ref));
}
/**
* Helper function to open a record in the desktop when running as a Button Process or On Save Process.
**/
public function desktopOpenRecordByIdAndType($type, $id) {
self::desktopAction(array('open_record_by_id_and_type' => array('type' => $type, 'id' => $id)));
}
/**
* Helper function to display a message box in the desktop when running as a Button Process or On Save Process.
**/
public function desktopMessage($title, $body) {
self::desktopAction(array('message' => array('title' => $title, 'body' => $body)));
}
/**
* Helper function to open a new browser tab from the desktop when running as a Button Process or On Save Process.
**/
public function desktopExternalUrl($url) {
self::desktopAction(array('external_new_window' => $url));
}
/**
* Helper function to activate a named tab in the current window on the desktop when running as a Button Process or On Save Process.
**/
public function desktopActivateTab($tab_name) {
self::desktopAction(array('activate_tab' => $tab_name));
}
/**
* Helper function which evaluates a response to determine how successful it was
* @param Array $response a response from the service API
* @return String One of: 'failed', 'ok', 'not-ok'
* 'failed' - this is unexpected.
* 'not-ok' - something in the request could not be satisfied; you should check the errors and warnings.
* 'ok' - completely successful.
**/
public function condensedStatus(&$response) {
$status = 'ok';
if (!isset($response['success'])) {
return 'failed'; // Unexpected failure - there should always be a 'success' element
} elseif (!$response['success']){
return 'failed'; // Something was quite wrong, not just a validation failure
} elseif (isset($response['errors'])) {
$status = 'not-ok';
} elseif (!isset($response['affected_object_information']) || !is_array($response['affected_object_information'])) {
return 'ok';
} else {
foreach ($response['affected_object_information'] as &$affected) {
if (!isset($affected['success'])) {
return 'failed'; // Again, this is unexpected.
}
if (!$affected['success']) {
$status = 'not-ok'; // There will be warnings or errors indicated which prevented complete success.
}
}
}
return $status;
}
/**
* Check responses are expected. Raises an exception if the response is not.
* @param Array $response a response from the service API.
* @param String $expected the expected type of response, defaults to 'ok'.
* @param String $raise_on_error the exception to raise if the response is not as expected.
**/
public function assertResponse(&$response, $expected='ok', $raise_on_error='Unexpected response from Workbooks API') {
$condensed_status = $this->condensedStatus($response);
if ($condensed_status != $expected) {
$this->log('Received an unexpected response', array ($condensed_status, $response, $expected));
throw new Exception($raise_on_error);
}
}
/*
* Extract ids and lock_versions from the 'affected_objects' of the response and return them as an Array of Arrays.
* @param Array $response a response from the service API.
* @return Array a set of id and lock_version values, one per affected object.
**/
public function idVersions(&$response) {
$retval = array();
foreach ($response['affected_objects'] as &$affected) {
$retval[]= array(
'id' => $affected['id'],
'lock_version' => $affected['lock_version'],
);
}
return $retval;
}
/**
* Login to the service to set up a session.
* Optional settings
* - api_key: An API key (this is preferred over username/password).
* - username: The user's login name (required if not set using setUsername) or using an API key.
* - password: The user's login password. Either this or a session_id must be specified.
* - session_id: The ID of a session to reconnect to. Either this or a password must be specified.
* - logical_database_id: The ID of a database to select - not required when the user has access to exactly one.
* others as defined in the API documentation (e.g. _time_zone, _strict_attribute_checking, _per_object_transactions).
* @param Array $params credentials and other options to the login API endpoint.
* @return Array (Integer the http status, String any failure reason, Array the decoded json)
*
* A successful login returns an http status of 200 (WorkbooksApi::HTTP_STATUS_OK).
* If more than one database is available the http status is 403 (WorkbooksApi::HTTP_STATUS_FORBIDDEN), the failure reason
* is 'no_database_selection_made' and the set of databases to choose from are in the decoded json beneath the 'databases'
* key. Repeat the login() call, passing in a logical_database_id: you might use the 'default_database_id' value which
* was returned in the previous login attempt.
* Otherwise the login has failed outright: see the Workbooks API documentation for a list of the possible http statuses.
**/
public function login($params) {
// $this->log('login() called with params', $params);
if (empty($params['api_key'])) {
$params['api_key'] = $this->getApiKey();
}
if (empty($params['username'])) {
$params['username'] = $this->getUsername();
}
if (empty($params['api_key']) && empty($params['username'])) {
throw new Exception('An API key or a username must be supplied');
}
if (empty($params['password']) && empty($params['session_id'])) {