api.megogo.php 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  1. <?php
  2. /**
  3. * Megogo OTT service low-level API
  4. */
  5. class MegogoApi {
  6. /**
  7. * System alter.ini config stored as array key=>value
  8. *
  9. * @var array
  10. */
  11. protected $altCfg = array();
  12. /**
  13. * Partner ID property via MG_PARTNERID
  14. *
  15. * @var string
  16. */
  17. protected $partnerId = '';
  18. /**
  19. * Users ID prefixes via MG_PREFIX
  20. *
  21. * @var string
  22. */
  23. protected $prefix = '';
  24. /**
  25. * Auth salt value via MG_SALT
  26. *
  27. * @var string
  28. */
  29. protected $salt = '';
  30. /**
  31. * subscribe/unsubscribe API URL
  32. *
  33. * @var string
  34. */
  35. protected $urlApi = '';
  36. /**
  37. * Contains web-login URL
  38. *
  39. * @var string
  40. */
  41. protected $urlCms = '';
  42. /**
  43. * Contains default ISP domain to perform users register.
  44. *
  45. * @var string
  46. */
  47. protected $ispDomain = '';
  48. /**
  49. * Authorization API URL
  50. *
  51. * @var string
  52. */
  53. protected $urlAuth = '';
  54. /**
  55. * Web-auth data database abstraction layer placeholder
  56. *
  57. * @var object
  58. */
  59. protected $credentialsDb = '';
  60. public function __construct() {
  61. $this->loadAlter();
  62. $this->setOptions();
  63. $this->initCredentials();
  64. }
  65. /**
  66. * Loads system alter config into private prop
  67. *
  68. * @return void
  69. */
  70. protected function loadAlter() {
  71. global $ubillingConfig;
  72. $this->altCfg = $ubillingConfig->getAlter();
  73. }
  74. /**
  75. * Sets basic configurable options for further usage
  76. *
  77. * @return void
  78. */
  79. protected function setOptions() {
  80. $this->partnerId = $this->altCfg['MG_PARTNERID'];
  81. $this->prefix = $this->altCfg['MG_PREFIX'];
  82. $this->salt = $this->altCfg['MG_SALT'];
  83. $this->ispDomain = @$this->altCfg['MG_DOMAIN'];
  84. $this->urlAuth = 'http://megogo.net/auth/by_partners/';
  85. //Production
  86. $this->urlCms = 'https://cms.megogo.net/';
  87. $this->urlApi = 'http://billing.megogo.net/partners/';
  88. }
  89. /**
  90. * Performs init of credentials database abscration layer
  91. *
  92. * @return void
  93. */
  94. protected function initCredentials() {
  95. $this->credentialsDb = new NyanORM('mg_credentials');
  96. }
  97. /**
  98. * Performs registering user for web auth
  99. *
  100. * @param string $login
  101. * @param string $password
  102. *
  103. * @return void/string on error
  104. */
  105. public function registerWebUser($login, $password) {
  106. $result = '';
  107. $login = trim($login);
  108. $password = trim($password);
  109. //is partner pseudo-mail domain set?
  110. if (!empty($this->ispDomain)) {
  111. if (!empty($login) AND ! empty($password)) {
  112. if (strlen($password) >= 6) {
  113. $userId = $this->prefix . $login;
  114. $queryUrl = $this->urlApi . $this->partnerId . '/user/changeCredentials';
  115. $pseudoMail = $login . '@' . $this->ispDomain;
  116. $requestArr = array(
  117. 'isdn' => $userId,
  118. 'email' => $pseudoMail,
  119. 'password' => $password
  120. );
  121. $requestJson = json_encode($requestArr);
  122. $ch = curl_init($queryUrl);
  123. curl_setopt($ch, CURLOPT_POST, 1);
  124. curl_setopt($ch, CURLOPT_POSTFIELDS, $requestJson);
  125. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  126. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
  127. $resultRaw = curl_exec($ch);
  128. if (!empty($resultRaw)) {
  129. //nothing to see here
  130. $resultRaw = json_decode($resultRaw, true);
  131. }
  132. //log auth data to credentials db
  133. $this->credentialsDb->where('login', '=', $login);
  134. $currentCredentials = $this->credentialsDb->getAll();
  135. if (empty($currentCredentials)) {
  136. $this->credentialsDb->data('isdn', $userId);
  137. $this->credentialsDb->data('login', $login);
  138. $this->credentialsDb->data('email', $pseudoMail);
  139. $this->credentialsDb->data('password', $password);
  140. $this->credentialsDb->create();
  141. } else {
  142. $this->credentialsDb->where('login', '=', $login);
  143. $this->credentialsDb->data('isdn', $userId);
  144. $this->credentialsDb->data('login', $login);
  145. $this->credentialsDb->data('email', $pseudoMail);
  146. $this->credentialsDb->data('password', $password);
  147. $this->credentialsDb->save();
  148. }
  149. } else {
  150. $result .= 'Password must be at least 6 characters long';
  151. }
  152. } else {
  153. $result .= 'Empty password';
  154. }
  155. }
  156. return($result);
  157. }
  158. /**
  159. * Subscribes user to some service
  160. *
  161. * @param string $login Existing user login to subscribe
  162. * @param string $service Valid serviceid
  163. *
  164. * @return bool
  165. */
  166. public function subscribe($login, $service) {
  167. $result = false;
  168. $query = $this->urlApi . $this->partnerId . '/subscription/subscribe?userId=' . $this->prefix . $login . '&serviceId=' . $service;
  169. $queryResult = file_get_contents($query);
  170. if (!empty($queryResult)) {
  171. $queryResult = json_decode($queryResult);
  172. if ($queryResult->successful) {
  173. $result = true;
  174. }
  175. }
  176. return ($result);
  177. }
  178. /**
  179. * Unsubscribes user for some service
  180. *
  181. * @param string $login Existing user login to subscribe
  182. * @param string $service Valid serviceid
  183. *
  184. * @return bool
  185. */
  186. public function unsubscribe($login, $service) {
  187. $result = false;
  188. $query = $this->urlApi . $this->partnerId . '/subscription/unsubscribe?userId=' . $this->prefix . $login . '&serviceId=' . $service;
  189. $queryResult = file_get_contents($query);
  190. if (!empty($queryResult)) {
  191. $queryResult = json_decode($queryResult);
  192. if ($queryResult->successful) {
  193. $result = true;
  194. }
  195. }
  196. return ($result);
  197. }
  198. /**
  199. * Returns auth codes
  200. *
  201. * @param string $login Existing user login
  202. * @return strig
  203. */
  204. public function authCode($login) {
  205. $result = '';
  206. $hashData = $this->prefix . $login . $this->partnerId . $this->salt;
  207. $token = md5($hashData);
  208. $result = $this->urlAuth . 'dialog?isdn=' . $this->prefix . $login . '&partner_key=' . $this->partnerId . '&token=' . $token;
  209. return ($result);
  210. }
  211. }
  212. /**
  213. * Megogo OTT service implementation class
  214. */
  215. class MegogoInterface {
  216. /**
  217. * System alter.ini config stored as array key=>value
  218. *
  219. * @var array
  220. */
  221. protected $altCfg = array();
  222. /**
  223. * System messages object placeholder
  224. *
  225. * @var object
  226. */
  227. protected $messages = '';
  228. /**
  229. * Contains available megogo service tariffs id=>tariffdata
  230. *
  231. * @var array
  232. */
  233. protected $allTariffs = array();
  234. /**
  235. * Contains available and active megogo service subscriptions as id=>data
  236. *
  237. * @var array
  238. */
  239. protected $allSubscribers = array();
  240. /**
  241. * Contains all subscribtions history by all of users id=>data
  242. *
  243. * @var array
  244. */
  245. protected $allHistory = array();
  246. /**
  247. * Contains all of available scheduled actions queue as id => queue data
  248. *
  249. * @var array
  250. */
  251. protected $allQueue = array();
  252. /**
  253. * Contains all of internet users data as login=>data
  254. *
  255. * @var array
  256. */
  257. protected $allUsers = array();
  258. const URL_ME = '?module=megogo';
  259. const URL_TARIFFS = 'tariffs=true';
  260. const URL_SUBS = 'subscriptions=true';
  261. const URL_AJSUBS = 'ajsubs=true';
  262. const URL_SUBVIEW = 'subview=true';
  263. const URL_REPORTS = 'reports=true';
  264. public function __construct() {
  265. $this->loadAlter();
  266. $this->initMessages();
  267. $this->loadUsers();
  268. $this->loadTariffs();
  269. $this->loadSubscribers();
  270. $this->loadHistory();
  271. $this->loadQueue();
  272. }
  273. /**
  274. * Loads system alter config into private prop
  275. *
  276. * @return void
  277. */
  278. protected function loadAlter() {
  279. global $ubillingConfig;
  280. $this->altCfg = $ubillingConfig->getAlter();
  281. }
  282. /**
  283. * Initializes system message helper
  284. *
  285. * @return void
  286. */
  287. protected function initMessages() {
  288. $this->messages = new UbillingMessageHelper();
  289. }
  290. /**
  291. * Loads existing tariffs from database for further usage
  292. *
  293. * @return void
  294. */
  295. protected function loadTariffs() {
  296. $query = "SELECT * from `mg_tariffs`";
  297. $all = simple_queryall($query);
  298. if (!empty($all)) {
  299. foreach ($all as $io => $each) {
  300. $this->allTariffs[$each['id']] = $each;
  301. }
  302. }
  303. }
  304. /**
  305. * Loads existing subscribers data
  306. *
  307. * @return void
  308. */
  309. protected function loadSubscribers() {
  310. $query = "SELECT * from `mg_subscribers`";
  311. $all = simple_queryall($query);
  312. if (!empty($all)) {
  313. foreach ($all as $io => $each) {
  314. $this->allSubscribers[$each['id']] = $each;
  315. }
  316. }
  317. }
  318. /**
  319. * Loads existing subscribers data
  320. *
  321. * @return void
  322. */
  323. protected function loadHistory() {
  324. $query = "SELECT * from `mg_history`";
  325. $all = simple_queryall($query);
  326. if (!empty($all)) {
  327. foreach ($all as $io => $each) {
  328. $this->allHistory[$each['id']] = $each;
  329. }
  330. }
  331. }
  332. /**
  333. * Loads scheduled queue from database
  334. *
  335. * @return void
  336. */
  337. protected function loadQueue() {
  338. $query = "SELECT * from `mg_queue`";
  339. $all = simple_queryall($query);
  340. if (!empty($all)) {
  341. foreach ($all as $io => $each) {
  342. $this->allQueue[$each['id']] = $each;
  343. }
  344. }
  345. }
  346. /**
  347. * Loads available users from database
  348. *
  349. * @return void
  350. */
  351. protected function loadUsers() {
  352. $all = zb_UserGetAllStargazerData();
  353. if (!empty($all)) {
  354. foreach ($all as $io => $each) {
  355. $this->allUsers[$each['login']] = $each;
  356. }
  357. }
  358. }
  359. /**
  360. * Returns tariffs Megogo service ID
  361. *
  362. * @param int $tariffid
  363. *
  364. * @return string
  365. */
  366. public function getTariffServiceId($tariffid) {
  367. $tariffid = vf($tariffid, 3);
  368. $result = '';
  369. if (!empty($this->allTariffs)) {
  370. foreach ($this->allTariffs as $io => $each) {
  371. if ($each['id'] == $tariffid) {
  372. $result = $each['serviceid'];
  373. break;
  374. }
  375. }
  376. }
  377. return ($result);
  378. }
  379. /**
  380. * Returns tariffs price
  381. *
  382. * @param int $tariffid
  383. *
  384. * @return float
  385. */
  386. public function getTariffFee($tariffid) {
  387. $tariffid = vf($tariffid, 3);
  388. $result = 0;
  389. if (!empty($this->allTariffs)) {
  390. foreach ($this->allTariffs as $io => $each) {
  391. if ($each['id'] == $tariffid) {
  392. $result = $each['fee'];
  393. break;
  394. }
  395. }
  396. }
  397. return ($result);
  398. }
  399. /**
  400. * Checks free period availability for user
  401. *
  402. * @param string $login
  403. *
  404. * @return bool
  405. */
  406. protected function checkFreePeriodAvail($login) {
  407. $query = "SELECT * from `mg_history` WHERE `login`='" . $login . "' AND `freeperiod`='1';";
  408. $raw = simple_query($query);
  409. $result = (empty($raw)) ? true : false;
  410. return ($result);
  411. }
  412. /**
  413. * Check user tariff subscribtion possibility
  414. *
  415. * @param string $login
  416. * @param int $tariffid
  417. *
  418. * @return bool
  419. */
  420. protected function checkTariffAvail($login, $tariffid) {
  421. $result = true;
  422. $tariffid = vf($tariffid, 3);
  423. if (!empty($this->allSubscribers)) {
  424. foreach ($this->allSubscribers as $io => $each) {
  425. if (($each['login'] == $login) AND ( $each['tariffid'] == $tariffid)) {
  426. $result = false;
  427. break;
  428. }
  429. }
  430. }
  431. return ($result);
  432. }
  433. /**
  434. * Checks user for only one primary subscription
  435. *
  436. * @param string $login
  437. *
  438. * @return bool
  439. */
  440. protected function checkTariffPrimary($login, $tariffid) {
  441. $result = true;
  442. $tariffData = $this->allTariffs[$tariffid];
  443. $tariffPrimary = $tariffData['primary'];
  444. if ($tariffPrimary) {
  445. if (!empty($this->allSubscribers)) {
  446. foreach ($this->allSubscribers as $io => $each) {
  447. if ($each['primary'] == 1) {
  448. if ($each['login'] == $login) {
  449. $result = false;
  450. break;
  451. }
  452. }
  453. }
  454. }
  455. }
  456. return ($result);
  457. }
  458. /**
  459. * Returns valid dayly fee for some tariff/month
  460. *
  461. * @param float $tariffFee
  462. *
  463. * @return float
  464. */
  465. protected function getDaylyFee($tariffFee) {
  466. $monthDays = date("t");
  467. $result = round(($tariffFee / $monthDays), 2);
  468. return ($result);
  469. }
  470. /**
  471. * Create subscription
  472. *
  473. * @param string $login
  474. * @param int $tariffid
  475. *
  476. * @return void/string on error
  477. */
  478. public function createSubscribtion($login, $tariffid) {
  479. $curdatetime = curdatetime();
  480. $loginF = mysql_real_escape_string($login);
  481. $tariffid = vf($tariffid, 3);
  482. $activeFlag = 1;
  483. $freePeriodFlag = 0;
  484. $result = '';
  485. if (isset($this->allUsers[$login])) {
  486. if (isset($this->allTariffs[$tariffid])) {
  487. if ($this->checkTariffAvail($login, $tariffid)) {
  488. if ($this->checkTariffPrimary($login, $tariffid)) {
  489. $tariffData = $this->allTariffs[$tariffid];
  490. if ($tariffData['freeperiod']) {
  491. $freePeriodFlag = ($this->checkFreePeriodAvail($login)) ? 1 : 0;
  492. }
  493. $query = "INSERT INTO `mg_subscribers` (`id`,`login`,`tariffid`,`actdate`,`active`,`primary`,`freeperiod`) VALUES";
  494. $query .= "(NULL,'" . $loginF . "','" . $tariffid . "','" . $curdatetime . "','" . $activeFlag . "','" . $tariffData['primary'] . "','" . $freePeriodFlag . "');";
  495. nr_query($query);
  496. log_register('MEGOGO SUBSCRIBE (' . $login . ') TARIFF [' . $tariffid . ']');
  497. $mgApi = new MegogoApi();
  498. $mgApi->subscribe($login, $tariffData['serviceid']);
  499. $userSystemData = $this->allUsers[$login];
  500. //TODO: remove following IF statement or replace with normal mechanics
  501. if (!empty($userSystemData['Password'])) {
  502. $webRegisterResult = $mgApi->registerWebUser($login, $userSystemData['Password']);
  503. if (!empty($webRegisterResult)) {
  504. $result = $webRegisterResult;
  505. }
  506. } else {
  507. $result = 'Empty password';
  508. }
  509. log_register('MEGOGO ACTIVATED (' . $login . ') SERVICE [' . $tariffData['serviceid'] . ']');
  510. //force fee
  511. if (!$freePeriodFlag) {
  512. if ($this->altCfg['MG_SPREAD']) {
  513. //charge fee only for current day
  514. if ($this->altCfg['MG_SPREAD'] == 1) {
  515. $tariffFee = $this->getTariffFee($tariffid);
  516. $tariffFee = $this->getDaylyFee($tariffFee);
  517. }
  518. //charge fee to the end of month
  519. if ($this->altCfg['MG_SPREAD'] == 2) {
  520. $tariffFee = $this->getTariffFee($tariffid);
  521. $currentDayOfMonth = date("d");
  522. $currentMonthDayCount = date("t");
  523. $tariffFeeDaily = $this->getDaylyFee($tariffFee);
  524. $tariffFee = ($currentMonthDayCount - $currentDayOfMonth) * $tariffFeeDaily;
  525. }
  526. } else {
  527. //charge full monthly fee
  528. $tariffFee = $this->getTariffFee($tariffid);
  529. }
  530. zb_CashAdd($login, '-' . $tariffFee, 'add', 1, 'MEGOGO:' . $tariffid);
  531. log_register('MEGOGO FEE (' . $login . ') -' . $tariffFee);
  532. } else {
  533. //free period mark for reports
  534. zb_CashAdd($login, '-0', 'add', 1, 'MEGOGO:' . $tariffid);
  535. log_register('MEGOGO FEE (' . $login . ') -0');
  536. }
  537. $queryHistory = "INSERT INTO `mg_history` (`id`,`login`,`tariffid`,`actdate`,`freeperiod`) VALUES";
  538. $queryHistory .= "(NULL,'" . $loginF . "','" . $tariffid . "','" . $curdatetime . "','" . $freePeriodFlag . "');";
  539. nr_query($queryHistory);
  540. } else {
  541. $result = 'Only one primary tariff allowed';
  542. }
  543. } else {
  544. $result = 'Already subscribed';
  545. }
  546. } else {
  547. $result = 'Wrong tariff';
  548. }
  549. } else {
  550. $result = 'Non existent user';
  551. }
  552. return ($result);
  553. }
  554. /**
  555. * Deletes existing subscription
  556. *
  557. * @param string $login
  558. * @param int $tariffid
  559. *
  560. * @return void
  561. */
  562. public function deleteSubscribtion($login, $tariffid) {
  563. $curdatetime = curdatetime();
  564. $loginF = mysql_real_escape_string($login);
  565. $tariffid = vf($tariffid, 3);
  566. $activeFlag = 1;
  567. if (isset($this->allTariffs[$tariffid])) {
  568. $tariffData = $this->allTariffs[$tariffid];
  569. $query = "DELETE from `mg_subscribers` WHERE `login`='" . $loginF . "' AND `tariffid`='" . $tariffid . "';";
  570. nr_query($query);
  571. log_register('MEGOGO UNSUBSCRIBE (' . $login . ') TARIFF [' . $tariffid . ']');
  572. $mgApi = new MegogoApi();
  573. $mgApi->unsubscribe($login, $tariffData['serviceid']);
  574. log_register('MEGOGO DEACTIVATED (' . $login . ') SERVICE [' . $tariffData['serviceid'] . ']');
  575. }
  576. }
  577. /**
  578. * Returns primary controls panel
  579. *
  580. * @return string
  581. */
  582. public function renderPanel() {
  583. $result = '';
  584. $result .= wf_Link(self::URL_ME . '&' . self::URL_SUBS, wf_img('skins/ukv/users.png') . ' ' . __('Subscriptions'), false, 'ubButton') . ' ';
  585. $result .= wf_Link(self::URL_ME . '&' . self::URL_TARIFFS, wf_img('skins/ukv/dollar.png') . ' ' . __('Tariffs'), false, 'ubButton') . ' ';
  586. $result .= wf_Link(self::URL_ME . '&' . self::URL_REPORTS, wf_img('skins/ukv/report.png') . ' ' . __('Reports'), false, 'ubButton') . ' ';
  587. return ($result);
  588. }
  589. /**
  590. * Renders available tariffs list
  591. *
  592. * @return string
  593. */
  594. public function renderTariffs() {
  595. $result = '';
  596. $cells = wf_TableCell(__('ID'));
  597. $cells .= wf_TableCell(__('Tariff name'));
  598. $cells .= wf_TableCell(__('Fee'));
  599. $cells .= wf_TableCell(__('Service ID'));
  600. $cells .= wf_TableCell(__('Primary'));
  601. $cells .= wf_TableCell(__('Free period'));
  602. $cells .= wf_TableCell(__('Actions'));
  603. $rows = wf_TableRow($cells, 'row1');
  604. if (!empty($this->allTariffs)) {
  605. foreach ($this->allTariffs as $io => $each) {
  606. $cells = wf_TableCell($each['id']);
  607. $cells .= wf_TableCell($each['name']);
  608. $cells .= wf_TableCell($each['fee']);
  609. $cells .= wf_TableCell($each['serviceid']);
  610. $cells .= wf_TableCell(web_bool_led($each['primary']));
  611. $cells .= wf_TableCell(web_bool_led($each['freeperiod']));
  612. $actLinks = wf_JSAlert(self::URL_ME . '&' . self::URL_TARIFFS . '&deletetariffid=' . $each['id'], web_delete_icon(), $this->messages->getDeleteAlert());
  613. $actLinks .= wf_modalAuto(web_edit_icon(), __('Edit tariff'), $this->tariffEditForm($each['id']));
  614. $cells .= wf_TableCell($actLinks);
  615. $rows .= wf_TableRow($cells, 'row3');
  616. }
  617. }
  618. $result = wf_TableBody($rows, '100%', 0, 'sortable');
  619. return ($result);
  620. }
  621. /**
  622. * Returns tariff creation form
  623. *
  624. * @return string
  625. */
  626. public function tariffCreateForm() {
  627. $result = '';
  628. $inputs = wf_TextInput('newtariffname', __('Tariff name'), '', true, '20');
  629. $inputs .= wf_TextInput('newtarifffee', __('Fee'), '', true, '5');
  630. $inputs .= wf_TextInput('newtariffserviceid', __('Service ID'), '', true, '10');
  631. $inputs .= wf_CheckInput('newtariffprimary', __('Primary'), true, false);
  632. $inputs .= wf_CheckInput('newtarifffreeperiod', __('Free period'), true, false);
  633. $inputs .= wf_Submit(__('Create'));
  634. $result = wf_Form('', 'POST', $inputs, 'glamour');
  635. return ($result);
  636. }
  637. /**
  638. * Returns tariff editing form
  639. *
  640. * @param int $tariffId
  641. *
  642. * @return string
  643. */
  644. protected function tariffEditForm($tariffId) {
  645. $result = '';
  646. $inputs = wf_HiddenInput('edittariffid', $tariffId);
  647. $inputs .= wf_TextInput('edittariffname', __('Tariff name'), $this->allTariffs[$tariffId]['name'], true, '20');
  648. $inputs .= wf_TextInput('edittarifffee', __('Fee'), $this->allTariffs[$tariffId]['fee'], true, '5');
  649. $inputs .= wf_TextInput('edittariffserviceid', __('Service ID'), $this->allTariffs[$tariffId]['serviceid'], true, '10');
  650. $primaryFlag = ($this->allTariffs[$tariffId]['primary']) ? true : false;
  651. $inputs .= wf_CheckInput('edittariffprimary', __('Primary'), true, $primaryFlag);
  652. $freePeriodFlag = ($this->allTariffs[$tariffId]['freeperiod']) ? true : false;
  653. $inputs .= wf_CheckInput('edittarifffreeperiod', __('Free period'), true, $freePeriodFlag);
  654. $inputs .= wf_Submit(__('Save'));
  655. $result = wf_Form('', 'POST', $inputs, 'glamour');
  656. return ($result);
  657. }
  658. /**
  659. * Catches tariff editing form data
  660. *
  661. * @return void/string on error
  662. */
  663. public function tariffSave() {
  664. $result = '';
  665. if (wf_CheckPost(array('edittariffid', 'edittariffname', 'edittarifffee', 'edittariffserviceid'))) {
  666. $tariffId = vf($_POST['edittariffid'], 3);
  667. if (isset($this->allTariffs[$tariffId])) {
  668. $where = " WHERE `id`='" . $tariffId . "';";
  669. $primaryFlag = (wf_CheckPost(array('edittariffprimary'))) ? 1 : 0;
  670. $freeperiodFlag = (wf_CheckPost(array('edittarifffreeperiod'))) ? 1 : 0;
  671. simple_update_field('mg_tariffs', 'name', $_POST['edittariffname'], $where);
  672. simple_update_field('mg_tariffs', 'fee', $_POST['edittarifffee'], $where);
  673. simple_update_field('mg_tariffs', 'serviceid', $_POST['edittariffserviceid'], $where);
  674. simple_update_field('mg_tariffs', 'primary', $primaryFlag, $where);
  675. simple_update_field('mg_tariffs', 'freeperiod', $freeperiodFlag, $where);
  676. log_register('MEGOGO TARIFF EDIT [' . $tariffId . '] `' . $_POST['edittariffname'] . '` FEE `' . $_POST['edittarifffee'] . '`');
  677. }
  678. } else {
  679. $result = $this->messages->getStyledMessage(__('No all of required fields is filled'), 'error');
  680. }
  681. return ($result);
  682. }
  683. /**
  684. * Creates new tariff in database
  685. *
  686. * @return void/string on error
  687. */
  688. public function tariffCreate() {
  689. $result = '';
  690. if (wf_CheckPost(array('newtariffname', 'newtarifffee', 'newtariffserviceid'))) {
  691. $nameF = mysql_real_escape_string($_POST['newtariffname']);
  692. $feeF = mysql_real_escape_string($_POST['newtarifffee']);
  693. $serviceidF = mysql_real_escape_string($_POST['newtariffserviceid']);
  694. $primary = wf_CheckPost(array('newtariffprimary')) ? 1 : 0;
  695. $freePeriod = wf_CheckPost(array('newtarifffreeperiod')) ? 1 : 0;
  696. if (zb_checkMoney($feeF)) {
  697. $query = "INSERT INTO `mg_tariffs` (`id`,`name`,`fee`,`serviceid`,`primary`,`freeperiod`) VALUES ";
  698. $query .= "(NULL,'" . $nameF . "','" . $feeF . "','" . $serviceidF . "','" . $primary . "','" . $freePeriod . "')";
  699. nr_query($query);
  700. $newId = simple_get_lastid('mg_tariffs');
  701. log_register('MEGOGO TARIFF CREATE [' . $newId . '] `' . $_POST['newtariffname'] . '` FEE `' . $_POST['newtarifffee'] . '`');
  702. } else {
  703. $result = $this->messages->getStyledMessage(__('Wrong format of a sum of money to pay'), 'error');
  704. }
  705. } else {
  706. $result = $this->messages->getStyledMessage(__('No all of required fields is filled'), 'error');
  707. }
  708. return ($result);
  709. }
  710. /**
  711. * Checks is tariff used by some users
  712. *
  713. * @param int $tariffid
  714. *
  715. * @return bool
  716. */
  717. protected function tariffProtected($tariffid) {
  718. $result = false;
  719. if (!empty($this->allSubscribers)) {
  720. foreach ($this->allSubscribers as $io => $each) {
  721. if ($each['tariffid'] == $tariffid) {
  722. $result = true;
  723. break;
  724. }
  725. }
  726. }
  727. return ($result);
  728. }
  729. /**
  730. * Deletes existing tariff from database
  731. *
  732. * @param int $tariffId
  733. *
  734. * @return void/string
  735. */
  736. public function tariffDelete($tariffId) {
  737. $tariffId = vf($tariffId, 3);
  738. $result = '';
  739. if (isset($this->allTariffs[$tariffId])) {
  740. if (!$this->tariffProtected($tariffId)) {
  741. $query = "DELETE from `mg_tariffs` WHERE `id`='" . $tariffId . "';";
  742. nr_query($query);
  743. log_register('MEGOGO TARIFF DELETE [' . $tariffId . ']');
  744. } else {
  745. $result = $this->messages->getStyledMessage(__('Tariff is used by some users'), 'error');
  746. }
  747. } else {
  748. $result = $this->messages->getStyledMessage(__('Not existing item'), 'error');
  749. }
  750. return ($result);
  751. }
  752. /**
  753. * Colorize important report columns
  754. *
  755. * @param string $data
  756. *
  757. * @return string
  758. */
  759. protected function colorImportant($data) {
  760. $result = '';
  761. if (!empty($data)) {
  762. $result .= wf_tag('font', false, '', 'color="#900000"') . $data . wf_tag('font', 'true');
  763. }
  764. return($result);
  765. }
  766. /**
  767. * Renders default subscriptions report
  768. *
  769. * @return string
  770. */
  771. public function renderSubscribtionsReportMonthly() {
  772. $result = '';
  773. //custom profit percents here
  774. $custPercents = array();
  775. if (isset($this->altCfg['MG_CUSTOM_PERCENTS'])) {
  776. if (!empty($this->altCfg['MG_CUSTOM_PERCENTS'])) {
  777. $custRaw = explode(',', $this->altCfg['MG_CUSTOM_PERCENTS']);
  778. if (!empty($custRaw)) {
  779. foreach ($custRaw as $io => $each) {
  780. $each = explode(':', $each);
  781. $custPercents[$each[0]] = $each[1];
  782. }
  783. }
  784. }
  785. }
  786. $selectedMonth = (wf_CheckPost(array('monthsel'))) ? $_POST['monthsel'] : date("m");
  787. $selectedYear = (wf_CheckPost(array('yearsel'))) ? $_POST['yearsel'] : date("Y");
  788. $inputs = wf_YearSelectorPreset('yearsel', __('Year'), false, $selectedYear) . ' ';
  789. $inputs .= wf_MonthSelector('monthsel', __('Month'), $selectedMonth, false) . ' ';
  790. $inputs .= wf_Submit(__('Show'));
  791. $result .= wf_Form('', 'POST', $inputs, 'glamour');
  792. $curYear = (wf_CheckPost(array('yearsel'))) ? vf($_POST['yearsel'], 3) : curyear();
  793. $curMonth = (wf_CheckPost(array('monthsel'))) ? vf($_POST['monthsel'], 3) : date("m");
  794. $query = "SELECT * from `payments` WHERE `date` LIKE '" . $curYear . "-" . $curMonth . "%' AND `note` LIKE 'MEGOGO:%';";
  795. $raw = simple_queryall($query);
  796. $tmpArr = array();
  797. if (!empty($raw)) {
  798. foreach ($raw as $io => $each) {
  799. $tariffId = explode(':', $each['note']);
  800. $tariffId = $tariffId[1];
  801. if (isset($tmpArr[$tariffId])) {
  802. $tmpArr[$tariffId]['summ'] = $tmpArr[$tariffId]['summ'] + abs($each['summ']);
  803. $tmpArr[$tariffId]['count'] ++;
  804. //try&buy user
  805. if ($each['summ'] == 0) {
  806. $tmpArr[$tariffId]['freeperiod'] ++;
  807. }
  808. } else {
  809. $tmpArr[$tariffId]['summ'] = abs($each['summ']);
  810. $tmpArr[$tariffId]['count'] = 1;
  811. //try&buy user
  812. if ($each['summ'] == 0) {
  813. $tmpArr[$tariffId]['freeperiod'] = 1;
  814. } else {
  815. $tmpArr[$tariffId]['freeperiod'] = 0;
  816. }
  817. }
  818. }
  819. }
  820. if (!empty($tmpArr)) {
  821. $cells = wf_TableCell(__('Tariff'));
  822. $cells .= wf_TableCell(__('Fee'));
  823. $cells .= wf_TableCell(__('Users'));
  824. $cells .= wf_TableCell(__('Free period'));
  825. $cells .= wf_TableCell(__('Total payments'));
  826. $cells .= wf_TableCell(__('Payouts for Megogo'));
  827. $cells .= wf_TableCell(__('Our profit'));
  828. $rows = wf_TableRow($cells, 'row1');
  829. $totalUsers = 0;
  830. $totalFree = 0;
  831. $totalSumm = 0;
  832. $totalPayout = 0;
  833. foreach ($tmpArr as $io => $each) {
  834. $totalUsers = $totalUsers + $each['count'];
  835. $totalFree = $totalFree + $each['freeperiod'];
  836. $totalSumm = $totalSumm + $each['summ'];
  837. $tariffPercent = (isset($custPercents[$io])) ? $custPercents[$io] : $this->altCfg['MG_PERCENT'];
  838. $ourProfit = zb_Percent($each['summ'], $tariffPercent);
  839. $megogoPayout = $each['summ'] - $ourProfit;
  840. $totalPayout = $totalPayout + $megogoPayout;
  841. $cells = wf_TableCell(@$this->allTariffs[$io]['name']);
  842. $cells .= wf_TableCell(@$this->allTariffs[$io]['fee']);
  843. $cells .= wf_TableCell($each['count']);
  844. $cells .= wf_TableCell($each['freeperiod']);
  845. $cells .= wf_TableCell($each['summ']);
  846. $cells .= wf_TableCell($this->colorImportant($megogoPayout));
  847. $cells .= wf_TableCell($ourProfit);
  848. $rows .= wf_TableRow($cells, 'row5');
  849. }
  850. $cells = wf_TableCell(wf_tag('b') . __('Total') . wf_tag('b', true));
  851. $cells .= wf_TableCell('');
  852. $cells .= wf_TableCell($totalUsers);
  853. $cells .= wf_TableCell($totalFree);
  854. $cells .= wf_TableCell($totalSumm);
  855. $cells .= wf_TableCell($this->colorImportant($totalPayout));
  856. $cells .= wf_TableCell(zb_Percent($totalSumm, $tariffPercent));
  857. $rows .= wf_TableRow($cells, 'row2');
  858. $result .= wf_TableBody($rows, '100%', 0, '');
  859. } else {
  860. $result .= $this->messages->getStyledMessage(__('Nothing found'), 'info');
  861. }
  862. return ($result);
  863. }
  864. /**
  865. * Performs basic data filtering
  866. *
  867. * @param string $data
  868. *
  869. * @return string
  870. */
  871. protected function jqDtFilter($data) {
  872. $result = trim($data);
  873. $result = str_replace('"', '', $result);
  874. return ($result);
  875. }
  876. /**
  877. * Renders default subscriptions report
  878. *
  879. * @return string
  880. */
  881. public function renderSubscribtionsReportDaily() {
  882. $result = '';
  883. $defaultDateTo = strtotime(curdate()) + 86400;
  884. $defaultDateTo = date("Y-m-d", $defaultDateTo);
  885. $inputs = wf_DatePickerPreset('datefrom', date("Y-m") . '-01', true);
  886. $inputs .= wf_DatePickerPreset('dateto', $defaultDateTo, true);
  887. $inputs .= wf_Submit(__('Show'));
  888. $result .= wf_Form('', 'POST', $inputs, 'glamour');
  889. $dateFrom = (wf_CheckPost(array('datefrom'))) ? mysql_real_escape_string($_POST['datefrom']) : date("Y-m") . '-01';
  890. $dateTo = (wf_CheckPost(array('dateto'))) ? mysql_real_escape_string($_POST['dateto']) : $defaultDateTo;
  891. $query = "SELECT * from `payments` WHERE `date` BETWEEN '" . $dateFrom . "' AND '" . $dateTo . "' AND `note` LIKE 'MEGOGO:%';";
  892. $raw = simple_queryall($query);
  893. $totalSumm = 0;
  894. $tmpArr = array();
  895. if (!empty($raw)) {
  896. foreach ($raw as $io => $each) {
  897. $tariffId = explode(':', $each['note']);
  898. $tariffId = $tariffId[1];
  899. if (isset($tmpArr[$tariffId])) {
  900. $tmpArr[$tariffId]['summ'] = $tmpArr[$tariffId]['summ'] + abs($each['summ']);
  901. $tmpArr[$tariffId]['count'] ++;
  902. //try&buy user
  903. if ($each['summ'] == 0) {
  904. $tmpArr[$tariffId]['freeperiod'] ++;
  905. }
  906. } else {
  907. $tmpArr[$tariffId]['summ'] = abs($each['summ']);
  908. $tmpArr[$tariffId]['count'] = 1;
  909. //try&buy user
  910. if ($each['summ'] == 0) {
  911. $tmpArr[$tariffId]['freeperiod'] = 1;
  912. } else {
  913. $tmpArr[$tariffId]['freeperiod'] = 0;
  914. }
  915. }
  916. }
  917. if (!empty($tmpArr)) {
  918. $cells = wf_TableCell(__('Tariff'));
  919. $cells .= wf_TableCell(__('Fee') . ' / ' . __('month'));
  920. $cells .= wf_TableCell(__('days'));
  921. $cells .= wf_TableCell(__('Free period'));
  922. $cells .= wf_TableCell(__('Total payments'));
  923. $cells .= wf_TableCell(__('Profit'));
  924. $rows = wf_TableRow($cells, 'row1');
  925. foreach ($tmpArr as $io => $each) {
  926. $cells = wf_TableCell(@$this->allTariffs[$io]['name']);
  927. $cells .= wf_TableCell(@$this->allTariffs[$io]['fee']);
  928. $cells .= wf_TableCell($each['count']);
  929. $cells .= wf_TableCell($each['freeperiod']);
  930. $cells .= wf_TableCell($each['summ']);
  931. $cells .= wf_TableCell(zb_Percent($each['summ'], $this->altCfg['MG_PERCENT']));
  932. $rows .= wf_TableRow($cells, 'row3');
  933. $totalSumm = $totalSumm + $each['summ'];
  934. }
  935. $cells = wf_TableCell(wf_tag('b') . __('Total') . wf_tag('b', true));
  936. $cells .= wf_TableCell('');
  937. $cells .= wf_TableCell('');
  938. $cells .= wf_TableCell('');
  939. $cells .= wf_TableCell($totalSumm);
  940. $cells .= wf_TableCell(zb_Percent($totalSumm, $this->altCfg['MG_PERCENT']));
  941. $rows .= wf_TableRow($cells, 'row2');
  942. $result .= wf_TableBody($rows, '100%', 0, '');
  943. }
  944. } else {
  945. $result .= $this->messages->getStyledMessage(__('Nothing found'), 'info');
  946. }
  947. return ($result);
  948. }
  949. /**
  950. * Returns data container for active subscriptions
  951. *
  952. * @return string
  953. */
  954. public function renderSubscribtions() {
  955. $result = '';
  956. $columns = array(('ID'), ('Login'), ('Full address'), ('Real Name'), ('Cash'), ('Current tariff'), ('Date'), ('Active'), ('Primary'), ('Free period'), ('Actions'));
  957. $result = wf_JqDtLoader($columns, self::URL_ME . '&' . self::URL_SUBS . '&' . self::URL_AJSUBS, true, __('Subscriptions'), '100');
  958. return ($result);
  959. }
  960. /**
  961. * Renders ajax data subscriptions
  962. *
  963. * @return void
  964. */
  965. public function subscribtionsListAjax() {
  966. $allAddress = zb_AddressGetFulladdresslistCached();
  967. $allRealNames = zb_UserGetAllRealnames();
  968. $allBalance = zb_UserGetAllBalance();
  969. $json = new wf_JqDtHelper();
  970. if (!empty($this->allSubscribers)) {
  971. foreach ($this->allSubscribers as $io => $each) {
  972. $userLink = wf_Link('?module=userprofile&username=' . $each['login'], web_profile_icon() . ' ' . $each['login'], false);
  973. $userLink = $this->jqDtFilter($userLink);
  974. @$address = $this->jqDtFilter($allAddress[$each['login']]);
  975. @$userRealName = $this->jqDtFilter($allRealNames[$each['login']]);
  976. $actFlag = ($each['active']) ? web_bool_led(true, false) . ' ' . __('Yes') : web_bool_led(false, false) . ' ' . __('No');
  977. $actFlag = $this->jqDtFilter($actFlag);
  978. $primFlag = ($each['primary']) ? web_bool_led(true, false) . ' ' . __('Yes') : web_bool_led(false, false) . ' ' . __('No');
  979. $primFlag = $this->jqDtFilter($primFlag);
  980. $freeperiodFlag = ($each['freeperiod']) ? web_bool_led(true, false) . ' ' . __('Yes') : web_bool_led(false, false) . ' ' . __('No');
  981. $freeperiodFlag = $this->jqDtFilter($freeperiodFlag);
  982. $actLinks = wf_Link(self::URL_ME . '&' . self::URL_SUBVIEW . '&subid=' . $each['id'], wf_img('skins/icon_edit.gif'));
  983. $actLinks = $this->jqDtFilter($actLinks);
  984. @$userCash = $this->jqDtFilter($allBalance[$each['login']]);
  985. $data[] = $each['id'];
  986. $data[] = $userLink;
  987. $data[] = $address;
  988. $data[] = $userRealName;
  989. $data[] = $userCash;
  990. $data[] = @$this->allTariffs[$each['tariffid']]['name'];
  991. $data[] = $each['actdate'];
  992. $data[] = $actFlag;
  993. $data[] = $primFlag;
  994. $data[] = $freeperiodFlag;
  995. $data[] = $actLinks;
  996. $json->addRow($data);
  997. unset($data);
  998. }
  999. }
  1000. $json->getJson();
  1001. }
  1002. /**
  1003. * Renders subscribtion management form
  1004. *
  1005. * @param int $subId
  1006. *
  1007. * @return string
  1008. */
  1009. public function renderSubManagerForm($subId) {
  1010. $subId = vf($subId, 3);
  1011. $result = '';
  1012. if (isset($this->allSubscribers[$subId])) {
  1013. $baseUrl = self::URL_ME . '&' . self::URL_SUBVIEW . '&subid=' . $subId;
  1014. $subData = $this->allSubscribers[$subId];
  1015. $cells = wf_TableCell(__('ID'));
  1016. $cells .= wf_TableCell(__('User'));
  1017. $cells .= wf_TableCell(__('Tariff'));
  1018. $cells .= wf_TableCell(__('Date'));
  1019. $cells .= wf_TableCell(__('Active'));
  1020. $cells .= wf_TableCell(__('Primary'));
  1021. $cells .= wf_TableCell(__('Free period'));
  1022. $rows = wf_TableRow($cells, 'row1');
  1023. $cells = wf_TableCell($subData['id']);
  1024. $cells .= wf_TableCell(wf_Link('?module=userprofile&username=' . $subData['login'], web_profile_icon() . ' ' . $subData['login']));
  1025. $cells .= wf_TableCell($this->allTariffs[$subData['tariffid']]['name']);
  1026. $cells .= wf_TableCell($subData['actdate']);
  1027. $cells .= wf_TableCell(web_bool_led($subData['active']));
  1028. $cells .= wf_TableCell(web_bool_led($subData['primary']));
  1029. $cells .= wf_TableCell(web_bool_led($subData['freeperiod']));
  1030. $rows .= wf_TableRow($cells, 'row3');
  1031. $result = wf_TableBody($rows, '100%', 0, '');
  1032. $result .= wf_delimiter();
  1033. $credentialsDb = new NyanORM('mg_credentials');
  1034. $credentialsDb->where('login', '=', $subData['login']);
  1035. $userCredentials = $credentialsDb->getAll();
  1036. if (!empty($userCredentials)) {
  1037. $userCredentials = $userCredentials[0];
  1038. $userCredentialsLabel = 'megogo.net ' . __('Login') . ': ' . $userCredentials['email'] . ' / ' . __('Password') . ': ' . $userCredentials['password'];
  1039. $result .= $this->messages->getStyledMessage($userCredentialsLabel, 'info');
  1040. $result .= wf_delimiter();
  1041. } else {
  1042. $result .= $this->messages->getStyledMessage(__('User have no authorization data for megogo.net'), 'warning');
  1043. $result .= wf_delimiter();
  1044. }
  1045. if (cfr('ROOT')) {
  1046. $controls = wf_Link($baseUrl . '&maction=subscribe', web_bool_star(1) . ' ' . __('Subscribe with Megogo API'), true, 'ubButton') . wf_tag('br');
  1047. $controls .= wf_Link($baseUrl . '&maction=unsubscribe', web_bool_star(0) . ' ' . __('Unubscribe with Megogo API'), true, 'ubButton') . wf_tag('br');
  1048. $controls .= wf_Link($baseUrl . '&maction=activate', web_bool_led(1) . ' ' . __('Activate subscription'), true, 'ubButton') . wf_tag('br');
  1049. $controls .= wf_Link($baseUrl . '&maction=deactivate', web_bool_led(0) . ' ' . __('Deactivate subscription'), true, 'ubButton') . wf_tag('br');
  1050. if (@$this->altCfg['MG_DOMAIN']) {
  1051. $controls .= wf_Link($baseUrl . '&maction=newcredentials', wf_img('skins/icon_key.gif') . ' ' . __('User registration') . ' ' . __('on') . ' ' . __('Megogo.net'), true, 'ubButton') . wf_tag('br');
  1052. } else {
  1053. $result .= $this->messages->getStyledMessage(__('Missed config option') . ' MG_DOMAIN', 'error');
  1054. $result .= wf_delimiter();
  1055. }
  1056. $controls .= wf_JSAlertStyled($baseUrl . '&maction=delete', web_delete_icon() . ' ' . __('Delete subscription'), $this->messages->getDeleteAlert(), 'ubButton');
  1057. $result .= $controls;
  1058. }
  1059. } else {
  1060. $result = $this->messages->getStyledMessage(__('Something went wrong') . ' EX_ID_NOEXISTS', 'error');
  1061. }
  1062. return ($result);
  1063. }
  1064. /**
  1065. * Catches and do some manual actions
  1066. *
  1067. * @return void/string
  1068. */
  1069. public function catchManualAction() {
  1070. $result = '';
  1071. if (wf_CheckGet(array('subid', 'maction'))) {
  1072. $action = vf($_GET['maction']);
  1073. $subId = vf($_GET['subid'], 3);
  1074. if (isset($this->allSubscribers[$subId])) {
  1075. $subData = $this->allSubscribers[$subId];
  1076. switch ($action) {
  1077. case 'subscribe':
  1078. $mgApi = new MegogoApi();
  1079. $serviceId = $this->allTariffs[$subData['tariffid']]['serviceid'];
  1080. $resubResult = $mgApi->subscribe($subData['login'], $serviceId);
  1081. log_register('MEGOGO MANUAL ACTION `' . $action . '` (' . $subData['login'] . ')');
  1082. if (!$resubResult) {
  1083. $result = $this->messages->getStyledMessage('EX_API_SUBSCRIPTION_FAIL', 'error');
  1084. }
  1085. break;
  1086. case 'unsubscribe':
  1087. $mgApi = new MegogoApi();
  1088. $serviceId = $this->allTariffs[$subData['tariffid']]['serviceid'];
  1089. $unsubResult = $mgApi->unsubscribe($subData['login'], $serviceId);
  1090. log_register('MEGOGO MANUAL ACTION `' . $action . '` (' . $subData['login'] . ')');
  1091. if (!$unsubResult) {
  1092. $result = $this->messages->getStyledMessage('EX_API_UNSUBSCRIPTION_FAIL', 'error');
  1093. }
  1094. break;
  1095. case 'activate':
  1096. simple_update_field('mg_subscribers', 'active', 1, "WHERE `id`='" . $subId . "';");
  1097. log_register('MEGOGO MANUAL ACTION `' . $action . '` (' . $subData['login'] . ')');
  1098. break;
  1099. case 'deactivate':
  1100. simple_update_field('mg_subscribers', 'active', 0, "WHERE `id`='" . $subId . "';");
  1101. log_register('MEGOGO MANUAL ACTION `' . $action . '` (' . $subData['login'] . ')');
  1102. break;
  1103. case 'delete':
  1104. nr_query("DELETE FROM `mg_subscribers` WHERE `id`='" . $subId . "';");
  1105. log_register('MEGOGO MANUAL ACTION `' . $action . '` (' . $subData['login'] . ')');
  1106. break;
  1107. case 'newcredentials':
  1108. $userLogin = $subData['login'];
  1109. $userData = zb_UserGetAllData($userLogin);
  1110. if (!empty($userData)) {
  1111. $userPassword = $userData[$userLogin]['Password'];
  1112. $mgApi = new MegogoApi();
  1113. $newCredResult = $mgApi->registerWebUser($userLogin, $userPassword);
  1114. if (!empty($newCredResult)) {
  1115. $result .= $this->messages->getStyledMessage($newCredResult, 'error');
  1116. }
  1117. log_register('MEGOGO MANUAL ACTION `' . $action . '` (' . $subData['login'] . ')');
  1118. }
  1119. break;
  1120. }
  1121. } else {
  1122. $result = $this->messages->getStyledMessage('EX_ID_NOEXISTS', 'error');
  1123. }
  1124. }
  1125. return ($result);
  1126. }
  1127. /**
  1128. * Returns some user balance
  1129. *
  1130. * @return float
  1131. */
  1132. protected function getUserBalance($login) {
  1133. $result = 0;
  1134. if (isset($this->allUsers[$login])) {
  1135. $result = $this->allUsers[$login]['Cash'];
  1136. }
  1137. return ($result);
  1138. }
  1139. /**
  1140. * Creates scheduler task in database
  1141. *
  1142. * @param string $login
  1143. * @param string $action
  1144. * @param int $tariffid
  1145. *
  1146. * @return void
  1147. */
  1148. protected function createQueue($login, $action, $tariffid) {
  1149. $loginF = mysql_real_escape_string($login);
  1150. $actionF = mysql_real_escape_string($action);
  1151. $tariffid = vf($tariffid, 3);
  1152. $curdate = curdatetime();
  1153. $query = "INSERT INTO `mg_queue` (`id`,`login`,`date`,`action`,`tariffid`) VALUES";
  1154. $query .= "(NULL,'" . $loginF . "','" . $curdate . "','" . $actionF . "','" . $tariffid . "')";
  1155. nr_query($query);
  1156. log_register('MEGOGO QUEUE CREATE (' . $login . ') TARIFF [' . $tariffid . '] ACTION `' . $action . '`');
  1157. }
  1158. /**
  1159. * Checks is queue for this login/tariff clean?
  1160. *
  1161. * @param string $login
  1162. * @param int $tariffid
  1163. *
  1164. * @return bool
  1165. */
  1166. protected function checkSchedule($login, $tariffid) {
  1167. $result = true;
  1168. if (!empty($this->allQueue)) {
  1169. foreach ($this->allQueue as $io => $each) {
  1170. if (($each['login'] == $login) AND ( $each['tariffid'] == $tariffid)) {
  1171. $result = false;
  1172. break;
  1173. }
  1174. }
  1175. }
  1176. return ($result);
  1177. }
  1178. /**
  1179. * Schedules tariff unsubscribe from next month
  1180. *
  1181. * @param string $login
  1182. * @param int $tariffid
  1183. *
  1184. * @return string
  1185. */
  1186. public function scheduleUnsubscribe($login, $tariffid) {
  1187. if ($this->checkSchedule($login, $tariffid)) {
  1188. $this->createQueue($login, 'unsub', $tariffid);
  1189. $result = 'The service will be disabled on the first day of the following month';
  1190. } else {
  1191. $result = 'Already scheduled';
  1192. }
  1193. return ($result);
  1194. }
  1195. /**
  1196. * Performs scheduler queue actions
  1197. *
  1198. * @return string
  1199. */
  1200. public function scheduleProcessing() {
  1201. $result = '';
  1202. if (!empty($this->allQueue)) {
  1203. foreach ($this->allQueue as $io => $each) {
  1204. //unsubscription management
  1205. if ($each['action'] == 'unsub') {
  1206. $query = "DELETE from `mg_queue` WHERE `id`='" . $each['id'] . "';";
  1207. nr_query($query);
  1208. $this->deleteSubscribtion($each['login'], $each['tariffid']);
  1209. $result .= $each['login'] . ' SCHEDULE UNSUB [' . $each['tariffid'] . ']' . "\n";
  1210. }
  1211. }
  1212. }
  1213. return ($result);
  1214. }
  1215. /**
  1216. * Performs available active subscriptions fee processing
  1217. *
  1218. * @return string
  1219. */
  1220. public function subscriptionFeeProcessing() {
  1221. $result = '';
  1222. $megogoApi = new MegogoApi();
  1223. if (!empty($this->allSubscribers)) {
  1224. foreach ($this->allSubscribers as $io => $each) {
  1225. if (!$each['freeperiod']) {
  1226. //active subscription - normal fee
  1227. $tariffFee = $this->getTariffFee($each['tariffid']);
  1228. if ($this->altCfg['MG_SPREAD']) {
  1229. //possible spread fee charge
  1230. $tariffFee = $this->getDaylyFee($tariffFee);
  1231. }
  1232. if ($each['active']) {
  1233. $userBalance = $this->getUserBalance($each['login']);
  1234. if ($userBalance >= 0) {
  1235. if ($userBalance - $tariffFee >= 0) {
  1236. zb_CashAdd($each['login'], '-' . $tariffFee, 'add', 1, 'MEGOGO:' . $each['tariffid']);
  1237. log_register('MEGOGO FEE (' . $each['login'] . ') -' . $tariffFee);
  1238. $result .= $each['login'] . ' FEE ' . $tariffFee . "\n";
  1239. } else {
  1240. $this->deleteSubscribtion($each['login'], $each['tariffid']);
  1241. $result .= $each['login'] . ' UNSUB [' . $each['tariffid'] . ']' . "\n";
  1242. }
  1243. } else {
  1244. $this->deleteSubscribtion($each['login'], $each['tariffid']);
  1245. $result .= $each['login'] . ' UNSUB [' . $each['tariffid'] . ']' . "\n";
  1246. }
  1247. }
  1248. } else {
  1249. //free period subscription
  1250. if ($this->altCfg['MG_SPREAD'] OR @ $this->altCfg['MG_FREEPERIOD_DAYS']) {
  1251. $freePeriodStart = strtotime($each['actdate']);
  1252. $freePeriodDaysOffset = 30; //default
  1253. if (isset($this->altCfg['MG_FREEPERIOD_DAYS'])) {
  1254. if ($this->altCfg['MG_FREEPERIOD_DAYS']) {
  1255. $freePeriodDaysOffset = $this->altCfg['MG_FREEPERIOD_DAYS']; //custom days limit
  1256. }
  1257. }
  1258. //delete subscribtion if required count of days past
  1259. if (time() >= ($freePeriodStart + 86400 * $freePeriodDaysOffset)) {
  1260. $this->deleteSubscribtion($each['login'], $each['tariffid']);
  1261. log_register('MEGOGO (' . $each['login'] . ') FREE PERIOD EXPIRED AFTER `' . $freePeriodDaysOffset . '` DAYS ON `MP`');
  1262. $result .= $each['login'] . ' UNSUB [' . $each['tariffid'] . '] FREE' . "\n";
  1263. }
  1264. } else {
  1265. //just finish free period at the start of new month
  1266. $this->deleteSubscribtion($each['login'], $each['tariffid']);
  1267. log_register('MEGOGO (' . $each['login'] . ') FREE PERIOD EXPIRED ON `MP`');
  1268. $result .= $each['login'] . ' UNSUB [' . $each['tariffid'] . '] FREE' . "\n";
  1269. }
  1270. }
  1271. }
  1272. }
  1273. return ($result);
  1274. }
  1275. /**
  1276. * Performs cleanup of expired free subscriptions
  1277. *
  1278. * @return string
  1279. */
  1280. public function subscriptionFreeCleanup() {
  1281. $result = '';
  1282. $megogoApi = new MegogoApi();
  1283. if (!empty($this->allSubscribers)) {
  1284. foreach ($this->allSubscribers as $io => $each) {
  1285. if ($each['freeperiod']) {
  1286. if ($this->altCfg['MG_SPREAD'] OR @ $this->altCfg['MG_FREEPERIOD_DAYS']) {
  1287. $freePeriodStart = strtotime($each['actdate']);
  1288. $freePeriodDaysOffset = 30; //default
  1289. if (isset($this->altCfg['MG_FREEPERIOD_DAYS'])) {
  1290. if ($this->altCfg['MG_FREEPERIOD_DAYS']) {
  1291. $freePeriodDaysOffset = $this->altCfg['MG_FREEPERIOD_DAYS']; //custom days limit
  1292. }
  1293. }
  1294. //delete subscribtion if required count of days past
  1295. if (time() >= ($freePeriodStart + 86400 * $freePeriodDaysOffset)) {
  1296. $this->deleteSubscribtion($each['login'], $each['tariffid']);
  1297. log_register('MEGOGO (' . $each['login'] . ') FREE PERIOD EXPIRED AFTER `' . $freePeriodDaysOffset . '` DAYS ON `MFC`');
  1298. $result .= $each['login'] . ' UNSUB [' . $each['tariffid'] . '] FREE' . "\n";
  1299. }
  1300. }
  1301. }
  1302. }
  1303. }
  1304. return ($result);
  1305. }
  1306. }
  1307. ?>