api.olltv.php 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584
  1. <?php
  2. /**
  3. * Oll.tv ispAPI class
  4. * @author Prakapas Andriy <prakapas@general-servers.com>
  5. * @copyright 2016 GeneralServers LLC
  6. * @license http://www.apache.org/licenses/LICENSE-2.0
  7. * @version 2.1.0 - for same ispAPI version 2.1.0
  8. * @link https://general-servers.com
  9. * @link https://github.com/General-Servers/Oll.tv
  10. */
  11. class OllTv {
  12. /* Oll.tv constants */
  13. const OTV_URL = 'http://oll.tv/'; // main production url
  14. const OTV_URL_DEV = 'http://dev.oll.tv/'; // development url for test
  15. const OTV_URL_API = 'ispAPI'; // main api url
  16. const OTV_URL_AUTH = 'auth2'; // auth url
  17. /* log constants */
  18. const ERROR = 1;
  19. const WARNING = 2;
  20. const INFO = 3;
  21. /**
  22. * Client ispAPI login
  23. * Assign in constructor
  24. * @var string
  25. */
  26. protected $_login;
  27. /**
  28. * Client ispAPI password
  29. * Assign in constructor
  30. * @var string
  31. */
  32. protected $_password;
  33. /**
  34. * ispAPI hash
  35. * Hash return ispAPI; using in all requests
  36. * @var string
  37. */
  38. protected $_hash;
  39. /**
  40. * Result variable
  41. * Return ispAPI
  42. * @var string
  43. */
  44. protected $_result;
  45. /**
  46. * ispAPI url
  47. * @var string
  48. */
  49. protected $_url;
  50. /* log vars */
  51. /**
  52. * Path to log file
  53. * @var string
  54. */
  55. protected $_log;
  56. /**
  57. * Log level variable
  58. * 0 - not show any messages
  59. * 1 - only Errors - DEFAULT
  60. * 2 - Errors, Warnings
  61. * 3 - Errors, Warnings and Informations
  62. * @var integer
  63. */
  64. protected $_logLevel = 1;
  65. /**
  66. * Log message type
  67. * Related with $_logLevel var
  68. * @var array
  69. */
  70. protected $_logType = array(
  71. 0 => '',
  72. 1 => 'Error',
  73. 2 => 'Warning',
  74. 3 => 'Info'
  75. );
  76. /* --end log vars */
  77. /* error vars */
  78. /**
  79. * ispAPI errors array:
  80. * key - error status
  81. * value has short message and full description
  82. * @var array
  83. */
  84. protected $_errors = array(
  85. 109 => array(
  86. 'message' => 'Hash expired',
  87. 'description' => 'Время действия хеша истекло или хеш не верен'
  88. ),
  89. 110 => array(
  90. 'message' => 'Authorization missed',
  91. 'description' => 'Хеш не указан'
  92. ),
  93. 111 => array(
  94. 'message' => 'Auth failed',
  95. 'description' => 'Неверный логин или пароль'
  96. ),
  97. 112 => array(
  98. 'message' => 'Login empty',
  99. 'description' => 'Не указан логин'
  100. ),
  101. 113 => array(
  102. 'message' => 'Password empty',
  103. 'description' => 'Не указан пароль'
  104. ),
  105. 115 => array(
  106. 'message' => 'Email already exists',
  107. 'description' => 'Указанный имейл уже есть в БД'
  108. ),
  109. 116 => array(
  110. 'message' => 'Email validation failed',
  111. 'description' => 'Формат указанного имейла неверен'
  112. ),
  113. 117 => array(
  114. 'message' => 'Result user account does not match provided',
  115. 'description' => 'Не указан аккаунт или он не совпадает с аккаунтом на который подвязано устройство'
  116. ),
  117. 119 => array(
  118. 'message' => 'Device with provided mac or/and serial number already exist',
  119. 'description' => 'Устройство с указанным мак-адресом и/или серийным номером уже присуствует в БД и за кем-то закреплено'
  120. ),
  121. 120 => array(
  122. 'message' => 'Wrong date format',
  123. 'description' => "Неверный формат даты"
  124. ),
  125. 200 => array(
  126. 'message' => 'Required fields missed',
  127. 'description' => "Остутствуют необходимые параметры"
  128. ),
  129. 201 => array(
  130. 'message' => 'Field email is required',
  131. 'description' => "Отсутствует необходимый параметр email"
  132. ),
  133. 203 => array(
  134. 'message' => 'Neither mac nor serial_number was found in your request',
  135. 'description' => "Отсутствуют параметры mac и serial_number"
  136. ),
  137. 205 => array(
  138. 'message' => 'Field new_email is required',
  139. 'description' => "Отсутствует необходимый параметр new_email"
  140. ),
  141. 301 => array(
  142. 'message' => 'Registration failed. Contact technical support',
  143. 'description' => "Ошибка добавления устройства пользователю или регистрации нового пользователя"
  144. ),
  145. 302 => array(
  146. 'message' => 'Wrong MAC address',
  147. 'description' => "Неверный формат мак-адреса"
  148. ),
  149. 303 => array(
  150. 'message' => 'Wrong Serial number',
  151. 'description' => "Неверный формат серийного номера"
  152. ),
  153. 304 => array(
  154. 'message' => 'Invalid binding code',
  155. 'description' => "Неверный код привязки устройства"
  156. ),
  157. 305 => array(
  158. 'message' => 'No devices can be binded by this code',
  159. 'description' => "Достигнут лимит кол-ва устройств, которые можно привязать по указанному коду привязки"
  160. ),
  161. 404 => array(
  162. 'message' => "Account not found",
  163. 'description' => "Пользователь не найден в БД"
  164. ),
  165. 405 => array(
  166. 'message' => "Not eligible device_type",
  167. 'description' => "Недопустимое значение в параметре device_type"
  168. ),
  169. 406 => array(
  170. 'message' => "Device not found in our DB",
  171. 'description' => "Устройство не найдено в БД или оно отвязано от пользователя",
  172. ),
  173. 407 => array(
  174. 'message' => "Subscription not found",
  175. 'description' => "Подписка, указанная в параметрах sub_id, new_sub_id или old_sub_id, не найдена"
  176. ),
  177. 408 => array(
  178. 'message' => "Subscription order violation",
  179. 'description' => "Нарушение очерёдности отключения или включения услуги согласно подписке"
  180. ),
  181. 501 => array(
  182. 'message' => "Access denied",
  183. 'description' => "Устройство привязано к пользователю другого провайдера"
  184. ),
  185. 504 => array(
  186. 'message' => "User already deactivated",
  187. 'description' => "Услуга была уже выключена ранее"
  188. ),
  189. 505 => array(
  190. 'message' => "User is attached to another operator",
  191. 'description' => "Пользователь привязан к другому провайдеру"
  192. ),
  193. 506 => array(
  194. 'message' => "Account is not active",
  195. 'description' => "Аккаунт пользователя не активен"
  196. )
  197. );
  198. /**
  199. * Last message array
  200. * You can get last message by type even when log has disabled
  201. * @var array
  202. */
  203. protected $_lastMessage = array(
  204. 0 => '', // empty
  205. 1 => '', // last error message
  206. 2 => '', // last warning message
  207. 3 => '' // last information message
  208. );
  209. /* --end error vars */
  210. /**
  211. * Assign last message
  212. * @param string $message message text
  213. * @param integer $type message type
  214. * @return boolean
  215. */
  216. protected function _setLastMessage($message, $type) {
  217. // verify arguments
  218. if (!is_string($message) || !is_numeric($type)) {
  219. return false;
  220. }
  221. // verify type in last message array
  222. if (!isset($this->_lastMessage[$type])) {
  223. return false;
  224. }
  225. // assign message by type
  226. $this->_lastMessage[$type] = $message;
  227. return true;
  228. }
  229. /**
  230. * Write to log file
  231. * @param string $message message text
  232. * @param integer $type type of message
  233. * @return boolean
  234. */
  235. protected function _toLog($message, $type = 1) {
  236. // verify arguments
  237. if (empty($message) || !is_string($message)) {
  238. return false;
  239. }
  240. // assign last message variable
  241. $this->_setLastMessage($message, $type);
  242. // verify log level
  243. if ($this->_logLevel == 0 || $type == 0 || !isset($this->_logType[$type])) {
  244. return false;
  245. }
  246. // compare $_logLevel and message type
  247. if ($type > $this->_logLevel) {
  248. return false;
  249. }
  250. // prepare message type
  251. $type = $this->_logType[$type] . ': ';
  252. // append write to file and get result
  253. $res = file_put_contents($this->_log, date('Y-m-d H:i:s') . ' ' . $type . $message . ";\n", FILE_APPEND);
  254. return (bool) $res;
  255. }
  256. /**
  257. * Method prepare default account data
  258. * @param array $params parametters array
  259. * accept parametters:
  260. * account OR email OR id OR ds_account
  261. * examples:
  262. * array('account' => 'test')
  263. * array('email' => 'test@test.com')
  264. * array('id' => 42)
  265. * array('ds_account' => 'test')
  266. *
  267. * @return array
  268. */
  269. protected function _prepareAccountDefaultData($params) {
  270. // init return array
  271. $args = array();
  272. // try find 'account'
  273. if (!empty($params['account'])) {
  274. $args = array(
  275. 'account' => $params['account']
  276. );
  277. } else {
  278. $this->_toLog('[' . __FUNCTION__ . '] - `account` not found in parametter array', self::INFO);
  279. }
  280. // try find 'email'
  281. if (!empty($params['email']) && filter_var($params['email'], FILTER_VALIDATE_EMAIL)) {
  282. $args = array(
  283. 'email' => $params['email']
  284. );
  285. } else {
  286. $this->_toLog('[' . __FUNCTION__ . '] - `email` not found in parametter array or `email` is not valid email', self::INFO);
  287. }
  288. // try find 'id'
  289. if (!empty($params['id']) && is_numeric($params['id'])) {
  290. $args = array(
  291. 'id' => $params['id']
  292. );
  293. } else {
  294. $this->_toLog('[' . __FUNCTION__ . '] - `id` not found in parametter array', self::INFO);
  295. }
  296. // try find 'ds_account'
  297. if (!empty($params['ds_account'])) {
  298. $args = array(
  299. 'ds_account' => $params['ds_account']
  300. );
  301. } else {
  302. $this->_toLog('[' . __FUNCTION__ . '] - `ds_account` not found in parametter array', self::INFO);
  303. }
  304. return $args;
  305. }
  306. /**
  307. * Method prepare purchase type
  308. * @param string $type
  309. * accept parametters:
  310. * subs_free_device — new contract - 24 months and equipment for 1 uah
  311. * subs_buy_device — new contract - buy equipment
  312. * subs_rent_device — new contract - rent equipment
  313. * subs_no_device — new contract - no equipment
  314. * subs_renew — restore the current contract
  315. * subs_negative_balance - money stop
  316. *
  317. * @return string|false
  318. */
  319. protected function _preparePurchaseType($type) {
  320. // init types array
  321. $typeArray = array('subs_free_device', 'subs_buy_device', 'subs_rent_device', 'subs_no_device', 'subs_renew', 'subs_negative_balance');
  322. // verify argument
  323. if (empty($type) || !in_array($type, $typeArray)) {
  324. $this->_toLog('[' . __FUNCTION__ . '] - purchase type is not correct');
  325. return false;
  326. }
  327. // return type
  328. return $type;
  329. }
  330. /**
  331. * Method prepare device type
  332. * @param string $type
  333. * accept parametters:
  334. * device_free — new contract - 24 months and equipment for 1 uah
  335. * device_buy — new contract - buy equipment
  336. * device_rent — new contract - rent equipment
  337. * device_change — service replace the current equipment
  338. *
  339. * @return string|false
  340. */
  341. protected function _prepareDeviceType($type) {
  342. // init types array
  343. $typeArray = array('device_free', 'device_buy', 'device_rent', 'device_change');
  344. // verify argument
  345. if (empty($type) || !in_array($type, $typeArray)) {
  346. $this->_toLog('[' . __FUNCTION__ . '] - device type is not correct');
  347. return false;
  348. }
  349. // return type
  350. return $type;
  351. }
  352. /**
  353. * Read result from ispAPI
  354. * @param string $result result string
  355. * @return boolean
  356. */
  357. protected function _readResult($result) {
  358. // verify result var
  359. if (empty($result) || !is_string($result)) {
  360. $this->_toLog('[' . __FUNCTION__ . '] - cannot read result; maybe empty or not string value: ' . var_export($result, true));
  361. return false;
  362. }
  363. // log info
  364. $this->_toLog('[' . __FUNCTION__ . '] - read result: ' . var_export($result, true), self::INFO);
  365. // decode from string
  366. $json = json_decode($result);
  367. // check json errors
  368. // commented due old PHP compatibility reasons
  369. //$error = json_last_error_msg();
  370. $error = print_r($json, true);
  371. if (!$json) {
  372. $this->_toLog('[' . __FUNCTION__ . '] - has json error: ' . $error);
  373. return false;
  374. }
  375. // all looks good
  376. $this->_result = $json;
  377. return true;
  378. }
  379. /**
  380. * Return ispAPI result
  381. * @return object|false
  382. */
  383. protected function _return() {
  384. // verify result
  385. if (empty($this->_result) || !is_object($this->_result) || !isset($this->_result->status)) {
  386. $this->_toLog('[' . __FUNCTION__ . '] - API result is bad type: ' . var_export($this->_result, true));
  387. return false;
  388. }
  389. // log warnings
  390. if (!empty($this->_result->warnings)) {
  391. $this->_toLog('[' . __FUNCTION__ . '] - API warnings: ' . print_r($this->_result->warnings, true));
  392. }
  393. // verify result status
  394. if ($this->_result->status !== 0) {
  395. // prepare error
  396. $error = '';
  397. if (!isset($this->_errors[$this->_result->status])) {
  398. if (isset($this->_result->message)) {
  399. $error = $this->_result->message;
  400. } else {
  401. $error = '[' . __FUNCTION__ . '] - API return false status';
  402. }
  403. } else {
  404. // prepare error string
  405. $error = 'Code #' . $this->_result->status;
  406. $error .= ' ' . $this->_errors[$this->_result->status]['message'];
  407. $error .= ' - ' . $this->_errors[$this->_result->status]['description'];
  408. }
  409. // log error
  410. $this->_toLog($error);
  411. // return false
  412. return false;
  413. }
  414. // all looks good
  415. else {
  416. // log action
  417. $this->_toLog('[' . __FUNCTION__ . '] - return API result', self::INFO);
  418. // return result
  419. return $this->_result;
  420. }
  421. }
  422. /**
  423. * Create ispAPI url
  424. * @param boolean $testMode testing mode flag, default - false
  425. * @return boolean
  426. */
  427. protected function _createUrl($testMode = false) {
  428. // verify argument
  429. if (!is_bool($testMode)) {
  430. $this->_toLog('[' . __FUNCTION__ . '] - $testMode not is boolean type; set to default `false`', self::WARNING);
  431. $testMode = false;
  432. }
  433. // assign url
  434. if ($testMode) {
  435. $this->_toLog('[' . __FUNCTION__ . '] - $testMode is `true`; set url to: ' . self::OTV_URL_DEV, self::INFO);
  436. $this->_url = self::OTV_URL_DEV;
  437. } else {
  438. $this->_toLog('[' . __FUNCTION__ . '] - $testMode is `false`; set url to: ' . self::OTV_URL, self::INFO);
  439. $this->_url = self::OTV_URL;
  440. }
  441. // add ispAPI link to url
  442. $this->_url .= self::OTV_URL_API;
  443. return true;
  444. }
  445. /**
  446. * Authenticate to ispAPI and assign hash
  447. * @return boolean
  448. */
  449. protected function _auth() {
  450. // verify login and pass
  451. if (empty($this->_login)) {
  452. $this->_toLog('[' . __FUNCTION__ . '] - login is empty');
  453. return false;
  454. }
  455. if (empty($this->_password)) {
  456. $this->_toLog('[' . __FUNCTION__ . '] - password is empty');
  457. return false;
  458. }
  459. // try to connect
  460. $res = $this->_sendToAPI(self::OTV_URL_AUTH, array(
  461. 'login' => $this->_login,
  462. 'password' => $this->_password
  463. ));
  464. // verify result and hash
  465. if (!$res || empty($this->_result->hash)) {
  466. $this->_toLog('[' . __FUNCTION__ . '] - false authenticate');
  467. return false;
  468. }
  469. // assign hash
  470. $this->_hash = $this->_result->hash;
  471. return true;
  472. }
  473. /**
  474. * Method send ispAPI action by CURL
  475. * @param string $method ispAPI method
  476. * @param array $args POST arguments
  477. * @return object|false
  478. */
  479. protected function _sendToAPI($method, $args) {
  480. // verify arguments
  481. if (!is_string($method)) {
  482. $this->_toLog('[' . __FUNCTION__ . '] - `$method` must to be string;');
  483. return false;
  484. }
  485. if (!is_array($args)) {
  486. $this->_toLog('[' . __FUNCTION__ . '] - `$args` is not array;');
  487. return false;
  488. }
  489. // add hash to arguments
  490. if ($method !== self::OTV_URL_AUTH) {
  491. $args['hash'] = $this->_hash;
  492. }
  493. // create curl link
  494. $curlLink = $this->_url . '/' . $method;
  495. // prepare data for log
  496. $logArgs = $args;
  497. // disable password - not show in logs!
  498. if (!empty($logArgs['password'])) {
  499. $logArgs['password'] = '*************';
  500. }
  501. // lof info
  502. $this->_toLog('[' . __FUNCTION__ . '] - send request to url: ' . $curlLink, self::INFO);
  503. $this->_toLog('[' . __FUNCTION__ . '] - send request data: ' . var_export($logArgs, true), self::INFO);
  504. // create and send curl
  505. $ch = curl_init();
  506. curl_setopt($ch, CURLOPT_URL, $curlLink);
  507. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  508. // curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/html;charset=utf-8'));
  509. // send post if need
  510. if (!empty($args)) {
  511. curl_setopt($ch, CURLOPT_POST, 1);
  512. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($args));
  513. }
  514. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  515. // execute curl
  516. $response = curl_exec($ch);
  517. curl_close($ch);
  518. // read result
  519. $this->_readResult($response);
  520. // return formed result by function _return()
  521. return $this->_return();
  522. }
  523. /**
  524. * Constructor
  525. * @depends _createUrl, _auth
  526. * @param string $login client login
  527. * @param string $pass client password
  528. * @param boolean $testMode test mode flag
  529. * @param string $log path to log file
  530. */
  531. public function __construct($login, $pass, $testMode = false, $log = '', $logLevel = 1) {
  532. // assign log file
  533. $this->_log = $log;
  534. // assign log level
  535. $logLevel = (int) $logLevel;
  536. $this->_logLevel = ($logLevel < 0 || $logLevel > 3) ? 1 : $logLevel;
  537. // assign login and password
  538. $this->_login = $login;
  539. $this->_password = $pass;
  540. // create API url
  541. $this->_createUrl($testMode);
  542. // try authenticate
  543. $this->_auth();
  544. }
  545. /**
  546. * Return last message
  547. * @param integer $type message type, default - 1 mean Error
  548. * @return string|false
  549. */
  550. public function getLastMessage($type = 1) {
  551. // verify arguments
  552. if (!is_numeric($type) || !isset($this->_lastMessage[$type])) {
  553. return false;
  554. }
  555. // return message
  556. return $this->_lastMessage[$type];
  557. }
  558. /* ispAPI functions */
  559. /* users functions */
  560. /**
  561. * Verify user email
  562. * @param string $email user email
  563. * @return integer|false false - smth is wrong; 0 - not exist; 1 - exist
  564. */
  565. public function emailExists($email) {
  566. // verify argument
  567. if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  568. $this->_toLog('[' . __FUNCTION__ . '] - `$email` is not valid email address');
  569. return false;
  570. }
  571. // prepare arguments array
  572. $args = array(
  573. 'email' => $email
  574. );
  575. // log info
  576. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  577. // run request to API and get result
  578. $res = $this->_sendToAPI(__FUNCTION__, $args);
  579. // verify and return result
  580. if (isset($res->data)) {
  581. return $res->data;
  582. } else {
  583. return false;
  584. }
  585. }
  586. /**
  587. * Return account object
  588. * @param string $account user account in provider base
  589. * @return mixed return object - user account or 0
  590. */
  591. public function accountExists($account) {
  592. // verify argument
  593. if (empty($account)) {
  594. $this->_toLog('[' . __FUNCTION__ . '] - `$account` is empty');
  595. return 0;
  596. }
  597. // prepare arguments array
  598. $args = array(
  599. 'account' => $account
  600. );
  601. // log info
  602. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  603. // run request to API and get result
  604. $res = $this->_sendToAPI(__FUNCTION__, $args);
  605. // verify and return
  606. if (isset($res->data)) {
  607. return $res->data;
  608. } else {
  609. return 0;
  610. }
  611. }
  612. /**
  613. * Add new user
  614. * @param string $email user email
  615. * @param string $account user account in provider base
  616. * @param array $addParams additional params
  617. * birth_date (YYYY-MM-DD or DD.MM.YYYY)
  618. * gender (M or F, default: M)
  619. * firstname (default: «Гость»/«Гостья»)
  620. * password (will generate automatic - if not set, must be longer 8 chars)
  621. * lastname
  622. * phone (example: 0501234567)
  623. * region
  624. * receive_news (value 1 or 0, default: 1)
  625. * send_registration_email (whether send the user a registration message, value 1 or 0, default: 1)
  626. * index (zip code or other identifier binding regional subscriber)
  627. *
  628. * @return string|false string - user ID; false - smth is wrong
  629. */
  630. public function addUser($email, $account, $addParams = array()) {
  631. // verify arguments
  632. if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  633. $this->_toLog('[' . __FUNCTION__ . '] - `$email` is not valid email address');
  634. return false;
  635. }
  636. // verify argument
  637. if (empty($account)) {
  638. $this->_toLog('[' . __FUNCTION__ . '] - `$account` is empty');
  639. return false;
  640. }
  641. // prepare arguments array
  642. $args = array(
  643. 'email' => $email,
  644. 'account' => $account,
  645. );
  646. // prepare birth date
  647. if (!empty($addParams['birth_date']) && strtotime($addParams['birth_date'])) {
  648. $args['birth_date'] = date('Y-m-d', strtotime($addParams['birth_date']));
  649. }
  650. // prepare gender
  651. if (!empty($addParams['gender']) && in_array($addParams['gender'], array('M', 'F'))) {
  652. $args['gender'] = $addParams['gender'];
  653. }
  654. // prepare firstname
  655. if (!empty($addParams['firstname'])) {
  656. $args['firstname'] = $addParams['firstname'];
  657. } else {
  658. $args['firstname'] = (isset($args['gender']) && $args['gender'] === 'F') ? 'Гостья' : 'Гость';
  659. }
  660. // prepare lastname
  661. if (!empty($addParams['lastname'])) {
  662. $args['lastname'] = $addParams['lastname'];
  663. }
  664. // prepare password
  665. if (!empty($addParams['password']) && strlen($addParams['password']) >= 8) {
  666. $args['password'] = $addParams['password'];
  667. } else {
  668. $this->_toLog('[' . __FUNCTION__ . '] - user password is empty or shorter than 8 chars; generate automatic', self::WARNING);
  669. }
  670. // prepare phone
  671. if (!empty($addParams['phone']) && is_string($addParams['phone']) &&
  672. preg_match('/^\d{10,}$/', $addParams['phone']) && $addParams['phone'][0] === '0'
  673. ) {
  674. $args['phone'] = $addParams['phone'];
  675. }
  676. // prepare region
  677. if (!empty($addParams['region'])) {
  678. $args['region'] = $addParams['region'];
  679. }
  680. // prepare receive_news
  681. if (!empty($addParams['receive_news']) && is_numeric($addParams['receive_news'])) {
  682. $args['receive_news'] = (int) (bool) $addParams['receive_news'];
  683. }
  684. // prepare send_registration_email
  685. if (!empty($addParams['send_registration_email']) && is_numeric($addParams['send_registration_email'])) {
  686. $args['send_registration_email'] = (int) (bool) $addParams['send_registration_email'];
  687. }
  688. // prepare index
  689. if (!empty($addParams['index'])) {
  690. $args['index'] = $addParams['index'];
  691. }
  692. // log info
  693. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  694. // run request to API and get result
  695. $res = $this->_sendToAPI(__FUNCTION__, $args);
  696. debarr($res);
  697. // verify and return
  698. if (isset($res->data)) {
  699. return $res->data;
  700. } else {
  701. return 0;
  702. }
  703. }
  704. /**
  705. * Return user list bound to provider
  706. * @param integer $offset offset
  707. * @param integer $limit limit
  708. * @return array
  709. */
  710. public function getUserList($offset = 0, $limit = 1000) {
  711. // verify arguments
  712. if (!is_numeric($offset) || $offset < 0) {
  713. // log info
  714. $this->_toLog('[' . __FUNCTION__ . '] - `$offset` is incorrect, set to 0', self::WARNING);
  715. $offset = 0;
  716. }
  717. if (!is_numeric($limit) || $limit <= 0 || $limit > 1000) {
  718. // log info
  719. $this->_toLog('[' . __FUNCTION__ . '] - `$limit` is incorrect, set to default 1000', self::WARNING);
  720. $limit = 1000;
  721. }
  722. // prepare arguments array
  723. $args = array(
  724. 'offset' => $offset,
  725. 'limit' => $limit
  726. );
  727. // log info
  728. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  729. // run request to API and get result
  730. $res = $this->_sendToAPI(__FUNCTION__, $args);
  731. // verify and return
  732. if (isset($res->data)) {
  733. return $res->data;
  734. } else {
  735. return array();
  736. }
  737. }
  738. /**
  739. * Assign provider account and bind user to account
  740. * @param string $email user email
  741. * @param string $account account
  742. * @return integer|false integer - status
  743. */
  744. public function changeAccount($email, $account) {
  745. // verify arguments
  746. if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  747. $this->_toLog('[' . __FUNCTION__ . '] - `$email` is not valid email address');
  748. return false;
  749. }
  750. // verify argument
  751. if (empty($account)) {
  752. $this->_toLog('[' . __FUNCTION__ . '] - `$account` is empty');
  753. return false;
  754. }
  755. // prepare arguments array
  756. $args = array(
  757. 'email' => $email,
  758. 'account' => $account,
  759. );
  760. // log info
  761. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  762. // run request to API and get result
  763. $res = $this->_sendToAPI(__FUNCTION__, $args);
  764. // verify and return
  765. if (isset($res->status)) {
  766. return $res->status;
  767. } else {
  768. return false;
  769. }
  770. }
  771. /**
  772. * Unbind user from provider by params
  773. * @param array $params
  774. * accept parametters:
  775. * account OR email OR id OR ds_account
  776. * examples:
  777. * array('account' => 'test')
  778. * array('email' => 'test@test.com')
  779. * array('id' => 42)
  780. * array('ds_account' => 'test')
  781. *
  782. * @return integer|false integer - status
  783. */
  784. public function deleteAccount($params) {
  785. // verify parametters
  786. if (empty($params)) {
  787. $this->_toLog('[' . __FUNCTION__ . '] - `$params` is empty');
  788. return false;
  789. }
  790. // prepare arguments array
  791. $args = $this->_prepareAccountDefaultData($params);
  792. // verify arguments
  793. if (empty($args)) {
  794. $this->_toLog('[' . __FUNCTION__ . '] - account parametter not found in `$params`');
  795. return false;
  796. }
  797. // log info
  798. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  799. // run request to API and get result
  800. $res = $this->_sendToAPI(__FUNCTION__, $args);
  801. // verify and return
  802. if (isset($res->status)) {
  803. return $res->status;
  804. } else {
  805. return false;
  806. }
  807. }
  808. /**
  809. * Change user email
  810. * @param string $email current user email
  811. * @param string $newEmail new user email
  812. * @return integer|false integer - status
  813. */
  814. public function changeEmail($email, $newEmail) {
  815. // verify arguments
  816. if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  817. $this->_toLog('[' . __FUNCTION__ . '] - `$email` is not valid email address');
  818. return false;
  819. }
  820. if (empty($newEmail) || !filter_var($newEmail, FILTER_VALIDATE_EMAIL)) {
  821. $this->_toLog('[' . __FUNCTION__ . '] - `$newEmail` is not valid email address');
  822. return false;
  823. }
  824. // prepare arguments array
  825. $args = array(
  826. 'email' => $email,
  827. 'new_email' => $newEmail
  828. );
  829. // log info
  830. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  831. // run request to API and get result
  832. $res = $this->_sendToAPI(__FUNCTION__, $args);
  833. // verify and return
  834. if (isset($res->status)) {
  835. return $res->status;
  836. } else {
  837. return false;
  838. }
  839. }
  840. /**
  841. * Return user information
  842. * @param array $params
  843. * accept parametters:
  844. * account OR email OR id OR ds_account
  845. * examples:
  846. * array('account' => 'test')
  847. * array('email' => 'test@test.com')
  848. * array('id' => 42)
  849. * array('ds_account' => 'test')
  850. *
  851. * @return object|false
  852. */
  853. public function getUserInfo($params) {
  854. // verify parametters
  855. if (empty($params)) {
  856. $this->_toLog('[' . __FUNCTION__ . '] - `$params` is empty');
  857. return false;
  858. }
  859. // prepare arguments array
  860. $args = $this->_prepareAccountDefaultData($params);
  861. // verify arguments
  862. if (empty($args)) {
  863. $this->_toLog('[' . __FUNCTION__ . '] - account parametter not found in `$params`');
  864. return false;
  865. }
  866. // log info
  867. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  868. // run request to API and get result
  869. $res = $this->_sendToAPI(__FUNCTION__, $args);
  870. // verify and return
  871. if (isset($res->data)) {
  872. return $res->data;
  873. } else {
  874. return false;
  875. }
  876. }
  877. /**
  878. * Return user information
  879. * @param array $params parametters array
  880. * accept parametters:
  881. *
  882. * one from following is required:
  883. * account OR email OR id OR ds_account
  884. * examples:
  885. * array('account' => 'test')
  886. * array('email' => 'test@test.com')
  887. * array('id' => 42)
  888. * array('ds_account' => 'test')
  889. *
  890. * additionals:
  891. * birth_date (YYYY-MM-DD or DD.MM.YYYY)
  892. * gender (M or F, default: M)
  893. * password (must be longer than 8 chars)
  894. * firstname
  895. * lastname
  896. * phone
  897. * region
  898. * index (zip code or other identifier binding regional subscriber)
  899. *
  900. * @return integer|false integer - status
  901. */
  902. public function changeUserInfo($params) {
  903. // verify parametters
  904. if (empty($params)) {
  905. $this->_toLog('[' . __FUNCTION__ . '] - `$params` is empty');
  906. return false;
  907. }
  908. // prepare arguments array
  909. // required parametters
  910. $args = $this->_prepareAccountDefaultData($params);
  911. // verify arguments
  912. if (empty($args)) {
  913. $this->_toLog('[' . __FUNCTION__ . '] - account parametter not found in `$params`');
  914. return false;
  915. }
  916. // additional parametters
  917. // prepare birth date
  918. if (!empty($addParams['birth_date']) && strtotime($addParams['birth_date'])) {
  919. $args['birth_date'] = date('Y-m-d', strtotime($addParams['birth_date']));
  920. }
  921. // prepare gender
  922. if (!empty($addParams['gender']) && in_array($addParams['gender'], array('M', 'F'))) {
  923. $args['gender'] = $addParams['gender'];
  924. }
  925. // prepare firstname
  926. if (!empty($addParams['firstname'])) {
  927. $args['firstname'] = $addParams['firstname'];
  928. } else {
  929. $args['firstname'] = (isset($args['gender']) && $args['gender'] === 'F') ? 'Гостья' : 'Гость';
  930. }
  931. // prepare lastname
  932. if (!empty($addParams['lastname'])) {
  933. $args['lastname'] = $addParams['lastname'];
  934. }
  935. // prepare password
  936. if (!empty($addParams['password']) && strlen($addParams['password']) >= 8) {
  937. $args['password'] = $addParams['password'];
  938. }
  939. // prepare phone
  940. if (!empty($addParams['phone']) && is_string($addParams['phone']) &&
  941. preg_match('/^\d{10,}$/', $addParams['phone']) && $addParams['phone']{0} === '0'
  942. ) {
  943. $args['phone'] = $addParams['phone'];
  944. }
  945. // prepare region
  946. if (!empty($addParams['region'])) {
  947. $args['region'] = $addParams['region'];
  948. }
  949. // prepare index
  950. if (!empty($addParams['index'])) {
  951. $args['index'] = $addParams['index'];
  952. }
  953. // log info
  954. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  955. // run request to API and get result
  956. $res = $this->_sendToAPI(__FUNCTION__, $args);
  957. // verify and return
  958. if (isset($res->data)) {
  959. return $res->data;
  960. } else {
  961. return false;
  962. }
  963. }
  964. /**
  965. * Reset parent control
  966. * @param array $params
  967. * accept parametters:
  968. * account OR email OR id OR ds_account
  969. * examples:
  970. * array('account' => 'test')
  971. * array('email' => 'test@test.com')
  972. * array('id' => 42)
  973. * array('ds_account' => 'test')
  974. *
  975. * @return integer|false false or integer - status
  976. */
  977. public function resetParentControl($params) {
  978. // verify parametters
  979. if (empty($params)) {
  980. $this->_toLog('[' . __FUNCTION__ . '] - `$params` is empty');
  981. return false;
  982. }
  983. // prepare arguments array
  984. $args = $this->_prepareAccountDefaultData($params);
  985. // verify arguments
  986. if (empty($args)) {
  987. $this->_toLog('[' . __FUNCTION__ . '] - account parametter not found in `$params`');
  988. return false;
  989. }
  990. // log info
  991. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  992. // run request to API and get result
  993. $res = $this->_sendToAPI(__FUNCTION__, $args);
  994. // verify and return
  995. if (isset($res->status)) {
  996. return $res->status;
  997. } else {
  998. return false;
  999. }
  1000. }
  1001. /* --end users functions */
  1002. /* purchases functions */
  1003. /**
  1004. * Enable bundle
  1005. * @param array $params
  1006. * accept parametters:
  1007. * account OR email OR id OR ds_account
  1008. * examples:
  1009. * array('account' => 'test')
  1010. * array('email' => 'test@test.com')
  1011. * array('id' => 42)
  1012. * array('ds_account' => 'test')
  1013. *
  1014. * @param string $subId purchase identificator
  1015. * @param string $type
  1016. * accept parametters:
  1017. * subs_free_device — new contract - 24 months and equipment for 1 uah
  1018. * subs_buy_device — new contract - - buy equipment
  1019. * subs_rent_device — new contract - rent equipment
  1020. * subs_no_device — new contract - no equipment
  1021. * subs_renew — restore the current contract
  1022. *
  1023. * @return integer|false
  1024. */
  1025. public function enableBundle($params, $subId, $type) {
  1026. // verify arguments
  1027. if (empty($params)) {
  1028. $this->_toLog('[' . __FUNCTION__ . '] - `$params` is empty');
  1029. return false;
  1030. }
  1031. if (empty($subId)) {
  1032. $this->_toLog('[' . __FUNCTION__ . '] - `$subId` is empty');
  1033. return false;
  1034. }
  1035. if (empty($type)) {
  1036. $this->_toLog('[' . __FUNCTION__ . '] - `$type` is empty');
  1037. return false;
  1038. }
  1039. // prepare arguments array
  1040. $args = $this->_prepareAccountDefaultData($params);
  1041. // verify arguments
  1042. if (empty($args)) {
  1043. $this->_toLog('[' . __FUNCTION__ . '] - account parametter not found in `$params`');
  1044. return false;
  1045. }
  1046. // assign subId
  1047. $args['sub_id'] = $subId;
  1048. // prepare type
  1049. $type = $this->_preparePurchaseType($type);
  1050. // verify type
  1051. if (!$type) {
  1052. $this->_toLog('[' . __FUNCTION__ . '] - `$type` is not correct');
  1053. return false;
  1054. }
  1055. // assign type
  1056. $args['type'] = $type;
  1057. // log info
  1058. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  1059. // run request to API and get result
  1060. $res = $this->_sendToAPI(__FUNCTION__, $args);
  1061. // verify and return
  1062. if (isset($res->data)) {
  1063. return $res->data;
  1064. } else {
  1065. return false;
  1066. }
  1067. }
  1068. /**
  1069. * Disable bundle
  1070. * @param array $params
  1071. * accept parametters:
  1072. * account OR email OR id OR ds_account
  1073. * examples:
  1074. * array('account' => 'test')
  1075. * array('email' => 'test@test.com')
  1076. * array('id' => 42)
  1077. * array('ds_account' => 'test')
  1078. *
  1079. * @param string $subId description
  1080. * @param string $type
  1081. * accept parametters:
  1082. * subs_free_device — new contract - 24 months and equipment for 1 uah
  1083. * subs_buy_device — new contract - - buy equipment
  1084. * subs_rent_device — new contract - rent equipment
  1085. * subs_no_device — new contract - no equipment
  1086. * subs_renew — restore the current contract
  1087. *
  1088. * @return integer|false
  1089. */
  1090. public function disableBundle($params, $subId, $type) {
  1091. // verify parametters
  1092. if (empty($params)) {
  1093. $this->_toLog('[' . __FUNCTION__ . '] - `$params` is empty;');
  1094. return false;
  1095. }
  1096. if (empty($subId)) {
  1097. $this->_toLog('[' . __FUNCTION__ . '] - `$subId` is empty');
  1098. return false;
  1099. }
  1100. if (empty($type)) {
  1101. $this->_toLog('[' . __FUNCTION__ . '] - `$type` is empty');
  1102. return false;
  1103. }
  1104. // prepare arguments array
  1105. $args = $this->_prepareAccountDefaultData($params);
  1106. // verify arguments
  1107. if (empty($args)) {
  1108. $this->_toLog('[' . __FUNCTION__ . '] - account parametter not found in `$params`');
  1109. return false;
  1110. }
  1111. // assign subId
  1112. $args['sub_id'] = $subId;
  1113. // prepare type
  1114. $type = $this->_preparePurchaseType($type);
  1115. // verify type
  1116. if (!$type) {
  1117. $this->_toLog('[' . __FUNCTION__ . '] - `$type` is not correct');
  1118. return false;
  1119. }
  1120. // assign type
  1121. $args['type'] = $type;
  1122. // log info
  1123. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  1124. // run request to API and get result
  1125. $res = $this->_sendToAPI(__FUNCTION__, $args);
  1126. // verify and return
  1127. if (isset($res->data)) {
  1128. return $res->data;
  1129. } else {
  1130. return false;
  1131. }
  1132. }
  1133. /**
  1134. * Check user bundle
  1135. * @param array $params
  1136. * accept parametters:
  1137. * account OR email OR id OR ds_account
  1138. * examples:
  1139. * array('account' => 'test')
  1140. * array('email' => 'test@test.com')
  1141. * array('id' => 42)
  1142. * array('ds_account' => 'test')
  1143. *
  1144. * @param string $subId description
  1145. *
  1146. * @return integer|false
  1147. */
  1148. public function checkBundle($params, $subId) {
  1149. // verify parametters
  1150. if (empty($params)) {
  1151. $this->_toLog('[' . __FUNCTION__ . '] - `$params` is empty');
  1152. return false;
  1153. }
  1154. if (empty($subId)) {
  1155. $this->_toLog('[' . __FUNCTION__ . '] - `$subId` is empty');
  1156. return false;
  1157. }
  1158. // prepare arguments array
  1159. $args = $this->_prepareAccountDefaultData($params);
  1160. // verify arguments
  1161. if (empty($args)) {
  1162. $this->_toLog('[' . __FUNCTION__ . '] - account parametter not found in `$params`');
  1163. return false;
  1164. }
  1165. // assign subId
  1166. $args['sub_id'] = $subId;
  1167. // log info
  1168. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  1169. // run request to API and get result
  1170. $res = $this->_sendToAPI(__FUNCTION__, $args);
  1171. // verify and return
  1172. if (isset($res->data)) {
  1173. return $res->data;
  1174. } else {
  1175. return false;
  1176. }
  1177. }
  1178. /**
  1179. * Change use bundle-subscription
  1180. * @param array $params account params array
  1181. * accept parametters:
  1182. * account OR email OR id OR ds_account
  1183. * examples:
  1184. * array('account' => 'test')
  1185. * array('email' => 'test@test.com')
  1186. * array('id' => 42)
  1187. * array('ds_account' => 'test')
  1188. *
  1189. * @param string $oldSubId old subscription
  1190. * @param string $newSubId new subscription
  1191. * @return integer|false false or integer - status
  1192. */
  1193. public function changeBundle($params, $oldSubId, $newSubId) {
  1194. // verify parametters
  1195. if (empty($params)) {
  1196. $this->_toLog('[' . __FUNCTION__ . '] - `$params` is empty');
  1197. return false;
  1198. }
  1199. if (empty($oldSubId)) {
  1200. $this->_toLog('[' . __FUNCTION__ . '] - `$oldSubId` is empty');
  1201. return false;
  1202. }
  1203. if (empty($newSubId)) {
  1204. $this->_toLog('[' . __FUNCTION__ . '] - `$newSubId` is empty');
  1205. return false;
  1206. }
  1207. // prepare arguments array
  1208. $args = $this->_prepareAccountDefaultData($params);
  1209. // verify arguments
  1210. if (empty($args)) {
  1211. $this->_toLog('[' . __FUNCTION__ . '] - account parametter not found in `$params`');
  1212. return false;
  1213. }
  1214. // assign subscriptions
  1215. $args['old_sub_id'] = $oldSubId;
  1216. $args['new_sub_id'] = $newSubId;
  1217. // log info
  1218. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  1219. // run request to API and get result
  1220. $res = $this->_sendToAPI(__FUNCTION__, $args);
  1221. // verify and return
  1222. if (isset($res->status)) {
  1223. return $res->status;
  1224. } else {
  1225. return false;
  1226. }
  1227. }
  1228. /**
  1229. * Get active provider's purchases
  1230. * @param string $startDate start date of reporting period
  1231. * @param integer $page page number
  1232. * @return object|false
  1233. */
  1234. public function getAllPurchases($startDate, $page = 1) {
  1235. // verify arguments
  1236. if (empty($startDate) || !strtotime($startDate)) {
  1237. $this->_toLog('[' . __FUNCTION__ . '] - parametter `$startDate` is not valida date type');
  1238. return false;
  1239. }
  1240. if (!is_numeric($page) || $page <= 0) {
  1241. $this->_toLog('[' . __FUNCTION__ . '] - `$page` is not numeric os less than 0');
  1242. return false;
  1243. }
  1244. // prepare arguments
  1245. $args = array(
  1246. 'start_date' => $startDate,
  1247. 'page' => $page
  1248. );
  1249. // log info
  1250. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  1251. // run request to API and get result
  1252. $res = $this->_sendToAPI(__FUNCTION__, $args);
  1253. // verify and return
  1254. if (isset($res->data)) {
  1255. return $res->data;
  1256. } else {
  1257. return false;
  1258. }
  1259. }
  1260. /* --end purchases functions */
  1261. /* devices functions */
  1262. /**
  1263. * Add device and bind to user
  1264. * $account is required
  1265. * $serialNumber or $mac is required, but advisable required TWO
  1266. * $binding_code is required for providers that work with purchases for access to additional devices
  1267. * $addParams may assigns 'device_type', 'device_model', 'type'
  1268. *
  1269. * @param string $account user account
  1270. * @param string $serialNumber device serial number
  1271. * @param string $mac mac address
  1272. * @param string $binding_code code for binding
  1273. * @param array $addParams additional params
  1274. * @return integer|false false or integer - status
  1275. */
  1276. public function addDevice($account, $serialNumber = null, $mac = null, $binding_code = null, $addParams = array()) {
  1277. // verify arguments
  1278. if (empty($account)) {
  1279. $this->_toLog('[' . __FUNCTION__ . '] - `$account` not set');
  1280. return false;
  1281. }
  1282. if (empty($serialNumber) && empty($mac)) {
  1283. $this->_toLog('[' . __FUNCTION__ . '] - must set `$serialNumber` or `$mac` or both');
  1284. return false;
  1285. }
  1286. // prepare arguments
  1287. $args = array(
  1288. 'account' => $account
  1289. );
  1290. if (!empty($serialNumber)) {
  1291. $args['serial_number'] = $serialNumber; // assign serial number
  1292. }
  1293. if (!empty($mac)) {
  1294. $args['mac'] = $mac; // assign mac
  1295. }
  1296. if (!empty($binding_code)) {
  1297. $args['binding_code'] = $binding_code; // assign binding code
  1298. }
  1299. // assign additional params
  1300. if (!empty($addParams['device_type'])) {
  1301. $args['device_type'] = $addParams['device_type']; // assign device type
  1302. }
  1303. if (!empty($addParams['device_model'])) {
  1304. $args['device_model'] = $addParams['device_model']; // assign device model
  1305. }
  1306. // assign device type
  1307. if (!empty($addParams['type'])) {
  1308. $args['type'] = $this->_prepareDeviceType($addParams['type']);
  1309. }
  1310. // log info
  1311. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  1312. // run request to API and get result
  1313. $res = $this->_sendToAPI(__FUNCTION__, $args);
  1314. // verify and return
  1315. if (isset($res->status)) {
  1316. return $res->status;
  1317. } else {
  1318. return false;
  1319. }
  1320. }
  1321. /**
  1322. * Unbind device from user
  1323. * $serialNumber or $mac is required, but advisable required TWO
  1324. * $account is NOT required
  1325. * $type may assigns:
  1326. * device_break_contract - end of contract
  1327. * device_change - equipment problem
  1328. *
  1329. * @param string $serialNumber device serial number
  1330. * @param string $mac device mac address
  1331. * @param string $account user account
  1332. * @param string $type device type
  1333. * @return mixed false or result
  1334. */
  1335. public function delDevice($serialNumber = null, $mac = null, $account = null, $type = null) {
  1336. // verify arguments
  1337. if (empty($serialNumber) && empty($mac)) {
  1338. $this->_toLog('[' . __FUNCTION__ . '] - must set `$serialNumber` or `$mac` or both');
  1339. return false;
  1340. }
  1341. // init arguments array
  1342. $args = array();
  1343. if (!empty($serialNumber)) {
  1344. $args['serial_number'] = $serialNumber; // assign serial number
  1345. }
  1346. if (!empty($mac)) {
  1347. $args['mac'] = $mac; // assign mac
  1348. }
  1349. if (!empty($account)) {
  1350. $args['account'] = $account; // assign account
  1351. }
  1352. if (!empty($type) && in_array($type, array('device_break_contract', 'device_change'))) {
  1353. $args['type'] = $type;
  1354. }
  1355. // log info
  1356. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  1357. // run request to API and get result
  1358. $res = $this->_sendToAPI(__FUNCTION__, $args);
  1359. // verify and return
  1360. if (isset($res->status)) {
  1361. return $res->status;
  1362. } else {
  1363. return false;
  1364. }
  1365. }
  1366. /**
  1367. * Check device
  1368. * $serialNumber or $mac is required, but advisable required TWO
  1369. *
  1370. * @param string $serialNumber device serial number
  1371. * @param string $mac device mac address
  1372. * @return mixed false or 0 or object
  1373. */
  1374. public function deviceExists($serialNumber = null, $mac = null) {
  1375. // verify arguments
  1376. if (empty($serialNumber) && empty($mac)) {
  1377. $this->_toLog('[' . __FUNCTION__ . '] - must set `$serialNumber` or `$mac` or both');
  1378. return false;
  1379. }
  1380. // init arguments array
  1381. $args = array();
  1382. if (!empty($serialNumber)) {
  1383. $args['serial_number'] = $serialNumber; // assign serial number
  1384. }
  1385. if (!empty($mac)) {
  1386. $args['mac'] = $mac; // assign mac
  1387. }
  1388. // log info
  1389. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  1390. // run request to API and get result
  1391. $res = $this->_sendToAPI(__FUNCTION__, $args);
  1392. // verify and return
  1393. if (isset($res->data)) {
  1394. return $res->data;
  1395. } else {
  1396. return false;
  1397. }
  1398. }
  1399. /**
  1400. * Return device list
  1401. * @param string $account user account
  1402. * @param string $email user email
  1403. * @param integer $offset offset parametter
  1404. * @param integer $limit limit parametter no more than 1000
  1405. * @return array|false
  1406. */
  1407. public function getDeviceList($account = null, $email = null, $offset = 0, $limit = 1000) {
  1408. // verify arguments
  1409. if (!is_numeric($offset) || $offset < 0) {
  1410. // log info
  1411. $this->_toLog('[' . __FUNCTION__ . '] - `$offset` is incorrect, set to 0', self::WARNING);
  1412. $offset = 0;
  1413. }
  1414. if (!is_numeric($limit) || $limit <= 0 || $limit > 1000) {
  1415. // log info
  1416. $this->_toLog('[' . __FUNCTION__ . '] - `$limit` is incorrect, set to default 1000', self::WARNING);
  1417. $limit = 1000;
  1418. }
  1419. // init arguments array
  1420. $args = array(
  1421. 'offset' => $offset,
  1422. 'limit' => $limit
  1423. );
  1424. if (!empty($account)) {
  1425. $args['account'] = $account; // assign account
  1426. }
  1427. if (empty($args['account']) && !empty($email)) {
  1428. $args['email'] = $email; // assign email
  1429. }
  1430. // log info
  1431. $this->_toLog('[' . __FUNCTION__ . '] - send params: ' . var_export($args, true), self::INFO);
  1432. // run request to API and get result
  1433. $res = $this->_sendToAPI(__FUNCTION__, $args);
  1434. // verify and return
  1435. if (isset($res->data)) {
  1436. return $res->data;
  1437. } else {
  1438. return false;
  1439. }
  1440. }
  1441. /* --end devices functions */
  1442. /* --end API functions */
  1443. }
  1444. // end class