-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathPlanfix_API.php
638 lines (536 loc) · 15.8 KB
/
Planfix_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
<?php
/**
* A simple library made for easy access to account data of Planfix users.
* Best suites for intergrating in CRM or administrator software for the sake of automation.
*
* You can use it absolutely free in commercial or non-commercial applications.
*
* Software provided AS IS without any warranty.
*
* @author Coding Hamster <[email protected]>
* @version 1.0.1
*/
/**
* Exception overriding for better catchability.
*/
class Planfix_API_Exception extends Exception {}
/**
* Main class with all the magic.
*/
class Planfix_API {
/**
* Version of the library
*/
const VERSION = '1.0.1';
/**
* Maximum size of a page for *.getList requests
*/
const MAX_PAGE_SIZE = 100;
/**
* Default Curl options
*/
public static $CURL_OPTS = array(
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 60,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_POSTREDIR => 1
);
/**
* Maximum simultaneous Curl handles in a Multi Curl session
*/
public static $MAX_BATCH_SIZE = 10;
/**
* Api url
*
* @var string
*/
protected $apiUrl;
/**
* Api key
*
* @var string
*/
protected $apiKey;
/**
* Api secret
*
* @var string
*/
protected $apiSecret;
/**
* Account name (*.planfix.ru)
*
* @var string
*/
protected $account;
/**
* User login
*
* @var string
*/
protected $userLogin;
/**
* User password
*
* @var string
*/
protected $userPassword;
/**
* Session identifier
*
* @var string
*/
protected $sid;
/**
* Initializes a Planfix Client
*
* Required parameters:
* - apiUrl - API Url
* - apiKey - Application Key
* - apiSecret - Application Secret
*
* @param array $config The array containing required parameters
*/
public function __construct($config) {
$this->setApiUrl($config['apiUrl']);
$this->setApiKey($config['apiKey']);
$this->setApiSecret($config['apiSecret']);
}
/**
* Set the Api url
*
* @param string $apiUrl Api url
* @return Planfix_API
*/
public function setApiUrl($apiUrl) {
$this->apiUrl = $apiUrl;
return $this;
}
/**
* Get the Api url
*
* @return string the Api url
*/
public function getApiUrl() {
return $this->apiUrl;
}
/**
* Set the Api key
*
* @param string $apiKey Api key
* @return Planfix_API
*/
public function setApiKey($apiKey) {
$this->apiKey = $apiKey;
return $this;
}
/**
* Get the Api key
*
* @return string the Api key
*/
public function getApiKey() {
return $this->apiKey;
}
/**
* Set the Api secret
*
* @param string $apiKey Api secret
* @return Planfix_API
*/
public function setApiSecret($apiSecret) {
$this->apiSecret = $apiSecret;
return $this;
}
/**
* Get the Api secret
*
* @return string the Api secret
*/
public function getApiSecret() {
return $this->apiSecret;
}
/**
* Set the Account
*
* @param string $account Account
* @return Planfix_API
*/
public function setAccount($account) {
$this->account = $account;
return $this;
}
/**
* Get the Account
*
* @return string the Account
*/
public function getAccount() {
return $this->account;
}
/**
* Set User Credentials
*
* Required parameters:
* - login - User login
* - password - User password
*
* @param array $user The array containing required parameters
*/
public function setUser($user) {
$this->setUserLogin($user['login']);
$this->setUserPassword($user['password']);
}
/**
* Set the User login
*
* @param string $userLogin User login
* @return Planfix_API
*/
public function setUserLogin($userLogin) {
$this->userLogin = $userLogin;
return $this;
}
/**
* Get the User login
*
* @return string the User login
*/
public function getUserLogin() {
return $this->userLogin;
}
/**
* Set the User password
*
* @param string $userPassword User password
* @return Planfix_API
*/
public function setUserPassword($userPassword) {
$this->userPassword = $userPassword;
return $this;
}
/**
* Get the User password
* Private for no external use
*
* @return string the User password
*/
private function getUserPassword() {
return $this->userPassword;
}
/**
* Set the Sid
*
* @param string $sid Sid
* @return Planfix_API
*/
public function setSid($sid) {
$this->sid = $sid;
return $this;
}
/**
* Get the Sid
*
* @return string the Sid
*/
public function getSid() {
return $this->sid;
}
/**
* Authenticate with previously set credentials
*
* @throws Planfix_API_Exception
* @return Planfix_API
*/
public function authenticate() {
$userLogin = $this->getUserLogin();
$userPassword = $this->getUserPassword();
if (!($userLogin && $userPassword)) {
throw new Planfix_API_Exception('User credentials are not set');
}
$requestXml = $this->createXml();
$requestXml['method'] = 'auth.login';
$requestXml->login = $userLogin;
$requestXml->password = $userPassword;
$requestXml->signature = $this->signXml($requestXml);
$response = $this->makeRequest($requestXml);
if (!$response['success']) {
throw new Planfix_API_Exception('Unable to authenticate: '.$response['error_str']);
}
$this->setSid($response['data']['sid']);
return $this;
}
/**
* Perform Api request
*
* @param string|array $method Api method to be called or group of methods for batch request
* @param array $params (optional) Parameters for called Api method
* @throws Planfix_API_Exception
* @return array the Api response
*/
public function api($method, $params = '') {
if (!$method) {
throw new Planfix_API_Exception('No method specified');
} elseif (is_array($method)) {
if (isset($method['method'])) {
$params = isset($method['params']) ? $method['params'] : '';
$method = $method['method'];
} else {
foreach($method as $request) {
if (!isset($request['method'])) {
throw new Planfix_API_Exception('No method specified');
}
}
}
}
$sid = $this->getSid();
if (!$sid) {
$this->authenticate();
$sid = $this->getSid();
}
if (is_array($method)) {
$batch = array();
foreach($method as $request) {
$requestXml = $this->createXml();
$requestXml['method'] = $request['method'];
$requestXml->sid = $sid;
$params = isset($request['params']) ? $request['params'] : '';
if (is_array($params) && $params) {
$this->importParams($requestXml, $params);
}
if (!isset($requestXml->pageSize)) {
$requestXml->pageSize = self::MAX_PAGE_SIZE;
}
$requestXml->signature = $this->signXml($requestXml);
$batch[] = $requestXml;
}
return $this->makeBatchRequest($batch);
} else {
$requestXml = $this->createXml();
$requestXml['method'] = $method;
$requestXml->sid = $sid;
if (is_array($params) && $params) {
$this->importParams($requestXml, $params);
}
if (!isset($requestXml->pageSize)) {
$requestXml->pageSize = self::MAX_PAGE_SIZE;
}
$requestXml->signature = $this->signXml($requestXml);
return $this->makeRequest($requestXml);
}
}
/**
* Create XML request
*
* @throws Planfix_API_Exception
* @return SimpleXMLElement the XML request
*/
protected function createXml() {
$requestXml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><request></request>');
$account = $this->getAccount();
if (!$account) {
throw new Planfix_API_Exception('Account is not set');
}
$requestXml->account = $account;
return $requestXml;
}
/**
* Import parameters to XML request
*
* @param SimpleXMLElement The XML request
* @param array Parameters
* @return SimpleXMLElement the XML request
*/
protected function importParams($requestXml, $params) {
foreach($params as $key => $val) {
if (is_array($val)) {
$requestXml->$key = new SimpleXMLElement("<$key/>");
foreach($val as $key2 => $val2) {
if (is_array($val2)) {
$this->importParams($requestXml->$key, $val2);
} else {
$requestXml->$key->addChild($key2, $val2);
}
}
} else {
$requestXml->addChild($key, $val);
}
}
return $requestXml;
}
/**
* Sign XML request
*
* @param SimpleXMLElement The XML request
* @throws Planfix_API_Exception
* @return string the Signature
*/
protected function signXml($requestXml) {
return md5($this->normalizeXml($requestXml).$this->getApiSecret());
}
/**
* Normalize the XML request
*
* @param SimpleXMLElement $node The XML request
* @return string the Normalized string
*/
protected function normalizeXml($node) {
$node = (array) $node;
ksort($node);
$normStr = '';
foreach ($node as $child) {
if (is_array($child)) {
$normStr .= implode('', array_map(array($this,'normalizeXml'), $child));
} elseif (is_object($child)) {
$normStr .= $this->normalizeXml($child);
} else {
$normStr .= (string) $child;
}
}
return $normStr;
}
/**
* Make the batch request to Api
*
* @param array $batch The array of XML requests
* @return array the array of Api responses
*/
protected function makeBatchRequest($batch) {
$mh = curl_multi_init();
$batchCnt = count($batch);
$max_size = $batchCnt < self::$MAX_BATCH_SIZE ? $batchCnt : self::$MAX_BATCH_SIZE;
$batchResult = array();
for ($i = 0; $i < $max_size; $i++) {
$requestXml = array_shift($batch);
$ch = $this->prepareCurlHandle($requestXml);
$chKey = (string) $ch;
$batchResult[$chKey] = array();
curl_multi_add_handle($mh, $ch);
}
do {
do {
$mrc = curl_multi_exec($mh, $running);
} while($mrc == CURLM_CALL_MULTI_PERFORM);
while ($request = curl_multi_info_read($mh)) {
$ch = $request['handle'];
$chKey = (string) $ch;
$batchResult[$chKey] = $this->parseApiResponse(curl_multi_getcontent($ch), curl_error($ch));
if (count($batch)) {
$requestXml = array_shift($batch);
$ch = $this->prepareCurlHandle($requestXml);
$chKey = (string) $ch;
$batchResult[$chKey] = array();
curl_multi_add_handle($mh, $ch);
}
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
}
if ($running) {
curl_multi_select($mh);
}
} while($running && $mrc == CURLM_OK);
return array_values($batchResult);
}
/**
* Make the request to Api
*
* @param SimpleXMLElement $requestXml The XML request
* @return array the Api response
*/
protected function makeRequest($requestXml) {
$ch = $this->prepareCurlHandle($requestXml);
$response = curl_exec($ch);
$error = curl_error($ch);
return $this->parseApiResponse($response, $error);
}
/**
* Prepare the Curl handle
*
* @param SimpleXMLElement $requestXml The XML request
* @return resource the Curl handle
*/
protected function prepareCurlHandle($requestXml) {
$ch = curl_init($this->getApiUrl());
curl_setopt_array($ch, self::$CURL_OPTS);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $this->getApiKey().':X');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXml->asXML());
return $ch;
}
/**
* Parse the Api response
*
* @link http://goo.gl/GWa1c List of Api error codes
*
* @param string $response The Api response
* @param string $error The Curl error if any
* @return array the Curl handle
*/
protected function parseApiResponse($response, $error) {
$result = array(
'success' => 1,
'error_str' => '',
'meta' => null,
'data' => null
);
if ($error) {
$result['success'] = 0;
$result['error_str'] = $error;
return $result;
}
try {
$responseXml = new SimpleXMLElement($response);
} catch (Exception $e) {
$result['success'] = 0;
$result['error_str'] = $e->getMessage();
return $result;
}
if ($responseXml['status'] == 'error') {
$result['success'] = 0;
$result['error_str'] = 'Code: '.$responseXml->code.' / Message: '.$responseXml->message;
return $result;
}
if (isset($responseXml->sid)) {
$result['data']['sid'] = (string) $responseXml->sid;
} else {
$responseXml = $responseXml->children();
foreach($responseXml->attributes() as $key => $val) {
$result['meta'][$key] = (int) $val;
}
if ($result['meta'] == null || $result['meta']['totalCount'] || $result['meta']['count']) {
$result['data'] = $this->exportData($responseXml);
}
}
return $result;
}
/**
* Exports the Xml response to array
*
* @param SimpleXMLElement $responseXml The Api response
* @return array the Exported data
*/
protected function exportData($responseXml) {
$root = $responseXml->getName();
$data[$root] = array();
$rootChildren = $responseXml->children();
$names = array();
foreach($rootChildren as $child) {
$names[] = $child->getName();
}
$is_duplicate = count(array_unique($names)) != count($names) ? true : false;
$grandchildren = $child->children();
if ($grandchildren->count() || count($grandchildren) > 1) {
if (count($child->children()) > 1) {
$data[$root] = array_merge($data[$root], $is_duplicate ? array($this->exportData($child)) : $this->exportData($child));
} else {
$data[$root][$child->getName()] = (string) $child;
}
}
return $data;
}
}
/* EOF */