· 5 years ago · Jul 08, 2020, 03:46 PM
1<?php
2/**
3 * PHP REST SQL class
4 * The base class for the Rest SQL system that opens up a REST interface to a MySQL database.
5 */
6
7class PHPRestSQL
8{
9 /**
10 * Global config object.
11 *
12 * @public Zend_Config_Ini
13 */
14 private $_gc = null;
15
16 /**
17 * Debug flag.
18 *
19 * @var boolean
20 */
21 private $_debug = true;
22
23 /**
24 * Database name.
25 *
26 * @public string
27 */
28 private $_dbName = '';
29
30 private $_fields = array();
31
32 public $eventHeader = '';
33 public $axmlHeader = '';
34 public $config;
35 public $eventServer="127.0.0.1";
36 public $eventPort=9999;
37 public $commandServer="127.0.0.1";
38 public $commandPort = 9998;
39 public $db;
40 public $method = 'GET';
41 public $requestData = NULL;
42 public $extension = NULL;
43 public $table = NULL;
44 public $service = NULL;
45 public $uid = NULL;
46 public $myKey = NULL;
47 public $order = NULL;
48 public $ordersort = NULL;
49 public $startRow = NULL;
50 public $limit = NULL;
51 public $myNVP = array();
52 public $myOperators = array();
53 public $myComparators = array();
54 public $output = array();
55 public $display = NULL;
56
57 /**
58 * Constructor.
59 *
60 * @return void
61 */
62 public function __construct($requestData = '')
63 {
64 $this->_gc = Nlss::getGlobalConfig();
65 $this->_debug = (in_array(getenv('APPLICATION_ENV'), array('local', 'development', 'test')));
66 $this->eventHeader = "<NLSSEvent xmlns=\"http://www.nlss.com/Gateway\">\n";
67 $this->axmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?" . ">\n";
68 $this->requestData = $requestData;
69 }
70
71 /**
72 * TODO
73 */
74 function beginAuth()
75 {
76 $this->table = 'DeviceCommands';
77 $this->myKey = 'authenticate';
78 $this->method = 'POST';
79 $this->parseContent();
80 $this->_exec();
81 }
82
83 /**
84 * TODO
85 */
86 function begin()
87 {
88 $this->parseHeaders();
89 $this->_exec();
90 }
91
92 /**
93 * TODO
94 */
95 function parseHeaders()
96 {
97 if (isset($_SERVER['REQUEST_URI']) && isset($_SERVER['REQUEST_METHOD'])) {
98 $this->parseContent();
99
100 $urlString = urldecode($_SERVER['REQUEST_URI']);
101 $urlParts = explode('/', $urlString);
102 $lastPart = array_pop($urlParts);
103 $dotPosition = strpos($lastPart, '.');
104
105 /*
106 if ($dotPosition !== false) {
107 $this->extension = substr($lastPart, $dotPosition + 1);
108 $lastPart = substr($lastPart, 0, $dotPosition);
109 }
110 */
111 array_push($urlParts, $lastPart);
112 if (isset($urlParts[0]) && $urlParts[0] == '') {
113 array_shift($urlParts);
114 }
115 if (isset($urlParts[0]) && $urlParts[0] == 'api') {
116 array_shift($urlParts);
117 }
118 if (isset($urlParts[0])) {
119 if (preg_match("/^[0-9a-z]{8}-([0-9a-z]{4}-){3}[0-9a-z]{12}$/", $urlParts[0])) {
120 $this->_dbName = array_shift($urlParts);
121 } elseif ($urlParts[0] == 'nlssgateway') {
122 $this->_dbName = Nlss_App::getDatabaseName();
123 array_shift($urlParts);
124 }
125 }
126 if (isset($urlParts[0]) && $urlParts[0] == 'v1') {
127 array_shift($urlParts);
128 }
129 if (isset($urlParts[0])) {
130 $this->table = $urlParts[0];
131 array_shift($urlParts);
132 }
133
134 $NVParray = array();
135 if (count($urlParts) > 1 && $urlParts[1] != '') {
136 $littlearrary = array();
137 $mycount=0;
138
139 foreach ($urlParts as $uid) {
140 if ($uid != '') {
141 $littlearrary[] = $uid;
142 $mycount+=1;
143 }
144 if ($mycount == 2) {
145 $NVParray[] = $littlearrary;
146 $littlearrary = array();
147 $mycount = 0;
148 }
149 }
150 }
151
152 if (count($NVParray) > 0) {
153 foreach ($NVParray as $nvp) {
154 switch (strtoupper($nvp[0])) {
155 case 'FIELD':
156 $this->_fields[] = $nvp[1];
157 break;
158
159 case 'COMPARATOR':
160 $this->myComparators[] = $nvp[1];
161 break;
162
163 case 'OPERATOR':
164 $this->myOperators[] = $nvp[1];
165 break;
166
167 case 'ORDER':
168 $this->order = $nvp[1];
169 break;
170
171 case 'SORT':
172 $this->ordersort = $nvp[1];
173 break;
174
175 case 'LIMIT':
176 $this->limit = $nvp[1];
177 break;
178
179 case 'START':
180 $this->startRow = $nvp[1];
181 break;
182
183 default:
184 $this->myNVP[] = $nvp;
185 break;
186 }
187 }
188 }
189 }
190
191 if (isset($urlParts[0])) {
192 $this->myKey = $urlParts[0];
193 array_shift($urlParts);
194 }
195
196 $this->method = $_SERVER['REQUEST_METHOD'];
197
198 if (count($this->myComparators) && count($this->myComparators) < (count($this->myNVP) - 1)) {
199 $this->parseHeadersOR();
200 }
201 }
202
203 /**
204 * TODO
205 */
206 function parseHeadersOR()
207 {
208 if (isset($_SERVER['REQUEST_URI']) && isset($_SERVER['REQUEST_METHOD'])) {
209 //$this->parseContent();
210
211 $urlString = urldecode($_SERVER['REQUEST_URI']);
212 $urlParts = explode('/', $urlString);
213 $lastPart = array_pop($urlParts);
214 $dotPosition = strpos($lastPart, '.');
215
216 /*
217 if ($dotPosition !== false) {
218 $this->extension = substr($lastPart, $dotPosition + 1);
219 $lastPart = substr($lastPart, 0, $dotPosition);
220 }
221 */
222 array_push($urlParts, $lastPart);
223 if (isset($urlParts[0]) && $urlParts[0] == '') {
224 array_shift($urlParts);
225 }
226 if (isset($urlParts[0]) && $urlParts[0] == 'api') {
227 array_shift($urlParts);
228 }
229 if (isset($urlParts[0])) {
230 if (preg_match("/^[0-9a-z]{8}-([0-9a-z]{4}-){3}[0-9a-z]{12}$/", $urlParts[0])) {
231 $this->_dbName = array_shift($urlParts);
232 } elseif ($urlParts[0] == 'nlssgateway') {
233 $this->_dbName = Nlss_App::getDatabaseName();
234 array_shift($urlParts);
235 }
236 }
237 if (isset($urlParts[0]) && $urlParts[0] == 'v1') {
238 array_shift($urlParts);
239 }
240 if (isset($urlParts[0])) {
241 $this->table = $urlParts[0];
242 array_shift($urlParts);
243 }
244
245 $NVParray = array();
246 if (count($urlParts) > 1 && $urlParts[1] != '') {
247 $littlearrary = array();
248 $mycount=0;
249
250 foreach ($urlParts as $uid) {
251 if ($uid != '') {
252 $littlearrary[] = $uid;
253 $mycount+=1;
254 }
255 if ($mycount == 2) {
256 $NVParray[] = $littlearrary;
257 $littlearrary = array();
258 $mycount = 0;
259 }
260 }
261 }
262
263 $i = -1;
264 $this->fields = array();
265 $this->myComparators = array();
266 $this->myOperators = array();
267 $this->myNVP = array();
268
269 if (count($NVParray) > 0) {
270 foreach ($NVParray as $nvp) {
271 switch (strtoupper($nvp[0])) {
272 case 'FIELD':
273 $this->_fields[] = $nvp[1];
274 break;
275
276 case 'COMPARATOR':
277 $this->myComparators[$i] = $nvp[1];
278 break;
279
280 case 'OPERATOR':
281 $this->myOperators[$i] = $nvp[1];
282 break;
283
284 case 'ORDER':
285 $this->order = $nvp[1];
286 break;
287
288 case 'SORT':
289 $this->ordersort = $nvp[1];
290 break;
291
292 case 'LIMIT':
293 $this->limit = $nvp[1];
294 break;
295
296 case 'START':
297 $this->startRow = $nvp[1];
298 break;
299
300 default:
301 $this->myNVP[] = $nvp;
302 $i++;
303 break;
304 }
305 }
306 }
307 }
308
309 if (isset($urlParts[0])) {
310 $this->myKey = $urlParts[0];
311 array_shift($urlParts);
312 }
313
314 $this->method = 'GETOR';
315 }
316
317 /**
318 * TODO
319 */
320 function parseContent()
321 {
322 if (!strlen($this->requestData) && isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > 0) {
323 $this->requestData = '';
324 $httpContent = fopen('php://input', 'r');
325 while ($data = fread($httpContent, 1024)) {
326 $this->requestData .= $data;
327 }
328 fclose($httpContent);
329 }
330 }
331
332 /**
333 * Connect to the database.
334 *
335 * @param string $dbName
336 * The database name.
337 * @return void
338 */
339 private function _connectToDatabase($dbName) {
340 require_once('mysql.php');
341 $this->db = new mysql($dbName);
342 $this->db->connect();
343 }
344
345 /**
346 * Execute the request.
347 *
348 * @return void
349 */
350 private function _exec() {
351 $this->_connectToDatabase($this->_dbName);
352
353 switch ($this->method) {
354 case 'GET':
355 $this->_get();
356 break;
357
358 case 'GETOR':
359 $this->_getOR();
360 break;
361
362 case 'POST':
363 $this->_post();
364 break;
365
366 case 'PUT':
367 $this->_put();
368 break;
369
370 case 'DELETE':
371 $this->_delete();
372 break;
373 }
374 }
375
376 /**
377 * Execute a GET request. A GET request fetches a list of tables when no
378 * table name is given, a list of rows when a table name is given, or a
379 * table row when a table and primary key(s) are given. It does not change
380 * the database contents.
381 *
382 * @return void
383 */
384 private function _get()
385 {
386 if ($this->table) {
387 $dnlAll = false;
388
389 if (strtolower($this->table) == 'devicenetworklookup2') {
390 $dnlAll = true;
391 $this->table = rtrim($this->table, '2');
392 }
393
394 try {
395 if (Nlss_Model::exists($this->table)) {
396 $model = Nlss_Model::factory($this->table, Nlss_Auth::getAuthenticatedEntity());
397 $model->setDatabaseName($this->_dbName);
398 $model->setTableName($this->table);
399
400 if (strlen($this->myKey)) {
401 $model->setPrimaryKeyValue($this->myKey);
402 }
403
404 $filterField = @$this->myNVP[0][0];
405 $filterValue = @$this->myNVP[0][1];
406
407 if (strlen($filterField) && strlen($filterValue)) {
408 if (in_array('LIKE', $this->myOperators)) {
409 $filterExp = "$filterField LIKE ?";
410 $filterValue = "%$filterValue%";
411 } else {
412 $filterExp = "$filterField = ?";
413 }
414
415 $result = $model->select('*', array($filterExp => $filterValue));
416 } else {
417 $result = $model->select('*');
418 }
419
420 if ($result !== false) {
421 $this->display = 'composite';
422 $this->output['composite'] = $result;
423 $this->generateResponseData();
424 return;
425 }
426 }
427 } catch (Exception $e) {
428 // TODO: Log exception.
429
430 $this->display = 'row';
431 $this->table = 'errors';
432 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error `getting` data.');
433 $this->badRequest();
434 $this->generateResponseData();
435
436 return;
437 }
438
439 $orderby = '';
440 if ($this->order != '') {
441 $orderby .=" ORDER BY ".$this->order;
442 }
443 if ($this->ordersort != '') {
444 $orderby .=" ".$this->ordersort;
445 }
446 if ($this->limit != '') {
447 if ($this->startRow == '') {
448 $this->startRow=0;
449 }
450 $orderby .= " LIMIT " . $this->startRow . ' , ' . $this->limit;
451 }
452 if (count($this->myNVP ) >= 1) {
453 $this->display = 'row';
454 $where = '';
455 $loopCount = 0;
456
457 foreach ($this->myNVP as $nvp) {
458 $myOp = ' = ';
459 $isLikeOp = false;
460 $isContainsOp = false;
461 $isOR = false;
462
463 if (@$this->myOperators[$loopCount] != "") {
464 $myOp = ' ' . $this->myOperators[$loopCount] . ' ';
465 switch ($this->myOperators[$loopCount]) {
466 case 'NOTEQUALS':
467 $myOp= ' <> ';
468 break;
469
470 case 'LT':
471 $myOp = ' < ';
472 break;
473
474 case 'LTE':
475 $myOp = ' <= ';
476 break;
477
478 case 'GT':
479 $myOp = ' > ';
480 break;
481
482 case 'GTE':
483 $myOp = ' >= ';
484 break;
485
486 case 'LIKE':
487 $myOp = ' LIKE ';
488 $isLikeOp=true;
489 break;
490
491 case 'CONTAINS':
492 $myOp = ' LIKE ';
493 $isContainsOp=true;
494 break;
495 }
496 }
497
498 if ($isLikeOp) {
499 $where .= $nvp[0] . $myOp.'\'' . $nvp[1] . '%';
500 } else {
501 if ($isContainsOp) {
502 $where .= $nvp[0] . $myOp . '\'' . '%' . $nvp[1] . '%';
503 } else {
504 $where .= $nvp[0] . $myOp . '\'' . $nvp[1];
505 }
506 }
507
508 //if ($this->myComparators[$loopCount] != "") {
509 if (isset($this->myComparators[$loopCount]) && $this->myComparators[$loopCount] != "") {
510 $where .= "' " . $this->myComparators[$loopCount] . " ";
511 } else {
512 $where .= '\' AND ';
513 }
514 $loopCount += 1;
515 }
516
517 $where = substr($where, 0, -5) . $orderby;
518
519 if ($this->_fields) {
520 $fields = implode(', ', $this->_fields);
521 } else {
522 $fields = '*';
523 }
524
525 // Swap org db with app db if querying devicenetworklookup.
526 if (strtolower($this->table) == 'devicenetworklookup') {
527 $this->db = new mysql(Nlss_App::getDatabaseName());
528 $this->db->connect();
529
530 $authEntity = Nlss_Auth::getAuthenticatedEntity();
531 $orgId = $authEntity->getOrganization()->getData('organizationID');
532 $where = "customerID = '$orgId' AND $where";
533 }
534
535 $resource = $this->db->getRow($fields, $this->table, $where);
536
537 if ($resource) {
538 if ($this->db->numRows($resource) > 0) {
539 $this->display = 'table';
540 $myrow = array();
541
542 while ($row = $this->db->row($resource)) {
543 $values = array();
544 $table = strtolower($this->table);
545
546 foreach ($row as $column => $data) {
547 if ($table == 'devicenetworklookup') {
548 if ($column == 'gatewayID') {
549 $gatewayId = $data;
550 } elseif ($column == 'deviceName') {
551 continue;
552 }
553 }
554
555 $field = array(
556 'field' => $column,
557 'value' => $data
558 );
559 $values[] = $field;
560 }
561
562 if ($table == 'devicenetworklookup') {
563 $values[] = array(
564 'field' => 'deviceName',
565 'value' => self::getDeviceName($gatewayId)
566 );
567 }
568
569 $myrecord = array('data' => $values);
570 $myrow[] = $myrecord;
571 }
572
573 // Sort devicenetworklookup
574 if (strtolower($this->table) == 'devicenetworklookup') {
575 if ($this->order == 'deviceName') {
576 $ordersort = $this->ordersort;
577 usort($myrow, function($a, $b) use ($ordersort) {
578 if ($ordersort == 'DESC') {
579 $tmp = $b;
580 $b = $a;
581 $a = $tmp;
582 }
583 $deviceNameA = end($a['data']);
584 $deviceNameB = end($b['data']);
585 return strnatcasecmp($deviceNameA['value'], $deviceNameB['value']);
586 });
587 }
588 }
589
590 $this->output['table'] = $myrow;
591 $this->generateResponseData();
592 } else {
593 $this->noRecords();
594 }
595 } else {
596 //$this->unauthorized();
597 }
598 } else {
599 $this->display = 'table';
600
601 if ($this->_fields) {
602 $fields = implode(', ', $this->_fields);
603 } else {
604 $fields = '*';
605 }
606
607 // Swap org db with app db if querying devicenetworklookup.
608 if (strtolower($this->table) == 'devicenetworklookup') {
609 $this->db = new mysql(Nlss_App::getDatabaseName());
610 $this->db->connect();
611
612 $authEntity = Nlss_Auth::getAuthenticatedEntity();
613 $orgId = $authEntity->getOrganization()->getData('organizationID');
614 $where = ($dnlAll) ? "customerID = '$orgId' $orderby" : "customerID = '$orgId' AND status = 1 $orderby";
615
616 $resource = $this->db->getRow($fields, $this->table, $where);
617 } else {
618 $resource = $this->db->getAll($fields, strtolower($this->table) . $orderby);
619 }
620
621 if ($resource) {
622 if ($this->db->numRows($resource) > 0) {
623 $myrow = array();
624 while ($row = $this->db->row($resource)) {
625 $values = array();
626 $table = strtolower($this->table);
627
628 foreach ($row as $column => $data) {
629 if ($table == 'devicenetworklookup') {
630 if ($column == 'gatewayID') {
631 $gatewayId = $data;
632 } elseif ($column == 'deviceName') {
633 continue;
634 }
635 }
636
637 $field = array(
638 'field' => $column,
639 'value' => $data
640 );
641 $values[] = $field;
642 }
643
644 if ($table == 'devicenetworklookup') {
645 $values[] = array(
646 'field' => 'deviceName',
647 'value' => self::getDeviceName($gatewayId)
648 );
649 }
650
651 $myrecord = array('data' => $values);
652 $myrow[] = $myrecord;
653 }
654
655 // Sort devicenetworklookup
656 if (strtolower($this->table) == 'devicenetworklookup') {
657 if ($this->order == 'deviceName') {
658 $ordersort = $this->ordersort;
659 usort($myrow, function($a, $b) use ($ordersort) {
660 if ($ordersort == 'DESC') {
661 $tmp = $b;
662 $b = $a;
663 $a = $tmp;
664 }
665 $deviceNameA = end($a['data']);
666 $deviceNameB = end($b['data']);
667 return strnatcasecmp($deviceNameA['value'], $deviceNameB['value']);
668 });
669 }
670 }
671
672 $this->output['table'] = $myrow;
673 $this->generateResponseData();
674 }
675 } else {
676 $this->unauthorized();
677 }
678 }
679 } else {
680 $this->display = 'database';
681 $resource = $this->db->getDatabase();
682 if ($resource) {
683 if ($this->db->numRows($resource) > 0) {
684 while ($row = $this->db->row($resource)) {
685 $this->output['database'][] = array(
686 'value' => reset($row)
687 );
688 }
689 $this->generateResponseData();
690 } else {
691 $this->notFound();
692 }
693 } else {
694 $this->unauthorized();
695 }
696 }
697 }
698
699 /**
700 * Execute a GET request. A GET request fetches a list of tables when no
701 * table name is given, a list of rows when a table name is given, or a
702 * table row when a table and primary key(s) are given. It does not change
703 * the database contents.
704 *
705 * @return void
706 */
707 private function _getOR()
708 {
709 if ($this->table) {
710 try {
711 if (Nlss_Model::exists($this->table)) {
712 $model = Nlss_Model::factory($this->table, Nlss_Auth::getAuthenticatedEntity());
713 $model->setDatabaseName($this->_dbName);
714 $model->setTableName($this->table);
715
716 if (strlen($this->myKey)) {
717 $model->setPrimaryKeyValue($this->myKey);
718 }
719
720 $filterField = @$this->myNVP[0][0];
721 $filterValue = @$this->myNVP[0][1];
722
723 if (strlen($filterField) && strlen($filterValue)) {
724 if (in_array('LIKE', $this->myOperators)) {
725 $filterExp = "$filterField LIKE ?";
726 $filterValue = "%$filterValue%";
727 } else {
728 $filterExp = "$filterField = ?";
729 }
730
731 $result = $model->select('*', array($filterExp => $filterValue));
732 } else {
733 $result = $model->select('*');
734 }
735
736 if ($result !== false) {
737 $this->display = 'composite';
738 $this->output['composite'] = $result;
739 $this->generateResponseData();
740 return;
741 }
742 }
743 } catch (Exception $e) {
744 // TODO: Log exception.
745
746 $this->display = 'row';
747 $this->table = 'errors';
748 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error `getting` data.');
749 $this->badRequest();
750 $this->generateResponseData();
751
752 return;
753 }
754
755 $orderby = '';
756 if ($this->order != '') {
757 $orderby .=" ORDER BY ".$this->order;
758 }
759 if ($this->ordersort != '') {
760 $orderby .=" ".$this->ordersort;
761 }
762 if ($this->limit != '') {
763 if ($this->startRow == '') {
764 $this->startRow=0;
765 }
766 $orderby .= " LIMIT " . $this->startRow . ' , ' . $this->limit;
767 }
768 if (count($this->myNVP ) >= 1) {
769 $this->display = 'row';
770 $where = '';
771 $loopCount = 0;
772 $parentheseOpened = false;
773
774 foreach ($this->myNVP as $nvp) {
775 $myOp = ' = ';
776 $isLikeOp = false;
777 $isContainsOp = false;
778
779 if (@$this->myOperators[$loopCount] != "") {
780 $myOp = ' ' . $this->myOperators[$loopCount] . ' ';
781 switch ($this->myOperators[$loopCount]) {
782 case 'NOTEQUALS':
783 $myOp= ' <> ';
784 break;
785
786 case 'LT':
787 $myOp = ' < ';
788 break;
789
790 case 'LTE':
791 $myOp = ' <= ';
792 break;
793
794 case 'GT':
795 $myOp = ' > ';
796 break;
797
798 case 'GTE':
799 $myOp = ' >= ';
800 break;
801
802 case 'LIKE':
803 $myOp = ' LIKE ';
804 $isLikeOp=true;
805 break;
806
807 case 'CONTAINS':
808 $myOp = ' LIKE ';
809 $isContainsOp=true;
810 break;
811 }
812 }
813
814 if ($this->myComparators[$loopCount] != "" && !$parentheseOpened) {
815 $where .= "(";
816 $parentheseOpened = true;
817 }
818
819 if ($isLikeOp) {
820 $where .= $nvp[0] . $myOp.'\'' . $nvp[1] . '%';
821 } else {
822 if ($isContainsOp) {
823 $where .= $nvp[0] . $myOp . '\'' . '%' . $nvp[1] . '%';
824 } else {
825 $where .= $nvp[0] . $myOp . '\'' . $nvp[1];
826 }
827 }
828
829 if ($this->myComparators[$loopCount] != "") {
830 $where .= "' " . $this->myComparators[$loopCount] . " ";
831 } else {
832 $where .= "' ";
833
834 if ($parentheseOpened) {
835 $where .= ")";
836 $parentheseOpened = false;
837 }
838
839 $where .= 'AND ';
840 }
841 $loopCount += 1;
842 }
843
844 $where = substr($where, 0, -5) . $orderby;
845
846 if ($this->_fields) {
847 $fields = implode(', ', $this->_fields);
848 } else {
849 $fields = '*';
850 }
851
852 // Swap org db with app db if querying devicenetworklookup.
853 if (strtolower($this->table) == 'devicenetworklookup') {
854 $this->db = new mysql(Nlss_App::getDatabaseName());
855 $this->db->connect();
856
857 $authEntity = Nlss_Auth::getAuthenticatedEntity();
858 $orgId = $authEntity->getOrganization()->getData('organizationID');
859 $where = "customerID = '$orgId' AND $where";
860 }
861
862 $resource = $this->db->getRow($fields, $this->table, $where);
863
864 if ($resource) {
865 if ($this->db->numRows($resource) > 0) {
866 $this->display = 'table';
867 $myrow = array();
868
869 while ($row = $this->db->row($resource)) {
870 $values = array();
871 $table = strtolower($this->table);
872
873 foreach ($row as $column => $data) {
874 if ($table == 'devicenetworklookup') {
875 if ($column == 'gatewayID') {
876 $gatewayId = $data;
877 } elseif ($column == 'deviceName') {
878 continue;
879 }
880 }
881
882 $field = array(
883 'field' => $column,
884 'value' => $data
885 );
886 $values[] = $field;
887 }
888
889 if ($table == 'devicenetworklookup') {
890 $values[] = array(
891 'field' => 'deviceName',
892 'value' => self::getDeviceName($gatewayId)
893 );
894 }
895
896 $myrecord = array('data' => $values);
897 $myrow[] = $myrecord;
898 }
899 $this->output['table'] = $myrow;
900 $this->generateResponseData();
901 } else {
902 $this->noRecords();
903 }
904 } else {
905 //$this->unauthorized();
906 }
907 } else {
908 $this->display = 'table';
909
910 if ($this->_fields) {
911 $fields = implode(', ', $this->_fields);
912 } else {
913 $fields = '*';
914 }
915
916 // Swap org db with app db if querying devicenetworklookup.
917 if (strtolower($this->table) == 'devicenetworklookup') {
918 $this->db = new mysql(Nlss_App::getDatabaseName());
919 $this->db->connect();
920
921 $authEntity = Nlss_Auth::getAuthenticatedEntity();
922 $orgId = $authEntity->getOrganization()->getData('organizationID');
923 $where = "customerID = '$orgId' AND status = 1 $orderby";
924
925 $resource = $this->db->getRow($fields, $this->table, $where);
926 } else {
927 $resource = $this->db->getAll($fields, strtolower($this->table) . $orderby);
928 }
929
930 if ($resource) {
931 if ($this->db->numRows($resource) > 0) {
932 $myrow = array();
933 while ($row = $this->db->row($resource)) {
934 $values = array();
935 $table = strtolower($this->table);
936
937 foreach ($row as $column => $data) {
938 if ($table == 'devicenetworklookup') {
939 if ($column == 'gatewayID') {
940 $gatewayId = $data;
941 } elseif ($column == 'deviceName') {
942 continue;
943 }
944 }
945
946 $field = array(
947 'field' => $column,
948 'value' => $data
949 );
950 $values[] = $field;
951 }
952
953 if ($table == 'devicenetworklookup') {
954 $values[] = array(
955 'field' => 'deviceName',
956 'value' => self::getDeviceName($gatewayId)
957 );
958 }
959
960 $myrecord = array('data' => $values);
961 $myrow[] = $myrecord;
962 }
963 $this->output['table'] = $myrow;
964 $this->generateResponseData();
965 }
966 } else {
967 $this->unauthorized();
968 }
969 }
970 } else {
971 $this->display = 'database';
972 $resource = $this->db->getDatabase();
973 if ($resource) {
974 if ($this->db->numRows($resource) > 0) {
975 while ($row = $this->db->row($resource)) {
976 $this->output['database'][] = array(
977 'value' => reset($row)
978 );
979 }
980 $this->generateResponseData();
981 } else {
982 $this->notFound();
983 }
984 } else {
985 $this->unauthorized();
986 }
987 }
988 }
989
990 /**
991 * Execute a POST request.
992 *
993 * @return void
994 */
995 private function _post()
996 {
997 if ($this->table == 'DeviceCommands') {
998 switch ($this->myKey) {
999 // DeviceCommands ----------------------------------------------
1000 case 'authenticate':
1001 $this->_authenticate();
1002 break;
1003
1004 case 'logout':
1005 $this->logout();
1006 break;
1007
1008 case 'checkAvailability':
1009 $this->_checkAvailability();
1010 break;
1011
1012 case 'requestApiInfo':
1013 $this->_requestApiInfo();
1014 break;
1015
1016 case 'sendEmail':
1017 $this->_sendEmail();
1018 break;
1019
1020 case 'generateTemporaryUri':
1021 $this->_generateTemporaryUri();
1022 break;
1023
1024 /*
1025 case 'parseTemporaryUri':
1026 $this->_parseTemporaryUri();
1027 break;
1028 */
1029
1030 case 'outboundEvent':
1031 $this->outboundEvent();
1032 break;
1033
1034 case 'inboundEvent':
1035 $this->inboundEvent();
1036 break;
1037
1038 case 'outboundCommand':
1039 $this->_outboundCommand();
1040 break;
1041
1042 case 'confirmRmsUser':
1043 $this->_confirmRmsUser();
1044 break;
1045
1046 case 'requestRmsServerInfo':
1047 $this->_requestRmsServerInfo();
1048 break;
1049
1050 case 'retrieveCustomersAndSites':
1051 $this->_retrieveCustomersAndSites();
1052 break;
1053
1054 case 'establishRmsTechnicalSupportTunnel':
1055 $this->_establishRmsTechnicalSupportTunnel();
1056 break;
1057
1058 case 'getUploadUri':
1059 $this->_getUploadUri();
1060 break;
1061
1062 case 'importConfigurations':
1063 $this->_importConfigurations();
1064 break;
1065
1066 // DeviceCommands:Gateway (only). ------------------------------
1067 case 'redeemRmsTokens':
1068 $this->_redeemRmsTokens();
1069 break;
1070
1071 case 'requestNetworkStatus':
1072 $this->_requestNetworkStatus();
1073 break;
1074
1075 case 'requestNetworkInfo':
1076 $this->_requestNetworkInfo();
1077 break;
1078
1079 case 'requestNewNetworkInfo':
1080 $this->_requestNetworkInfo();
1081 break;
1082
1083 case 'confirmNetworkInfo':
1084 $this->_confirmNetworkInfo();
1085 break;
1086
1087 case 'updateRtmfpDataKey':
1088 $this->_updateRtmfpDataKey();
1089 break;
1090
1091 case 'transferPullRequest':
1092 $this->_transferPullRequest();
1093 break;
1094
1095 case 'syncConfigs':
1096 $this->_syncConfigs();
1097 break;
1098
1099 case 'reportCheckupdateStarted':
1100 $this->_reportCheckupdateStarted();
1101 break;
1102
1103 case 'setCardStatus':
1104 $this->_setCardStatus();
1105 break;
1106
1107 case 'authenticationCheck':
1108 $this->_authenticationCheck();
1109 break;
1110
1111 // DeviceCommands:Customer (only). -----------------------------
1112 case 'deviceNetworkLookup':
1113 $this->_deviceNetworkLookup();
1114 break;
1115
1116 case 'writeTransferPush':
1117 $this->_writeTransferPush();
1118 break;
1119
1120 case 'requestTransferId':
1121 $this->_requestTransferId();
1122 break;
1123
1124 case 'transferPushRequest':
1125 $this->_transferPushRequest();
1126 break;
1127
1128 case 'cancel':
1129 $this->_cancel();
1130 break;
1131
1132 case 'requestImportInfo':
1133 $this->_requestImportInfo();
1134 break;
1135
1136 case 'requestExportInfo':
1137 $this->_requestExportInfo();
1138 break;
1139
1140 case 'exportConfigurations':
1141 $this->_exportConfigurations();
1142 break;
1143
1144 case 'requestRemoteCheckUpdateInfo':
1145 $this->_requestRemoteCheckUpdateInfo();
1146 break;
1147
1148 case 'requestRemoteCheckUpdate':
1149 $this->_requestRemoteCheckUpdate();
1150 break;
1151
1152 case 'requestBulkTransferInfo':
1153 $this->_requestBulkTransferInfo();
1154 break;
1155
1156 case 'requestBulkTransfer':
1157 $this->_requestBulkTransfer();
1158 break;
1159
1160 // DeviceCommands:Partner (only). ------------------------------
1161 case 'generateCode':
1162 $this->_generateCode();
1163 break;
1164
1165 // DeviceCommands:Host,Partner (only). -------------------------
1166 case 'createOrganization':
1167 $this->_createOrganization();
1168 break;
1169
1170 case 'destroyOrganization':
1171 $this->_destroyOrganization();
1172 break;
1173
1174 // DeviceCommands:Host,Partner,Customer (only). ----------------
1175 case 'paginate':
1176 $this->_paginate();
1177 break;
1178
1179 case 'serverTime':
1180 passthru($this->_gc->directory->bin . 'get_server_time.sh');
1181 break;
1182
1183 case 'serverTimeZone':
1184 passthru($this->_gc->directory->bin . 'get_server_time_zone.sh');
1185 break;
1186 }
1187 } else {
1188 $this->_postSQL();
1189 }
1190 }
1191
1192 /**
1193 * Updates database with request data.
1194 *
1195 * @return void
1196 */
1197 private function _postSQL()
1198 {
1199 if ($this->table) {
1200 try {
1201 $this->_checkConfigurationOperation();
1202
1203 if (Nlss_Model::exists($this->table)) {
1204 $xml = simplexml_load_string($this->requestData);
1205 $submittedData = $this->_removeTransferStatus($this->table, (array) $this->objectsIntoArray($xml, array(), true));
1206
1207 $model = Nlss_Model::factory($this->table, Nlss_Auth::getAuthenticatedEntity());
1208 $model->setDatabaseName($this->_dbName);
1209 $model->setTableName($this->table);
1210 $model->setPrimaryKeyValue($this->myKey);
1211 $result = $model->update($submittedData);
1212
1213 if ($result !== false) {
1214 if (!$result) {
1215 throw new Nlss_Exception("Unexpected 0 rows affected.");
1216 }
1217
1218 return;
1219 }
1220 }
1221 } catch (Exception $e) {
1222 // TODO: Log exception.
1223
1224 $this->display = 'row';
1225 $this->table = 'errors';
1226 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error `posting` data.');
1227 $this->badRequest();
1228 $this->generateResponseData();
1229
1230 return;
1231 }
1232
1233 if ($this->requestData) {
1234 $this->requestData = $this->axmlHeader . $this->requestData;
1235
1236 if ($this->validateXSD()) {
1237 $xml = simplexml_load_string($this->requestData);
1238 $pairs = $this->_removeTransferStatus($this->table, (array) $this->simplexml2array($xml));
1239
1240 $passwordEncrypted = false;
1241 if (strtolower($this->table) == 'person') {
1242 if (strlen($pairs['password'])) {
1243 if (!preg_match("/^[0-9a-f]{32}$/", $pairs['password'])) {
1244 $_resource = $this->db->getRow('*', 'person', "personID = '{$pairs['personID']}'");
1245 if ($this->db->numRows($_resource) == 1) {
1246 $_row = $this->db->row($_resource);
1247 if ($_row['password'] != $pairs['password']) {
1248 $pairs['password'] = "MD5(CONCAT('{$pairs['password']}', 'ten.sltxen'))";
1249 $passwordEncrypted = true;
1250 }
1251
1252 }
1253 }
1254
1255 // Getting authenticated user.
1256 $authenticatedUser = Nlss_Auth::getAuthenticatedEntity();
1257 $org = $authenticatedUser->getOrganization();
1258 $orgDb = $org->getDatabase();
1259
1260 // Getting role of user being updated.
1261 $userTypeId = @$pairs['userTypeID'];
1262 $personId = @$pairs['personID'];
1263 $result = $orgDb->selectFirst('*', 'usertype', array('userTypeID = ?' => $userTypeId));
1264
1265 // Preventing from assigning roles derived from Master to users.
1266 if (!$result || (@$result['baseUserType'] == '00000000-0000-0000-0000-000000000000' && @$result['userTypeID'] != '00000000-0000-0000-0000-000000000000')) {
1267 $this->badRequest();
1268 return;
1269 }
1270
1271 // Only Masters assign Master roles.
1272 if ($userTypeId == '00000000-0000-0000-0000-000000000000' && $authenticatedUser->getData('userTypeID') != '00000000-0000-0000-0000-000000000000') {
1273 $this->badRequest();
1274 return;
1275 }
1276
1277 // Cannot assign the "base roles" to user (need to clone first).
1278 $baseUserTypes = array(
1279 'master' => '00000000-0000-0000-0000-000000000000',
1280 'super' => '00000000-0000-0000-0000-000000000001',
1281 'admin' => '00000000-0000-0000-0000-000000000002',
1282 'operator' => '00000000-0000-0000-0000-000000000003'
1283 );
1284
1285 // If assigning base role
1286 if (in_array($userTypeId, $baseUserTypes)) {
1287
1288 // Only allow if master role applied to master user by master user (meaning: role has not been changed).
1289 if (!($userTypeId == $baseUserTypes['master'] && $personId == 'master00-0000-0000-0000-000000000000' && $authenticatedUser->getData('personID') == 'master00-0000-0000-0000-000000000000')) {
1290 $this->badRequest();
1291 return;
1292 }
1293 }
1294
1295 // If modifying the primary Master account.
1296 if ($personId == 'master00-0000-0000-0000-000000000000') {
1297
1298 // Only the primary Master can modify its own account.
1299 if ($personId != $authenticatedUser->getData('personID')) {
1300 $this->badRequest();
1301 return;
1302 }
1303
1304 // The primary master cannot change its role.
1305 if ($userTypeId != '00000000-0000-0000-0000-000000000000') {
1306 $this->badRequest();
1307 return;
1308 }
1309 }
1310 } elseif (!strlen($pairs['userID'])) {
1311 $model = Nlss_Model::factory('Cardholder', Nlss_Auth::getAuthenticatedEntity());
1312 $model->setPrimaryKeyValue($this->myKey);
1313 $model->saveUpload();
1314 }
1315 }
1316
1317 $_values = array();
1318 foreach ($pairs as $column => $value) {
1319 if (strtolower($this->table) == 'schedule' && $column == 'scheduleID') {
1320 $value = null;
1321 }
1322 if ($passwordEncrypted && $column == 'password') {
1323 $_values[] = "`$column` = $value";
1324 continue;
1325 }
1326 $value = addslashes($value);
1327 $_value = ($value === '' || $value === null) ? "NULL" : "'$value'";
1328 $_values[] = "`$column` = $_value";
1329 }
1330 $values = implode(', ', $_values);
1331
1332 $where = '';
1333 if (strlen($this->myKey)) {
1334 $primary = $this->getPrimaryKeys();
1335 $where .= $primary . ' = \'' . $this->myKey . '\' AND ';
1336 $where = substr($where, 0, -5);
1337 } else {
1338 foreach ($this->myNVP as $nvp)
1339 {
1340 $where .= $nvp[0] . ' = \'' . $nvp[1] . '\' AND ';
1341 }
1342 $where = substr($where, 0, -5);
1343 }
1344
1345 $resource = $this->db->updateRow($this->table, $values, $where);
1346 if ($resource) {
1347 if ($this->db->numAffected() > 0) {
1348 ; //$this->putEventXML('2', '16', '5'); // 'System.DBRowUpdated'
1349 } else {
1350 $this->badRequest();
1351 }
1352 } else {
1353 if ($this->_debug) {
1354 Nlss_Log::write('phprestsql-debug', "Error executing UPDATE {$this->table} SET $values WHERE $where" . PHP_EOL . mysql_error());
1355 }
1356
1357 $this->badRequest();
1358 }
1359 }
1360 }
1361 }
1362 }
1363
1364 /**
1365 * Execute a PUT request. A PUT request adds a new row to a table given a
1366 * table and name=value pairs in the request body.
1367 *
1368 * @return void
1369 */
1370 private function _put()
1371 {
1372 if ($this->table) {
1373 try {
1374 $this->_checkConfigurationOperation();
1375
1376 if (Nlss_Model::exists($this->table)) {
1377 $xml = simplexml_load_string($this->requestData);
1378 $submittedData = $this->_removeTransferStatus($this->table, (array) $this->objectsIntoArray($xml, array(), true));
1379
1380 $model = Nlss_Model::factory($this->table, Nlss_Auth::getAuthenticatedEntity());
1381 $model->setDatabaseName($this->_dbName);
1382 $model->setTableName($this->table);
1383
1384 $model->setPrimaryKeyValue($this->myKey);
1385 $result = $model->insert($submittedData);
1386
1387 if ($result !== false) {
1388 if (!$result) {
1389 throw new Nlss_Exception("Unexpected 0 rows affected.");
1390 }
1391
1392 return;
1393 }
1394 }
1395 } catch (Exception $e) {
1396 // TODO: Log exception.
1397 // echo $e->getMessage(); return ;
1398
1399 $this->display = 'row';
1400 $this->table = 'errors';
1401 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error `putting` data.');
1402
1403 $this->badRequest();
1404 $this->generateResponseData();
1405
1406 return;
1407 }
1408
1409 if ($this->requestData) {
1410 $this->requestData = $this->axmlHeader . $this->requestData;
1411
1412 if ($this->validateXSD()) {
1413 $myxml = simplexml_load_string($this->requestData);
1414 $pairs = $this->_removeTransferStatus($this->table, (array) $this->simplexml2array($myxml));
1415
1416 $passwordEncrypted = false;
1417 if (strtolower($this->table) == 'person') {
1418 if (strlen($pairs['password'])) {
1419 if (!preg_match("/^[0-9a-f]{32}$/", $pairs['password'])) {
1420 $pairs['password'] = "MD5(CONCAT('{$pairs['password']}', 'ten.sltxen'))";
1421 $passwordEncrypted = true;
1422 }
1423
1424 // Getting authenticated user.
1425 $authenticatedUser = Nlss_Auth::getAuthenticatedEntity();
1426 $org = $authenticatedUser->getOrganization();
1427 $orgDb = $org->getDatabase();
1428
1429 // Getting role of the user being inserted.
1430 $userTypeId = @$pairs['userTypeID'];
1431 $result = $orgDb->selectFirst('*', 'usertype', array('userTypeID = ?' => $userTypeId));
1432
1433 // Preventing creating users with roles derived from Master.
1434 if (!$result || (@$result['baseUserType'] == '00000000-0000-0000-0000-000000000000' && @$result['userTypeID'] != '00000000-0000-0000-0000-000000000000')) {
1435 $this->badRequest();
1436 return;
1437 }
1438
1439 // Only Masters can create Masters
1440 if ($userTypeId == '00000000-0000-0000-0000-000000000000' && $authenticatedUser->getData('userTypeID') != '00000000-0000-0000-0000-000000000000') {
1441 $this->badRequest();
1442 return;
1443 }
1444
1445 // Cannot assign the "base roles" to user (need to clone first).
1446 $baseUserTypes = array(
1447 '00000000-0000-0000-0000-000000000000',
1448 '00000000-0000-0000-0000-000000000001',
1449 '00000000-0000-0000-0000-000000000002',
1450 '00000000-0000-0000-0000-000000000003'
1451 );
1452
1453 if (in_array($userTypeId, $baseUserTypes)) {
1454 $this->badRequest();
1455 return;
1456 }
1457 } elseif (!strlen($pairs['userID'])) {
1458 $model = Nlss_Model::factory('Cardholder', Nlss_Auth::getAuthenticatedEntity());
1459 $model->setPrimaryKeyValue($this->myKey);
1460 $model->saveUpload();
1461 }
1462 }
1463
1464 $_values = array();
1465 foreach ($pairs as $column => $value) {
1466 if (strtolower($this->table) == 'person' && $column == 'siteID') {
1467 $value = Nlss_Common_Model_Configuration::DEFAULT_SITE_ID;
1468 }
1469 if (strtolower($this->table) == 'schedule' && $column == 'scheduleID') {
1470 $value = null;
1471 }
1472 if ($passwordEncrypted && $column == 'password') {
1473 $_values[] = $value;
1474 continue;
1475 }
1476 $value = addslashes($value);
1477 $_values[] = ($value === '' || $value === null) ? "NULL" : "'$value'";
1478 }
1479 $values = implode(', ', $_values);
1480
1481 $names = join(', ', array_keys($pairs));
1482 $resource = $this->db->insertRow($this->table, $names, $values);
1483
1484 if ($resource) {
1485 if ($this->db->numAffected() > 0) {
1486 ; //$this->putEventXML('2', '15', '5'); // 'System.DBRowInserted'
1487 } else {
1488 $this->badRequest();
1489 }
1490 } else {
1491 if ($this->_debug) {
1492 Nlss_Log::write('phprestsql-debug', "Error executing INSERT INTO {$this->table} ($names) VALUES ($values)" . PHP_EOL . mysql_error());
1493 }
1494
1495 $this->badRequest();
1496 }
1497 }
1498 }
1499 }
1500 }
1501
1502 /**
1503 * Execute a DELETE request. A DELETE request removes a row from the
1504 * database given a table and primary key(s).
1505 *
1506 * @return void
1507 */
1508 private function _delete()
1509 {
1510 if ($this->table && $this->myKey) {
1511 if (strtolower($this->table) == 'person') {
1512 $authenticatedUser = Nlss_Auth::getAuthenticatedEntity();
1513 $org = $authenticatedUser->getOrganization();
1514 $orgDb = $org->getDatabase();
1515 $userToDelete = $orgDb->selectFirst('*', 'person', array('personID = ?' => $this->myKey));
1516
1517 if ($userToDelete) {
1518
1519 // Cannot delete primary Master user.
1520 if ($this->myKey == 'master00-0000-0000-0000-000000000000') {
1521 $this->badRequest();
1522 return;
1523 }
1524
1525 // Only Master users can delete Master users.
1526 if ($authenticatedUser->getData('userTypeID') != '00000000-0000-0000-0000-000000000000' && @$userToDelete['userTypeID'] == '00000000-0000-0000-0000-000000000000') {
1527 $this->badRequest();
1528 return;
1529 }
1530 }
1531 }
1532
1533 try {
1534 $this->_checkConfigurationOperation();
1535
1536 if (Nlss_Model::exists($this->table)) {
1537 $model = Nlss_Model::factory($this->table, Nlss_Auth::getAuthenticatedEntity());
1538 $model->setDatabaseName($this->_dbName);
1539 $model->setTableName($this->table);
1540 $model->setPrimaryKeyValue($this->myKey);
1541 $result = $model->delete(array($this->getPrimaryKeys() . ' = ?' => $this->myKey));
1542
1543 if ($result !== false) {
1544 if (!$result) {
1545 throw new Nlss_Exception("Unexpected 0 rows affected.");
1546 }
1547
1548 return;
1549 }
1550 }
1551 } catch (Exception $e) {
1552 // TODO: Log exception.
1553
1554 $this->display = 'row';
1555 $this->table = 'errors';
1556 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error `deleting` data.');
1557 $this->badRequest();
1558 $this->generateResponseData();
1559
1560 return;
1561 }
1562
1563 $table = $this->table;
1564 $pkName = $this->getPrimaryKeys();
1565 $pkValue = $this->myKey;
1566 $where = "$pkName = '$pkValue'";
1567 $resource = $this->db->deleteRow($table, $where);
1568
1569 if ($resource) {
1570 if ($this->db->numAffected() > 0) {
1571 ; //$this->putEventXML('2', '17', '5');//'System.DBRowDeleted'
1572 $this->successOk();
1573 } else {
1574 $this->notFound();
1575 }
1576 } else {
1577 if ($this->_debug) {
1578 Nlss_Log::write('phprestsql-debug', "Error executing DELETE FROM $table WHERE $where" . PHP_EOL . mysql_error());
1579 }
1580
1581 $this->unauthorized();
1582 }
1583 } elseif ($this->table) {
1584 $this->methodNotAllowed('GET, HEAD, PUT');
1585 } else {
1586 $this->methodNotAllowed('GET, HEAD');
1587 }
1588 }
1589
1590 /**
1591 * Checks the availability of the specified item.
1592 * e.g. subdomain, email address, organization name, etc..
1593 *
1594 * @return void
1595 */
1596 private function _checkAvailability()
1597 {
1598 try {
1599 // Load request data.
1600 $xml = simplexml_load_string($this->requestData);
1601
1602 if (!(isset($xml->name) && isset($xml->value))) {
1603 throw new Nlss_Exception("Required fields (`name`, `value`) not supplied.");
1604 }
1605
1606 $name = trim($xml->name);
1607 $value = trim($xml->value);
1608
1609 $user = Nlss_Auth::getAuthenticatedEntity();
1610 $org = $user->getOrganization();
1611
1612 // Determine if item is available.
1613 switch ($name) {
1614 case 'organizationName':
1615 $result = $org->isOrganizationNameAvailable($value);
1616 break;
1617
1618 case 'userID':
1619 $result = $user->isUserIdAvailable($value);
1620 break;
1621
1622 case 'cardNumber':
1623 $result = ! (boolean) sizeof($user->getOrganization()->getDatabase()->selectFirst('cardNumber', 'card', array('cardNumber = ?' => $value)));
1624 break;
1625
1626 case 'employeeNumber':
1627 $result = ! (boolean) sizeof($user->getOrganization()->getDatabase()->selectFirst('employeeNumber', 'person', array('employeeNumber = ?' => $value)));
1628 break;
1629
1630 case 'accessLevelName':
1631 $result = ! (boolean) sizeof($user->getOrganization()->getDatabase()->selectFirst('accessLevelName', 'accesslevel', array('accessLevelName = ?' => $value)));
1632 break;
1633
1634 case 'cardProfileName':
1635 $result = ! (boolean) sizeof($user->getOrganization()->getDatabase()->selectFirst('cardProfileName', 'cardprofile', array('cardProfileName = ?' => $value)));
1636 break;
1637
1638 case 'badgeProfileName':
1639 $result = ! (boolean) sizeof($user->getOrganization()->getDatabase()->selectFirst('badgeProfileName', 'badgeprofile', array('badgeProfileName = ?' => $value)));
1640 break;
1641
1642 case 'userTypeName':
1643 $result = ! (boolean) sizeof($user->getOrganization()->getDatabase()->selectFirst('userTypeName', 'usertype', array('userTypeName = ?' => $value, 'AND deleted = ?' => 0)));
1644 break;
1645
1646 default:
1647 throw new Nlss_Exception("Invalid item `$name`=`$value` specified for availability check.");
1648 }
1649
1650 $this->display = 'row';
1651 $this->table = 'Availability';
1652 $this->output['row'][] = array('field' => 'result', 'value' => (int) $result);
1653 } catch (Exception $e) {
1654 // TODO: Log exception.
1655
1656 $this->display = 'row';
1657 $this->table = 'errors';
1658 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error checking the availability of the specified item.');
1659 $this->badRequest();
1660 }
1661
1662 // Generate response.
1663 $this->generateResponseData();
1664 }
1665
1666 /**
1667 * Requests the current api info.
1668 *
1669 * @return void
1670 */
1671 private function _requestApiInfo()
1672 {
1673 $this->display = 'row';
1674 $this->table = 'Api';
1675 $this->output['row'][] = array('field' => 'rmsVersion', 'value' => $this->_gc->rms->version);
1676 //$this->output['row'][] = array('field' => 'apiVersion', 'value' => $this->_gc->api->version);
1677 //$this->output['row'][] = array('field' => 'apiRelease', 'value' => $this->_gc->api->release);
1678
1679 $this->generateResponseData();
1680 }
1681
1682 /**
1683 * Sends email.
1684 *
1685 * @return void
1686 */
1687 private function _sendEmail()
1688 {
1689 try {
1690 // Load request data.
1691 $xml = simplexml_load_string($this->requestData);
1692
1693 // Send email.
1694 Nlss_Mail::send(trim(@$xml->from), trim(@$xml->to), trim(@$xml->subject), trim(@$xml->body));
1695 } catch (Exception $e) {
1696 $this->display = 'row';
1697 $this->table = 'errors';
1698 $this->output['row'][] = array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage());
1699
1700 $this->generateResponseData();
1701 }
1702 }
1703
1704 /**
1705 * Generates temporary URI.
1706 *
1707 * @return void
1708 */
1709 private function _generateTemporaryUri()
1710 {
1711 try {
1712 // Load request data.
1713 $xml = simplexml_load_string($this->requestData);
1714 $submitted = $this->objectsIntoArray($xml, array(), true);
1715
1716 // Generate URI.
1717 $this->display = 'row';
1718 $this->table = 'generated';
1719 $this->output['row'][] = array('field' => 'uri', 'value' => Nlss_Uri::generateTemporaryUri($submitted));
1720 } catch (Exception $e) {
1721 $this->display = 'row';
1722 $this->table = 'errors';
1723 $this->output['row'][] = array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage());
1724 }
1725
1726 // Generate response.
1727 $this->generateResponseData();
1728 }
1729
1730 /**
1731 * Parses temporary URI.
1732 *
1733 * @return void
1734 */
1735 /*
1736 private function _parseTemporaryUri()
1737 {
1738 try {
1739 // Load request data.
1740 $xml = simplexml_load_string($this->requestData);
1741 $submitted = $this->objectsIntoArray($xml, array(), true);
1742
1743 // Parse URI.
1744 $this->display = 'row';
1745 $this->table = 'generated';
1746 $result = Nlss_Uri::parseTemporaryUri($submitted);
1747
1748 foreach ($result as $field => $value) {
1749 $this->output['row'][] = array('field' => $field, 'value' => $value);
1750 }
1751 } catch (Exception $e) {
1752 $this->display = 'row';
1753 $this->table = 'errors';
1754 $this->output['row'][] = array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage());
1755 }
1756
1757 // Generate response.
1758 $this->generateResponseData();
1759 }
1760 */
1761
1762 /**
1763 * Redeems RMS tokens and completes enrollment for RMS services.
1764 *
1765 * @return void
1766 */
1767 private function _redeemRmsTokens()
1768 {
1769 try {
1770 // Parse tokens.
1771 $tokens = explode(',', trim(@$this->myNVP[0][1]));
1772
1773 // Load request data.
1774 $xml = simplexml_load_string($this->requestData);
1775 $submitted = $this->objectsIntoArray($xml, array(), true);
1776
1777 // Redeem RMS tokens.
1778 $this->display = 'composite';
1779 $this->table = null;
1780 $this->output['composite'] = Nlss::getApp()->redeemRmsTokens($tokens, $submitted);
1781 } catch (Exception $e) {
1782 $this->display = 'row';
1783 $this->table = 'errors';
1784 $this->output['row'][] = array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage());
1785 }
1786
1787 // Generate response.
1788 $this->generateResponseData();
1789 }
1790
1791 /**
1792 * Generates a unique integer used for customer code or site code.
1793 *
1794 * @return void
1795 */
1796 private function _generateCode()
1797 {
1798 try {
1799 // Generate code.
1800 $this->display = 'row';
1801 $this->table = 'generated';
1802 $this->output['row'][] = array('field' => 'code', 'value' => Nlss::generateCode());
1803 } catch (Exception $e) {
1804 $this->display = 'row';
1805 $this->table = 'errors';
1806 $this->output['row'][] = array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage());
1807 }
1808
1809 // Generate response.
1810 $this->generateResponseData();
1811 }
1812
1813 /**
1814 * Creates organization database and directories.
1815 *
1816 * @return void
1817 */
1818 private function _createOrganization()
1819 {
1820 try {
1821 // Load request data.
1822 {
1823 $xml = simplexml_load_string($this->requestData);
1824
1825 if (!(isset($xml->organizationID) && isset($xml->organizationName) && isset($xml->organizationTypeID))) {
1826 return;
1827 }
1828 }
1829
1830 // Create database and directories.
1831 {
1832 $org = Nlss_Organization::create(
1833 array(
1834 'organizationID' => trim($xml->organizationID),
1835 'organizationName' => trim($xml->organizationName),
1836 'organizationTypeID' => trim($xml->organizationTypeID)
1837 )
1838 );
1839
1840 if (!$org) {
1841 throw new Nlss_Exception;
1842 }
1843 }
1844
1845 // Populate organizationlookup table.
1846 {
1847 $organizationID = trim($xml->organizationID);
1848 $parentOrganizationID = (isset($xml->parentOrganizationID)) ? trim($xml->parentOrganizationID) : $this->_gc->host->organization->id;
1849 $database = Nlss_App::getDatabaseName();
1850 $table = 'organizationlookup';
1851 $names = '`organizationID`, `parentOrganizationID`';
1852 $values = "$organizationID', '$parentOrganizationID";
1853
1854 $this->_connectToDatabase($database);
1855
1856 $resource = $this->db->insertRow($table, $names, $values);
1857
1858 if (!$resource || ($resource && $this->db->numAffected() != 1)) {
1859 throw new Nlss_Exception;
1860 }
1861 }
1862
1863 // Update authenticated user object, so that new child organization is recognized.
1864 {
1865 $user = Nlss_Auth::getAuthenticatedEntity();
1866 $org = $user->getOrganization();
1867 $userData = $user->getData();
1868 $orgData = $org->getData();
1869
1870 Nlss_Auth::authenticateUser($userData['userID'], $userData['password'], $orgData['organizationName']);
1871 }
1872
1873 // Create default hosting map.
1874 {
1875 $srcFile = $this->_gc->directory->public . 'nlss/images/maps/sitemap.jpg';
1876 $newFile = $this->_gc->directory->public . 'nlss/images/maps/' . $organizationID . '.jpg';
1877
1878 if (!file_exists($srcFile) || !is_file($srcFile)) {
1879 throw new Nlss_Exception;
1880 }
1881
1882 if (!copy($srcFile, $newFile)) {
1883 throw new Nlss_Exception;
1884 }
1885 }
1886 } catch (Exception $e) {
1887 $this->display = 'row';
1888 $this->table = 'errors';
1889 $this->output['row'][] = array('field' => 'error', 'value' => 'Error creating organization database and directories.');
1890
1891 $this->generateResponseData();
1892 }
1893 }
1894
1895 /**
1896 * Drops organization database and removes directories.
1897 *
1898 * @return void
1899 */
1900 private function _destroyOrganization()
1901 {
1902 try {
1903 // Drop database and remove directories.
1904 $organizationName = trim(@$this->myNVP[0][1]);
1905
1906 if (!strlen($organizationName)) {
1907 throw new Nlss_Exception;
1908 }
1909
1910 Nlss_Organization::destroy($organizationName);
1911 } catch (Exception $e) {
1912 $this->display = 'row';
1913 $this->table = 'errors';
1914 $this->output['row'][] = array('field' => 'error', 'value' => 'Error dropping organization database and removing directories.');
1915
1916 $this->generateResponseData();
1917 }
1918 }
1919
1920 /**
1921 * Builds a record set and pagination options based on request data.
1922 *
1923 * @return void/
1924 */
1925 private function _paginate()
1926 {
1927 try {
1928 $xml = simplexml_load_string($this->requestData);
1929
1930 if (!(isset($xml->tableName) && isset($xml->primaryKeyName) && isset($xml->recordsPerPage) && isset($xml->pageRange) && isset($xml->currentPageNumber) && isset($xml->sortFieldName) && isset($xml->sortDirection) && isset($xml->submittedMethod))) {
1931 throw new Nlss_Exception("Required fields (`tableName`, `primaryKeyName`, `recordsPerPage`, `pageRange`, `currentPageNumber`, `sortFieldName`, `sortDirection`, `submittedMethod`) not supplied.");
1932 }
1933
1934 $orgId = Nlss_Auth::getAuthenticatedEntity()->getOrganization()->getData('organizationID');
1935 $data = (array) $this->objectsIntoArray($xml, array(), true);
1936 $paginator = new Nlss_Paginator($orgId);
1937 $this->display = 'composite';
1938 $this->output['composite'] = $paginator->build($data);
1939 } catch (Exception $e) {
1940 // TODO: Log exception.
1941
1942 $this->display = 'row';
1943 $this->table = 'errors';
1944 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error paginating.');
1945 $this->badRequest();
1946 }
1947
1948 $this->generateResponseData();
1949 }
1950
1951 /**
1952 * Authenticates a user by organization, user id, and password.
1953 *
1954 * @return void
1955 */
1956 private function _authenticate()
1957 {
1958 // Load request data.
1959 {
1960 $xml = simplexml_load_string($this->requestData);
1961
1962 if (!(isset($xml->userID) && isset($xml->password) && isset($xml->location))) {
1963 return;
1964 }
1965 }
1966
1967 try {
1968 // Get credentials.
1969 $userId = trim($xml->userID);
1970 $password = trim($xml->password);
1971 $orgName = trim($xml->location);
1972
1973 // Check for support user.
1974 if ($userId == $this->_gc->support->user->userid && $password == $this->_gc->support->user->password && !strlen($orgName)) {
1975 $orgName = $this->_gc->host->organization->name;
1976 }
1977
1978 // Authenticate user.
1979 $user = Nlss_Auth::authenticateUser($userId, $password, $orgName, true);
1980
1981 if ($user) {
1982 /*
1983 // Restrict access only to customer organization type.
1984 $orgData = $user->getOrganization()->getData();
1985
1986 if ($orgData['organizationTypeID'] != $this->_gc->customer->organization->typeid) {
1987 $auth = Zend_Auth::getInstance();
1988 $auth->clearIdentity();
1989 throw new Nlss_Exception("Invalid organization type specified.");
1990 }
1991 */
1992
1993 // Build response.
1994 $values = array();
1995 $this->display = 'row';
1996 $this->table = 'Person';
1997
1998 foreach ($user->getData() as $column => $data) {
1999 switch ($column) {
2000 case 'userID':
2001 $data = $userId;
2002 break;
2003
2004 case 'password':
2005 $data = $password;
2006 break;
2007
2008 case 'location':
2009 $data = $orgName;
2010 break;
2011
2012 case 'title':
2013 $data = $this->_gc->fmes->server->ip;
2014 break;
2015
2016 case 'suffix':
2017 $sessionId = Nlss::generateUuid();
2018 $data = (Nlss::allowCliRest()) ? $sessionId : '';
2019 break;
2020 }
2021
2022 $values[] = array('field' => $column, 'value' => $data);
2023 }
2024
2025 $this->output['row'] = $values;
2026
2027 $user->getOrganization()->getDatabase()->insert('rmssession', array('rmsSessionID' => Zend_Session::getId(), 'isBrowserSession' => (int) !Nlss::isMobileAppSession(), 'startTime' => time(), 'userID' => $user->getData('userID'), 'deviceSessionID' => $sessionId, 'allowCliRest' => (int) Nlss::allowCliRest()));
2028 }
2029 } catch (Exception $e) {
2030 // TODO: Log exception.
2031
2032 if ($this->_debug) {
2033 $this->display = 'row';
2034 $this->table = 'errors';
2035 $this->output['row'][] = array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage());
2036 }
2037 }
2038
2039 // Generate response.
2040 $this->generateResponseData();
2041 }
2042
2043 /**
2044 * Fetches devicenetworklookup status for the specified gateway id.
2045 *
2046 * @return void
2047 */
2048 private function _requestNetworkStatus()
2049 {
2050 // Load request data.
2051 {
2052 $xml = simplexml_load_string($this->requestData);
2053
2054 if (!isset($xml->gatewayID)) {
2055 return;
2056 }
2057 }
2058
2059 // Conncect to database.
2060 {
2061 $gatewayId = trim($xml->gatewayID);
2062 $database = Nlss_App::getDatabaseName();
2063 $table = 'devicenetworklookup';
2064 $where = "gatewayID = '$gatewayId'";
2065
2066 $this->_connectToDatabase($database);
2067 }
2068
2069 // Lookup device network info for the specified gateway id.
2070 {
2071 $resource = $this->db->getRow('*', $table, $where);
2072
2073 if ($this->db->numRows($resource) != 1) {
2074 return;
2075 }
2076
2077 $row = $this->db->row($resource);
2078 $values = array();
2079 $this->display = 'row';
2080 $this->table = $table;
2081
2082 foreach ($row as $column => $data) {
2083 $values[] = array('field' => $column, 'value' => $data);
2084 }
2085
2086 $this->output['row'] = $values;
2087
2088 $this->generateResponseData();
2089 }
2090 }
2091
2092 /**
2093 * Fetches devicenetworklookup data for the specified gateway id.
2094 * If new ports is true, then two new, available ports for web and rtmp
2095 * will be assigned. This function is only for devices like gateway.
2096 *
2097 * @param boolean $newPorts
2098 * Whether or not to get new ports.
2099 * @return void
2100 */
2101 private function _requestNetworkInfo($newPorts = true)
2102 {
2103 // Load request data.
2104 {
2105 $xml = simplexml_load_string($this->requestData);
2106
2107 if (!isset($xml->gatewayID)) {
2108 return;
2109 }
2110
2111 $gatewayId = trim($xml->gatewayID);
2112 }
2113
2114 // Unblock a site from connecting if it's previous checkupdate has started more than 3 minutes ago.
2115 {
2116 $appDb = Nlss_App::getDatabase();
2117 $tableName = 'devicenetworklookup';
2118 $where = array('gatewayID = ?' => $gatewayId);
2119 $device = $appDb->selectFirst('*', $tableName, $where);
2120 $now = time();
2121
2122 $updateInfo = $appDb->selectFirst('*', 'firmwareupdate', array('customerID = ?' => @$device['customerID'], 'AND siteID = ?' => @$device['siteID'], 'AND gatewayID = ?' => $gatewayId));
2123
2124 if ($updateInfo && ($updateInfo['startTime'] < $now - 180)) {
2125 Nlss_Device_Gateway_Update::writeFirmwareUpdate(array(
2126 'customerID' => @$device['customerID'],
2127 'siteID' => @$device['siteID'],
2128 'gatewayID' => $gatewayId,
2129 'endTime' => $now
2130 ));
2131
2132 Nlss_Network::unblockDevice($gatewayId, 'gateway');
2133 }
2134 }
2135
2136 // Prevent connections if site is blocked.
2137 if (Nlss_Network::isDeviceBlocked($gatewayId, 'gateway')) {
2138 return;
2139 }
2140
2141 // Update status to 'connecting' and verify device network info is set correctly.
2142 {
2143 $appDb->update($tableName, array('status' => Nlss_Network::NOT_CONNECTED), $where);
2144 $appDb->update($tableName, array('status' => Nlss_Network::CONNECTING), $where);
2145
2146 $device = $appDb->selectFirst('*', $tableName, $where);
2147 }
2148
2149 // Get new ports, if specified, and update device network info for the specified gateway id.
2150 if ($newPorts || (!$device['deviceWebPort'] || !$device['deviceRtmpPort'] || !$device['deviceSshPort'] || !$device['deviceDbPort'] || !$device['siteID'] || !$device['deviceModel'])) {
2151 $orgDb = Nlss_Database::factory($device['customerID']);
2152 $hosting = $orgDb->selectFirst('siteID', 'hosting', $where);
2153 $gateway = $orgDb->selectFirst('deviceModel', 'gateway', array('deviceID = ?' => $gatewayId));
2154 $ports = Nlss_Network::getSetOfAvailableSshProxyPorts();
2155
2156 $clearPorts = Nlss_Network::clearOfflinePortConflicts($ports, $gatewayId);
2157
2158 $updateData = $ports;
2159 $updateData['siteID'] = @$hosting['siteID'];
2160 $updateData['deviceModel'] = @$gateway['deviceModel'];
2161
2162 $appDb->update($tableName, $updateData, $where);
2163 }
2164
2165 // Lookup device network info for the specified gateway id.
2166 {
2167 /*
2168 $this->display = 'composite';
2169 $this->table = null;
2170 $this->output['composite'] = array('NetworkInfo' => $appDb->selectFirst('*', $tableName, $where));
2171
2172 $this->generateResponseData();
2173 */
2174
2175 $device = $appDb->selectFirst('*', $tableName, $where);
2176 $device['NetworkInfo'] = $device;
2177
2178 $networkInfo = array(
2179 'NetworkInfo' => $device
2180 );
2181
2182 echo $this->axmlHeader;
2183 echo Nlss_Xml::arrayToString($networkInfo);
2184 }
2185 }
2186
2187 /**
2188 * Confirms that web and rtmp ports have been bound for ssh proxy
2189 * by specified gateway. If confirmed, status is set to 1.
2190 * This function is only for devices like gateway.
2191 *
2192 * @return void
2193 */
2194 private function _confirmNetworkInfo()
2195 {
2196 // Load request data.
2197 {
2198 $xml = simplexml_load_string($this->requestData);
2199
2200 if (!(isset($xml->gatewayID) && isset($xml->deviceName) && isset($xml->firmwareVersion) && isset($xml->deviceIp) && isset($xml->deviceWebPort) && isset($xml->deviceRtmpPort))) {
2201 return;
2202 }
2203
2204 $gatewayId = trim($xml->gatewayID);
2205 $deviceName = trim($xml->deviceName);
2206 $firmwareVersion = trim($xml->firmwareVersion);
2207 $deviceWebPort = trim($xml->deviceWebPort);
2208 $deviceRtmpPort = trim($xml->deviceRtmpPort);
2209
2210 $appDb = Nlss::getApp()->getDatabase();
2211 $tableName = 'devicenetworklookup';
2212 $where = array('gatewayID = ?' => $gatewayId);
2213 $device = $appDb->selectFirst('*', $tableName, $where);
2214
2215 if (Nlss::checkFirmwareCompatibility($firmwareVersion, Nlss::getMinGatewayVersion())) {
2216 if (!(isset($xml->deviceSshPort) && isset($xml->deviceDbPort))) {
2217 return;
2218 }
2219
2220 $deviceSshPort = trim($xml->deviceSshPort);
2221 $deviceDbPort = trim($xml->deviceDbPort);
2222 } else {
2223 $deviceSshPort = $xml->deviceSshPort = @$device['deviceSshPort'];
2224 $deviceDbPort = $xml->deviceDbPort = @$device['deviceDbPort'];
2225 }
2226 }
2227
2228 // Lookup device network info for the specified gateway id,
2229 // and compare to submitted data.
2230 {
2231 $requiredFieldNames = array('gatewayID', 'deviceIp', 'deviceWebPort', 'deviceRtmpPort', 'deviceSshPort', 'deviceDbPort');
2232
2233 foreach ($requiredFieldNames as $requiredFieldName) {
2234 if ($requiredFieldName == 'deviceIp') {
2235 continue;
2236 }
2237
2238 if (strcasecmp(@$device[$requiredFieldName], trim($xml->$requiredFieldName)) != 0) {
2239 return;
2240 }
2241 }
2242 }
2243
2244 // Update status to 'connected', if ssh proxy ports are bound.
2245 {
2246 $status = (Nlss_Network::sshProxyPortsAreBound($deviceWebPort, $deviceRtmpPort, $deviceSshPort, $deviceDbPort, $firmwareVersion)) ? Nlss_Network::CONNECTED : Nlss_Network::NOT_CONNECTED;
2247
2248 $appDb->update($tableName, array('firmwareVersion' => $firmwareVersion, 'status' => $status), $where);
2249 $appDb->update($tableName, array('deviceName' => $deviceName), $where);
2250 }
2251 }
2252
2253 /**
2254 * Updates RTMFP data key in devicenetworklookup table.
2255 */
2256 private function _updateRtmfpDataKey()
2257 {
2258 // Load request data.
2259 {
2260 $xml = simplexml_load_string($this->requestData);
2261
2262 if (!(isset($xml->gatewayID) && isset($xml->dataKey))) {
2263 return;
2264 }
2265 }
2266
2267 // Update data key.
2268 {
2269 $gatewayId = trim($xml->gatewayID);
2270 $dataKey = trim($xml->dataKey);
2271 $result = Nlss::getApp()->getDatabase()->update('devicenetworklookup', array('dataKey' => $dataKey), array('gatewayID = ?' => $gatewayId));
2272 }
2273 }
2274
2275 /**
2276 * Processes transfer pull request from gateway to rms.
2277 */
2278 private function _transferPullRequest()
2279 {
2280 return;
2281
2282 /*
2283 try {
2284 $xml = simplexml_load_string($this->requestData);
2285
2286 if (!isset($xml->transferTypeID)) {
2287 throw new Nlss_Exception("Required field `transferTypeID` not supplied.");
2288 }
2289
2290 $transferTypeId = trim($xml->transferTypeID);
2291
2292 switch ($transferTypeId) {
2293 case Nlss_Queue_Work_Transfer::TRANSFER_TYPE_DATA:
2294 throw new Nlss_Exception("Specified transfer type id `$transferTypeId` not supported.");
2295 break;
2296
2297 case Nlss_Queue_Work_Transfer::TRANSFER_TYPE_FILE:
2298 {
2299 if (!(isset($xml->transferFileID) && isset($xml->mediaType) && isset($xml->checksums) && isset($xml->customerID) && isset($xml->siteID) && isset($xml->gatewayID) && isset($xml->prepStartTime))) {
2300 throw new Nlss_Exception("Required fields (`transferFileID`, `mediaType`, `checksums`, `customerID`, `siteID`, `gatewayID`, `prepStartTime`) not supplied.");
2301 }
2302
2303 $data = array(
2304 'transferFileId' => trim($xml->transferFileID),
2305 'mediaType' => trim($xml->mediaType),
2306 'checksums' => unserialize(trim($xml->checksums)),
2307 'customerId' => trim($xml->customerID),
2308 'siteId' => trim($xml->siteID),
2309 'gatewayId' => trim($xml->gatewayID),
2310 'prepStartTime' => trim($xml->prepStartTime)
2311 );
2312
2313 break;
2314 }
2315
2316 default:
2317 throw new Nlss_Exception("Invalid transfer type id `$transferTypeId` specified.");
2318 }
2319
2320 $enqueuer = Nlss_Queue_Enqueuer_Transfer_Pull::factory($transferTypeId, $data);
2321 $enqueuer->enqueueWork();
2322 } catch (Exception $e) {
2323 // TODO: Log exception.
2324
2325 $this->display = 'row';
2326 $this->table = 'errors';
2327 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error processing transfer pull request.');
2328 $this->badRequest();
2329 $this->generateResponseData();
2330 }
2331 */
2332 }
2333
2334 /**
2335 * Synchronizes Gateway configurations with RMS.
2336 */
2337 private function _syncConfigs()
2338 {
2339 // Tune PHP to handle long-running syncs.
2340 ini_set('max_execution_time', '0');
2341 ini_set('max_input_time', '-1');
2342 ini_set('memory_limit', '-1');
2343
2344 try {
2345 $xml = simplexml_load_string($this->requestData);
2346
2347 if (!(isset($xml->customerID) && isset($xml->siteID) && isset($xml->gatewayID) && isset($xml->data))) {
2348 throw new Nlss_Exception("Required fields (`customerID`, `siteID`, `gatewayID`, `data`) not supplied.");
2349 }
2350
2351 $orgId = trim($xml->customerID);
2352 $siteId = trim($xml->siteID);
2353 $gatewayId = trim($xml->gatewayID);
2354 $data = unserialize(trim($xml->data));
2355 $config = new Nlss_Rms_Configuration($orgId, $siteId);
2356
2357 $this->display = 'row';
2358 $this->table = 'Configurations';
2359 $this->output['row'][] = array('field' => 'data', 'value' => serialize($config->syncConfigs($data)));
2360 } catch (Exception $e) {
2361 // TODO: Log exception.
2362
2363 $this->display = 'row';
2364 $this->table = 'errors';
2365 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error synchronizing Gateway configurations with RMS.');
2366 $this->badRequest();
2367 }
2368
2369 $this->generateResponseData();
2370 }
2371
2372 /**
2373 * Reports a checkupdate for the specified Gateway.
2374 *
2375 * @return void
2376 */
2377 private function _reportCheckupdateStarted()
2378 {
2379 try {
2380 $xml = simplexml_load_string($this->requestData);
2381
2382 if (!(isset($xml->customerID) && isset($xml->siteID) && isset($xml->gatewayID) && isset($xml->oldFirmwareVersion) && isset($xml->newFirmwareVersion))) {
2383 throw new Nlss_Exception("Required fields (`customerID`, `siteID`, `gatewayID`, `oldFirmwareVersion`, `newFirmwareVersion`) not supplied.");
2384 }
2385
2386 $customerId = trim($xml->customerID);
2387 $siteId = trim($xml->siteID);
2388 $gatewayId = trim($xml->gatewayID);
2389 $oldFirmwareVersion = trim($xml->oldFirmwareVersion);
2390 $newFirmwareVersion = trim($xml->newFirmwareVersion);
2391 $db = Nlss::getApp()->getDatabase();
2392 $networkInfo = $db->selectFirst('*', 'devicenetworklookup', array('customerID = ?' => $customerId, 'AND siteID = ?' => $siteId, 'AND gatewayID = ?' => $gatewayId));
2393
2394 if (!$networkInfo) {
2395 throw new Nlss_Exception('Invalid devicenetworklookup fields specified.');
2396 }
2397
2398 Nlss_Network::blockDevice($gatewayId, 'gateway');
2399
2400 Nlss_Device_Gateway_Update::writeFirmwareUpdate(array(
2401 'customerID' => $customerId,
2402 'siteID' => $siteId,
2403 'gatewayID' => $gatewayId,
2404 'oldFirmwareVersion' => $oldFirmwareVersion,
2405 'newFirmwareVersion' => $newFirmwareVersion,
2406 'startTime' => time(),
2407 'endTime' => 0
2408 ));
2409 } catch (Exception $e) {
2410 // TODO: Log exception.
2411
2412 $this->display = 'row';
2413 $this->table = 'errors';
2414 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error reporting the checkupdate.');
2415 $this->badRequest();
2416 }
2417
2418 $this->generateResponseData();
2419 }
2420
2421 /**
2422 * Sets card status and enqueues a transfer for cardholder of the card.
2423 */
2424 private function _setCardStatus()
2425 {
2426 try {
2427 $xml = simplexml_load_string($this->requestData);
2428
2429 if (!(isset($xml->customerID) && isset($xml->siteID) && isset($xml->gatewayID) && isset($xml->personID) && isset($xml->cardID) && isset($xml->cardStatusID))) {
2430 throw new Nlss_Exception("Required fields (`customerID`, `siteID`, `gatewayID`, `personID`, `cardID`, `cardStatusID`) not supplied.");
2431 }
2432
2433 $orgId = trim($xml->customerID);
2434 $siteId = trim($xml->siteID);
2435 $gatewayId = trim($xml->gatewayID);
2436 $personId = trim($xml->personID);
2437 $cardId = trim($xml->cardID);
2438 $cardStatusId = trim($xml->cardStatusID);
2439 $config = new Nlss_Rms_Configuration($orgId);
2440
2441 Nlss_Database::factory($orgId)->update('card', array('cardStatusID' => $cardStatusId), array('cardID = ?' => $cardId, 'personID = ?' => $personId));
2442
2443 $transferId = $config->writeTransferPush(Nlss_Common_Model_Configuration::CARDHOLDERS, $personId);
2444 $enqueuer = Nlss_Queue_Enqueuer_Transfer_Push::factory($orgId, $transferId);
2445
2446 $enqueuer->enqueueWork();
2447 } catch (Exception $e) {
2448 // TODO: Log exception.
2449
2450 $this->display = 'row';
2451 $this->table = 'errors';
2452 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error setting card status.');
2453 $this->badRequest();
2454 $this->generateResponseData();
2455 }
2456 }
2457
2458 /**
2459 * Performs an authentication check for cli-rest login at a Gateway.
2460 */
2461 private function _authenticationCheck()
2462 {
2463 try {
2464 $xml = simplexml_load_string($this->requestData);
2465
2466 if (!(isset($xml->customerID) && isset($xml->userID) && isset($xml->sessionID))) {
2467 throw new Nlss_Exception("Required fields (`customerID`, `userID`, `sessionID`) not supplied.");
2468 }
2469
2470 $customerId = trim($xml->customerID);
2471 $userId = trim($xml->userID);
2472 $sessionId = trim($xml->sessionID);
2473 $result = Nlss_Database::factory($customerId)->selectFirst('allowCliRest', 'rmssession', array('userID = ?' => $userId, 'AND deviceSessionID = ?' => $sessionId));
2474 $allow = (int) (@$result['allowCliRest'] == 1);
2475 } catch (Exception $e) {
2476 // TODO: Log exception.
2477
2478 $allow = 0;
2479 }
2480
2481 $this->display = 'composite';
2482 $this->output['composite'] = array(
2483 'AuthenticationCheck' => array(
2484 'allowCliRest' => $allow
2485 )
2486 );
2487 $this->generateResponseData();
2488 }
2489
2490 /**
2491 * Fetches devicenetworklookup data for the specified gateway id.
2492 * This function is only for users of customer organizations.
2493 *
2494 * @return void
2495 */
2496 private function _deviceNetworkLookup()
2497 {
2498 // Load request data.
2499 $xml = simplexml_load_string($this->requestData);
2500
2501 if (!isset($xml->gatewayID)) {
2502 return;
2503 }
2504
2505 // Get logged in user data.
2506 $user = Nlss_Auth::getAuthenticatedEntity();
2507 $userData = ($user) ? $user->getData() : array();
2508
2509 // Conncect to database.
2510 {
2511 $gatewayId = trim($xml->gatewayID);
2512 $customerId = $userData['customerID'];
2513 $database = Nlss_App::getDatabaseName();
2514 $table = 'devicenetworklookup';
2515 $where = "gatewayID = '$gatewayId' AND customerID = '$customerId'";
2516
2517 $this->_connectToDatabase($database);
2518 }
2519
2520 // Lookup device network info for the specified gateway id.
2521 {
2522 $resource = $this->db->getRow('*', $table, $where);
2523
2524 if ($this->db->numRows($resource) != 1) {
2525 return;
2526 }
2527
2528 $row = $this->db->row($resource);
2529 $this->display = 'composite';
2530 $this->table = null;
2531 $this->output['composite'] = array('DeviceNetworkLookup' => $row);
2532
2533 $this->generateResponseData();
2534 }
2535 }
2536
2537 /**
2538 * Writes (inserts or updates) a transferpush record for the specified config.
2539 */
2540 private function _writeTransferPush()
2541 {
2542 try {
2543 $xml = simplexml_load_string($this->requestData);
2544
2545 if (!(isset($xml->configName) && isset($xml->pkName) && isset($xml->pkValue))) {
2546 throw new Nlss_Exception("Required fields (`configName`, `pkName`, `pkValue`) not supplied.");
2547 }
2548
2549 $orgId = Nlss_Auth::getAuthenticatedEntity()->getOrganization()->getData('organizationID');
2550 $configName = trim($xml->configName);
2551 $pkName = trim($xml->pkName);
2552 $pkValue = trim($xml->pkValue);
2553 $config = new Nlss_Rms_Configuration($orgId);
2554
2555 $this->display = 'row';
2556 $this->table = 'TransferPush';
2557 $this->output['row'][] = array('field' => 'transferID', 'value' => $config->writeTransferPush($configName, $pkValue));
2558 } catch (Exception $e) {
2559 // TODO: Log exception.
2560
2561 $this->display = 'row';
2562 $this->table = 'errors';
2563 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error writing transfer push record.');
2564 $this->badRequest();
2565 }
2566
2567 $this->generateResponseData();
2568 }
2569
2570 /**
2571 * Retrieves the transfer id of the specified config transferpush record.
2572 */
2573 private function _requestTransferId()
2574 {
2575 try {
2576 $xml = simplexml_load_string($this->requestData);
2577
2578 if (!(isset($xml->configName) && isset($xml->pkName) && isset($xml->pkValue))) {
2579 throw new Nlss_Exception("Required fields (`configName`, `pkName`, `pkValue`) not supplied.");
2580 }
2581
2582 $orgId = Nlss_Auth::getAuthenticatedEntity()->getOrganization()->getData('organizationID');
2583 $configName = trim($xml->configName);
2584 $pkName = trim($xml->pkName);
2585 $pkValue = trim($xml->pkValue);
2586 $config = new Nlss_Rms_Configuration($orgId);
2587
2588 $this->display = 'row';
2589 $this->table = 'TransferPush';
2590 $this->output['row'][] = array('field' => 'transferID', 'value' => $config->getTransferId($configName, $pkValue));
2591 } catch (Exception $e) {
2592 // TODO: Log exception.
2593
2594 $this->display = 'row';
2595 $this->table = 'errors';
2596 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error processing request for transfer id.');
2597 $this->badRequest();
2598 }
2599
2600 $this->generateResponseData();
2601 }
2602
2603 /**
2604 * Processes transfer push request from rms to gateway.
2605 *
2606 * @return void
2607 */
2608 private function _transferPushRequest()
2609 {
2610 try {
2611 $xml = simplexml_load_string($this->requestData);
2612
2613 if (!(isset($xml->transferID) && isset($xml->customerID) && isset($xml->transferRequestTypeID))) {
2614 throw new Nlss_Exception("Required fields (`transferID`, `customerID`, `transferRequestTypeID`) not supplied.");
2615 }
2616
2617 $transferId = trim($xml->transferID);
2618 $customerId = trim($xml->customerID);
2619 $transferRequestTypeId = trim($xml->transferRequestTypeID);
2620 $entity = Nlss_Auth::getAuthenticatedEntity();
2621
2622 if ($customerId != $entity->getOrganization()->getData('organizationID')) {
2623 throw new Nlss_Exception("Unauthorized transfer request for specified customer id `$customerId`.");
2624 }
2625
2626 $enqueuer = Nlss_Queue_Enqueuer_Transfer_Push::factory($customerId, $transferId);
2627
2628 switch ($transferRequestTypeId) {
2629 case Nlss_Queue_Enqueuer::STOP_QUEUED_WORK:
2630 $result = $enqueuer->stopQueuedWork();
2631 break;
2632
2633 case Nlss_Queue_Enqueuer::ENQUEUE_WORK:
2634 $result = $enqueuer->enqueueWork();
2635 break;
2636
2637 default:
2638 throw new Nlss_Exception("Invalid transfer request type id `$transferRequestTypeId` specified.");
2639 }
2640
2641 $status = $result['Status'];
2642 $message = $result['Message'];
2643 $exception = '';
2644 } catch (Exception $e) {
2645 // TODO: Log exception.
2646
2647 $status = '0';
2648 $message = 'There was an error processing transfer push request.';
2649 $exception = ($this->_debug) ? 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage() : '';
2650
2651 $this->badRequest();
2652 }
2653
2654 $this->display = 'composite';
2655 $this->output['composite'] = array(
2656 'Result' => array(
2657 'Status' => $status,
2658 'Message' => $message,
2659 'Exception' => $exception
2660 )
2661 );
2662 $this->generateResponseData();
2663 }
2664
2665 /**
2666 * Removes possibly uploaded files when the user cancels a cardholder or badge profile creation.
2667 *
2668 * @return void
2669 */
2670 private function _cancel()
2671 {
2672 try {
2673 $xml = simplexml_load_string($this->requestData);
2674
2675 if (!(isset($xml->primaryKeyName) && isset($xml->primaryKeyValue) && isset($xml->configurationName))) {
2676 throw new Nlss_Exception("Required fields (`primaryKeyName`, `primaryKeyValue`, `configurationName`) not supplied.");
2677 }
2678
2679 $pkName = trim($xml->primaryKeyName);
2680 $pkValue = trim($xml->primaryKeyValue);
2681 $configName = trim($xml->configurationName);
2682 $user = Nlss_Auth::getAuthenticatedEntity();
2683
2684 switch ($configName) {
2685 case Nlss_Common_Model_Configuration::CARDHOLDERS:
2686 $model = Nlss_Model::factory('Cardholder', $user);
2687 break;
2688
2689 case Nlss_Common_Model_Configuration::BADGE_PROFILES:
2690 $model = Nlss_Model::factory('BadgeProfile', $user);
2691 break;
2692
2693 default:
2694 throw new Nlss_Exception("Invalid configuration `$configName` specified.");
2695 }
2696
2697 $model->setPrimaryKeyValue($pkValue);
2698 $model->setPrimaryKeyName($pkName);
2699 $model->cancelUpload();
2700 } catch (Exception $e) {
2701 // TODO: Log exception.
2702
2703 $this->display = 'row';
2704 $this->table = 'errors';
2705 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error cancelling.');
2706 $this->badRequest();
2707 }
2708
2709 $this->generateResponseData();
2710 }
2711
2712 /**
2713 * Retrieves import information.
2714 *
2715 * @return void
2716 */
2717 private function _requestImportInfo()
2718 {
2719 try {
2720 $xml = simplexml_load_string($this->requestData);
2721
2722 if (!(isset($xml->configurationName) && isset($xml->customerID))) {
2723 throw new Nlss_Exception("Required fields (`configurationName`, `customerID`) not supplied.");
2724 }
2725
2726 $customerId = trim($xml->customerID);
2727 $configName = trim($xml->configurationName);
2728 $adapter = new Nlss_Rms_Configuration($customerId);
2729 $config = Nlss_Common_Model_Configuration::factory($configName, $adapter);
2730 $this->display = 'composite';
2731
2732 $this->output['composite'] = array('ImportInfo' => $config->getImportInfo());
2733 } catch (Exception $e) {
2734 // TODO: Log exception.
2735
2736 $this->display = 'row';
2737 $this->table = 'errors';
2738 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => "There was an error processing request for import info.");
2739 $this->badRequest();
2740 }
2741
2742 $this->generateResponseData();
2743 }
2744
2745 /**
2746 * Retrieves export information.
2747 *
2748 * @return void
2749 */
2750 private function _requestExportInfo()
2751 {
2752 try {
2753 $xml = simplexml_load_string($this->requestData);
2754
2755 if (!(isset($xml->configurationName) && isset($xml->customerID))) {
2756 throw new Nlss_Exception("Required fields (`configurationName`, `customerID`) not supplied.");
2757 }
2758
2759 $customerId = trim($xml->customerID);
2760 $configName = trim($xml->configurationName);
2761 $adapter = new Nlss_Rms_Configuration($customerId);
2762 $config = Nlss_Common_Model_Configuration::factory($configName, $adapter);
2763 $this->display = 'composite';
2764
2765 $this->output['composite'] = array('ExportInfo' => $config->getExportInfo());
2766 } catch (Exception $e) {
2767 // TODO: Log exception.
2768
2769 $this->display = 'row';
2770 $this->table = 'errors';
2771 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => "There was an error processing request for export info.");
2772 $this->badRequest();
2773 }
2774
2775 $this->generateResponseData();
2776 }
2777
2778 /**
2779 * Imports configuration from csv file into the system.
2780 *
2781 * @return void
2782 */
2783 private function _importConfigurations()
2784 {
2785 try {
2786 $xml = simplexml_load_string($this->requestData);
2787
2788 if (!(isset($xml->configurationName) && isset($xml->customerID))) {
2789 throw new Nlss_Exception("Required fields (`configurationName`, `customerID`) not supplied.");
2790 }
2791
2792 $configName = trim($xml->configurationName);
2793 $customerId = trim($xml->customerID);
2794 $time = time();
2795 $adapter = new Nlss_Rms_Configuration($customerId);
2796 $config = Nlss_Common_Model_Configuration::factory($configName, $adapter);
2797
2798 // Write import/export.
2799 $importExportId = $config->writeImportExport(Nlss_Common_Model_Configuration::OP_IMPORT, array(
2800 'startTime' => $time,
2801 'endTime' => 0,
2802 'successes' => 0,
2803 'errors' => 0
2804 ));
2805
2806 // Reset the import log.
2807 $config->resetImportLog();
2808
2809 // Upload csv file.
2810 {
2811 $file = $this->_gc->directory->tmp . 'import_' . $importExportId . '.csv';
2812
2813 $validators = array(
2814 'Count' => array(
2815 'min' => 1,
2816 'max' => 1,
2817 'breakChainOnFailure' => true
2818 )
2819 );
2820 $filters = array(
2821 'Rename' => array(
2822 'target' => $file,
2823 'overwrite' => true
2824 )
2825 );
2826
2827 $result = Nlss_File::receiveUpload($validators, $filters);
2828
2829 if (!$result || $result['Status'] == 0) {
2830 $message = (strlen(@$result['Message'])) ? $result['Message'] : "Error uploading file to `$file`.";
2831
2832 throw new Nlss_Exception($message);
2833 }
2834
2835 if (!file_exists($file)) {
2836 throw new Nlss_Exception("File not uploaded.");
2837 }
2838 }
2839
2840 $enqueuer = Nlss_Queue_Enqueuer_Import::factory(Nlss_Queue_Work::WORK_TYPE_IMPORT_CONFIGURATION, $importExportId, Nlss_Queue_Work_Import::OP_TYPE_SAVE, array(), Nlss_Queue::QUEUE_TYPE_ON_DEMAND, Nlss_Queue_Work::STATUS_IDLE, 1, $customerId, null, null);
2841 $enqueuer->enqueueWork();
2842 } catch (Exception $e) {
2843 // TODO: Log exception.
2844
2845 if ($config) {
2846 $config->writeImportLog('Error uploading configurations file.');
2847 $config->incrementErrorCount();
2848 $config->writeImportExport(Nlss_Common_Model_Configuration::OP_IMPORT, array('endTime' => $time, 'successes' => $config->getSuccessCount(), 'errors' => $config->getErrorCount()));
2849 }
2850
2851 $this->display = 'row';
2852 $this->table = 'errors';
2853 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error importing configurations.');
2854 $this->badRequest();
2855 }
2856
2857 $this->generateResponseData();
2858 }
2859
2860 /**
2861 * Exports configurations from the system to csv file.
2862 *
2863 * @return void
2864 */
2865 private function _exportConfigurations()
2866 {
2867 try {
2868 $xml = simplexml_load_string($this->requestData);
2869
2870 if (!(isset($xml->configurationName) && isset($xml->customerID))) {
2871 throw new Nlss_Exception("Required fields (`configurationName`, `customerID`) not supplied.");
2872 }
2873
2874 $configName = trim($xml->configurationName);
2875 $customerId = trim($xml->customerID);
2876 $time = time();
2877 $adapter = new Nlss_Rms_Configuration($customerId);
2878 $config = Nlss_Common_Model_Configuration::factory($configName, $adapter);
2879
2880 // Write import/export.
2881 $importExportId = $config->writeImportExport(Nlss_Common_Model_Configuration::OP_EXPORT, array(
2882 'startTime' => $time,
2883 'endTime' => 0,
2884 'successes' => 0,
2885 'errors' => 0
2886 ));
2887
2888 // Reset the import log.
2889 $config->resetExportLog();
2890
2891 // Generate export file.
2892 {
2893 $orgName = $config->getOrgName();
2894 $clientExportFile = 'export_' . $importExportId . '.csv';
2895 $serverExportFile = '_' . $clientExportFile;
2896 $fileUri = Nlss::getHttpProtocol() . '://' . rtrim($_SERVER['HTTP_HOST'], '/') . '/export/' . $orgName . '/' . $clientExportFile;
2897
2898 $apacheUser = $this->_gc->apache->user;
2899 $apacheGroup = $this->_gc->apache->group;
2900 $mode = 0755;
2901 $publicExportDir = $this->_gc->directory->public . 'export/' . $orgName . '/';
2902 $filePath = $publicExportDir . $serverExportFile;
2903
2904 if (!is_dir($publicExportDir)) {
2905 if (!mkdir($publicExportDir, $mode, true)) {
2906 throw new Nlss_Exception("Error creating public export directory `$publicExportDir`.");
2907 }
2908 if (`chown -R $apacheUser $publicExportDir`) {
2909 throw new Nlss_Exception("Error changing owner of organization directories under and including `$publicExportDir` to `$apacheUser`.");
2910 }
2911 if (`chgrp -R $apacheGroup $publicExportDir`) {
2912 throw new Nlss_Exception("Error changing group of organization directories under and including `$publicExportDir` to `$apacheGroup`.");
2913 }
2914 }
2915
2916 $env = getenv('APPLICATION_ENV');
2917 $command = "export APPLICATION_ENV=$env; " . $this->_gc->directory->bin . "export_configurations.php $customerId $configName $filePath > /dev/null 2>&1 &";
2918
2919 exec($command);
2920 }
2921
2922 $this->display = 'composite';
2923 $this->output['composite'] = array(
2924 'ExportConfigurations' => array(
2925 'Uri' => $fileUri
2926 )
2927 );
2928 } catch (Exception $e) {
2929 // TODO: Log exception.
2930
2931 if ($config) {
2932 $config->writeExportLog('Error exporting configuration records.');
2933 $config->incrementErrorCount();
2934 $config->writeImportExport(Nlss_Common_Model_Configuration::OP_EXPORT, array('endTime' => $time, 'successes' => $config->getSuccessCount(), 'errors' => $config->getErrorCount()));
2935 }
2936
2937 $this->display = 'row';
2938 $this->table = 'errors';
2939 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error exporting configurations.');
2940 $this->badRequest();
2941 }
2942
2943 $this->generateResponseData();
2944 }
2945
2946 /**
2947 * Retreives checkupdate information for a given site and customer.
2948 *
2949 * @return void
2950 */
2951 private function _requestRemoteCheckUpdateInfo()
2952 {
2953 try {
2954 $xml = simplexml_load_string($this->requestData);
2955
2956 if (!isset($xml->siteID)) {
2957 throw new Nlss_Exception("Required field `siteID` not supplied.");
2958 }
2959
2960 $siteId = trim($xml->siteID);
2961 $this->display = 'composite';
2962
2963 if (strlen($siteId)) {
2964 $this->output['composite'] = array('CheckUpdateInfo' => Nlss_Device_Gateway_Update::getRemoteCheckUpdateInfo($siteId));
2965 } else {
2966 $this->output['composite'] = array(
2967 'CheckUpdateInfo' => array(
2968 'deviceName' => null,
2969 'deviceModel' => null,
2970 'firmwareVersion' => null,
2971 'availableFirmwareVersion' => null,
2972 'allowCheckupdate' => null,
2973 'updateInProgress' => null,
2974 'status' => null
2975 )
2976 );
2977 }
2978 } catch (Exception $e) {
2979 // TODO: Log exception.
2980
2981 $this->display = 'row';
2982 $this->table = 'errors';
2983 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error processing request for remote check update info.');
2984 $this->badRequest();
2985 }
2986
2987 $this->generateResponseData();
2988 }
2989
2990 /**
2991 * Requests a remote checkupdate on a site.
2992 *
2993 * @return void
2994 */
2995 private function _requestRemoteCheckUpdate()
2996 {
2997 try {
2998 $xml = simplexml_load_string($this->requestData);
2999
3000 if (!isset($xml->siteID)) {
3001 throw new Nlss_Exception("Required field `siteID` not supplied.");
3002 }
3003
3004 $siteId = trim($xml->siteID);
3005 Nlss_Device_Gateway_Update::requestRemoteCheckUpdate($siteId);
3006 } catch (Exception $e) {
3007 // TODO: Log exception.
3008
3009 $this->display = 'row';
3010 $this->table = 'errors';
3011 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error processing request for remote checkupdate.');
3012 $this->badRequest();
3013 }
3014
3015 $this->generateResponseData();
3016 }
3017
3018 /**
3019 * Retreives bulk transfer information for a given site and customer.
3020 *
3021 * @return void
3022 */
3023 private function _requestBulkTransferInfo()
3024 {
3025 try {
3026 $xml = simplexml_load_string($this->requestData);
3027
3028 if (!(isset($xml->siteID) && isset($xml->customerID))) {
3029 throw new Nlss_Exception("Required fields (`siteID`, `customerID`) not supplied.");
3030 }
3031
3032 $siteId = trim($xml->siteID);
3033 $customerId = trim($xml->customerID);
3034 $configuration = new Nlss_Rms_Configuration($customerId, $siteId);
3035 $this->display = 'composite';
3036 $this->output['composite'] = array('BulkTransferInfo' => $configuration->getBulkTransferInfo());
3037 } catch (Exception $e) {
3038 // TODO: Log exception.
3039
3040 $this->display = 'row';
3041 $this->table = 'errors';
3042 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error processing request for bulk transfer info.');
3043 $this->badRequest();
3044 }
3045
3046 $this->generateResponseData();
3047 }
3048
3049 /**
3050 * Requests a bulk transfer to a site.
3051 *
3052 * @void
3053 */
3054 private function _requestBulkTransfer()
3055 {
3056 try {
3057 $xml = simplexml_load_string($this->requestData);
3058
3059 if (!(isset($xml->siteID) && isset($xml->customerID) && isset($xml->configurationName))) {
3060 throw new Nlss_Exception("Required fields (`siteID`, `customerID`, `configurationName`) not supplied.");
3061 }
3062
3063 $siteId = trim($xml->siteID);
3064 $customerId = trim($xml->customerID);
3065 $bulkTransferList = explode(',', trim($xml->configurationName));
3066 $configuration = new Nlss_Rms_Configuration($customerId, $siteId);
3067
3068 $configuration->bulkTransfer($bulkTransferList);
3069 } catch (Exception $e) {
3070 // TODO: Log exception.
3071
3072 $this->display = 'row';
3073 $this->table = 'errors';
3074 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error processing request for bulk transfer.');
3075 $this->badRequest();
3076 }
3077
3078 $this->generateResponseData();
3079 }
3080
3081 /**
3082 * Removes transfer status from payload data.
3083 *
3084 * @param string $table
3085 * Table name.
3086 * @param array $data
3087 * Payload data.
3088 * @return array
3089 * Payload data with transfer status removed.
3090 */
3091 private function _removeTransferStatus($table, array $data)
3092 {
3093 if (strlen(Nlss_Common_Model_Configuration::getConfigNameByPrimaryTable(strtolower($table)))) {
3094 unset($data['status']);
3095 }
3096
3097 return $data;
3098 }
3099
3100 /**
3101 * Get the primary keys for the request table.
3102 * @return str[] The primary key field names
3103 */
3104 function getPrimaryKeys() {
3105 return $this->db->getPrimaryKeys($this->table);
3106
3107 #$resource = $this->db->getColumns($this->table);
3108 #$primary = NULL;
3109 #if ($resource) {
3110 # while ($row = $this->db->row($resource)) {
3111 # if ($row['Key'] == 'PRI') {
3112 # $primary[] = $row['Field'];
3113 # }
3114 # }
3115 #}
3116 #return $primary;
3117 }
3118
3119 /**
3120 * TODO
3121 */
3122 function logout()
3123 {
3124 $auth = Zend_Auth::getInstance();
3125 $auth->clearIdentity();
3126
3127 header("Content-type:text/xml");
3128 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
3129 header("Cache-Control: no-cache");
3130 header("Pragma: no-cache");
3131 }
3132
3133 /**
3134 * TODO
3135 */
3136 function inboundEvent()
3137 {
3138 try{
3139 $fp = @fsockopen($this->eventServer, $this->eventPort, $errno, $errstr);
3140 if (!$fp) {
3141
3142 } else {
3143 echo fread($fp, 65536);
3144 fclose($fp);
3145 }
3146 }catch (Exception $e){
3147 }
3148 }
3149
3150 /**
3151 * TODO
3152 */
3153 function runReport()
3154 {
3155 $myUUID='php /var/www/api/nlssgateway/v1/phpreports/runReport.php > /var/www/nlss/reports/'.$this->myNVP[0][1].'.html';
3156 $aUUID="report.xml";
3157 //echo $myUUID;
3158 $filename = "/var/www/api/nlssgateway/v1/phpreports/" . $aUUID;
3159 $myheader=$this->requestData;
3160 if (!@file_put_contents($filename, $myheader)) {
3161 /* echo $filename . $this->requestData; */
3162 //$this->internalServerError();
3163 }
3164 exec($myUUID);
3165 }
3166
3167 /**
3168 * TODO
3169 */
3170 function outboundEvent()
3171 {
3172 try{
3173 $fp = @fsockopen($this->eventServer, $this->eventPort, $errno, $errstr);
3174 if (!is_resource($fp)) {
3175 // echo "ERROR: $errno - $errstr<br />\n";
3176 } else {
3177 if ($this->requestData)
3178 {
3179 // if ($this->validateXSD())
3180 // {
3181 $myInData = $this->axmlHeader;
3182 $myInData .= $this->requestData;
3183 fwrite($fp, $myInData);
3184 //////////////
3185 //$this->requestData = $myInData;
3186 //$myxml = simplexml_load_string($this->requestData);
3187 //$pairs = $this->simplexml2array($myxml);
3188 //$values = join('", "', $pairs);
3189 //$names = join('`, `', array_keys($pairs));
3190 //$resource = $this->db->insertRow("nlssevent", $names, $values);
3191 // }
3192 }
3193 fclose($fp);
3194 }
3195 }catch (Exception $e){
3196 }
3197 }
3198
3199 /**
3200 * TODO
3201 */
3202 private function _outboundCommand()
3203 {
3204 try {
3205 $fp = @fsockopen($this->commandServer, $this->commandPort, $errno, $errstr);
3206 if (!$fp) {
3207 ;
3208 } else {
3209 if ($this->requestData) {
3210 if ($this->validateXSD("NLSSCommands.xsd")) {
3211 $data = $this->axmlHeader;
3212 $data .= $this->requestData;
3213 fwrite($fp, $data);
3214 }
3215 }
3216
3217 fclose($fp);
3218 }
3219 } catch (Exception $e) {
3220 ;
3221 }
3222 }
3223
3224 /**
3225 * Confirms RMS 'Master' user credentials.
3226 */
3227 private function _confirmRmsUser()
3228 {
3229 try {
3230 $xml = simplexml_load_string($this->requestData);
3231
3232 if (!(isset($xml->organizationID) && isset($xml->gatewayID) && isset($xml->password))) {
3233 throw new Nlss_Exception("Required fields (`organizationID`, `gatewayID`, `password`) not supplied.");
3234 }
3235
3236 $organizationId = trim($xml->organizationID);
3237 $gatewayId = trim($xml->gatewayID);
3238 $password = trim($xml->password);
3239 $result = Nlss_User::verifyRmsUser($organizationId, $gatewayId, $password);
3240
3241 $this->display = 'composite';
3242 $this->output['composite'] = ($result) ? array('Person' => $result) : $result;
3243 } catch (Exception $e) {
3244 // TODO: Log exception.
3245
3246 $this->display = 'row';
3247 $this->table = 'errors';
3248 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => 'There was an error processing RMS user confirmation.');
3249 $this->badRequest();
3250 }
3251
3252 $this->generateResponseData();
3253 }
3254
3255 /**
3256 * Fetches RMS server info for specified region code.
3257 */
3258 private function _requestRmsServerInfo()
3259 {
3260 try {
3261 $xml = simplexml_load_string($this->requestData);
3262
3263 if (!isset($xml->rmsServerID)) {
3264 throw new Nlss_Exception("Required field `rmsServerID` not supplied.");
3265 }
3266
3267 $rmsServerId = trim($xml->rmsServerID);
3268
3269 // Primary NLSS RMS server knows all public RMS servers.
3270 if ($this->_gc->rms->server->code == '000') {
3271 $result = Nlss::getApp()->getDatabase()->selectFirst('*', 'rmsserver', array('rmsServerID = ?' => $rmsServerId));
3272 }
3273
3274 // Get RMS server info for this server.
3275 elseif ($this->_gc->rms->server->code == $rmsServerId) {
3276 $result = array(
3277 'rmsServerID' => $this->_gc->rms->server->code,
3278 'rmsServerName' => $this->_gc->rms->server->name,
3279 'rmsServerIp' => $this->_gc->rms->server->ip,
3280 'fmesServerName' => $this->_gc->fmes->server->name,
3281 'fmesServerIp' => $this->_gc->fmes->server->ip,
3282 'updateServerName' => $this->_gc->update->server->name,
3283 'updateServerIp' => $this->_gc->update->server->ip,
3284 'httpProtocol' => $this->_gc->protocol->rms->http,
3285 'region' => $this->_gc->rms->server->region,
3286 'rmsApiCmndVersion' => $this->_gc->api->version
3287 );
3288 }
3289
3290 if (!@$result) {
3291 throw new Nlss_Exception("Invalid RMS server id `$rmsServerId` specified.");
3292 }
3293
3294 $this->display = 'composite';
3295 $this->output['composite'] = array('RmsServer' => $result);
3296 } catch (Exception $e) {
3297 // TODO: Log exception.
3298
3299 $this->display = 'row';
3300 $this->table = 'errors';
3301 $this->output['row'][] = ($this->_debug) ? array('field' => 'error', 'value' => 'file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage()) : array('field' => 'error', 'value' => "Invalid RMS server id `$rmsServerId` specified.");
3302 $this->badRequest();
3303 }
3304
3305 $this->generateResponseData();
3306 }
3307
3308 /**
3309 * Retrieves customers and corresponding sites for RMS technical support tunnel.
3310 */
3311 private function _retrieveCustomersAndSites()
3312 {
3313 try {
3314
3315 // Get database object.
3316 $appDb = Nlss::getApp()->getDatabase();
3317
3318 // Get all customers and corresponding sites.
3319 {
3320 $return = '';
3321
3322 // Get devicenetworklookup data.
3323 {
3324 $deviceNetworkLookups = array();
3325 foreach ($appDb->select('gatewayID, status', 'devicenetworklookup') as $deviceNetworkLookup) {
3326 $deviceNetworkLookups[$deviceNetworkLookup['gatewayID']] = $deviceNetworkLookup;
3327 }
3328 }
3329
3330 // Get site data for each customer.
3331 foreach ($appDb->select('organizationID, organizationName', 'organization', array('organizationTypeID = ?' => $this->_gc->customer->organization->typeid, 'AND apiRelease = ? ORDER BY organizationName' => $this->_gc->api->release)) as $organization) {
3332 $orgDb = Nlss_Database::factory($organization['organizationID']);
3333
3334 // Get hosting data.
3335 {
3336 $hostings = array();
3337 foreach ($orgDb->select('siteID, gatewayID', 'hosting') as $hosting) {
3338 $hostings[$hosting['siteID']] = $hosting;
3339 }
3340 }
3341
3342 // Get site data.
3343 // TODO: Raffy: Modify Nlss_Xml to handle proper nesting of integer keys from arrays.
3344 {
3345 $sites = '';
3346 foreach ($orgDb->select('siteID, siteName', 'site', array('rms = ? ORDER BY siteName' => 1)) as $site) {
3347 $siteId = $site['siteID'];
3348
3349 if (array_key_exists($siteId, $hostings)) {
3350 $siteName = $site['siteName'];
3351 $gatewayId = $hostings[$siteId]['gatewayID'];
3352 $status = $deviceNetworkLookups[$gatewayId]['status'];
3353 $sites .= Nlss_Xml::arrayToString(
3354 array(
3355 'site' => array(
3356 'siteID' => $siteId,
3357 'siteName' => $siteName,
3358 'gatewayID' => $gatewayId,
3359 'status' => $status
3360 )
3361 ),
3362 2
3363 );
3364 }
3365 }
3366 }
3367
3368 $return .= Nlss_Xml::arrayToString(
3369 array(
3370 'organization' => array(
3371 'organizationID' => $organization['organizationID'],
3372 'organizationName' => $organization['organizationName'],
3373 'sites' => "\n" . $sites . ' '
3374 )
3375 )
3376 );
3377 }
3378
3379 echo trim($this->axmlHeader . '<organizations>' . "\n" . $return . '</organizations>');
3380
3381 return;
3382 }
3383 } catch (Exception $e) {
3384 // TODO: Log exception.
3385
3386 $this->display = 'row';
3387 $this->table = 'response';
3388 $this->output['row'][] = ($this->_debug) ? array('field' => 'result', 'value' => 'failure (file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage() . ')') : array('field' => 'result', 'value' => 'failure');
3389 $this->badRequest();
3390 }
3391
3392 $this->generateResponseData();
3393 }
3394
3395 /**
3396 * Establishes RMS technical support tunnel.
3397 */
3398 private function _establishRmsTechnicalSupportTunnel()
3399 {
3400 try {
3401
3402 // Set connection params.
3403 {
3404 $xml = simplexml_load_string($this->requestData);
3405
3406 if (!(isset($xml->gatewayID) && isset($xml->port))) {
3407 throw new Nlss_Exception("Required fields (`gatewayID`, `port`) not supplied.");
3408 }
3409
3410 $gatewayId = trim($xml->gatewayID);
3411 $port = trim($xml->port);
3412 $host = $this->_gc->support->server->name;
3413 }
3414
3415 // Get database object.
3416 $appDb = Nlss::getApp()->getDatabase();
3417
3418 // Get devicenetworklookup data.
3419 {
3420 $deviceNetworkLookup = $appDb->selectFirst('*', 'devicenetworklookup', array('gatewayID = ?' => $gatewayId));
3421 if (!$deviceNetworkLookup) {
3422 throw new Nlss_Exception("Unable to retrieve device network lookup data for specified gateway id `$gatewayId`.");
3423 }
3424 $customerId = $deviceNetworkLookup['customerID'];
3425 $deviceWebPort = $deviceNetworkLookup['deviceWebPort'];
3426 }
3427
3428 // Get RMS user.
3429 {
3430 $user = Nlss_User::getRmsUser($customerId, $gatewayId);
3431 if (!$user) {
3432 throw new Nlss_Exception("Unable to retrieve RMS user data for specified customer id `$customerId` and gateway id `$gatewayId`.");
3433 }
3434 }
3435
3436 // Authenticate with gateway.
3437 {
3438 $curl = new Nlss_Network_Curl(
3439 Nlss::getHttpProtocol(Nlss::SERVER_TYPE_GATEWAY) . '://localhost:' . $deviceWebPort . '/api/nlssgateway/v1/DeviceCommands/authenticate',
3440 'POST',
3441 array(
3442 'Person' => array(
3443 'userID' => $user['userID'],
3444 'password' => $user['password']
3445 )
3446 )
3447 );
3448 $result = $curl->exec();
3449 if (!$result || (isset($result[0]) && !trim($result[0]))) {
3450 throw new Nlss_Exception("Unable to authenticate over device web port `$deviceWebPort`.");
3451 }
3452 if (isset($result['error'])) {
3453 throw new Nlss_Exception("Unable to authenticate over device web port `$deviceWebPort`: `{$result['error']}`");
3454 }
3455 }
3456
3457 // Make sure SSH is enabled.
3458 {
3459 $curl = new Nlss_Network_Curl(
3460 Nlss::getHttpProtocol(Nlss::SERVER_TYPE_GATEWAY) . '://localhost:' . $deviceWebPort . '/api/nlssgateway/v1/Gateway',
3461 'GET',
3462 ''
3463 );
3464 $result = $curl->exec();
3465 if (!$result || (isset($result[0]) && !trim($result[0]))) {
3466 throw new Nlss_Exception("Unable to query gateway table over device web port `$deviceWebPort`.");
3467 }
3468 if (isset($result['error'])) {
3469 throw new Nlss_Exception("Unable to query gateway table over device web port `$deviceWebPort`: `{$result['error']}`");
3470 }
3471
3472 $gatewayId = @$result['Gateway']['deviceID'];
3473 $isSshEnabled = (bool) @$result['Gateway']['enableSSH'];
3474
3475 if (!$isSshEnabled) {
3476 $curl = new Nlss_Network_Curl(
3477 Nlss::getHttpProtocol(Nlss::SERVER_TYPE_GATEWAY) . '://localhost:' . $deviceWebPort . '/api/nlssgateway/v1/gateway/' . $gatewayId,
3478 'POST',
3479 array(
3480 'Gateway' => array(
3481 'enableSSH' => '1'
3482 )
3483 )
3484 );
3485 $result = $curl->exec();
3486 }
3487 }
3488
3489 // Establish tunnel.
3490 {
3491 $curl = new Nlss_Network_Curl(
3492 Nlss::getHttpProtocol(Nlss::SERVER_TYPE_GATEWAY) . '://localhost:' . $deviceWebPort . '/api/nlssgateway/v1/DeviceCommands/establishRmsTechnicalSupportTunnel',
3493 'POST',
3494 array(
3495 'Person' => array(
3496 'host' => $host,
3497 'port' => $port
3498 )
3499 )
3500 );
3501 $result = $curl->exec();
3502 if (!$result || (isset($result[0]) && !trim($result[0]))) {
3503 throw new Nlss_Exception("Unable to establish RMS technical support tunnel over device web port `$deviceWebPort`.");
3504 }
3505 if (isset($result['error'])) {
3506 throw new Nlss_Exception("Unable to establish RMS technical support tunnel over device web port `$deviceWebPort`: `{$result['error']}`");
3507 }
3508 if (@$result['result'] != 'success') {
3509 throw new Nlss_Exception("Unable to establish an RMS technical support tunnel on port `$port` for gateway id `$gatewayId`.");
3510 }
3511
3512 //echo "\n\n\nConnect to gateway by: ssh nlss@localhost -p $port\n\n\nWhen you are finished, please close tunnel by killing the ssh tunnel process on the gateway for port number $port.\n\n\n";
3513
3514 $this->display = 'row';
3515 $this->table = 'response';
3516 $this->output['row'][] = array('field' => 'result', 'value' => 'success');
3517 }
3518 } catch (Exception $e) {
3519 // TODO: Log exception.
3520
3521 $this->display = 'row';
3522 $this->table = 'response';
3523 $this->output['row'][] = ($this->_debug) ? array('field' => 'result', 'value' => 'failure (file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage() . ')') : array('field' => 'result', 'value' => 'failure');
3524 $this->badRequest();
3525 }
3526
3527 $this->generateResponseData();
3528 }
3529
3530 /**
3531 * TODO
3532 */
3533 private function _getUploadUri()
3534 {
3535 try {
3536 $uploadPath = Nlss::getHttpProtocol() . '://' . rtrim($_SERVER['HTTP_HOST'], '/') . '/upload';
3537
3538 $this->display = 'row';
3539 $this->table = 'UploadUri';
3540 $this->output['row'][] = array('field' => 'Uri', 'value' => $uploadPath);
3541 } catch (Exception $e) {
3542 // TODO: Log exception.
3543
3544 $this->display = 'row';
3545 $this->table = 'response';
3546 $this->output['row'][] = ($this->_debug) ? array('field' => 'result', 'value' => 'failure (file: ' . $e->getFile() . ', line: ' . $e->getLine() . ', message: ' . $e->getMessage() . ')') : array('field' => 'result', 'value' => 'failure');
3547 $this->badRequest();
3548 }
3549
3550 $this->generateResponseData();
3551 }
3552
3553 /**
3554 * TODO
3555 */
3556 private function _checkConfigurationOperation()
3557 {
3558 $db = Nlss_Database::factory($this->_dbName);
3559 $user = Nlss_Auth::getAuthenticatedEntity();
3560 $userRole = $db->selectFirst('*', 'usertype', array('userTypeID = ?' => $user->getData('userTypeID')));
3561 $tableNames = array('cardholder');
3562 $configsAndTables = Nlss_Common_Model_Configuration::getConfigsAndTables();
3563
3564 foreach ($configsAndTables as $configTableNames) {
3565 foreach ($configTableNames as $tableName) {
3566 $tableNames[] = $tableName;
3567 }
3568 }
3569
3570
3571 if (!in_array($userRole['baseUserType'], array('00000000-0000-0000-0000-000000000000','00000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002')) && in_array(strtolower($this->table), $tableNames)) {
3572 throw new Nlss_Exception("Only Roles cloned from Master, Super, or Admin can insert/update/delete configurations.");
3573 }
3574 }
3575
3576 /**
3577 * TODO
3578 */
3579 function putEventXML($arg1, $arg2, $arg3)
3580 {
3581 $myCustomerID = '';
3582 $mySiteID = '';
3583 $starttime =round(microtime(true))*100;
3584
3585 $myCustomerID = 'c8ee2b6c-ed28-11df-b5cc-00012ebc3260';
3586 $mySiteID = 'c8ee2b6c-ed28-11df-b5cc-00012ebc3260';
3587
3588 $myXML = "";
3589 $myXML.= $this->axmlHeader;
3590 $myXML.= $this->eventHeader;
3591 $myXML.= '<eventID>'.$this->uuid().'</eventID>'."\n";
3592 $myXML.= '<customerID>'.$myCustomerID.'</customerID>'."\n";
3593 $myXML.= '<siteID>'.$mySiteID.'</siteID>'."\n";
3594 $myXML.= '<eventTime>'.$starttime.'</eventTime>'."\n";
3595 $myXML.= '<eventCategory>'.$arg1.'</eventCategory>'."\n";
3596 $myXML.= '<eventType>'.$arg2.'</eventType>'."\n";
3597 $myXML.= '<eventSeverityID>'.$arg3.'</eventSeverityID>'."\n";
3598 $myXML.= '<eventDescription>'.$this->table.'</eventDescription>'."\n";
3599 $myXML.= '<eventResource>'.$this->myKey.'</eventResource>'."\n";
3600 $myXML.= '</NLSSEvent>'."\n";
3601 $this->outboundDBEvent($myXML);
3602 }
3603
3604 /**
3605 * TODO
3606 */
3607 function uuid()
3608 {
3609 $chars = md5(uniqid(mt_rand(), true));
3610 $uuid = substr($chars,0,8) . '-';
3611 $uuid .= substr($chars,8,4) . '-';
3612 $uuid .= substr($chars,12,4) . '-';
3613 $uuid .= substr($chars,16,4) . '-';
3614 $uuid .= substr($chars,20,12);
3615 return $uuid;
3616 }
3617
3618 /**
3619 * TODO
3620 */
3621 function outboundDBEvent($xml)
3622 {
3623 try {
3624 $fp = @fsockopen($this->eventServer, $this->eventPort, $errno, $errstr);
3625 if (!$fp) {
3626 } else {
3627 if ($xml)
3628 {
3629 fwrite($fp, $xml);
3630 }
3631 fclose($fp);
3632 }
3633 }catch (Exception $e){
3634 }
3635 }
3636
3637 /**
3638 * Validate XML against XSD.
3639 * @return boolean
3640 */
3641 function validateXSD($xmlschema='Gateway.xsd')
3642 {
3643 /*
3644 libxml_use_internal_errors(true);
3645 $xml = new DOMDocument();
3646 $xml->loadXML($this->requestData);
3647
3648 if (!$xml->schemaValidate($xmlschema))
3649 {
3650 echo "NO VALIDATION";
3651 return false;
3652 //return true;
3653 }
3654 else {
3655 echo "VALIDATION";
3656 return true;
3657 }
3658 return true;
3659 */
3660
3661 return true;
3662 }
3663
3664 /**
3665 * TODO
3666 */
3667 function simplexml2array($xml)
3668 {
3669 if (is_object($xml) && get_class($xml) == 'SimpleXMLElement') {
3670 $attributes = $xml->attributes();
3671 //print_r($attributes);
3672 foreach($attributes as $k=>$v) {
3673 if ($v) $a[$k] = (string) $v;
3674 }
3675 $x = $xml;
3676 $xml = get_object_vars($xml);
3677 }
3678 if (is_array($xml)) {
3679 // print_r($xml);
3680 if (count($xml) == 0)
3681 {
3682 //return $x;
3683 //return (string) $x;
3684 //SI Added: check if field is empty, then no need to add CDATA
3685 if((string) $x != "")
3686 {
3687 return '<![CDATA['.(string) $x.']]>'; // for CDATA
3688 } else {
3689 return '';
3690 }
3691 }
3692 $r = array();
3693 foreach($xml as $key=>$value)
3694 {
3695 $r[$key] = $this->simplexml2array($value);
3696 }
3697 if (isset($a)) $r['@'] = $a; // Attributes
3698 return $r;
3699 }
3700
3701 return (string) $xml;
3702 }
3703
3704 /**
3705 * Parse the HTTP request data.
3706 * @return str[] Array of name value pairs
3707 */
3708 function objectsIntoArray($arrObjData, $arrSkipIndices = array(), $emptyString = false)
3709 {
3710 $arrData = array();
3711 if (is_object($arrObjData)) {
3712 $arrObjData = get_object_vars($arrObjData);
3713 }
3714 if (is_array($arrObjData)) {
3715 foreach ($arrObjData as $index => $value) {
3716 if (is_object($value) || is_array($value)) {
3717 $value = $this->objectsIntoArray($value, $arrSkipIndices, $emptyString);
3718 }
3719 if (in_array($index, $arrSkipIndices)) {
3720 continue;
3721 }
3722 $arrData[$index] = $value;
3723 }
3724 }
3725 return (!$arrData && $emptyString) ? '' : $arrData;
3726 }
3727
3728 /**
3729 * Generate the HTTP response data.
3730 */
3731 function generateResponseData() {
3732 if (isset($_SERVER['HTTP_ACCEPT'])) {
3733 $accepts = explode(',', $_SERVER['HTTP_ACCEPT']);
3734 $orderedAccepts = array();
3735 foreach ($accepts as $key => $accept) {
3736 $exploded = explode(';', $accept);
3737 if (isset($exploded[1]) && substr($exploded[1], 0, 2) == 'q=') {
3738 $orderedAccepts[substr($exploded[1], 2)][] = $exploded[0];
3739 } else {
3740 $orderedAccepts['1'][] = $exploded[0];
3741 }
3742 }
3743 krsort($orderedAccepts);
3744 }
3745
3746 require_once('xml.php');
3747 $renderer = new PHPRestSQLRenderer();
3748 $renderer->render($this, $this->table);
3749 }
3750
3751 /**
3752 * Send a HTTP 200 response header.
3753 */
3754 function successOk() {
3755 header('HTTP/1.0 200 Success');
3756 }
3757
3758 /**
3759 * Send a HTTP 200 response header.
3760 */
3761 function noRecords() {
3762 header('HTTP/1.0 200 Success');
3763 }
3764
3765 /**
3766 * Send a HTTP 201 response header.
3767 */
3768 function created($url = FALSE) {
3769 header('HTTP/1.0 201 Created');
3770 if ($url) {
3771 header('Location: '.$url);
3772 }
3773 }
3774
3775 /**
3776 * Send a HTTP 204 response header.
3777 */
3778 function noContent() {
3779 header('HTTP/1.0 204 No Content');
3780 }
3781
3782 /**
3783 * Send a HTTP 400 response header.
3784 */
3785 function badRequest() {
3786 header('HTTP/1.0 400 Bad Request');
3787 }
3788
3789 /**
3790 * Send a HTTP 401 response header.
3791 */
3792 function unauthorized($realm = 'PHPRestSQL') {
3793 /*
3794 header('WWW-Authenticate: Basic realm="' . $realm . '"');
3795 header('HTTP/1.0 401 Unauthorized');
3796 */
3797 $this->notFound();
3798 }
3799
3800 /**
3801 * Send a HTTP 404 response header.
3802 */
3803 function notFound() {
3804 Nlss::displayPageNotFound();
3805 exit;
3806 }
3807
3808 /**
3809 * Send a HTTP 405 response header.
3810 */
3811 function methodNotAllowed($allowed = 'GET, HEAD') {
3812 header('HTTP/1.0 405 Method Not Allowed');
3813 header('Allow: '.$allowed);
3814 }
3815
3816 /**
3817 * Send a HTTP 411 response header.
3818 */
3819 function lengthRequired() {
3820 header('HTTP/1.0 411 Length Required');
3821 }
3822
3823 /**
3824 * Send a HTTP 500 response header.
3825 */
3826 function internalServerError() {
3827 header('HTTP/1.0 500 Internal Server Error');
3828 }
3829
3830 public static function getDeviceName($gatewayId) {
3831 static $firstTime = true;
3832 static $hosting = array();
3833
3834 if ($firstTime) {
3835 $firstTime = false;
3836 $gc = Nlss::getGlobalConfig();
3837 $appDb = Nlss::getApp()->getDatabase();
3838 $authEntity = Nlss_Auth::getAuthenticatedEntity();
3839 $orgDb = $authEntity->getOrganization()->getDatabase();
3840 $orgId = $authEntity->getOrganization()->getData('organizationID');
3841
3842 $sites = array();
3843 $result = $orgDb->select('siteID, siteName', 'site');
3844 foreach ($result as &$row) {
3845 $sites[$row['siteID']] = $row['siteName'];
3846 }
3847
3848 $result = $orgDb->select('siteID, gatewayID', 'hosting');
3849 foreach ($result as &$row) {
3850 $hosting[$row['gatewayID']] = $sites[$row['siteID']];
3851 }
3852 }
3853
3854 return @$hosting[$gatewayId];
3855 }
3856}