PageRenderTime 72ms CodeModel.GetById 37ms RepoModel.GetById 0ms app.codeStats 0ms

/datafeed.php

https://bitbucket.org/itoxable/chiron-gaming
PHP | 1900 lines | 1606 code | 241 blank | 53 comment | 240 complexity | beea1dbdb008de0009afa42f84c269e1 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. include_once "general_include.php";
  3. include_once("adodb/dbconfig.php");
  4. include('transaction_status.class.php');
  5. function js2PhpTime($jsdate){
  6. if(preg_match('@(\d+)/(\d+)/(\d+)\s+(\d+):(\d+)@', $jsdate, $matches)==1){
  7. $ret = mktime($matches[4], $matches[5], 0, $matches[1], $matches[2], $matches[3]);
  8. }else if(preg_match('@(\d+)/(\d+)/(\d+)@', $jsdate, $matches)==1){
  9. $ret = mktime(0, 0, 0, $matches[1], $matches[2], $matches[3]);
  10. }
  11. return $ret;
  12. }
  13. function php2MySqlTime($phpDate){
  14. return date("Y-m-d H:i:s", $phpDate);
  15. }
  16. if(!isset($_SESSION['user_id'])){
  17. echo "session not started";
  18. return;
  19. }
  20. function getPostOrGetParam($param){
  21. if(isset($_POST[$param]))
  22. return $_POST[$param];
  23. else{
  24. if(isset($_GET[$param]))
  25. return $_GET[$param];
  26. else
  27. return "";
  28. }
  29. }
  30. class Status{
  31. public static $AVAILABLE = 1;
  32. public static $ACTIVE = 2;
  33. public static $DELETED = 3;
  34. public static $PENDING = 4;
  35. public static $ACCEPTED = 5;
  36. public static $FINISHED = 6;
  37. public static $DECLINED = 7;
  38. public static $REQUESTED = 8;
  39. }
  40. class LessonStatus{
  41. const OPEN = 1;
  42. const PAID = 2;
  43. const COMPLETED = 3;
  44. const CLOSED_WITH_PAYMENT_TO_COACH = 4;
  45. const CANCELED = 5;
  46. const WAITING_CONFIRMATION = 6;
  47. }
  48. class LessonType{
  49. const REGULAR = 0;
  50. const INSTANT = 1;
  51. }
  52. class UserType{
  53. const COACH = 1;
  54. const STUDENT = 2;
  55. const TRAINNING_PARTNER = 3;
  56. }
  57. class ErrorCode{
  58. public static $UNKNOWN= 0;
  59. public static $ALREADY_USED = -2;
  60. public static $NO_EVENTS = -3;
  61. public static $ALREADY_SCHEDULED = -4;
  62. }
  63. class NotificationTypes{
  64. public static $GENERAL= 0;
  65. public static $SCHEDULE_ALERT = 1;
  66. public static $UNKNOWN = 2;
  67. public static $INSTANT_LESSON = 3;
  68. public static $INSTANT_LESSON_RESPONSE = 5;
  69. public static $MESSAGE = 4;
  70. }
  71. class Constants{
  72. public static $TIMES_ARRAY = array("0:00","0:30","1:00","1:30","2:00","2:30","3:00","3:30","4:00","4:30","5:00","5:30","6:00","6:30","7:00","7:30",
  73. "8:00","8:30","9:00","9:30","10:00","10:30","11:00","11:30","12:00","12:30","13:00","13:30","14:00","14:30","15:00",
  74. "15:30","16:00","16:30","17:00","17:30","18:00","18:30","19:00","19:30","20:00","20:30","21:00","21:30","22:00","22:30","23:00","23:30","23:59");
  75. public static $SLOTS_ARRAY = array("h0","h1","h2","h3",
  76. "h4","h5","h6","h7","h8","h9","h10","h11","h12","h13","h14","h15","h16","h17","h18","h19",
  77. "h20","h21","h22","h23","h24","h25","h26","h27","h28","h29","h30","h31","h32","h33",
  78. "h34","h35","h36","h37","h38","h39","h40","h41","h42","h43","h44","h45","h46","h47");
  79. }
  80. function login($username,$password){
  81. try{
  82. $db = new DBConnection();
  83. $db->getConnection();
  84. $sql = "select * from `nk_user` where `email`='".$username."' and `password`='".$password."'";
  85. $handle = mysql_query($sql);
  86. $linha = mysql_fetch_row($handle);
  87. $_SESSION['user_id'] = $linha[0];
  88. $_SESSION['logged_username'] = $linha[3];
  89. return true;
  90. }catch(Exception $e){
  91. return $e->getMessage();
  92. }
  93. }
  94. class Notification{
  95. public $notification_id;
  96. public $user_id;
  97. public $title;
  98. public $introduction;
  99. public $text;
  100. public $date_value;
  101. public $link;
  102. public $new;
  103. public $date_readed;
  104. public $modified_date;
  105. public $creation_date;
  106. public $origin;
  107. public $type;
  108. public $extra_data;
  109. public function setNotification($notification_id=0,$user_id=0,$type=0,$origin="",$title="",$introduction="",$text="",$date_readed="",$date_value="",$link="",$new="", $modified_date="", $creation_date="") {
  110. $this->notification_id = $notification_id;
  111. $this->user_id = $user_id;
  112. $this->title = $title;
  113. $this->introduction = $introduction;
  114. $this->text = $text;
  115. $this->date_readed = $date_readed;
  116. $this->creation_date = $creation_date;
  117. $this->modified_date = $modified_date;
  118. $this->date_value = $date_value;
  119. $this->link = $link;
  120. $this->origin = $origin;
  121. $this->type = $type;
  122. }
  123. public function __construct($row) {
  124. $this->notification_id = $row->notification_id;
  125. $this->user_id = $row->user_id;
  126. $this->title = $row->title;
  127. $this->introduction = $row->introduction;
  128. $this->text = $row->text;
  129. $this->creation_date = $row->creation_date;
  130. $this->modified_date = $row->modified_date;
  131. $this->date_readed = $row->date_readed;
  132. $this->date_value = $row->date_value;
  133. $this->link = $row->link;
  134. $this->new = $row->new;
  135. $this->origin = $row->origin;
  136. $this->type = $row->nofication_type;
  137. $this->extra_data = $row->extra_data;
  138. }
  139. public function __toString(){
  140. return "";
  141. }
  142. }
  143. class Event{
  144. public $status = "";
  145. public $calendarRef = "";
  146. public $description = "";
  147. public $requestoruserId = "";
  148. public $availableSpot = "";
  149. public $isEmpty = 0;
  150. public $requestorTxt = "";
  151. public $slot = "";
  152. public $calendarId = "";
  153. public $gameId = array();
  154. public $userId = "";
  155. public $date = "";
  156. public $day = "";
  157. public $month = "";
  158. public $year = "";
  159. public $lessonId = "";
  160. function setStatus($status){
  161. $this->status = $status;
  162. }
  163. function setCalendarRef($calendarRef){
  164. $this->calendarRef = $calendarRef;
  165. }
  166. function setDescription($description){
  167. $this->description = $description;
  168. }
  169. function setRequestoruserId($requestoruserId){
  170. $this->requestoruserId = $requestoruserId;
  171. }
  172. function setAvailableSpot($availableSpot){
  173. $this->$availableSpot = $availableSpot;
  174. }
  175. function setIsEmpty($isEmpty){
  176. $this->isEmpty = $isEmpty;
  177. }
  178. function setRequestorTxt($requestorTxt){
  179. $this->requestorTxt = $requestorTxt;
  180. }
  181. function setGameId($gameId){
  182. $this->gameId = $gameId;
  183. }
  184. function setLessonIdId($lessonId){
  185. $this->lessonId = $lessonId;
  186. }
  187. public function setEvent($status="",$description="",$availableSpot="",$gameId="", $requestoruserId="",$calendarRef="",$requestorTxt="",$isEmpty=0,$slot="",$lessonId="") {
  188. $this->status = $status;
  189. $this->description = $description;
  190. $this->availableSpot = $availableSpot;
  191. $this->requestoruserId = $requestoruserId;
  192. $this->calendarRef = $calendarRef;
  193. $this->requestorTxt = $requestorTxt;
  194. $this->isEmpty = $isEmpty;
  195. $this->slot = $slot;
  196. $this->lessonId = $lessonId;
  197. if(is_array($gameId))
  198. $this->gameId = $gameId;
  199. else
  200. $this->gameId = split('#', $gameId);
  201. }
  202. public function __construct($event=null, $slot="", $row=null) {
  203. if(is_null($event)){
  204. $this->isEmpty = true;
  205. }else{
  206. list ($this->status, $this->description,$this->availableSpot, $gameId, $this->requestoruserId, $this->calendarRef, $this->requestorTxt,$this->lessonId) = split(',', $event);
  207. $this->gameId = split('#', $gameId);
  208. }
  209. $this->slot = $slot;
  210. if($row != null){
  211. $this->calendarId = $row->calendar_id;
  212. $this->userId = $row->user_id;
  213. $this->date = $row->date;
  214. $this->day = $row->day;
  215. $this->month = $row->month;
  216. $this->year = $row->year;
  217. }
  218. }
  219. public function __toString(){
  220. if($this->isEmpty){
  221. return "NULL";
  222. }
  223. $i=0;
  224. foreach ($this->gameId as $g){
  225. if($i==0)
  226. $gameId = $g;
  227. else
  228. $gameId = $gameId."#".$g;
  229. $i++;
  230. }
  231. return "'".$this->status.",".$this->description.",".$this->availableSpot.",".$gameId.",".$this->requestoruserId.",".$this->calendarRef.",".$this->requestorTxt.",".$this->lessonId."'";
  232. }
  233. }
  234. function getAllSlots($userid,$day){
  235. return getSlots($userid,$day,Constants::$SLOTS_ARRAY);
  236. }
  237. function getAllSlotsByCalendarId($calendarId){
  238. return getSlotsByCalendarId($calendarId,Constants::$SLOTS_ARRAY);
  239. }
  240. function getSlots($userid,$date,$slots){
  241. $ret = array();
  242. try{
  243. $db = new DBConnection();
  244. $db->getConnection();
  245. $sql = "select calendar_id, user_id, date, day, month, year, ";
  246. $i = 0;
  247. foreach ($slots as $slot){
  248. if($i == 0)
  249. $sql = $sql." `".$slot."` ";
  250. else
  251. $sql = $sql.", `".$slot."` ";
  252. $i++;
  253. }
  254. $sql = $sql."from `nk_user_calendar` where `user_id` = " .$userid;
  255. $sql = $sql." and `date` =".$date;
  256. $handle = mysql_query($sql);
  257. $row = mysql_fetch_object($handle);
  258. foreach ($slots as $slot){
  259. $ret[] = new Event($row->$slot, $slot, $row);
  260. }
  261. }catch(Exception $e){
  262. $ret['error'] = $e->getMessage();
  263. }
  264. return $ret;
  265. }
  266. function getCalendarById($calendarId){
  267. $ret = array();
  268. try{
  269. $db = new DBConnection();
  270. $db->getConnection();
  271. $sql = "select * from `nk_user_calendar` where `calendar_id` = ".$calendarId;
  272. $handle = mysql_query($sql);
  273. return mysql_fetch_object($handle);
  274. }catch(Exception $e){
  275. $ret['error'] = $e->getMessage();
  276. }
  277. return $ret;
  278. }
  279. function getSlotsByCalendarId($calendarId,$slots){
  280. $ret = array();
  281. try{
  282. $db = new DBConnection();
  283. $db->getConnection();
  284. $sql = "select calendar_id, user_id, date, day, month, year, ";
  285. $i = 0;
  286. foreach ($slots as $slot){
  287. if($i == 0)
  288. $sql = $sql." `".$slot."` ";
  289. else
  290. $sql = $sql.", `".$slot."` ";
  291. $i++;
  292. }
  293. $sql = $sql."from `nk_user_calendar` where `calendar_id` = ".$calendarId;
  294. $handle = mysql_query($sql);
  295. $row = mysql_fetch_object($handle);
  296. foreach ($slots as $slot){
  297. $ret[] = new Event($row->$slot, $slot, $row);
  298. }
  299. }catch(Exception $e){
  300. $ret['error'] = $e->getMessage();
  301. }
  302. return $ret;
  303. }
  304. function listCalendar($userid,$date="0",$timezoneOffset=0){
  305. $ret = array();
  306. $ret['events'] = array();
  307. try{
  308. $db = new DBConnection();
  309. $db->getConnection();
  310. $sql = "SELECT * FROM `nk_user_calendar` WHERE `user_id` = " .$userid;
  311. if($date != "0"){
  312. $sql = $sql." AND `date` = ".$date;
  313. }
  314. //logToFile($sql);
  315. $handle = mysql_query($sql);
  316. while ($row = mysql_fetch_object($handle)) {
  317. $ret['events'][] = array(
  318. $row->calendar_id,
  319. $row->user_id,
  320. $row->date,
  321. $row->day,
  322. $row->month,
  323. $row->year,
  324. array(
  325. new Event($row->h0,"h0",$row),
  326. new Event($row->h1,"h1",$row),
  327. new Event($row->h2,"h2",$row),
  328. new Event($row->h3,"h3",$row),new Event($row->h4,"h4",$row),new Event($row->h5,"h5",$row),new Event($row->h6,"h6",$row),new Event($row->h7,"h7",$row),
  329. new Event($row->h8,"h8",$row),new Event($row->h9,"h9",$row),new Event($row->h10,"h10",$row),new Event($row->h11,"h11",$row),new Event($row->h12,"h12",$row),new Event($row->h13,"h13",$row),new Event($row->h14,"h14",$row),new Event($row->h15,"h15",$row),
  330. new Event($row->h16,"h16",$row),new Event($row->h17,"h17",$row),new Event($row->h18,"h18",$row),new Event($row->h19,"h19",$row),new Event($row->h20,"h20",$row),new Event($row->h21,"h21",$row),new Event($row->h22,"h22",$row),new Event($row->h23,"h23",$row),
  331. new Event($row->h24,"h24",$row),new Event($row->h25,"h25",$row),new Event($row->h26,"h26",$row),new Event($row->h27,"h27",$row),new Event($row->h28,"h28",$row),new Event($row->h29,"h29",$row),new Event($row->h30,"h30",$row),new Event($row->h31,"h31",$row),
  332. new Event($row->h32,"h32",$row),new Event($row->h33,"h33",$row),new Event($row->h34,"h34",$row),new Event($row->h35,"h35",$row),new Event($row->h36,"h36",$row),new Event($row->h37,"h37",$row),new Event($row->h38,"h38",$row),new Event($row->h39,"h39",$row),
  333. new Event($row->h40,"h40",$row),new Event($row->h41,"h41",$row),new Event($row->h42,"h42",$row),new Event($row->h43,"h43",$row),new Event($row->h44,"h44",$row),new Event($row->h45,"h45",$row),new Event($row->h46,"h46",$row),new Event($row->h47,"h47",$row)
  334. )
  335. );
  336. }
  337. // $sql = "SELECT * FROM `nk_user_calendar` WHERE `user_id` = " .$userid;
  338. // if($date != "0"){
  339. // if($timezoneOffset != 0){
  340. // $sql = $sql." AND (`date` = ".(intval($date)+(24*3600))." OR `date` = ".(intval($date)-(24*3600)).") ORDER BY `date` ASC";
  341. // //logToFile($sql);
  342. // $handle = mysql_query($sql);
  343. // while ($row = mysql_fetch_object($handle)) {
  344. // $ret['events'][($row->date < $date)?'before':'after'] = array(
  345. // $row->calendar_id,
  346. // $row->user_id,
  347. // $row->date,
  348. // $row->day,
  349. // $row->month,
  350. // $row->year,
  351. // array(
  352. // new Event($row->h0,"h0",$row),new Event($row->h1,"h1",$row),new Event($row->h2,"h2",$row),new Event($row->h3,"h3",$row),new Event($row->h4,"h4",$row),new Event($row->h5,"h5",$row),new Event($row->h6,"h6",$row),new Event($row->h7,"h7",$row),
  353. // new Event($row->h8,"h8",$row),new Event($row->h9,"h9",$row),new Event($row->h10,"h10",$row),new Event($row->h11,"h11",$row),new Event($row->h12,"h12",$row),new Event($row->h13,"h13",$row),new Event($row->h14,"h14",$row),new Event($row->h15,"h15",$row),
  354. // new Event($row->h16,"h16",$row),new Event($row->h17,"h17",$row),new Event($row->h18,"h18",$row),new Event($row->h19,"h19",$row),new Event($row->h20,"h20",$row),new Event($row->h21,"h21",$row),new Event($row->h22,"h22",$row),new Event($row->h23,"h23",$row),
  355. // new Event($row->h24,"h24",$row),new Event($row->h25,"h25",$row),new Event($row->h26,"h26",$row),new Event($row->h27,"h27",$row),new Event($row->h28,"h28",$row),new Event($row->h29,"h29",$row),new Event($row->h30,"h30",$row),new Event($row->h31,"h31",$row),
  356. // new Event($row->h32,"h32",$row),new Event($row->h33,"h33",$row),new Event($row->h34,"h34",$row),new Event($row->h35,"h35",$row),new Event($row->h36,"h36",$row),new Event($row->h37,"h37",$row),new Event($row->h38,"h38",$row),new Event($row->h39,"h39",$row),
  357. // new Event($row->h40,"h40",$row),new Event($row->h41,"h41",$row),new Event($row->h42,"h42",$row),new Event($row->h43,"h43",$row),new Event($row->h44,"h44",$row),new Event($row->h45,"h45",$row),new Event($row->h46,"h46",$row),new Event($row->h47,"h47",$row)
  358. // )
  359. // );
  360. // }
  361. // }
  362. // }
  363. }catch(Exception $e){
  364. $ret['error'] = $e->getMessage();
  365. }
  366. return $ret;
  367. }
  368. function updateSlots($slots, $requestoruserid, $calendarref, $description,$status="1",$remove=false,$lessonId=0){
  369. $sl = array();
  370. foreach ($slots as $slot){
  371. $sl[] = $slot->slot;
  372. }
  373. return updateCalendar($slots[0]->userId, $slots[0]->date ,$sl, $status, $slots[0]->description, "0", $slots[0]->gameId, $requestoruserid, $calendarref, $description,false,$lessonId);
  374. }
  375. function updateCalendar($userid,$date,$slots,$status="1",$description="_",$availablespot="1", $gameId="0",$requestoruserid="0",$calendarref="0",$requestorTxt="",$remove=false,$lessonId=0){
  376. $ret = array();
  377. try{
  378. $db = new DBConnection();
  379. $db->getConnection();
  380. $event = new Event();
  381. $event->setEvent($status, $description, $availablespot, $gameId, $requestoruserid, $calendarref, $requestorTxt, $remove,"",$lessonId);
  382. $sql = "update `nk_user_calendar` set ";
  383. $i = 0;
  384. foreach ($slots as $slot){
  385. if($i == 0)
  386. $sql = $sql." `".$slot."` = ".$event;
  387. else
  388. $sql = $sql.", `".$slot."` = ".$event;
  389. $i++;
  390. }
  391. $sql = $sql." where `user_id` = '".$userid."' AND `date` = ".$date;
  392. if(mysql_query($sql)==false){
  393. $ret['IsSuccess'] = false;
  394. $ret['Msg'] = mysql_error();
  395. }else{
  396. $ret['IsSuccess'] = true;
  397. $ret['Msg'] = 'add success';
  398. $ret['Data'] = $date;
  399. }
  400. }catch(Exception $e){
  401. $ret['IsSuccess'] = false;
  402. $ret['Msg'] = $e->getMessage();
  403. }
  404. return $ret;
  405. }
  406. function insertCalendar($userid,$date,$slots,$status="1",$description="_",$availablespot="1", $gameId="0", $requestoruserid="0",$calendarref="0",$requestorTxt="",$lessonId=0){
  407. $ret = array();
  408. try{
  409. $db = new DBConnection();
  410. $db->getConnection();
  411. list ($day, $month, $year) = split ('-', gmdate('d-m-Y', $date));
  412. $event = new Event();
  413. //setEvent($status="",$description="",$availableSpot="",$gameId="", $requestoruserId="",$calendarRef="",$requestorTxt="",$isEmpty=0,$slot="",$lessonId="")
  414. $event->setEvent($status,$description,$availablespot,$gameId,$requestoruserid,$calendarref,$requestorTxt,0,"",$lessonId);
  415. $sql = "insert into `nk_user_calendar` (`user_id`, `date`, `day`, `month`,`year`";
  416. foreach ($slots as $slot){
  417. $sql = $sql.",`".$slot."`";
  418. }
  419. $sql = $sql.") values ('".$userid."', ".$date.", '".$day."', '".$month."', '".$year."'";
  420. foreach ($slots as $slot){
  421. $sql = $sql.", ".$event."";
  422. }
  423. $sql = $sql.")";
  424. if(mysql_query($sql)==false){
  425. $ret['IsSuccess'] = false;
  426. $ret['Msg'] = mysql_error();
  427. }else{
  428. $ret['IsSuccess'] = true;
  429. $ret['Msg'] = 'add success';
  430. $ret['Data'] = $date;
  431. $ret['Id'] = mysql_insert_id();
  432. }
  433. }catch(Exception $e){
  434. $ret['IsSuccess'] = false;
  435. $ret['Msg'] = $e->getMessage();
  436. }
  437. return $ret;
  438. }
  439. function getMonthCalendar($userid){
  440. $events = array();
  441. $fullCalendar = listCalendar($userid);
  442. if (empty($fullCalendar))
  443. return "{}";
  444. if(!array_key_exists("events", $fullCalendar))
  445. return "{}";
  446. $ret ="{";
  447. $i = 0;
  448. foreach ($fullCalendar['events'] as $event) {
  449. list ($day, $month,$year) = split ('-', gmdate('d-m-Y',$event[2]));
  450. $key = "D".$day."_".$month."_".$year;
  451. $sizeof_day = sizeof($event);
  452. $notEmptySpots = 0;
  453. $availableSpots = 0;
  454. foreach ($event[6] as &$hour){
  455. if($hour->isEmpty)
  456. continue;
  457. $notEmptySpots++;
  458. if($hour->availableSpot == 1){
  459. $availableSpots++;
  460. continue;
  461. }
  462. }
  463. if($i != 0)
  464. $ret = $ret.',';
  465. if($notEmptySpots == 0){
  466. $ret = $ret.'"'.$key.'":"NOT_AVAILABLE"';
  467. }else if($availableSpots == $notEmptySpots){
  468. $ret = $ret.'"'.$key.'":"ALL_FREE"';
  469. }else if($availableSpots == 0){
  470. $ret = $ret.'"'.$key.'":"ALL_BOOKED"';
  471. }else {
  472. $ret = $ret.'"'.$key.'":"AVAILABLE_SPOTS"';
  473. }
  474. $i++;
  475. }
  476. $ret = $ret."}";
  477. return $ret;
  478. }
  479. function changeStatus($id, $userid, $status){
  480. //TODO
  481. }
  482. function acceptSchedule($id, $userid){
  483. //TODO
  484. }
  485. function addSlots($date, $schedules, $userid, $description,$overwrite,$games){
  486. $ret = array();
  487. $slots = getSlotsArray($schedules);
  488. $event = listCalendar($userid,$date);
  489. $sizeof_day = sizeof($event);
  490. if(sizeof($event['events']) == 0){
  491. $ret = insertCalendar($userid, $date ,$slots, 1, $description, 1,$games);
  492. }else{
  493. if($overwrite == 0){
  494. $times = split(',', $schedules);
  495. foreach ($times as $time){
  496. $e = $event['events'][0][6][$time];
  497. // if(!$event['events'][0][6][$time]->isEmpty){
  498. if(!$e->isEmpty && $e->availableSpot != 1){
  499. $ret['IsSuccess'] = false;
  500. $ret['ErrorCode'] = ErrorCode::$ALREADY_USED;
  501. return $ret;
  502. }
  503. }
  504. }
  505. $ret = updateCalendar($userid,$date,$slots,"1",$description,"1",$games);
  506. }
  507. return $ret;
  508. }
  509. function cancel($userid,$date,$schedules,$cancelClientEvents="0", $offSet=0){//TODO: Agrupar slots por
  510. try{
  511. $ret = array();
  512. $warnList = array();
  513. $lessonList = array();
  514. $clientEvents = array();
  515. $users = array();
  516. $loggedUser = $_SESSION['ch_user'];
  517. $slots = getSlotsArray($schedules);
  518. $event = getSlots($userid, $date, $slots);//gets the data from the selected slots
  519. if(sizeof($event) == 0){
  520. $ret['IsSuccess'] = false;
  521. $ret['ErrorCode'] = ErrorCode::$NO_EVENTS;
  522. return $ret;
  523. }else{
  524. if($cancelClientEvents == 0){
  525. foreach ($event as $e){
  526. if(!$e->isEmpty && $e->availableSpot != 1){
  527. $ret['IsSuccess'] = false;
  528. $ret['ErrorCode'] = ErrorCode::$ALREADY_SCHEDULED;
  529. return $ret;
  530. }
  531. }
  532. }else{
  533. $usersEvents = array();
  534. foreach ($event as $evn){
  535. //TODO: Check events with offset
  536. $events = getSlotsByCalendarId($evn->calendarRef,$slots);
  537. foreach ($events as $ev){
  538. $usersEvents[$ev->userId][]= $ev;
  539. }
  540. }
  541. foreach ($usersEvents as $userEvents){
  542. $res = updateStatus($userEvents, Status::$DELETED);
  543. if(!in_array($userEvents[0]->userId, $lessonList)){
  544. $lessonList[] = $userEvents[0]->lessonId;
  545. }
  546. }
  547. }
  548. $ret = updateCalendar($userid,$date,$slots,"1","","","","","","",true);
  549. foreach ($lessonList as $lessonId){
  550. $lesson = getLesson($lessonId);
  551. changeLessonStatus($lessonId, LessonStatus::CANCELED);
  552. $rate = $lesson->rate;
  553. $returnValue = sizeof($event) * $rate;
  554. if($lesson->coach_id == $_SESSION['user_id']){
  555. $user = getUserInfo($lesson->student_id);
  556. insertTransaction($user->user_id, TransactionStatus::ACTIVE, TransactionType::CREDIT_REFUND, $returnValue, $user->total_points, UserType::STUDENT, ("Refund from canceled lesson from ".$loggedUser['username']));
  557. insertTransaction($_SESSION['user_id'], TransactionStatus::ACTIVE, TransactionType::DEBIT_REFUND, $returnValue, $loggedUser['total_points'],UserType::COACH, ("Refund from canceled lesson to ".$user->username));
  558. }else if($lesson->student_id == $_SESSION['user_id']){
  559. $user = getUserInfo($lesson->coach_id);
  560. insertTransaction($user->user_id, TransactionStatus::ACTIVE, TransactionType::DEBIT_REFUND, $returnValue, $user->total_points,UserType::COACH, ("Refund from canceled lesson to ".$loggedUser['username']));
  561. insertTransaction($_SESSION['user_id'], TransactionStatus::ACTIVE, TransactionType::CREDIT_REFUND, $returnValue, $loggedUser['total_points'],UserType::STUDENT, ("Refund from canceled lesson from ".$user->username));
  562. }else{
  563. echo "\n----- BAD NEWS!! -----\n";
  564. }
  565. insertNotifications($user->id, NotificationTypes::$SCHEDULE_ALERT, $userid, "Schedule", "", "User ".$user->username." has canceled a schedule, please check your calendar","","/schedule.php");
  566. }
  567. }
  568. }catch(Exception $e){
  569. $ret['IsSuccess'] = false;
  570. $ret['Msg'] = $e->getMessage();
  571. }
  572. return $ret;
  573. }
  574. function updateStatus($slots, $status){
  575. $sl = array();
  576. foreach ($slots as $slot){
  577. $sl[] = $slot->slot;
  578. }
  579. return updateCalendar($slots[0]->userId, $slots[0]->date ,$sl, $status, $slots[0]->description, "0", $slots[0]->gameId, $slots[0]->requestoruserId, $slots[0]->calendarref, $slots[0]->requestorTxt);
  580. }
  581. function getSequenceOfRequestor($index,$calendarId){
  582. $events = getAllSlotsByCalendarId($calendarId);
  583. $mainevent = $events[$index];
  584. $requestor = $mainevent->requestoruserId;
  585. $slots = array();
  586. $slots[]=$mainevent->slot;
  587. $ret = ($index<10?"0".$index:$index);
  588. for ($i = ($index+1); $i < 48; $i++) {
  589. if(!$events[$i]->isEmpty){
  590. if($events[$i]->requestoruserId == $requestor){
  591. $ret = $ret."#".($i<10?"0".$i:$i);
  592. }else
  593. break;
  594. }else
  595. break;
  596. }
  597. for ($i = ($index-1); $i >= 0; $i--) {
  598. if(!$events[$i]->isEmpty){
  599. if($events[$i]->requestoruserId == $requestor){
  600. $ret = $ret."#".($i<10?"0".$i:$i);
  601. }else
  602. break;
  603. }else
  604. break;
  605. }
  606. return '{"values":"'.$ret.'"}';
  607. }
  608. function getSequenceOfCalendarRef($index,$calendarId){
  609. $events = getAllSlotsByCalendarId($calendarId);
  610. $mainevent = $events[$index];
  611. $calendarRef = $mainevent->calendarRef;
  612. $slots = array();
  613. $slots[]=$mainevent->slot;
  614. $ret = ($index<10?"0".$index:$index);
  615. for ($i = ($index+1); $i < 48; $i++) {
  616. if(!$events[$i]->isEmpty){
  617. if($events[$i]->calendarRef == $calendarRef){
  618. $ret = $ret."#".($i<10?"0".$i:$i);
  619. }else
  620. break;
  621. }else
  622. break;
  623. }
  624. for ($i = ($index-1); $i >= 0; $i--) {
  625. if(!$events[$i]->isEmpty){
  626. if($events[$i]->calendarRef == $calendarRef){
  627. $ret = $ret."#".($i<10?"0".$i:$i);
  628. }else
  629. break;
  630. }else
  631. break;
  632. }
  633. return '{"values":"'.$ret.'"}';
  634. }
  635. function getSlotsArray($schedules,$offSet=0){
  636. $times = split(',', $schedules);
  637. foreach ($times as $time){
  638. $slots[] = Constants::$SLOTS_ARRAY[$time - $offSet];
  639. }
  640. return $slots;
  641. }
  642. function getDateFromTimeAndSlot($date, $schedules){
  643. $ret = array();
  644. $d = gmdate("Y-m-d",$date);
  645. $times = split(',', $schedules);
  646. $ret['start'] = $d." ".Constants::$TIMES_ARRAY[$times[0]];
  647. $ret['end'] = $d." ".Constants::$TIMES_ARRAY[$times[(sizeof($times)-1)]+1];
  648. return $ret;
  649. }
  650. function checkIfAlreadyUsed($date,$schedules,$offSet=0){
  651. $event = listCalendar($_SESSION['user_id'],$date);
  652. if(sizeof($event['events']) > 0){
  653. $times = split(',', $schedules);
  654. foreach ($times as $time){
  655. if(!$event['events'][0][6][$time - $offSet]->isEmpty){
  656. $ret['IsSuccess'] = false;
  657. $ret['ErrorCode'] = ErrorCode::$ALREADY_USED;
  658. return $ret;
  659. }
  660. }
  661. }
  662. $ret['IsSuccess'] = true;
  663. return $ret;
  664. }
  665. function scheduleLesson($userid, $date, $schedules, $description, $gameId, $total, $studentPoints, $coachPoints,$requestorname,$coachname,$rate,$offSet=0,$sendEmail="0",$email=""){
  666. $ret = array();
  667. $times = split(',', $schedules);
  668. $s = sizeof($times);
  669. $schedulesArray = array();
  670. $j = 0;
  671. for ($i=0; $i<= ($s-1); $i++){
  672. $schVar = intval($times[$i]);
  673. $beforeSchVar = 0;
  674. if($i > 0){
  675. $beforeSchVar = intval($times[$i-1]);
  676. }
  677. if(($schVar-$beforeSchVar) > 1){
  678. $j++;
  679. $schedulesArray[$j][]=$schVar;
  680. continue;
  681. }
  682. $schedulesArray[$j][]=$schVar;
  683. }
  684. foreach($schedulesArray as $scd){
  685. $schedulesX = implode(",", $scd);
  686. $slots = getSlotsArray($schedulesX);
  687. $slotsStudent = getSlotsArray($schedulesX,$offSet);
  688. $calendarRef = "0";
  689. $event = listCalendar($_SESSION['user_id'],$date);
  690. $events = getSlots($userid,$date,$slots);
  691. $eventsStudent = getSlots($userid,$date,$slotsStudent);
  692. $hours = sizeof($slots);
  693. $startEnd = getDateFromTimeAndSlot($date, $schedulesX);
  694. $lessonPrice = ($rate * sizeof($scd))/2;
  695. $lesson = insertLesson($lessonPrice, $rate, $userid, $_SESSION['user_id'], $gameId, ($hours/2), LessonStatus::OPEN, ($offSet/2),$startEnd['start'], $startEnd['end']);
  696. $lessonId = $lesson['lessonId'];
  697. if(sizeof($event['events']) > 0){
  698. //If a record for the day already exists, it just updates the selected spots
  699. $result = updateCalendar($_SESSION['user_id'], $date ,$slotsStudent,Status::$ACTIVE,$description,"0",$events[0]->gameId,$_SESSION['user_id'],$events[0]->calendarId,"",false,$lessonId);
  700. $calendarRef = $event['events'][0][0];
  701. }else{
  702. $ret = insertCalendar($_SESSION['user_id'], $date ,$slotsStudent, "2", $description,"0",$gameId,$_SESSION['user_id'], $events[0]->calendarId,"",$lessonId);
  703. $calendarRef = $ret['Id'];
  704. }
  705. //Updating coach calendar
  706. $ret = updateSlots($events, $_SESSION['user_id'], $calendarRef, $description, Status::$ACTIVE,false, $lessonId);
  707. if($ret['IsSuccess']){
  708. $desc = "Lesson, coach: ".$coachname;
  709. $ch_user = getUserInfo($_SESSION['user_id']);
  710. $studentTransaction = insertTransaction($_SESSION['user_id'], TransactionStatus::BOOKED, TransactionType::DEBIT, $lessonPrice, $ch_user->total_points,0.0, UserType::STUDENT, $desc);
  711. if($studentTransaction['IsSuccess'])
  712. $studentPoints = $studentTransaction['newpoints'];
  713. $user = getUserInfo($userid);
  714. $descr = "Lesson, student: ".$requestorname;
  715. $coachTransaction = insertTransaction($userid, TransactionStatus::BOOKED, TransactionType::CREDIT, $lessonPrice, $user->total_points, floatval($lesson['commision']) , UserType::COACH, $descr);
  716. if($coachTransaction['IsSuccess'])
  717. $coachPoints = $coachTransaction['newpoints'];
  718. if($sendEmail == "1"){
  719. sendScheduleEmail($email, $coachname, "Chiron Gaming - Schedule","scheduled",$ch_user->username, $startEnd['start']." - ".$startEnd['end']);
  720. }
  721. }
  722. }
  723. insertNotifications($userid, 1, $_SESSION['user_id'], "Schedule", "", "User ".$requestorname." has schedule a lesson, please check your calendar","","/schedule.php");
  724. return $ret;
  725. }
  726. function sendScheduleEmail($to,$toName,$subject,$action,$fromName,$date){
  727. $TemplateFile="email_templates/schedule_notification.html";
  728. $TemplateFileHandler=fopen($TemplateFile,"r");
  729. $TemplateMessage=fread($TemplateFileHandler,filesize($TemplateFile));
  730. fclose($TemplateFileHandler);
  731. $TemplateMessage=str_replace("[TO]",$toName,$TemplateMessage);
  732. $TemplateMessage=str_replace("[FROM]",$fromName,$TemplateMessage);
  733. $TemplateMessage=str_replace("[ACTION]",$action,$TemplateMessage);
  734. $TemplateMessage=str_replace("[DATE]",$date,$TemplateMessage);
  735. sendEmail($to,$subject,$TemplateMessage);
  736. }
  737. function getUserInfo($userId){
  738. try{
  739. $db = new DBConnection();
  740. $db->getConnection();
  741. $sql = "SELECT * FROM `nk_user` WHERE `user_id` = '".$userId."'";
  742. $handle = mysql_query($sql);
  743. $row = mysql_fetch_object($handle);
  744. return $row;
  745. }catch(Exception $e){
  746. return $e->getMessage();
  747. }
  748. }
  749. function getGames(){
  750. $ret = array();
  751. try{
  752. $db = new DBConnection();
  753. $db->getConnection();
  754. $sql = "SELECT * FROM `nk_game`";
  755. $handle = mysql_query($sql);
  756. $rows = array();
  757. while ($games = mysql_fetch_object($handle)) {
  758. $ret[]=$games;
  759. }
  760. return $ret;
  761. }catch(Exception $e){
  762. return $e->getMessage();
  763. }
  764. }
  765. function getGame($gameId){
  766. $ret = array();
  767. try{
  768. $db = new DBConnection();
  769. $db->getConnection();
  770. $sql = "SELECT * FROM `nk_game` where game_id = ".$gameId;
  771. $handle = mysql_query($sql);
  772. return mysql_fetch_object($handle);
  773. }catch(Exception $e){
  774. return $e->getMessage();
  775. }
  776. }
  777. function getUserFullInfo($userId){//TODO: separate in 3 functions
  778. try{
  779. $db = new DBConnection();
  780. $db->getConnection();
  781. $sql = "SELECT * FROM `nk_user` WHERE `user_id` = '".$userId."'";
  782. $handle = mysql_query($sql);
  783. $row = mysql_fetch_object($handle);
  784. $row->onlinestatus = getUserStatusObject($row);
  785. $sql = "SELECT ut.user_type_id, ut.user_type_name, ut.user_type_description FROM nk_user_type_user_relation utr, nk_user_type ut WHERE utr.user_type_id = ut.user_type_id AND utr.user_id =".$row->user_id;
  786. $handle = mysql_query($sql);
  787. $row->user_types = array();
  788. while ($types = mysql_fetch_object($handle)) {
  789. $row->user_types[]=$types;
  790. }
  791. $sql = "SELECT * FROM nk_game g, nk_user_game ug WHERE g.game_id = ug.game_id AND ug.user_type_id = 1 AND ug.user_id =".$row->user_id;
  792. $handle = mysql_query($sql);
  793. $row->games = array();
  794. while ($games = mysql_fetch_object($handle)) {
  795. $row->games[]=$games;
  796. }
  797. if($userId == $_SESSION['user_id'])
  798. $row->owncalendar = '1';
  799. else{
  800. $row->owncalendar = '0';
  801. $sql = "SELECT * FROM `nk_user` WHERE `user_id` = '".$_SESSION['user_id']."'";
  802. $handle = mysql_query($sql);
  803. $row->loggedUser = mysql_fetch_object($handle);
  804. }
  805. return $row;
  806. }catch(Exception $e){
  807. return $e->getMessage();
  808. }
  809. }
  810. function updateScheduleStatus($id, $startTime, $endTime, $status){
  811. }
  812. function removeSlots($userid,$date,$schedules){
  813. $slots = getSlotsArray($schedules);
  814. $ret = updateCalendar($userid,$date,$slots,"1","","","","","","",true);
  815. }
  816. function getUsers(){
  817. try{
  818. $db = new DBConnection();
  819. $db->getConnection();
  820. $sql = "select * from `nk_user`";
  821. $handle = mysql_query($sql);
  822. echo "<br/>";
  823. while ($row = mysql_fetch_object($handle)) {
  824. echo "<a onclick=\"showCalendar('".$row->user_id."');\" id=\"calendar_".$row->user_id."\" href=\"javascript:;\">".$row->user_id." - ".$row->email."</a>";
  825. echo "<br/>";
  826. }
  827. }catch(Exception $e){
  828. $ret['error'] = $e->getMessage();
  829. }
  830. }
  831. function getNotifications(){
  832. $ret = array();
  833. $ret['notifications'] = array();
  834. try{
  835. $db = new DBConnection();
  836. $db->getConnection();
  837. //Notification
  838. $sql = "select * from `nk_notification` where `user_id` = " .$_SESSION['user_id'];
  839. $sql = $sql." order by `modified_date` DESC";
  840. $handle = mysql_query($sql);
  841. $unread = 0;
  842. while ($row = mysql_fetch_object($handle)) {
  843. if($row->new == 'Y')
  844. $unread++;
  845. $ret['notifications'][] = array(new Notification($row));
  846. }
  847. $ret['unreaded'] = $unread;
  848. $sql = "SELECT * FROM ".TABLEPREFIX."_user WHERE user_id = ".$_SESSION['user_id'];
  849. $handle = mysql_query($sql);
  850. $_SESSION['ch_user'] = mysql_fetch_array($handle);
  851. }catch(Exception $e){
  852. $ret['error'] = $e->getMessage();
  853. }
  854. return $ret;
  855. }
  856. function updateNotifications($userId, $title="", $introduction="", $text="", $date=""){//TODO
  857. $ret = array();
  858. try{
  859. $db = new DBConnection();
  860. $db->getConnection();
  861. $sql = "update `nk_notification` set ";
  862. if($title != "")
  863. $sql = $sql.",`title` = ";
  864. if($introduction != "")
  865. $sql = $sql.",`introduction`";
  866. if($text != "")
  867. $sql = $sql.",`text`";
  868. if($date != "")
  869. $sql = $sql.",`date_value`";
  870. $sql = $sql.",`modified_date`,`creation_date`) VALUES (".$userId;
  871. if($title != "")
  872. $sql = $sql.",'".$title."'";
  873. if($introduction != "")
  874. $sql = $sql.",'".$introduction."'";
  875. if($text != "")
  876. $sql = $sql.",'".$text."'";
  877. if($date != "")
  878. $sql = $sql.",'".php2MySqlTime(js2PhpTime($date))."'";
  879. $sql = $sql.",SYSDATE(), SYSDATE());";
  880. // echo $sql;
  881. if(mysql_query($sql)==false){
  882. $ret['IsSuccess'] = false;
  883. $ret['Msg'] = mysql_error();
  884. }else{
  885. $ret['IsSuccess'] = true;
  886. $ret['Msg'] = 'add success';
  887. $ret['Data'] = $date;
  888. $ret['Id'] = mysql_insert_id();
  889. }
  890. }catch(Exception $e){
  891. $ret['IsSuccess'] = false;
  892. $ret['Msg'] = $e->getMessage();
  893. }
  894. return $ret;
  895. }
  896. function insertNotifications($userId, $type=1, $origin="" , $title="", $introduction="", $text="", $date="",$link="",$extra_data="", $sendmail=false,$user=null){
  897. $ret = array();
  898. try{
  899. $db = new DBConnection();
  900. $db->getConnection();
  901. $sql = "INSERT INTO `nk_notification` (`user_id`,`nofication_type`";
  902. if($origin != "")
  903. $sql = $sql.",`origin`";
  904. if($title != "")
  905. $sql = $sql.",`title`";
  906. if($introduction != "")
  907. $sql = $sql.",`introduction`";
  908. if($text != "")
  909. $sql = $sql.",`text`";
  910. if($date != "")
  911. $sql = $sql.",`date_value`";
  912. if($link != "")
  913. $sql = $sql.",`link`";
  914. if($extra_data != "")
  915. $sql = $sql.",`extra_data`";
  916. $sql = $sql.",`modified_date`,`creation_date`) VALUES (".$userId.",".$type;
  917. if($origin != "")
  918. $sql = $sql.",'".$origin."'";
  919. if($title != "")
  920. $sql = $sql.",'".$title."'";
  921. if($introduction != "")
  922. $sql = $sql.",'".$introduction."'";
  923. if($text != "")
  924. $sql = $sql.",'".$text."'";
  925. if($date != "")
  926. $sql = $sql.",'".php2MySqlTime(js2PhpTime($date))."'";
  927. if($link != "")
  928. $sql = $sql.",'".$link."'";
  929. if($extra_data != "")
  930. $sql = $sql.",'".$extra_data."'";
  931. $sql = $sql.",NOW(), NOW());";
  932. // logToFile($sql);
  933. if(mysql_query($sql)==false){
  934. $ret['IsSuccess'] = false;
  935. $ret['Msg'] = mysql_error();
  936. }else{
  937. $ret['IsSuccess'] = true;
  938. $ret['Msg'] = 'add success';
  939. $ret['Data'] = $date;
  940. $ret['Id'] = mysql_insert_id();
  941. }
  942. }catch(Exception $e){
  943. $ret['IsSuccess'] = false;
  944. $ret['Msg'] = $e->getMessage();
  945. }
  946. if($sendmail){
  947. $body = "<h1></h1>
  948. <div>Hi ".$user->username."<br/></div>
  949. ";
  950. sendEmail($mail, $title,($link));
  951. }
  952. return $ret;
  953. }
  954. function sendEmail($to,$subject,$body, $from=""){
  955. if($from == "")
  956. $from = "no-reply@chirongaming.com";
  957. $headers = 'MIME-Version: 1.0' . "\r\n";
  958. $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
  959. $headers .= 'From: Chirongamming <no-reply@chirongaming.com>';
  960. mail($to, $subject, $body, $headers);
  961. }
  962. function markAsRead($ids){
  963. $ret = array();
  964. try{
  965. $db = new DBConnection();
  966. $db->getConnection();
  967. $sql = "update `nk_notification` set `new` = 'N', `date_readed` = SYSDATE() where `notification_id` in (".str_replace('#',',',$ids).")";
  968. if(mysql_query($sql)==false){
  969. $ret['IsSuccess'] = false;
  970. $ret['Msg'] = mysql_error();
  971. }else{
  972. $ret['IsSuccess'] = true;
  973. $ret['Msg'] = 'add success';
  974. }
  975. }catch(Exception $e){
  976. $ret['IsSuccess'] = false;
  977. $ret['Msg'] = $e->getMessage();
  978. }
  979. return $ret;
  980. }
  981. function deleteNotifications($ids){
  982. $ret = array();
  983. try{
  984. $db = new DBConnection();
  985. $db->getConnection();
  986. $sql = "DELETE FROM `nk_notification` WHERE `notification_id` IN (".str_replace('#',',',$ids).")";
  987. if(mysql_query($sql)==false){
  988. $ret['IsSuccess'] = false;
  989. $ret['Msg'] = mysql_error();
  990. }else{
  991. $ret['IsSuccess'] = true;
  992. $ret['Msg'] = 'add success';
  993. }
  994. }catch(Exception $e){
  995. $ret['IsSuccess'] = false;
  996. $ret['Msg'] = $e->getMessage();
  997. }
  998. return $ret;
  999. }
  1000. function getNextEvents($date,$day){
  1001. $date = gmdate("d#m#Y#H#i", $date);
  1002. list ($d, $month, $year,$hour,$minute) = split ('#',$date);
  1003. $calendar= listCalendar($_SESSION['user_id'], $day);
  1004. if (empty($calendar))
  1005. return "{}";
  1006. if(!array_key_exists("events", $calendar))
  1007. return "{}";
  1008. $ret = array();
  1009. $events = $calendar['events'][0][6];
  1010. for ($i = (($hour*2)+1); $i < 48; $i++) {
  1011. $event = $events[$i];
  1012. if($event->isEmpty || $event->availableSpot == 0 || $event->status == 3)
  1013. continue;
  1014. else{
  1015. $ret['events'][] = $event;
  1016. }
  1017. }
  1018. return $ret;
  1019. }
  1020. function doPing(){
  1021. $ret = array();
  1022. try{
  1023. $db = new DBConnection();
  1024. $db->getConnection();
  1025. $sql = "UPDATE `nk_user` SET `last_ping_time` = SYSDATE(),is_logged_in = 1 WHERE `user_id` = ".$_SESSION['user_id'];
  1026. if(mysql_query($sql)==false){
  1027. $ret['IsSuccess'] = false;
  1028. $ret['Msg'] = mysql_error();
  1029. }else{
  1030. $ret['IsSuccess'] = true;
  1031. $ret['Msg'] = 'update success';
  1032. }
  1033. }catch(Exception $e){
  1034. $ret['IsSuccess'] = false;
  1035. $ret['Msg'] = $e->getMessage();
  1036. }
  1037. return $ret;
  1038. }
  1039. function insertLesson($price,$rate, $coachid, $studentid, $gameId, $hours="1",$status=1, $time_zone_offset = 0, $start=0, $end=0, $lessonType=0){
  1040. try{
  1041. $db = new DBConnection();
  1042. $db->getConnection();
  1043. $user = $_SESSION['ch_user'];
  1044. $game = getGame($gameId);
  1045. $coach_name = "";
  1046. $student_name = "";
  1047. if($coachid == $_SESSION['user_id']){
  1048. $coach_name = $user['username'];
  1049. $st = getUserInfo($studentid);
  1050. $student_name = $st->username;
  1051. }else{
  1052. $student_name = $user['username'];
  1053. $co = getUserInfo($coachid);
  1054. $coach_name = $co->username;
  1055. }
  1056. $commision = getDefaultComission();
  1057. $sql = "INSERT INTO `nk_lesson` (`coach_name`,`student_name`,`lesson_type`,`time_zone_offset`,`game_id`,`lesson_title`,`lesson_description`, `coach_id`, `student_id`, `lesson_price`,`rate`, `lesson_commision_admin`, `lesson_status_id`, `lesson_payment_date`, `lesson_payment_transaction_no`, `lesson_closed_date`, `date_added`, `date_edited`,`start`,`end`) VALUES";
  1058. $sql .= " ('".$coach_name."','".$student_name."',".$lessonType.",".$time_zone_offset.",".$gameId.",'Lesson for game ".$game->game_name."', 'Lesson for game ".$game->game_name."',".$coachid.", ".$studentid.", ".$price.",".$rate.", ".$commision.", $status, NOW(), '0', NOW(), NOW(), NOW()";//,NOW(), NOW()+INTERVAL ".$hours." HOUR)";
  1059. if($start == 0){
  1060. $sql .= ",NOW()";
  1061. }else{
  1062. $sql .= ",'".$start."'";
  1063. }
  1064. if($end == 0){
  1065. $sql .= ", NOW()+INTERVAL ".$hours." HOUR";
  1066. }else{
  1067. $sql .= ",'".$end."'";
  1068. }
  1069. $sql .= ")";
  1070. // logToFile($sql);
  1071. if(mysql_query($sql)==false){
  1072. $ret['IsSuccess'] = false;
  1073. $ret['Msg'] = mysql_error();
  1074. }else{
  1075. $ret['IsSuccess'] = true;
  1076. $ret['gameName'] = $game->game_name;
  1077. $ret['text'] = "<div>User <b>".$user['username']."</b> has requested an instant lesson for <b>".$game->game_name."</b></div><div style=\'margin-top: 5px; font-size: 12px\'>If you confirm, the student\'s points will be instantly charged. You must initiate a chat and start coaching now!</div>";
  1078. $ret['lessonId'] = mysql_insert_id();
  1079. $ret['commision'] = $commision;
  1080. }
  1081. }catch(Exception $e){
  1082. $ret['IsSuccess'] = false;
  1083. $ret['Msg'] = $e->getMessage();
  1084. }
  1085. return $ret;
  1086. }
  1087. function getLesson($lessonId){
  1088. $ret = array();
  1089. try{
  1090. $db = new DBConnection();
  1091. $db->getConnection();
  1092. $sql = "SELECT * FROM `nk_lesson` WHERE `lesson_id` = ".$lessonId;
  1093. $handle = mysql_query($sql);
  1094. $row = mysql_fetch_object($handle);
  1095. return $row;
  1096. }catch(Exception $e){
  1097. $ret['error'] = $e->getMessage();
  1098. }
  1099. return $ret;
  1100. }
  1101. function changeLessonStatus($lessonId, $status, $statusReason=""){
  1102. try{
  1103. $ret = array();
  1104. $db = new DBConnection();
  1105. $db->getConnection();
  1106. $sql = "UPDATE `nk_lesson` SET `lesson_status_id` = ".$status.", `status_reason` = '".$statusReason."' WHERE `lesson_id` = ".$lessonId;
  1107. if(mysql_query($sql)==false){
  1108. $ret['IsSuccess'] = false;
  1109. $ret['Msg'] = mysql_error();
  1110. }else{
  1111. $ret['IsSuccess'] = true;
  1112. $ret['Msg'] = 'add success';
  1113. }
  1114. }catch(Exception $e){
  1115. $ret['error'] = $e->getMessage();
  1116. }
  1117. return $ret;
  1118. }
  1119. function removeCanceledLesson($lessonId, $utype){
  1120. try{
  1121. $ret = array();
  1122. $ret['lessonId'] = $lessonId;
  1123. $db = new DBConnection();
  1124. $db->getConnection();
  1125. $sql = "UPDATE `nk_lesson` SET `".$utype."` = 1 WHERE `lesson_id` = ".$lessonId;
  1126. if(mysql_query($sql)==false){
  1127. $ret['IsSuccess'] = false;
  1128. $ret['Msg'] = mysql_error();
  1129. }else{
  1130. $ret['IsSuccess'] = true;
  1131. $ret['Msg'] = 'add success';
  1132. }
  1133. }catch(Exception $e){
  1134. $ret['error'] = $e->getMessage();
  1135. }
  1136. return $ret;
  1137. }
  1138. function acceptInstantLesson($accept, $lessonId, $notifId){
  1139. $ret = array();
  1140. try{
  1141. markAsRead($notifId);
  1142. $db = new DBConnection();
  1143. $db->getConnection();
  1144. $coach = $_SESSION['ch_user'];
  1145. $lesson = getLesson($lessonId);
  1146. if($accept == 0){
  1147. $sql = "UPDATE `nk_lesson` SET `date_edited` = NOW(), `lesson_payment_date` = NOW(),`status_reason` = 'Instant Lesson not accepted', `lesson_status_id` = ".LessonStatus::CANCELED." WHERE `lesson_id` = ".$lessonId;
  1148. // logToFile($sql);
  1149. $text = "<b>".$coach['username']."</b> refused your Instant Lesson request. Please try again later.";
  1150. if(mysql_query($sql)==false){
  1151. $ret['IsSuccess'] = false;
  1152. $ret['text'] = $text;
  1153. $ret['studentid'] = $lesson->student_id;
  1154. $ret['Msg'] = mysql_error();
  1155. }else{
  1156. $ret['IsSuccess'] = true;
  1157. $ret['text'] = $text;
  1158. $ret['Msg'] = 'add success';
  1159. $ret['studentid'] = $lesson->student_id;
  1160. }
  1161. return $ret;
  1162. }else{
  1163. $student = getUserInfo($lesson->student_id);
  1164. if(intval($student->total_points) >= intval($lesson->lesson_price)){
  1165. insertTransaction($lesson->student_id, TransactionStatus::BOOKED , TransactionType::DEBIT, $lesson->lesson_price,$student->total_points, 0.0,UserType::STUDENT, "Instant Lesson, coach: ".$coach->username);
  1166. insertTransaction($_SESSION['user_id'], TransactionStatus::BOOKED , TransactionType::CREDIT, $lesson->lesson_price, $coach['total_points'],$lesson->lesson_commision_admin,UserType::COACH, "Instant Lesson, student: ".$student->username);
  1167. $sql = "UPDATE `nk_lesson` SET `date_edited` = NOW(), `lesson_payment_date` = NOW(), `lesson_status_id` = ".LessonStatus::PAID." WHERE `lesson_id` = ".$lessonId;
  1168. if(mysql_query($sql)==false){
  1169. $ret['IsSuccess'] = false;
  1170. $ret['Msg'] = mysql_error();
  1171. }else{
  1172. $ret['coachid'] = $_SESSION['user_id'];
  1173. $ret['studentid'] = $lesson->student_id;
  1174. $ret['lessonId'] = $lessonId;
  1175. $ret['IsSuccess'] = true;
  1176. $ret['text'] = "<div>User <b>".$coach['username']."</b> confirmed your Instant Lesson request.</div><div style=\'margin-top: 5px; font-size: 12px\'><b>".$coach['username']."</b> will initiate a chat to start your lesson shortly</div>";
  1177. $ret['Msg'] = 'add success';
  1178. }
  1179. }else{
  1180. $sql = "UPDATE `nk_lesson` SET `date_edited` = NOW(),`status_reason` = 'Not enough points', `lesson_payment_date` = NOW(), `lesson_status_id` = ".LessonStatus::CANCELED." WHERE `lesson_id` = ".$lessonId;
  1181. if(mysql_query($sql)==false){
  1182. $ret['IsSuccess'] = false;
  1183. $ret['Msg'] = mysql_error();
  1184. }
  1185. $ret['IsSuccess'] = false;
  1186. $ret['Msg'] = 'The student doesn\'t have enough points';
  1187. }
  1188. }
  1189. }catch(Exception $e){
  1190. $ret['error'] = $e->getMessage();
  1191. }
  1192. return $ret;
  1193. }
  1194. function calculateCommission($value,$comission=0.0,$userId, $userType, $txType){
  1195. try{
  1196. $value = floatval($value);
  1197. if($comission == 0.0)
  1198. $comission = getDefaultComission();
  1199. $percentage = floatval($comission)/100;
  1200. // if(TransactionType::CREDIT_REFUND == $txType){
  1201. // $value = $value+($value*$percentage);
  1202. // //remove points to chiron
  1203. // }else
  1204. if(TransactionType::CREDIT == $txType || TransactionType::CREDIT_REFUND == $txType){
  1205. $value = $value-($value*$percentage);
  1206. //add points to chiron
  1207. }
  1208. return $value;
  1209. }catch(Exception $e){
  1210. return $value;
  1211. }
  1212. }
  1213. function insertTransaction($userId, $txStatus, $txType, $value, $oldPoints, $comission=0.0, $userType=1, $description=""){
  1214. $ret = array();
  1215. try{
  1216. $value = calculateCommission($value,$comission,$userId,$userType,$txType);
  1217. $txDate = date("d/m/Y : H:i:s", time());
  1218. $txId = md5($userId.$txDate);
  1219. $newpoints = 0;
  1220. if($txType == TransactionType::CREDIT || $txType == TransactionType::DEBIT_REFUND)
  1221. $newpoints = $oldPoints+$value;
  1222. else
  1223. $newpoints = $oldPoints-$value;
  1224. $db = new DBConnection();
  1225. $db->getConnection();
  1226. $sql = "INSERT INTO nk_user_transaction(commission, nk_user_id, tx_date, rate_point_id, status, nk_tx_id,transaction_type, qty_points, description, total_before , total_after) VALUES(". $comission .",". $userId .", STR_TO_DATE('". $txDate ."', '%d/%m/%Y : %H:%i:%s'),-1, ". $txStatus .",'". $txId ."',".$txType.",".$value.",'".$description."',".$oldPoints.", ".$newpoints.")";
  1227. //logToFile($sql);
  1228. if(mysql_query($sql)==false){
  1229. $ret['IsSuccess'] = false;
  1230. $ret['Msg'] = mysql_error();
  1231. }else{
  1232. $ret['IsSuccess'] = true;
  1233. $ret['Msg'] = 'add success';
  1234. $ret['newpoints'] = $newpoints;
  1235. updateUserPoints($newpoints, $userId);
  1236. }
  1237. }catch(Exception $e){
  1238. $ret['error'] = $e->getMessage();
  1239. }
  1240. return $ret;
  1241. }
  1242. function getDefaultComission(){
  1243. try{
  1244. $db = new DBConnection();
  1245. $db->getConnection();
  1246. $sql = "SELECT default_comision_value FROM nk_default_comision";
  1247. $handle = mysql_query($sql);
  1248. $row = mysql_fetch_object($handle);
  1249. return $row->default_comision_value;
  1250. }catch(Exception $e){
  1251. return 1;
  1252. }
  1253. return 1;
  1254. }
  1255. function updateUserPoints($points,$userId=""){
  1256. $ret = array();
  1257. try{
  1258. if($userId == "")
  1259. $userId = $_SESSION['user_id'];
  1260. $sql = "UPDATE ".TABLEPREFIX."_user SET total_points = '".$points."' WHERE user_id = ".$userId;
  1261. if(mysql_query($sql)==false){
  1262. $ret['IsSuccess'] = false;
  1263. $ret['Msg'] ="Error: ".mysql_error();
  1264. }else{
  1265. $ret['IsSuccess'] = true;
  1266. $ret['Msg'] = "";
  1267. if($userId == $_SESSION['user_id']){
  1268. $sql = "SELECT * FROM ".TABLEPREFIX."_user WHERE user_id = ".$userId;
  1269. $handle = mysql_query($sql);
  1270. $_SESSION['ch_user'] = mysql_fetch_array($handle);
  1271. }
  1272. // $loggedUser = $_SESSION['ch_user'];
  1273. }
  1274. }catch(Exception $e){
  1275. $ret['IsSuccess'] = false;
  1276. $ret['Msg'] = $e->getMessage();
  1277. }
  1278. return $ret;
  1279. }
  1280. function getAllEvents(){
  1281. $calendar= listCalendar($_SESSION['user_id']);
  1282. if (empty($calendar))
  1283. return "{}";
  1284. if(!array_key_exists("events", $calendar))
  1285. return "{}";
  1286. $ret = array();
  1287. $events = $calendar['events'][0][6];
  1288. foreach($events as $event){
  1289. if($event->isEmpty || $event->availableSpot == 0 || $event->status == 3)
  1290. continue;
  1291. else{
  1292. $ret['events'][] = $event;
  1293. }
  1294. }
  1295. return $ret;
  1296. }
  1297. function addAsFriend($user){
  1298. $ret = array();
  1299. try{
  1300. $db = new DBConnection();
  1301. $db->getConnection();
  1302. $sqlCheck = "SELECT * FROM nk_user_f…

Large files files are truncated, but you can click here to view the full file