PageRenderTime 46ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 2ms

/lib/applicationlib.php

https://github.com/sportsynergy/clubpro
PHP | 6486 lines | 4237 code | 1169 blank | 1080 comment | 521 complexity | fbe1054208d01d13503510492a4b7040 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-3.0
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4: */
  3. /* ====================================================================
  4. * GNU Lesser General Public License
  5. * Version 2.1, February 1999
  6. *
  7. * <one line to give the library's name and a brief idea of what it does.>
  8. *
  9. * Copyright (C) 2001~2012 Adam Preston
  10. *
  11. *
  12. * This library is free software; you can redistribute it and/or
  13. * modify it under the terms of the GNU Lesser General Public
  14. * License as published by the Free Software Foundation; either
  15. * version 2.1 of the License, or (at your option) any later version.
  16. *
  17. * This library is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  20. * Lesser General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Lesser General Public
  23. * License along with this library; if not, write to the Free Software
  24. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  25. * $Id:$
  26. */
  27. /*
  28. Gets the possible outcomes for a match
  29. */
  30. function mysqli_result($res, $row, $field=0) {
  31. $res->data_seek($row);
  32. $datarow = $res->fetch_array();
  33. return $datarow[$field];
  34. }
  35. function getMatchScores($reservationid){
  36. $query = "SELECT gameswon,gameslost
  37. FROM tblMatchScore
  38. INNER JOIN tblCourts ON tblMatchScore.courttypeid = tblCourts.courttypeid
  39. INNER JOIN tblReservations ON tblCourts.courtid = tblReservations.courtid
  40. WHERE tblReservations.reservationid = $reservationid";
  41. return db_query($query);
  42. }
  43. function get_site_password($siteid){
  44. $sitePasswordQuery = "SELECT sites.password FROM tblClubSites sites WHERE sites.siteid = $siteid";
  45. $sitePasswordResult = db_query($sitePasswordQuery);
  46. $sitePasswordResultArray = mysqli_fetch_array($sitePasswordResult);
  47. return $sitePasswordResultArray[0];
  48. }
  49. /*
  50. Use send grid to send out emails from the admin
  51. */
  52. function sendgrid_clubmail($subject, $to_emails, $content, $category ){
  53. if (isDebugEnabled(1)) {
  54. logMessage("applicationlib.sendgrid_clubmail: sending email with subject $subject with a size " . count($to_emails) );
  55. }
  56. if( count($to_emails) == 0){
  57. if (isDebugEnabled(1)) {
  58. logMessage("applicationlib.sendgrid_clubmail: there is a problem with sending mail for $subject, exiting..." );
  59. }
  60. return;
  61. }
  62. $apiKey = $_SESSION["CFG"]["sendgrid_api"];
  63. $sendgrid = new SendGrid($apiKey);
  64. $mail = new SendGrid\Mail();
  65. foreach ($to_emails as $k=>$v){
  66. if (isDebugEnabled(1)) logMessage("applicationlib.sendgrid_email: sending email to: $k with subject $subject and category $category" );
  67. $personalization = new SendGrid\Personalization();
  68. $email = new SendGrid\Email($v['name'], $k);
  69. $personalization->addTo($email);
  70. $personalization->addSubstitution("%firstname%", $v['name']);
  71. if ( array_key_exists('url', $v) ){
  72. $personalization->addSubstitution("%signupurl%", $v['url']);
  73. }
  74. else {
  75. $personalization->addSubstitution("%signupurl%","");
  76. }
  77. $mail->addPersonalization($personalization);
  78. }
  79. $file_contents = file_get_contents($_SESSION["CFG"]["templatedir"]."/email/blank.email.html");
  80. $template = str_replace("%sitecode%", get_sitecode(), $file_contents);
  81. $template = str_replace("%content%", $content->line1, $template);
  82. $template = str_replace("%dns%", $_SESSION["CFG"]["dns"], $template);
  83. $template = str_replace("%app_root%", $_SESSION["CFG"]["wwwroot"], $template);
  84. $html_content = new SendGrid\Content("text/html", $template);
  85. $from_email = new SendGrid\Email(get_userfullname(), get_email() );
  86. $mail->setFrom($from_email);
  87. $mail->setSubject($subject);
  88. $mail->addCategory("Club Email");
  89. $mail->addCategory($content->clubname);
  90. $mail->addContent($html_content);
  91. try {
  92. $response = $sendgrid->client->mail()->send()->post($mail);
  93. } catch (Exception $e) {
  94. if (isDebugEnabled(1)) logMessage("applicationlib.sendgrid_email: Caught exception: " );
  95. }
  96. if (isDebugEnabled(1)) logMessage("applicationlib.sendgrid_email: mail was sent with status ". $response->statusCode() ." number of emails sent: ". count($personalization->getTos()) );
  97. }
  98. /*
  99. Uses sendgrid to send out system generated emails. Check out Sendgrid.com
  100. */
  101. function sendgrid_email($subject, $to_emails, $content, $category){
  102. if (isDebugEnabled(1)) {
  103. logMessage("applicationlib.sendgrid_email: sending email with subject $subject with a size " . count($to_emails) );
  104. }
  105. if( count($to_emails) == 0){
  106. if (isDebugEnabled(1)) {
  107. logMessage("applicationlib.sendgrid_email: there is a problem with sending mail for $subject, exiting..." );
  108. }
  109. return;
  110. }
  111. $apiKey = $_SESSION["CFG"]["sendgrid_api"];
  112. $sendgrid = new SendGrid($apiKey);
  113. $file_contents = file_get_contents($_SESSION["CFG"]["templatedir"]."/email/standard.email.html");
  114. $template = str_replace("%clubname%", $content->clubname, $file_contents);
  115. $template = str_replace("%sitecode%", get_sitecode(), $template);
  116. $template = str_replace("%content%", $content->line1, $template);
  117. $template = str_replace("%dns%", $_SESSION["CFG"]["dns"], $template);
  118. $template = str_replace("%app_root%", $_SESSION["CFG"]["wwwroot"], $template);
  119. $mail = new SendGrid\Mail();
  120. foreach ($to_emails as $k=>$v){
  121. if (isDebugEnabled(1)) logMessage("applicationlib.sendgrid_email: sending email to: $k with subject $subject and category $category and ".$v['name'] );
  122. $personalization = new SendGrid\Personalization();
  123. $email = new SendGrid\Email($v['name'], $k);
  124. $personalization->addTo($email);
  125. $personalization->addSubstitution("%firstname%", $v['name']);
  126. if ( array_key_exists('url', $v) ){
  127. $personalization->addSubstitution("%signupurl%", $v['url']);
  128. }
  129. else {
  130. $personalization->addSubstitution("%signupurl%","");
  131. }
  132. $mail->addPersonalization($personalization);
  133. }
  134. $from_email = new SendGrid\Email("Sportsynergy", $_SESSION["CFG"]["mailer.email"]);
  135. $html_content = new SendGrid\Content("text/html", $template);
  136. $mail->setFrom($from_email);
  137. $mail->setSubject($subject);
  138. $mail->addCategory($category);
  139. $mail->addCategory($content->clubname);
  140. $mail->addContent($html_content);
  141. try {
  142. $response = $sendgrid->client->mail()->send()->post($mail);
  143. } catch (Exception $e) {
  144. echo 'Caught exception: ', $e->getMessage(), "\n";
  145. }
  146. if (isDebugEnabled(1)) logMessage("applicationlib.sendgrid_email: mail was sent with status ". $response->statusCode() );
  147. if (isDebugEnabled(1)) logMessage("applicationlib.sendgrid_email: number of emails sent: ". count($personalization->getTos()) );
  148. if (isDebugEnabled(1)) logMessage("applicationlib.sendgrid_email: response body: ". $response->body() );
  149. }
  150. /**
  151. * Calls the PostageApp
  152. *
  153. * @param $subject
  154. * @param $to_email
  155. * @param $to_name
  156. * @param $content an array of line1, line2, line3
  157. */
  158. function send_email($subject, $to_emails, $from_email, $content, $template) {
  159. if (isDebugEnabled(1)) {
  160. logMessage("applicationlib.send_email: sending email with subject $subject with a size " . count($to_emails) . " from $from_email");
  161. }
  162. $variables = array(
  163. 'line1' => $content->line1,
  164. 'clubname' => $content->clubname
  165. );
  166. // Setup some headers
  167. $header = array(
  168. 'From' => $from_email,
  169. 'Reply-to' => $from_email
  170. );
  171. // Send it all
  172. $ret = PostageApp::mail($to_emails, $subject, $template, $header, $variables);
  173. // Checkout the response
  174. if ($ret->response->status == 'ok') {
  175. if (isDebugEnabled(1)) logMessage("applicationlib.send_email: SUCCESS An email was sent and the following response was received ".$ret->response->message);
  176. } else {
  177. if (isDebugEnabled(1)) logMessage("applicationlib.send_email: ERROR sending your email: ".$ret->response->status );
  178. }
  179. //return $response;
  180. }
  181. /**
  182. *
  183. * @param $dateString
  184. */
  185. function formatDate($dateString) {
  186. return date("Y-n-d G:i:s", $dateString);
  187. }
  188. /**
  189. * Logs in user
  190. *
  191. * One very interesting thing here is that anyone can use a superpassword to login.
  192. *
  193. * @param String $username
  194. * @param String $password
  195. * @param bool $encodedpassword
  196. */
  197. function verify_login($username, $password, $encodedpassword) {
  198. /* verify the username and password. if it is a valid login, return an array
  199. * with the username, firstname, lastname, and email address of the user */
  200. $superpassword = "20ffeee869abfadb176a66075c5f1816";
  201. if ($encodedpassword) {
  202. $password = md5($password);
  203. }
  204. if (isDebugEnabled(1)) logMessage("applicationlib.verify_login: Logging in $username");
  205. $loginQuery = "SELECT users.userid, users.username, users.firstname, users.lastname, users.email, clubuser.roleid, club.clubname
  206. FROM tblUsers users, tblClubUser clubuser, tblClubs club
  207. WHERE users.username = '$username'
  208. AND users.userid = clubuser.userid
  209. AND clubuser.clubid='" . get_clubid() . "'
  210. AND club.clubid = clubuser.clubid
  211. AND users.password = '$password'
  212. AND clubuser.enable='y'
  213. AND clubuser.enddate IS NULL";
  214. $loginResult = db_query($loginQuery);
  215. // If the login fails see if the superpassword was used
  216. if (mysqli_num_rows($loginResult) == 0) {
  217. //encode the superpassword
  218. // If they used the superpassword, then just get the user.
  219. if ($superpassword == $password) {
  220. $loginQuery = "SELECT users.userid, users.username, users.firstname, users.lastname, users.email, clubuser.roleid, club.clubname
  221. FROM tblUsers users, tblClubUser clubuser, tblClubs club
  222. WHERE users.username = '$username'
  223. AND users.userid = clubuser.userid
  224. AND clubuser.clubid='" . get_clubid() . "'
  225. AND club.clubid = clubuser.clubid
  226. AND clubuser.enable='y'
  227. AND clubuser.enddate IS NULL";
  228. $loginResult = db_query($loginQuery);
  229. }
  230. }
  231. return db_fetch_array($loginResult);
  232. }
  233. /**
  234. * Loads user (logs in with no password)
  235. * @param
  236. */
  237. function load_user($userid) {
  238. $loginQuery = "SELECT users.userid, users.username, users.firstname, users.lastname, users.email, clubuser.clubid, clubuser.roleid, club.clubname
  239. FROM tblUsers users, tblClubUser clubuser, tblClubs club
  240. WHERE users.userid = clubuser.userid
  241. AND clubuser.clubid
  242. AND clubuser.clubid='" . get_clubid() . "'
  243. AND users.userid = '$userid'
  244. AND clubuser.enable='y'
  245. AND club.clubid = clubuser.clubid
  246. AND clubuser.enddate IS NULL ";
  247. $loginResult = db_query($loginQuery);
  248. return db_fetch_array($loginResult);
  249. }
  250. /**
  251. * Returns all users with the given username.
  252. * @param unknown_type $username
  253. * @param unknown_type $clubid
  254. */
  255. function getAllUsersWithIdResult($username, $clubid) {
  256. $usersQuery = "SELECT users.userid, users.firstname, users.lastname
  257. FROM tblUsers users, tblClubUser clubuser
  258. WHERE users.username = '$username'
  259. AND users.userid = clubuser.userid
  260. AND clubuser.clubid='" . get_clubid() . "'
  261. AND clubuser.enddate IS NULL";
  262. return db_query($usersQuery);
  263. }
  264. /**
  265. * This determines if the user is valid for a sport.
  266. *
  267. * @param unknown_type $siteid
  268. * @return boolean
  269. */
  270. function amiValidForSite($siteid) {
  271. $amiauthforsiteQuery = "SELECT tblkupSiteAuth.userid, tblkupSiteAuth.siteid
  272. FROM tblkupSiteAuth
  273. WHERE (((tblkupSiteAuth.userid)=" . get_userid() . ") AND ((tblkupSiteAuth.siteid)=$siteid))";
  274. $amiauthforsiteResult = db_query($amiauthforsiteQuery);
  275. if (mysqli_num_rows($amiauthforsiteResult) == 0) {
  276. if (isDebugEnabled(1)) logMessage("applicationlib.amiValidForSite: " . get_userid() . " is NOT valid for $siteid");
  277. return FALSE;
  278. } else {
  279. if (isDebugEnabled(1)) logMessage("applicationlib.amiValidForSite: " . get_userid() . " is valid for $siteid");
  280. return TRUE;
  281. }
  282. }
  283. /**
  284. * This determines if the user is valid for a site.
  285. * @param unknown_type $courttypeid
  286. * @param unknown_type $userid
  287. * @return boolean Returns either TRUE or FALSE
  288. */
  289. function isValidForCourtType($courttypeid, $userid) {
  290. $amiauthforCourtTypeQuery = "SELECT tblUserRankings.courttypeid
  291. FROM tblUserRankings
  292. WHERE tblUserRankings.userid=$userid
  293. AND tblUserRankings.courttypeid=$courttypeid
  294. AND tblUserRankings.usertype=0";
  295. $amiauthforCourtTypeResult = db_query($amiauthforCourtTypeQuery);
  296. if (mysqli_num_rows($amiauthforCourtTypeResult) == 0) {
  297. if (isDebugEnabled(1)) logMessage("applicationlib.amiValidForCourtType: $userid is NOT valid for $courttypeid");
  298. return FALSE;
  299. } else {
  300. if (isDebugEnabled(1)) logMessage("applicationlib.amiValidForCourtType: $userid is valid for $courttypeid");
  301. return TRUE;
  302. }
  303. }
  304. /**
  305. * Check to see if I am a buddy
  306. * @param unknown_type $userid
  307. */
  308. function amIaBuddyOf($userid) {
  309. $imabuddy = FALSE;
  310. $imabuddyQuery = "SELECT buddyid FROM tblBuddies WHERE userid=$userid";
  311. $imabuddyResult = db_query($imabuddyQuery);
  312. while ($imabuddyArray = mysqli_fetch_array($imabuddyResult)) {
  313. if ($imabuddyArray['buddyid'] == get_userid()) {
  314. $imabuddy = TRUE;
  315. }
  316. }
  317. return $imabuddy;
  318. }
  319. /**
  320. * Checks to see if this person is a buddy.
  321. * @param unknown_type $buddyid
  322. * @return boolean
  323. */
  324. function isABuddyOfMine($buddyid) {
  325. $isABuddy = FALSE;
  326. $imabuddyQuery = "SELECT buddyid FROM tblBuddies WHERE userid=" . get_userid();
  327. $imabuddyResult = db_query($imabuddyQuery);
  328. while ($imabuddyArray = mysqli_fetch_array($imabuddyResult)) {
  329. if ($imabuddyArray['buddyid'] == $buddyid) {
  330. $isABuddy = TRUE;
  331. }
  332. }
  333. return $isABuddy;
  334. }
  335. /**
  336. * This is used to quickly set a match type. Right now as far as I know there are 4 possible match types:
  337. * 0 practice match
  338. * 1 box league match
  339. * 2 challenge match
  340. * 3 buddy match
  341. * @param unknown_type $resid
  342. * @param unknown_type $matchtype
  343. */
  344. function markMatchType($resid, $matchtype) {
  345. $markMatchTypeQuery = "Update tblReservations SET matchtype=$matchtype WHERE reservationid=$resid AND enddate IS NULL";
  346. $markMatchTypeResult = db_query($markMatchTypeQuery);
  347. }
  348. /**
  349. * This will find out if the calling user is in a box of the
  350. * courttype fo the court passed in as the argument.
  351. * Not very fancy here, true if they are false if they are not.
  352. *
  353. * @param unknown_type $courtid
  354. * @param unknown_type $userid
  355. */
  356. function is_inabox($courtid, $userid) {
  357. $amIinThisBox = FALSE;
  358. $courtTypeId = get_courtTypeForCourt($courtid);
  359. $amiinaboxquery = "SELECT boxleagues.courttypeid, boxleaguedetails.userid
  360. FROM tblBoxLeagues boxleagues, tblkpBoxLeagues boxleaguedetails
  361. WHERE boxleagues.boxid = boxleaguedetails.boxid
  362. AND boxleagues.courttypeid=$courtTypeId
  363. AND boxleaguedetails.userid=$userid";
  364. // run the query on the database
  365. $amiinaboxresult = db_query($amiinaboxquery);
  366. if (mysqli_num_rows($amiinaboxresult) > 0) {
  367. $amIinThisBox = TRUE;
  368. }
  369. return $amIinThisBox;
  370. }
  371. /**
  372. * returns the match type for the given reservationid
  373. *
  374. * @param unknown_type $resid
  375. * @return unknown
  376. */
  377. function getMatchType($resid) {
  378. $matchtypequery = "SELECT matchtype FROM `tblReservations` WHERE reservationid=$resid";
  379. $matchtyperesult = db_query($matchtypequery);
  380. $matchtypevalueArray = mysqli_fetch_array($matchtyperesult);
  381. $matchtypevalue = $matchtypevalueArray[0];
  382. return $matchtypevalue;
  383. }
  384. /**
  385. * When you need to just get the first and last name of a user and you only
  386. * seem to have there userid handy then this is the function for you.
  387. *
  388. * @param unknown_type $tid
  389. * @return string
  390. */
  391. function get_partnerbytid($tid) {
  392. $firstandlastquery = "SELECT users.firstname, users.lastname
  393. FROM tblkpTeams teamdetails, tblUsers users
  394. WHERE teamdetails.userid = users.userid
  395. AND teamdetails.teamid=$tid
  396. AND users.userid !=" . get_userid();
  397. $firstandlastresult = db_query($firstandlastquery);
  398. $firstandlastarray = mysqli_fetch_array($firstandlastresult);
  399. return "$firstandlastarray[0] $firstandlastarray[1]";
  400. }
  401. /**
  402. * Figuers out if this user is in this league.
  403. *
  404. * @param unknown_type $userid
  405. * @param unknown_type $courttypeid
  406. * @param unknown_type $clubid
  407. */
  408. function isUserInClubLadder($userid, $courttypeid, $clubid) {
  409. $query = "SELECT 1 FROM tblClubLadder ladder WHERE ladder.userid = $userid AND ladder.courttypeid = $courttypeid AND ladder.clubid = $clubid";
  410. $result = db_query($query);
  411. if (mysqli_num_rows($result) > 0) {
  412. return true;
  413. } else {
  414. return false;
  415. }
  416. }
  417. /**
  418. * Does not look at the reservation match type but only if the two players
  419. * are in a box together and that haven't recorded the score yet.
  420. *
  421. * @param unknown_type $reservationid
  422. * @return boolean Returns true if this is an unscore box league.
  423. */
  424. function isUnscoredBoxLeagueReservation($reservationid) {
  425. //Check reservation History
  426. $query = "SELECT * FROM tblBoxHistory history, tblkpUserReservations reservationdetails
  427. WHERE history.reservationid = $reservationid
  428. AND reservationdetails.reservationid = history.reservationid
  429. AND reservationdetails.outcome = 0";
  430. $results = db_query($query);
  431. //If reservation hasnt't been scored
  432. if (mysqli_num_rows($results) == 2) {
  433. return true;
  434. }
  435. return false;
  436. }
  437. /**
  438. * Called by the court reservation page to valiidate that
  439. * the the user is actually in a box leage with this opponent.
  440. *
  441. * @param unknown_type $playerOneId
  442. * @param unknown_type $playerTwoId
  443. */
  444. function getBoxIdTheseTwoGuysAreInTogether($playerOneId, $playerTwoId) {
  445. if( empty($playerOneId) || empty($playerTwoId) ){
  446. return false;
  447. }
  448. $playeronequery = "SELECT boxleagues.boxid, boxleaguedetails.userid
  449. FROM tblBoxLeagues boxleagues, tblkpBoxLeagues boxleaguedetails
  450. WHERE boxleagues.boxid = boxleaguedetails.boxid
  451. AND boxleaguedetails.userid=$playerOneId";
  452. // run the query on the database
  453. $playeroneresult = db_query($playeronequery);
  454. $p1stack = array();
  455. $p2stack = array();
  456. //Put all boxes for the user in an array
  457. while ($playeronearray = db_fetch_array($playeroneresult)) {
  458. array_push($p1stack, $playeronearray[0]);
  459. }
  460. $playertwoquery = "SELECT boxleagues.boxid, boxleaguedetails.userid
  461. FROM tblBoxLeagues boxleagues, tblkpBoxLeagues boxleaguedetails
  462. WHERE boxleagues.boxid = boxleaguedetails.boxid
  463. AND boxleaguedetails.userid=$playerTwoId";
  464. // run the query on the database
  465. $playertworesult = db_query($playertwoquery);
  466. //Put all boxes for the user in an array
  467. while ($playertwoarray = db_fetch_array($playertworesult)) {
  468. array_push($p2stack, $playertwoarray[0]);
  469. }
  470. $playersintersect = array_intersect($p1stack, $p2stack);
  471. return $playersintersect[0];
  472. }
  473. /**
  474. * Returns the box id when of the box that the players share. This function is called by
  475. * the court reservation page to validate that the the user is actually in a
  476. * box leage with this opponent
  477. * @param $playerone
  478. * @param $playertwo
  479. */
  480. function are_boxplayers($playerone, $playertwo) {
  481. if( empty($playerone) || empty($playertwo) ){
  482. return false;
  483. }
  484. $playeronequery = "SELECT boxleagues.boxid, boxleaguedetails.userid
  485. FROM tblBoxLeagues boxleagues, tblkpBoxLeagues boxleaguedetails
  486. WHERE boxleagues.boxid = boxleaguedetails.boxid
  487. AND boxleaguedetails.userid=$playerone";
  488. // run the query on the database
  489. $playeroneresult = db_query($playeronequery);
  490. $p1stack = array();
  491. $p2stack = array();
  492. //Put all boxes for the user in an array
  493. while ($playeronearray = db_fetch_array($playeroneresult)) {
  494. array_push($p1stack, $playeronearray[0]);
  495. }
  496. $playertwoquery = "SELECT boxleagues.boxid, boxleaguedetails.userid
  497. FROM tblBoxLeagues boxleagues, tblkpBoxLeagues boxleaguedetails
  498. WHERE boxleagues.boxid = boxleaguedetails.boxid
  499. AND boxleaguedetails.userid=$playertwo";
  500. // run the query on the database
  501. $playertworesult = db_query($playertwoquery);
  502. //Put all boxes for the user in an array
  503. while ($playertwoarray = db_fetch_array($playertworesult)) {
  504. array_push($p2stack, $playertwoarray[0]);
  505. }
  506. $playersintersect = array_intersect($p1stack, $p2stack);
  507. if (count($playersintersect) > 0) {
  508. return true;
  509. } else {
  510. return false;
  511. }
  512. }
  513. /**
  514. * this function will return true if the user has logged in. a user is logged
  515. * in if the $_SESSION["user"] is set (by the login.php page) and also if the
  516. * remote IP address matches what we saved in the session ($_SESSION["ip"])
  517. * from login.php -- this is not a robust or secure check by any means, but it
  518. * will do for now
  519. */
  520. function is_logged_in() {
  521. return isset($_SESSION) && isset($_SESSION["user"]);
  522. }
  523. /**
  524. * this function checks to see if the user is logged in. if not, it will show
  525. * the login screen before allowing the user to continue
  526. */
  527. function require_login() {
  528. if (!is_logged_in()) {
  529. $_SESSION["wantsurl"] = qualified_me();
  530. redirect($_SESSION["CFG"]["wwwroot"] . "/login.php");
  531. }
  532. }
  533. /**
  534. * this function checks to see if the user is logged in. if not, it will show
  535. * the login screen before allowing the user to continue
  536. */
  537. function require_loginwq() {
  538. if (!is_logged_in()) {
  539. // For clubsites set to auto login, look for username and password REQUEST parameters to
  540. // use for logging in.
  541. if( isSiteAutoLogin() ){
  542. $url_parts = parse_url(qualified_mewithq());
  543. parse_str($url_parts['query'], $params);
  544. if( isset($params['username']) && isset($params['password']) ){
  545. if (isDebugEnabled(1)) logMessage("applicationlib.require_loginwq: logging in autologin user: ". $params['username']);
  546. $user = verify_login( $params['username'],$params['password'], false );
  547. if( $user ){
  548. if (isDebugEnabled(1)) logMessage("applicationlib.require_loginwq: valid user");
  549. $_SESSION["user"] = $user;
  550. } else{
  551. redirect($_SESSION["CFG"]["wwwroot"] . "/login.php");
  552. }
  553. } else{
  554. redirect($_SESSION["CFG"]["wwwroot"] . "/login.php");
  555. }
  556. } else {
  557. $_SESSION["wantsurl"] = qualified_mewithq();
  558. redirect($_SESSION["CFG"]["wwwroot"] . "/login.php");
  559. }
  560. }
  561. }
  562. /**
  563. * this function simply returns the clubid.
  564. */
  565. function get_tzdelta() {
  566. return $_SESSION["siteprefs"]["timezone"] * 3600;
  567. }
  568. /**
  569. * this function simply returns the clubid.
  570. */
  571. function get_clubid() {
  572. return $_SESSION["siteprefs"]["clubid"];
  573. }
  574. /**
  575. * this function simply returns the siteid.
  576. */
  577. function get_siteid() {
  578. return $_SESSION["siteprefs"]["siteid"];
  579. }
  580. /**
  581. * this function simply returns the autologin status
  582. */
  583. function isSiteAutoLogin() {
  584. return $_SESSION["siteprefs"]["enableautologin"] == 'y' ? true : false;
  585. }
  586. /**
  587. * this function simply returns whether or not the recent activity should be displayed
  588. * @return boolean
  589. */
  590. function isDisplayRecentActivity() {
  591. return $_SESSION["siteprefs"]["displayrecentactivity"] == 'y' ? true : false;
  592. }
  593. /**
  594. * this function simply returns the daysahead or the parameter that defines how far in advance users can make.
  595. */
  596. function get_displaytime() {
  597. return $_SESSION["siteprefs"]["displaytime"];
  598. }
  599. /**
  600. * this function simply returns the whether or not the site has solo reservations enabled.
  601. * @return boolean
  602. */
  603. function isSoloReservationEnabled() {
  604. return $_SESSION["siteprefs"]["allowsoloreservations"] == 'y' ? true : false;
  605. }
  606. function isLadderRankingScheme() {
  607. /* this function simply returns the whether or not the site has solo reservations enabled. */
  608. return $_SESSION["siteprefs"]["rankingscheme"] == 'ladder' ? true : false;
  609. }
  610. function getChallengeRange() {
  611. /* this function simply returns the challenge range*/
  612. return $_SESSION["siteprefs"]["challengerange"];
  613. }
  614. function isPointRankingScheme() {
  615. /* this function simply returns the whether or not the site has solo reservations enabled. */
  616. return $_SESSION["siteprefs"]["rankingscheme"] == 'point' ? true : false;
  617. }
  618. function isSelfScoreEnabled() {
  619. /* this function simply returns the whether or not the site has self score enabled. */
  620. return $_SESSION["siteprefs"]["allowselfscore"] == 'y' ? true : false;
  621. }
  622. function isSiteEnabled() {
  623. /* this function simply returns the whether or not the site is enabled. */
  624. return $_SESSION["siteprefs"]["enable"] == 'y' ? true : false;
  625. }
  626. function getRankingAdjustment() {
  627. /* this function simply returns the site ranking adjustment. */
  628. return $_SESSION["siteprefs"]["rankingadjustment"];
  629. }
  630. function isSiteGuestReservationEnabled() {
  631. /* this function simply returns the siteid. */
  632. return $_SESSION["siteprefs"]["enableguestreservation"] == 'y' ? true : false;
  633. }
  634. function get_daysahead() {
  635. /* this function simply returns the daysahead or the parameter that defines how far in advance users can make. */
  636. return $_SESSION["siteprefs"]["daysahead"];
  637. }
  638. function get_facebookurl() {
  639. /* this function simply returns the the url. This is optional. */
  640. return $_SESSION["siteprefs"]["facebookurl"];
  641. }
  642. function isLiteVersion() {
  643. /* this function returns if the site is the free version. */
  644. return $_SESSION["siteprefs"]["isliteversion"] == 'y' ? true : false;
  645. }
  646. function isAllowAllSiteAdvertising() {
  647. return $_SESSION["siteprefs"]["allowallsiteadvertising"] == 'y' ? true : false;
  648. }
  649. function isNearRankingAdvertising() {
  650. return $_SESSION["siteprefs"]["allownearrankingadvertising"] == 'y' ? true : false;
  651. }
  652. function isDisplaySiteNavigation() {
  653. return $_SESSION["siteprefs"]["displaysitenavigation"] == 'y' ? true : false;
  654. }
  655. function isAllowPlayerslooking() {
  656. return $_SESSION["siteprefs"]["allowplayerslooking "] == 'y' ? true : false;
  657. }
  658. function get_reminders() {
  659. return $_SESSION["siteprefs"]["reminders"];
  660. }
  661. function isDisplayCourtTypeName() {
  662. return $_SESSION["siteprefs"]["displaycourttype"];
  663. }
  664. function isShowPlayerNames() {
  665. return $_SESSION["siteprefs"]["showplayernames"] == 'y' ? true : false;
  666. }
  667. function isRequireLogin() {
  668. return $_SESSION["siteprefs"]["requirelogin"] == 'y' ? true : false;
  669. }
  670. // Getter
  671. function get_roleid() {
  672. /* this function simply returns the roleid. */
  673. if( isset($_SESSION["user"]) ){
  674. return $_SESSION["user"]["roleid"];
  675. }
  676. return;
  677. }
  678. // Getter
  679. function get_userid() {
  680. /* this function simply returns the userid. */
  681. if( isset($_SESSION["user"]) ){
  682. return $_SESSION["user"]["userid"];
  683. }
  684. return;
  685. }
  686. function get_email() {
  687. /* this function simply returns the email. */
  688. return $_SESSION["user"]["email"];
  689. }
  690. function get_userfullname() {
  691. /* this function simply returns the logged in users first and last name. */
  692. return $_SESSION["user"]["firstname"] . " " . $_SESSION["user"]["lastname"];
  693. }
  694. function get_userfirstname() {
  695. /* this function simply returns the logged in users first and last name. */
  696. return $_SESSION["user"]["firstname"];
  697. }
  698. /*
  699. * this function simply returns the club name
  700. *
  701. * */
  702. function get_clubname() {
  703. return $_SESSION["siteprefs"]["clubname"];
  704. }
  705. function require_priv($roleid) {
  706. /* this function checks to see if the user has the privilege $roleid. if not,
  707. * it will display an Insufficient Privileges page and stop */
  708. if ($_SESSION["user"]["roleid"] != $roleid) {
  709. include ($_SESSION["CFG"]["templatedir"] . "/insufficient_privileges.php");
  710. die;
  711. }
  712. }
  713. function require_priv_user($userid) {
  714. /* just make sure current userid and specified user are in the same club */
  715. $my_site = $_SESSION["siteprefs"]["siteid"];
  716. $query = "SELECT * FROM tblkupSiteAuth WHERE userid = $userid AND siteid = $my_site";
  717. $result = db_query($query);
  718. if (mysqli_num_rows($result) == 0) {
  719. include ($_SESSION["CFG"]["templatedir"] . "/insufficient_privileges.php");
  720. die;
  721. }
  722. }
  723. function require_priv_reservation($reservationid) {
  724. /* just make sure current userid and specified user are in the same club */
  725. $my_site = $_SESSION["siteprefs"]["siteid"];
  726. $query = "SELECT 1 FROM tblReservations reservations
  727. INNER JOIN tblCourts courts ON reservations.courtid = courts.courtid
  728. WHERE reservations.reservationid = $reservationid
  729. AND courts.siteid = $my_site";
  730. $result = db_query($query);
  731. if (mysqli_num_rows($result) == 0) {
  732. if (isDebugEnabled(1)) logMessage("require_priv_reservation not allowed with site: $my_site and reservationid: $reservationid");
  733. include ($_SESSION["CFG"]["templatedir"] . "/insufficient_privileges.php");
  734. die;
  735. }
  736. }
  737. function require_priv_box($boxid) {
  738. /* just make sure current user and specified boxid are in the same club */
  739. $query = "SELECT siteid from tblBoxLeagues where boxid = $boxid";
  740. $result = db_query($query);
  741. $box_siteArray = mysqli_fetch_array($result);
  742. $box_site = $box_siteArray[0];
  743. if ($_SESSION["siteprefs"]["siteid"] != $box_site) {
  744. include ($_SESSION["CFG"]["templatedir"] . "/insufficient_privileges.php");
  745. die;
  746. }
  747. }
  748. function has_priv($roleid) {
  749. /* returns true if the user has the privilege $priv */
  750. if (isset($_SESSION["user"])) {
  751. return $_SESSION["user"]["roleid"] == $roleid;
  752. }
  753. }
  754. function atleastof_priv($roleid) {
  755. /* returns true if the user has the privilege $priv */
  756. return $_SESSION["user"]["roleid"] >= $roleid;
  757. }
  758. function err(&$errorvar) {
  759. /* if $errorvar is set, then print an error marker << */
  760. if (isset($errorvar)) {
  761. echo "<font color=#ff0000>&lt;&lt;</font>";
  762. }
  763. }
  764. function err2(&$errorvar) {
  765. /* like err(), but prints the marker >> */
  766. if (isset($errorvar)) {
  767. echo "<font color=#ff0000>&gt;&gt;</font>";
  768. }
  769. }
  770. function username_exists($username) {
  771. /* returns the true if the username exists */
  772. $qid = db_query("SELECT 1 FROM tblUsers users, tblClubUser clubuser
  773. WHERE users.username = '$username'
  774. AND users.userid = clubuser.userid
  775. AND clubuser.enddate IS NULL
  776. AND clubuser.clubid = " . get_clubid() . "");
  777. return db_num_rows($qid);
  778. }
  779. /**
  780. * Used to see if there is another one.
  781. */
  782. function username_already_exists($username, $userid) {
  783. /* returns the true if the username exists */
  784. $qid = db_query("SELECT users.username, users.userid FROM tblUsers users, tblClubUser clubuser
  785. WHERE users.username = '$username'
  786. AND users.userid = clubuser.userid
  787. AND clubuser.enddate IS NULL
  788. AND clubuser.clubid = " . get_clubid() . "");
  789. $userArray = db_fetch_array($qid);
  790. //If no rows are returned or if the username/userid is unique then the username is unique.
  791. if (db_num_rows($qid) == 0 || ($userArray['username'] == $username && $userArray['userid'] == $userid)) {
  792. return false;
  793. } else {
  794. return true;
  795. }
  796. }
  797. function email_exists($email) {
  798. /* returns true the email address exists */
  799. $query = "SELECT 1 FROM tblUsers users
  800. WHERE users.email = '$email'
  801. AND users.enddate IS NULL";
  802. $qid = db_query($query);
  803. return db_num_rows($qid);
  804. }
  805. /*
  806. *******************************************************************************************************
  807. ** makeTeamForCurrentUser
  808. creates a team, assigns a reanking and returns the new teamid for the current user
  809. *******************************************************************************************************
  810. */
  811. function makeTeamForCurrentUser($sportname, $partnerid) {
  812. global $dbh;
  813. /* Set the team identifier */
  814. $setteamquery = "INSERT INTO tblTeams (
  815. courttypeid
  816. ) VALUES (
  817. '$sportname')";
  818. // run the query on the database
  819. $setteamresult = db_query($setteamquery);
  820. /* Get the team id */
  821. $lastinsert = mysqli_insert_id($dbh);
  822. $addselfquery = "INSERT INTO tblkpTeams (
  823. teamid, userid
  824. ) VALUES ( $lastinsert
  825. ,'" . get_userid() . "')";
  826. // run the query on the database
  827. $addselfresult = db_query($addselfquery);
  828. /* Now add partner */
  829. // add self to new team
  830. $addpartnerquery = "INSERT INTO tblkpTeams (
  831. teamid, userid
  832. ) VALUES ( $lastinsert
  833. ,$partnerid)";
  834. // run the query on the database
  835. $addpartnerresult = db_query($addpartnerquery);
  836. // Finally update the rankings for the new team
  837. //Get the users doubles ranking for each team member
  838. $usersrankquery = "SELECT tblUserRankings.ranking
  839. FROM tblUserRankings
  840. WHERE (((tblUserRankings.userid)=" . get_userid() . "
  841. Or (tblUserRankings.userid)=$partnerid)
  842. AND ((tblUserRankings.courttypeid)=$sportname)
  843. AND ((tblUserRankings.usertype)=0))";
  844. $usersrankresult = db_query($usersrankquery);
  845. $rank1Array = mysqli_fetch_array($usersrankresult);
  846. $rank1 = $rank1Array[0];
  847. $usersrankresult = db_query($usersrankquery);
  848. $rank2Array = mysqli_fetch_array($usersrankresult);
  849. $rank2 = $rank2Array[0];
  850. $averagerank = ($rank1 + $rank2) / 2;
  851. $rankquery = "INSERT INTO tblUserRankings (
  852. userid, courttypeid, ranking, usertype
  853. ) VALUES (
  854. '$lastinsert'
  855. ,'$sportname'
  856. ,'$averagerank'
  857. ,1)";
  858. $rankresult = db_query($rankquery);
  859. $teaminfoarray = array(
  860. $averagerank,
  861. $lastinsert
  862. );
  863. return $teaminfoarray;
  864. }
  865. /*
  866. *******************************************************************************************************
  867. ** makeTeamForPlayers
  868. creates a team, assigns a reanking and returns the new teamid for two different players
  869. *******************************************************************************************************
  870. */
  871. function makeTeamForPlayers($sportname, $player1id, $player2id) {
  872. global $dbh;
  873. /* Set the team identifier */
  874. $setteamquery = "INSERT INTO tblTeams (
  875. courttypeid
  876. ) VALUES (
  877. '$sportname')";
  878. // run the query on the database
  879. $setteamresult = db_query($setteamquery);
  880. /* Get the team id */
  881. $lastinsert = mysqli_insert_id($dbh);
  882. $addselfquery = "INSERT INTO tblkpTeams (
  883. teamid, userid
  884. ) VALUES ( $lastinsert
  885. ,$player1id)";
  886. // run the query on the database
  887. $addselfresult = db_query($addselfquery);
  888. /* Now add partner */
  889. // add self to new team
  890. $addpartnerquery = "INSERT INTO tblkpTeams (
  891. teamid, userid
  892. ) VALUES ( $lastinsert
  893. ,$player2id)";
  894. // run the query on the database
  895. $addpartnerresult = db_query($addpartnerquery);
  896. // Finally update the rankings for the new team
  897. //Get the users doubles ranking for each team member
  898. $usersrankquery = "SELECT tblUserRankings.ranking
  899. FROM tblUserRankings
  900. WHERE (((tblUserRankings.userid)=$player1id
  901. Or (tblUserRankings.userid)=$player2id)
  902. AND ((tblUserRankings.courttypeid)=$sportname)
  903. AND ((tblUserRankings.usertype)=0))";
  904. $usersrankresult = db_query($usersrankquery);
  905. $rank1Array = mysqli_fetch_array($usersrankresult);
  906. $rank1 = $rank1Array[0];
  907. $usersrankresult = db_query($usersrankquery);
  908. $rank2Array = mysqli_fetch_array($usersrankresult);
  909. $rank2 = $rank2Array[0];
  910. $averagerank = ($rank1 + $rank2) / 2;
  911. $rankquery = "INSERT INTO tblUserRankings (
  912. userid, courttypeid, ranking, usertype
  913. ) VALUES (
  914. '$lastinsert'
  915. ,'$sportname'
  916. ,'$averagerank'
  917. ,1)";
  918. $rankresult = db_query($rankquery);
  919. $teaminfoarray = array(
  920. $averagerank,
  921. $lastinsert
  922. );
  923. return $teaminfoarray;
  924. }
  925. /**
  926. * This is really just an array funnction that will return the first element that is a duplication in the list
  927. */
  928. function findSelfTeam($array) {
  929. while ($teamid = array_pop($array)) {
  930. if (in_array($teamid, $array)) {
  931. return $teamid;
  932. }
  933. }
  934. }
  935. /**
  936. *
  937. * Enter description here ...
  938. * @param unknown_type $resid
  939. * @param unknown_type $emailType
  940. */
  941. function email_players($resid, $emailType) {
  942. if (isDebugEnabled(1)) logMessage("applicationlib.email_players: emailing Players about reservation id: $resid for a $emailType kind of email");
  943. //Check to see if the reservation is for a doubles court
  944. $usertypequery = "SELECT usertype FROM tblReservations WHERE reservationid=$resid";
  945. $usertyperesult = db_query($usertypequery);
  946. $usertypevalArray = mysqli_fetch_array($usertyperesult);
  947. $usertypeval = $usertypevalArray[0];
  948. if ($usertypeval == 0) {
  949. //email about a singles court
  950. $rquery = "SELECT courts.courtname, courts.courtid, reservations.time, users.userid, users.firstname, users.lastname, courttype.courttypeid, rankings.ranking, users.email, users.homephone, users.cellphone, users.workphone, matchtype.name
  951. FROM tblCourts courts, tblReservations reservations, tblUsers users, tblCourtType courttype, tblUserRankings rankings, tblkpUserReservations reservationdetails, tblMatchType matchtype
  952. WHERE users.userid = rankings.userid
  953. AND reservations.courtid = courts.courtid
  954. AND reservationdetails.reservationid = reservations.reservationid
  955. AND courttype.courttypeid = rankings.courttypeid
  956. AND courts.courttypeid = courttype.courttypeid
  957. AND reservationdetails.userid = users.userid
  958. AND matchtype.id = reservations.matchtype
  959. AND reservations.reservationid = $resid
  960. AND rankings.usertype=0";
  961. $rresult = db_query($rquery);
  962. $robj = mysqli_fetch_object($rresult);
  963. $var = new Object;
  964. if (isDebugEnabled(1)) logMessage("applicationlib.emailplayers: courtid " . $robj->courtid);
  965. /* email the user with the new account information */
  966. $var->userid = $robj->userid;
  967. $var->firstname = $robj->firstname;
  968. $var->lastname = $robj->lastname;
  969. $var->email = $robj->email;
  970. $var->homephone = $robj->homephone;
  971. $var->cellphone = $robj->cellphone;
  972. $var->workphone = $robj->workphone;
  973. $var->ranking = $robj->ranking;
  974. $var->courtname = $robj->courtname;
  975. $var->courtid = $robj->courtid;
  976. $var->matchtype = $robj->name;
  977. $var->time = gmdate("l F j g:i a", $robj->time);
  978. $var->timestamp = $robj->time;
  979. $var->dns = $_SESSION["CFG"]["dns"];
  980. $var->wwwroot = $_SESSION["CFG"]["wwwroot"];
  981. $var->fullname = $robj->firstname . " " . $robj->lastname;
  982. $var->support = $_SESSION["CFG"]["support"];
  983. //Set the URL
  984. $rawurl = "http://" . $var->dns . "" . $var->wwwroot . "/users/court_reservation.php?time=" . $var->timestamp . "&courtid=" . $var->courtid . "&userid=" . $var->userid;
  985. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/singles_wanted.php", $var);
  986. $emailbody = nl2br($emailbody);
  987. if ($emailType == "3") {
  988. $emailidquery = "SELECT DISTINCTROW users.firstname, users.lastname, users.email, clubuser.memberid, users.password
  989. FROM tblUsers users, tblUserRankings rankings, tblClubUser clubuser
  990. WHERE users.userid = rankings.userid
  991. AND users.userid = clubuser.userid
  992. AND clubuser.clubid=" . get_clubid() . "
  993. AND clubuser.recemail='y'
  994. AND rankings.courttypeid=$robj->courttypeid
  995. AND rankings.usertype = 0
  996. AND users.userid != " . get_userid() . "
  997. AND clubuser.enable= 'y'
  998. AND clubuser.enddate IS NULL";
  999. } elseif ($emailType == "2") {
  1000. $emailidquery = "SELECT users.firstname, users.lastname, users.email, clubuser.memberid, users.password
  1001. FROM tblUsers users, tblBuddies buddies, tblClubUser clubuser, tblUserRankings rankings
  1002. WHERE users.userid = buddies.buddyid
  1003. AND users.userid = clubuser.userid
  1004. AND clubuser.clubid=" . get_clubid() . "
  1005. AND buddies.userid=" . get_userid() . "
  1006. AND rankings.courttypeid=$robj->courttypeid
  1007. AND rankings.usertype = 0
  1008. AND users.userid = rankings.userid
  1009. AND clubuser.enable= 'y'
  1010. AND clubuser.enddate IS NULL";
  1011. } elseif ($emailType == "1") {
  1012. //Get the rankdev of the club
  1013. $rankdevquery = "SELECT rankdev FROM tblClubs WHERE clubid=" . get_clubid() . "";
  1014. // run the query on the database
  1015. $rankdevresult = db_query($rankdevquery);
  1016. $rankdevvalArray = mysqli_fetch_array($rankdevresult);
  1017. $rankdevval = $rankdevvalArray[0];
  1018. $highrange = $robj->ranking + $rankdevval;
  1019. $lowrange = $robj->ranking - $rankdevval;
  1020. //Now get all players who receive players wanted notifications at the club and are within
  1021. //the set skill range
  1022. $emailidquery = "SELECT DISTINCTROW users.firstname, users.lastname, users.email, clubuser.memberid, users.password
  1023. FROM tblUsers users, tblUserRankings rankings, tblClubUser clubuser
  1024. WHERE users.userid = rankings.userid
  1025. AND users.userid = clubuser.userid
  1026. AND clubuser.clubid=" . get_clubid() . "
  1027. AND rankings.ranking>$lowrange
  1028. AND rankings.ranking<$highrange
  1029. AND clubuser.recemail='y'
  1030. AND rankings.courttypeid=$robj->courttypeid
  1031. AND rankings.usertype = 0
  1032. AND users.userid != " . get_userid() . "
  1033. AND clubuser.enable='y'
  1034. AND clubuser.enddate IS NULL";
  1035. }
  1036. // run the query on the database
  1037. $emailidresult = db_query($emailidquery);
  1038. if (isDebugEnabled(1)) logMessage("applicationlib.emailplayers query: $emailidquery");
  1039. $to_emails = array();
  1040. while ($emailidrow = db_fetch_row($emailidresult)) {
  1041. // Append username and password to signup url
  1042. if( isSiteAutoLogin() ){
  1043. //guard
  1044. if( empty($emailidrow[3]) || empty($emailidrow[4]) ){
  1045. if (isDebugEnabled(1)) logMessage("applicationlib.emailplayers: problems sending email to autologin user: ".$emailidrow[2]);
  1046. continue;
  1047. }
  1048. $rawurl .= "&username=$emailidrow[3]&password=$emailidrow[4]";
  1049. }
  1050. $signupurl = "<a href=\"$rawurl\">here</a>.";
  1051. if( !empty($emailidrow[0]) && !empty($emailidrow[1]) && !empty($emailidrow[2])){
  1052. $to_email = "$emailidrow[2]";
  1053. $to_emails[$to_email] = array(
  1054. 'name' => $emailidrow[0],
  1055. 'url' => $signupurl
  1056. );
  1057. } else {
  1058. if (isDebugEnabled(1)) logMessage("applicationlib.emailplayers: ".get_userfullname()." not sending to $emailidrow[0] because of incomplete information");
  1059. }
  1060. }
  1061. $content = new Object;
  1062. $content->line1 = $emailbody;
  1063. $content->clubname = get_clubname();
  1064. $template = get_sitecode();
  1065. $subject = "Player's Market Place - ". get_clubname();
  1066. //Send the email
  1067. sendgrid_email($subject, $to_emails, $content, "Players Wanted");
  1068. }
  1069. //email about a doubles court
  1070. else {
  1071. $rquery = "SELECT
  1072. courts.courtname,
  1073. courts.courttypeid,
  1074. reservations.time,
  1075. users.firstname,
  1076. users.lastname,
  1077. courts.courtid,
  1078. users.userid,
  1079. matchtype.name,
  1080. teamdetails.teamid
  1081. FROM
  1082. tblReservations reservations,
  1083. tblkpUserReservations reservationdetails,
  1084. tblkpTeams teamdetails,
  1085. tblUsers users,
  1086. tblCourts courts,
  1087. tblMatchType matchtype,
  1088. tblClubUser clubuser
  1089. WHERE reservationdetails.reservationid = reservations.reservationid
  1090. AND teamdetails.teamid = reservationdetails.userid
  1091. AND reservationdetails.usertype = 1
  1092. AND users.userid = teamdetails.userid
  1093. AND courts.courtid = reservations.courtid
  1094. AND matchtype.id = reservations.matchtype
  1095. AND reservationdetails.reservationid=$resid
  1096. AND users.userid = clubuser.userid
  1097. AND clubuser.clubid =" . get_clubid();
  1098. $rresult = db_query($rquery);
  1099. $robj = mysqli_fetch_object($rresult);
  1100. $extraPlayerQuery = "SELECT reservationdetails.userid
  1101. FROM tblReservations reservations, tblkpUserReservations reservationdetails
  1102. WHERE reservations.reservationid = reservationdetails.reservationid
  1103. AND reservationdetails.reservationid=$resid
  1104. AND reservationdetails.usertype=0
  1105. ORDER BY reservationdetails.userid";
  1106. $extraPlayerResult = db_query($extraPlayerQuery);
  1107. $extraPlayerArray = mysqli_fetch_array($extraPlayerResult);
  1108. //Get Court Type. The reason this is done here is that in the cases of partial
  1109. //reservations, this is empty in the query above.
  1110. $ctQuery = "SELECT courts.courttypeid
  1111. FROM tblReservations reservations, tblCourts courts
  1112. WHERE reservations.reservationid=$resid
  1113. AND reservations.courtid = courts.courtid";
  1114. $ctResult = db_query($ctQuery);
  1115. $courtTypeArray = mysqli_fetch_array($ctResult);
  1116. $courtType = $courtTypeArray[0];
  1117. $player1 = $robj->userid;
  1118. $var = new Object;
  1119. /* email the user with the new account information */
  1120. $var->firstname1 = $robj->firstname;
  1121. $var->lastname1 = $robj->lastname;
  1122. $var->fullname1 = $robj->firstname . " " . $robj->lastname;
  1123. $var->teamid = $robj->teamid;
  1124. //Get the next result
  1125. $robj = mysqli_fetch_object($rresult);
  1126. $player2 = $robj->userid;
  1127. $var->firstname2 = $robj->firstname;
  1128. $var->lastname2 = $robj->lastname;
  1129. $var->fullname2 = $robj->firstname . " " . $robj->lastname;
  1130. $var->courtid = $robj->courtid;
  1131. $var->courtname = $robj->courtname;
  1132. $var->matchtype = $robj->name;
  1133. $var->time = gmdate("l F j g:i a", $robj->time);
  1134. $var->timestamp = $robj->time;
  1135. $var->dns = $_SESSION["CFG"]["dns"];
  1136. $var->wwwroot = $_SESSION["CFG"]["wwwroot"];
  1137. $var->support = $_SESSION["CFG"]["support"];
  1138. $clubfullname = get_clubname();
  1139. $var->clubfullname = $clubfullname;
  1140. $var->clubadminemail = "Sportsynergy <player.mailer@sportsynergy.net>";
  1141. /* if this reservation is made with a player looking for a partner, something will
  1142. be set in the extraPlayerQuery, if so display a different email message .
  1143. $extraPlayerobj->userid will be 0 when taking a player removes himself
  1144. from a reservation where he was looking for a match.
  1145. */
  1146. $extraPlayerUserId = 0;
  1147. //Check for three players wanted
  1148. if (db_num_rows($extraPlayerResult) == 2 && $extraPlayerArray['userid'] == 0) {
  1149. if (isDebugEnabled(1)) logMessage("applicationlib.emailplayers: three players are wanted");
  1150. //Obtain the court and matchtype information
  1151. $rquery = "SELECT courts.courtname, matchtype.name, reservations.time, courts.courtid
  1152. FROM tblMatchType matchtype, tblCourts courts, tblReservations reservations
  1153. WHERE reservations.reservationid=$resid
  1154. AND reservations.courtid = courts.courtid
  1155. AND matchtype.id = reservations.matchtype";
  1156. $rresult = db_query($rquery);
  1157. $robj = mysqli_fetch_object($rresult);
  1158. $var->courtname = $robj->courtname;
  1159. $var->courtid = $robj->courtid;
  1160. $var->matchtype = $robj->name;
  1161. $var->timestamp = $robj->time;
  1162. $var->time = gmdate("l F j g:i a", $robj->time);
  1163. $extraPlayerArray = mysqli_fetch_array($extraPlayerResult);
  1164. // check for invalid reservation
  1165. if($extraPlayerArray['userid'] == 0){
  1166. if (isDebugEnabled(1)) logMessage("applicationlib.emailplayers: $resid doesn't have any players in it.");
  1167. return;
  1168. }
  1169. $var->userid = $extraPlayerArray['userid'];
  1170. $partnerQuery = "SELECT tblUsers.firstname, tblUsers.lastname
  1171. FROM tblUsers
  1172. WHERE tblUsers.userid=$var->userid";
  1173. $partnerResult = db_query($partnerQuery);
  1174. $partnerobj = mysqli_fetch_object($partnerResult);
  1175. $var->single1 = $partnerobj->firstname . " " . $partnerobj->lastname;
  1176. $rawurl = "http://" . $var->dns . "" . $var->wwwroot . "/users/court_reservation.php?time=" . $var->timestamp . "&courtid=" . $var->courtid . "&userid=" . $var->userid;
  1177. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/threePlayersWanted.php", $var);
  1178. }
  1179. //Check for two players wanted
  1180. elseif (db_num_rows($extraPlayerResult) == 2 && $extraPlayerArray['userid'] != 0) {
  1181. if (isDebugEnabled(1)) logMessage("applicationlib.emailplayers: two players are wanted");
  1182. //Obtain the court and matchtype information
  1183. $rquery = "SELECT courts.courtname, matchtype.name, reservations.time
  1184. FROM tblMatchType matchtype, tblCourts courts, tblReservations reservations
  1185. WHERE reservations.reservationid=$resid
  1186. AND reservations.courtid = courts.courtid
  1187. AND matchtype.id = reservations.matchtype";
  1188. $rresult = db_query($rquery);
  1189. $robj = mysqli_fetch_object($rresult);
  1190. $var->courtname = $robj->courtname;
  1191. $var->matchtype = $robj->name;
  1192. $var->time = gmdate("l F j g:i a", $robj->time);
  1193. //Single Player One
  1194. $singlePlayerOne = $extraPlayerArray['userid'];
  1195. $playerOneQuery = "SELECT tblUsers.firstname, tblUsers.lastname
  1196. FROM tblUsers
  1197. WHERE ((tblUsers.userid)=$singlePlayerOne) ";
  1198. $playerOneResult = db_query($playerOneQuery);
  1199. $playerOneobj = mysqli_fetch_object($playerOneResult);
  1200. $var->single1 = $playerOneobj->firstname . " " . $playerOneobj->lastname;
  1201. //Single Player Two
  1202. $extraPlayerArray = mysqli_fetch_array($extraPlayerResult);
  1203. $singlePlayerTwo = $extraPlayerArray['userid'];
  1204. $playerTwoQuery = "SELECT tblUsers.firstname, tblUsers.lastname
  1205. FROM tblUsers
  1206. WHERE ((tblUsers.userid)=$singlePlayerTwo) ";
  1207. $playerTwoResult = db_query($playerTwoQuery);
  1208. $playerTwoobj = mysqli_fetch_object($playerTwoResult);
  1209. $var->single2 = $playerTwoobj->firstname . " " . $playerTwoobj->lastname;
  1210. $rawurl = "http://" . $var->dns . "" . $var->wwwroot . "/users/court_reservation.php?time=" . $var->timestamp . "&courtid=" . $var->courtid . "&userid=" . $singlePlayerOne;
  1211. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/twoPlayersWanted.php", $var);
  1212. }
  1213. //Check for one player wanted
  1214. elseif ($extraPlayerArray['userid'] != null && $extraPlayerArray['userid'] != 0) {
  1215. if (isDebugEnabled(1)) logMessage("applicationlib.emailplayers: one player is wanted.");
  1216. $extraPlayerUserId = $extraPlayerArray['userid'];
  1217. $partnerQuery = "SELECT tblUsers.firstname, tblUsers.lastname
  1218. FROM tblUsers WHERE tblUsers.userid=$extraPlayerUserId";
  1219. $partnerResult = db_query($partnerQuery);
  1220. $partnerobj = mysqli_fetch_object($partnerResult);
  1221. $var->partner = $partnerobj->firstname . " " . $partnerobj->lastname;
  1222. $rawurl = "http://" . $var->dns . "" . $var->wwwroot . "/users/court_reservation.php?time=" . $var->timestamp . "&courtid=" . $var->courtid . "&userid=" . $extraPlayerUserId;
  1223. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/partner_wanted.php", $var);
  1224. }
  1225. //Default for team wanted
  1226. else {
  1227. //guard against certain types of situations
  1228. if (empty($var->timestamp) || empty($var->courtid) || empty($var->teamid)) {
  1229. return;
  1230. }
  1231. $rawurl = "http://" . $var->dns . "" . $var->wwwroot . "/users/court_reservation.php?time=" . $var->timestamp . "&courtid=" . $var->courtid . "&userid=" . $var->teamid;
  1232. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/doubles_wanted.php", $var);
  1233. }
  1234. //INitialize to avoid situations where these are not set, such as when emails are
  1235. //being sent and not all players are set.
  1236. if (!isset($player1)) {
  1237. $player1 = 0;
  1238. }
  1239. if (!isset($player2)) {
  1240. $player2 = 0;
  1241. }
  1242. /*
  1243. * Email Advertisments are either set to the whole club or the list of buddies of the person making the reservation.
  1244. */
  1245. if ($emailType == "3") {
  1246. if (isDebugEnabled(1)) logMessage("applicationlib.emailplayers: gathering up the names to email to the whole club");
  1247. $emailidquery = "SELECT DISTINCTROW users.firstname, users.lastname, users.email,clubuser.memberid, users.password
  1248. FROM tblUsers users, tblUserRankings rankings, tblClubUser clubuser
  1249. WHERE users.userid = rankings.userid
  1250. AND users.userid = clubuser.userid
  1251. AND clubuser.clubid=" . get_clubid() . "
  1252. AND clubuser.recemail='y'
  1253. AND rankings.courttypeid=$courtType
  1254. AND rankings.usertype=0
  1255. AND users.userid != " . get_userid() . "
  1256. AND clubuser.enable='y'
  1257. AND clubuser.enddate IS NULL";
  1258. } elseif ($emailType == "2") {
  1259. if (isDebugEnabled(1)) logMessage("applicationlib.emailplayers: gathering up the names to email to ".get_userfullname()."'s buddy list");
  1260. $emailidquery = "SELECT DISTINCTROW users.firstname, users.lastname, users.email,clubuser.memberid, users.password
  1261. FROM tblUsers users, tblBuddies buddies, tblClubUser clubuser
  1262. WHERE users.userid = buddies.buddyid
  1263. AND users.userid = clubuser.userid
  1264. AND clubuser.clubid=" . get_clubid() . "
  1265. AND users.userid NOT IN ($player1, $player2, $extraPlayerUserId)
  1266. AND buddies.userid=" . get_userid() . "
  1267. AND clubuser.enable='y'
  1268. AND clubuser.enddate IS NULL";
  1269. } else {
  1270. //Get the rankdev of the club
  1271. $rankdevquery = "SELECT rankdev FROM tblClubs WHERE clubid=" . get_clubid() . "";
  1272. // run the query on the database
  1273. $rankdevresult = db_query($rankdevquery);
  1274. $rankdevvalArray = mysqli_fetch_array($rankdevresult);
  1275. $rankdevval = $rankdevvalArray[0];
  1276. // Get the Ranking of the current user (this based on the resid)
  1277. $query = "SELECT rankings.ranking
  1278. FROM tblUserRankings rankings, tblReservations reservations, tblCourts courts
  1279. WHERE reservations.reservationid = $resid
  1280. AND courts.courtid = reservations.courtid
  1281. AND courts.courttypeid = rankings.courttypeid
  1282. AND rankings.usertype = 0
  1283. AND rankings.userid = " . get_userid();
  1284. $result = db_query($query);
  1285. $rankingArray = mysqli_fetch_array($result);
  1286. $ranking = $rankingArray[0];
  1287. $highrange = $ranking + $rankdevval;
  1288. $lowrange = $ranking - $rankdevval;
  1289. //Now get all players who receive players wanted notifications at the club and are within the set skill range
  1290. $emailidquery = "SELECT users.firstname, users.lastname, users.email, clubuser.memberid, users.password
  1291. FROM tblUsers users
  1292. INNER JOIN tblUserRankings rankings ON users.userid = rankings.userid
  1293. INNER JOIN tblClubUser clubuser ON users.userid = clubuser.userid
  1294. WHERE users.userid = clubuser.userid
  1295. AND clubuser.clubid=" . get_clubid() . "
  1296. AND clubuser.recemail='y'
  1297. AND rankings.ranking>$lowrange
  1298. AND rankings.ranking<$highrange
  1299. AND rankings.courttypeid=$courtType
  1300. AND rankings.usertype =0
  1301. AND users.userid != $player1
  1302. AND users.userid != $player2
  1303. AND users.userid != $extraPlayerUserId
  1304. AND clubuser.enable='y'
  1305. AND clubuser.enddate IS NULL";
  1306. }
  1307. if (isDebugEnabled(1)) logMessage("applicationlib.email_players: query". $emailidquery );
  1308. // run the query on the database
  1309. $emailidresult = db_query($emailidquery);
  1310. $to_emails = array();
  1311. while ($emailidrow = db_fetch_row($emailidresult)) {
  1312. if (isDebugEnabled(1)) logMessage("applicationlib.emailplayers: sending email to ".$emailidrow[2]);
  1313. // Append username and password to signup url
  1314. if( isSiteAutoLogin() ){
  1315. $customurl = $rawurl."&username=$emailidrow[3]&password=$emailidrow[4]";
  1316. $signupurl = "<a href=\"$customurl\">here</a>.";
  1317. } else {
  1318. $signupurl = "<a href=\"$rawurl\">here</a>.";
  1319. }
  1320. if( !empty($emailidrow[0]) && !empty($emailidrow[1]) && !empty($emailidrow[2])){
  1321. $to_email = "$emailidrow[2]";
  1322. $to_emails[$to_email] = array(
  1323. 'name' => $emailidrow[0],
  1324. 'url' => $signupurl
  1325. );
  1326. }
  1327. }
  1328. $content = new Object;
  1329. $content->line1 = $emailbody;
  1330. $content->clubname = get_clubname();
  1331. $template = get_sitecode();
  1332. $subject = "Player's Market Place - ". get_clubname();
  1333. //Send the email
  1334. sendgrid_email($subject, $to_emails, $content, "Players Wanted");
  1335. }
  1336. }
  1337. /**
  1338. * This will advertise the reservation to box memebers (who haven't already played the current user)
  1339. * @param unknown_type $resid
  1340. * @param unknown_type $boxid
  1341. */
  1342. function email_boxmembers($resid, $boxid) {
  1343. /* load up the reservation infomation */
  1344. $rquery = "SELECT courts.courtname, reservations.time, users.firstname, users.lastname, rankings.ranking, reservations.matchtype, users.email, users.homephone, users.cellphone, users.workphone
  1345. FROM tblCourts courts, tblReservations reservations, tblUsers users, tblUserRankings rankings, tblkpUserReservations reservationdetails, tblCourtType courttype
  1346. WHERE users.userid = rankings.userid
  1347. AND courts.courtid = reservations.courtid
  1348. AND reservationdetails.reservationid = reservations.reservationid
  1349. AND courttype.courttypeid = rankings.courttypeid
  1350. AND courts.courttypeid = courttype.courttypeid
  1351. AND users.userid = reservationdetails.userid
  1352. AND reservations.reservationid=$resid
  1353. AND rankings.usertype=0";
  1354. $rresult = db_query($rquery);
  1355. //Get the next result
  1356. $robj = mysqli_fetch_object($rresult);
  1357. /* email the user with the new account information */
  1358. $var = new Object;
  1359. $var->matchtype = "league";
  1360. $var->firstname = $robj->firstname;
  1361. $var->lastname = $robj->lastname;
  1362. $var->email = $robj->email;
  1363. $var->homephone = $robj->homephone;
  1364. $var->cellphone = $robj->cellphone;
  1365. $var->workphone = $robj->workphone;
  1366. $var->ranking = $robj->ranking;
  1367. $var->courtname = $robj->courtname;
  1368. $var->time = gmdate("l F j g:i a", $robj->time);
  1369. $var->timestamp = $robj->time;
  1370. $var->dns = $_SESSION["CFG"]["dns"];
  1371. $var->wwwroot = $_SESSION["CFG"]["wwwroot"];
  1372. $var->fullname = $robj->firstname . " " . $robj->lastname;
  1373. $var->support = $_SESSION["CFG"]["support"];
  1374. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/singles_wanted.php", $var);
  1375. //Now get all boxmembers
  1376. $emailidquery = "SELECT users.userid, users.firstname, users.lastname, users.email
  1377. FROM tblUsers users, tblkpBoxLeagues boxdetails
  1378. WHERE users.userid = boxdetails.userid
  1379. AND boxdetails.boxid=$boxid
  1380. AND users.enddate IS NULL
  1381. AND users.userid<>" . get_userid();
  1382. // run the query on the database
  1383. $emailidresult = db_query($emailidquery);
  1384. $to_emails = array();
  1385. while ($emailidrow = mysqli_fetch_array($emailidresult)) {
  1386. if (!hasPlayedBoxWith(get_userid() , $emailidrow[userid], $boxid)) {
  1387. if (isDebugEnabled(1)) logMessage($emailbody);
  1388. $to_emails[$emailidrow[3]] = array(
  1389. 'name' => $emailidrow[1]
  1390. );
  1391. }
  1392. }
  1393. $content = new Object;
  1394. $content->line1 = $emailbody;
  1395. $content->clubname = get_clubname();
  1396. $template = get_sitecode();
  1397. $subject = "Player's Market Place - ".get_clubname();
  1398. //Send the email
  1399. sendgrid_email($subject, $to_emails, $content, "Box Members Wanted");
  1400. }
  1401. /**
  1402. *
  1403. * Enter description here ...
  1404. * @param unknown_type $resid
  1405. * @param unknown_type $isNewReservation
  1406. */
  1407. function confirm_singles($resid, $isNewReservation) {
  1408. $rquery = "SELECT courts.courtname, reservations.time, users.firstname, users.lastname, users.email, courts.courtid, reservations.matchtype, matchtype.name, reservations.usertype
  1409. FROM tblCourts courts, tblReservations reservations, tblUsers users, tblkpUserReservations reservationdetails, tblMatchType matchtype, tblClubUser clubuser
  1410. WHERE courts.courtid = reservations.courtid
  1411. AND users.userid = reservationdetails.userid
  1412. AND reservations.reservationid = reservationdetails.reservationid
  1413. AND reservations.reservationid=$resid
  1414. AND reservations.matchtype = matchtype.id
  1415. AND users.userid = clubuser.userid
  1416. AND clubuser.clubid=" . get_clubid();
  1417. $rresult = db_query($rquery);
  1418. $robj = mysqli_fetch_object($rresult);
  1419. $matchtype = $robj->matchtype;
  1420. if (isDebugEnabled(1)) logMessage("applicationlib.confirm_singles: sending out emails for a singles reservation matchtype: $matchtype");
  1421. /* email the user with the new account information */
  1422. $var = new Object;
  1423. $var->courtname = $robj->courtname;
  1424. $var->time = gmdate("l F j g:i a", $robj->time);
  1425. $var->timestamp = $robj->time;
  1426. $var->dns = $_SESSION["CFG"]["dns"];
  1427. $var->wwwroot = $_SESSION["CFG"]["wwwroot"];
  1428. $var->support = $_SESSION["CFG"]["support"];
  1429. $var->courtid = $robj->courtid;
  1430. $var->matchtype = $robj->name;
  1431. //Get the first player
  1432. $var->firstname1 = $robj->firstname;
  1433. $var->lastname1 = $robj->lastname;
  1434. $var->fullname1 = $robj->firstname . " " . $robj->lastname;
  1435. //Get the second player
  1436. $robj = mysqli_fetch_object($rresult);
  1437. $var->firstname2 = $robj->firstname;
  1438. $var->lastname2 = $robj->lastname;
  1439. $var->fullname2 = $robj->firstname . " " . $robj->lastname;
  1440. if (db_num_rows($rresult) == 1) {
  1441. if($matchtype == 4){
  1442. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/confirm_singles_lesson_looking.php", $var);
  1443. } elseif($matchtype == 5){
  1444. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/confirm_solo.php", $var);
  1445. } else {
  1446. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/confirm_singles_looking.php", $var);
  1447. }
  1448. } elseif ($matchtype == 4) {
  1449. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/confirm_lesson.php", $var);
  1450. } else {
  1451. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/confirm_singles.php", $var);
  1452. }
  1453. // Set the Subject
  1454. if ($isNewReservation) {
  1455. $subject = "Court Reservation Notice - ".get_clubname() ;
  1456. } else {
  1457. $subject = "Updated Court Reservation Notice - ".get_clubname();
  1458. }
  1459. //Reset the result pointer to the begining
  1460. mysqli_data_seek($rresult, 0);
  1461. $to_emails = array();
  1462. while ($emailidrow = db_fetch_row($rresult)) {
  1463. //If they don't even bother to put in an email address
  1464. //don't waste your time trying to send them an email.
  1465. if (!empty($emailidrow[4])) {
  1466. $to_emails[$emailidrow[4]] = array(
  1467. 'name' => $emailidrow[2]
  1468. );
  1469. }
  1470. }
  1471. $content = new Object;
  1472. $content->line1 = $emailbody;
  1473. $content->clubname = get_clubname();
  1474. $template = get_sitecode();
  1475. //Send the email
  1476. sendgrid_email($subject, $to_emails, $content, "Confirm Singles");
  1477. }
  1478. /**
  1479. *
  1480. * Enter description here ...
  1481. * @param unknown_type $resid
  1482. * @param unknown_type $isNewReservation
  1483. */
  1484. function audit_singles($resid, $isNewReservation) {
  1485. $rquery = "SELECT courts.courtname, reservations.time, users.firstname, users.lastname, users.email, courts.courtid, reservations.matchtype, matchtype.name, reservations.usertype, users.userid
  1486. FROM tblCourts courts, tblReservations reservations, tblUsers users, tblkpUserReservations reservationdetails, tblMatchType matchtype, tblClubUser clubuser
  1487. WHERE courts.courtid = reservations.courtid
  1488. AND users.userid = reservationdetails.userid
  1489. AND reservations.reservationid = reservationdetails.reservationid
  1490. AND reservations.reservationid=$resid
  1491. AND reservations.matchtype = matchtype.id
  1492. AND users.userid = clubuser.userid
  1493. AND clubuser.clubid=" . get_clubid();
  1494. $rresult = db_query($rquery);
  1495. $robj = mysqli_fetch_object($rresult);
  1496. $matchtype = $robj->matchtype;
  1497. if (isDebugEnabled(1)) logMessage("applicationlib.audit_singles: sending out emails for a singles reservation matchtype: $matchtype");
  1498. $players_in_reservation[] = $robj->userid;
  1499. /* email the user with the new account information */
  1500. $var = new Object;
  1501. $var->courtname = $robj->courtname;
  1502. $var->time = gmdate("l F j g:i a", $robj->time);
  1503. $var->timestamp = $robj->time;
  1504. $var->dns = $_SESSION["CFG"]["dns"];
  1505. $var->wwwroot = $_SESSION["CFG"]["wwwroot"];
  1506. $var->support = $_SESSION["CFG"]["support"];
  1507. $var->courtid = $robj->courtid;
  1508. $var->matchtype = $robj->name;
  1509. //Get the first player
  1510. $var->firstname1 = $robj->firstname;
  1511. $var->lastname1 = $robj->lastname;
  1512. $var->fullname1 = $robj->firstname . " " . $robj->lastname;
  1513. //Get the second player
  1514. $robj = mysqli_fetch_object($rresult);
  1515. $players_in_reservation[] = $robj->userid;
  1516. $var->firstname2 = $robj->firstname;
  1517. $var->lastname2 = $robj->lastname;
  1518. $var->fullname2 = $robj->firstname . " " . $robj->lastname;
  1519. if (db_num_rows($rresult) == 1) {
  1520. if($matchtype == 4){
  1521. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/confirm_singles_lesson_looking.php", $var);
  1522. } elseif($matchtype == 5){
  1523. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/confirm_solo.php", $var);
  1524. } else {
  1525. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/confirm_singles_looking.php", $var);
  1526. }
  1527. } elseif ($matchtype == 4) {
  1528. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/confirm_lesson.php", $var);
  1529. } else {
  1530. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/confirm_singles.php", $var);
  1531. }
  1532. // Set the Subject
  1533. if ($isNewReservation) {
  1534. $subject = "New Player Reservation Notice - ".get_clubname() ;
  1535. } else {
  1536. $subject = "Updated Player Reservation Notice - ".get_clubname();
  1537. }
  1538. //Reset the result pointer to the begining
  1539. mysqli_data_seek($rresult, 0);
  1540. $to_emails = array();
  1541. $auditQuery = "SELECT users.userid, users.username, users.firstname, users.lastname, users.email
  1542. FROM tblUsers users, tblClubUser clubuser, tblClubs club
  1543. WHERE users.userid = clubuser.userid
  1544. AND clubuser.clubid='" . get_clubid() . "'
  1545. AND club.clubid = clubuser.clubid
  1546. AND clubuser.enable='y'
  1547. AND clubuser.ccnew='y'
  1548. AND clubuser.enddate IS NULL";
  1549. $auditResult = db_query($auditQuery);
  1550. while ($auditor = db_fetch_array($auditResult)) {
  1551. // if any of the people in the reservation have this setting, don't send
  1552. if (in_array($auditor['userid'], $players_in_reservation)) {
  1553. if (isDebugEnabled(1)) logMessage("applicationlib.audit_singles: not sending audit to ". $auditor['userid']. " because this person is in reservation. redundant.");
  1554. continue;
  1555. }
  1556. $to_emails[$auditor['email']] = array(
  1557. 'name' => $auditor['firstname']
  1558. );
  1559. }
  1560. $content = new Object;
  1561. $content->line1 = $emailbody;
  1562. $content->clubname = get_clubname();
  1563. $template = get_sitecode();
  1564. //Send the email
  1565. sendgrid_email($subject, $to_emails, $content, "Confirm Singles");
  1566. }
  1567. /**
  1568. *
  1569. * Enter description here ...
  1570. * @param unknown_type $resid
  1571. */
  1572. function cancel_singles($resid) {
  1573. $rquery = "SELECT DISTINCTROW courts.courtname, reservations.time, users.firstname, users.lastname, users.email, courts.courtid, reservations.matchtype, matchtype.name
  1574. FROM tblCourts courts, tblUsers users, tblReservations reservations, tblkpUserReservations reservationdetails, tblUserRankings rankings, tblMatchType matchtype, tblClubUser clubuser
  1575. WHERE courts.courtid = reservations.courtid
  1576. AND rankings.userid = users.userid
  1577. AND reservationdetails.userid = users.userid
  1578. AND reservations.reservationid = reservationdetails.reservationid
  1579. AND reservations.reservationid=$resid
  1580. AND reservations.matchtype = matchtype.id
  1581. AND users.userid = clubuser.userid
  1582. AND clubuser.clubid=" . get_clubid();
  1583. $rresult = db_query($rquery);
  1584. $robj = mysqli_fetch_object($rresult);
  1585. /* email the user with the new account information */
  1586. $var = new Object;
  1587. $var->courtname = $robj->courtname;
  1588. $var->time = gmdate("l F j g:i a", $robj->time);
  1589. $var->timestamp = $robj->time;
  1590. $var->dns = $_SESSION["CFG"]["dns"];
  1591. $var->wwwroot = $_SESSION["CFG"]["wwwroot"];
  1592. $var->support = $_SESSION["CFG"]["support"];
  1593. $var->courtid = $robj->courtid;
  1594. $var->matchtype = $robj->name;
  1595. //Get the first player
  1596. $var->firstname1 = $robj->firstname;
  1597. $var->lastname1 = $robj->lastname;
  1598. $var->fullname1 = $robj->firstname . " " . $robj->lastname;
  1599. //Get the second player
  1600. $robj = mysqli_fetch_object($rresult);
  1601. $var->firstname2 = $robj->firstname;
  1602. $var->lastname2 = $robj->lastname;
  1603. $var->fullname2 = $robj->firstname . " " . $robj->lastname;
  1604. if (db_num_rows($rresult) == 1) {
  1605. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/cancel_singles_looking.php", $var);
  1606. } else
  1607. if ($robj->matchtype == 4) {
  1608. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/cancel_lesson.php", $var);
  1609. } elseif ($robj->matchtype == 5) {
  1610. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/cancel_solo.php", $var);
  1611. } else {
  1612. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/cancel_singles.php", $var);
  1613. }
  1614. //Reset the result pointer to the begining
  1615. mysqli_data_seek($rresult, 0);
  1616. $to_emails = array();
  1617. while ($emailidrow = db_fetch_row($rresult)) {
  1618. if (!empty($emailidrow[4])) {
  1619. $to_emails[$emailidrow[4]] = array(
  1620. 'name' => $emailidrow[2]
  1621. );
  1622. }
  1623. }
  1624. $content = new Object;
  1625. $content->line1 = $emailbody;
  1626. $content->clubname = get_clubname();
  1627. $template = get_sitecode();
  1628. $subject = "Court Cancellation Notice";
  1629. //Send the email
  1630. sendgrid_email($subject, $to_emails, $content, "Cancel Singles");
  1631. }
  1632. /**
  1633. * This function only sends out emails to those players who are currently in the
  1634. * reservation, this includes players in a team or singles players who are still
  1635. * looking for partner.
  1636. * @param unknown_type $resid
  1637. * @param unknown_type $isNewReservation
  1638. */
  1639. function confirm_doubles($resid, $isNewReservation) {
  1640. if (isDebugEnabled(1)) logMessage("applicationlib.confirm_doubles: confirming reservation $resid isNewReservation $isNewReservation");
  1641. $var = new Object;
  1642. $template = get_sitecode();
  1643. $from_email = "Sportsynergy <player.mailer@sportsynergy.net>";
  1644. //Obtain the court and matchtype information
  1645. $timeQuery = "SELECT courts.courtname, matchtype.name, reservations.time
  1646. FROM tblMatchType matchtype, tblCourts courts, tblReservations reservations
  1647. WHERE reservations.reservationid=$resid
  1648. AND reservations.courtid = courts.courtid
  1649. AND matchtype.id = reservations.matchtype";
  1650. $timeResult = db_query($timeQuery);
  1651. $timeObject = mysqli_fetch_object($timeResult);
  1652. $var->courtname = $timeObject->courtname;
  1653. $var->matchtype = $timeObject->name;
  1654. $var->time = gmdate("l F j g:i a", $timeObject->time);
  1655. //Obtain player information
  1656. $playerQuery = "SELECT DISTINCTROW users.firstname, users.lastname, users.email
  1657. FROM tblReservations reservations, tblUsers users, tblkpTeams teamdetails, tblkpUserReservations reservationdetails
  1658. WHERE reservationdetails.reservationid = reservations.reservationid
  1659. AND teamdetails.teamid = reservationdetails.userid
  1660. AND users.userid = teamdetails.userid
  1661. AND reservationdetails.reservationid=$resid
  1662. AND reservationdetails.usertype = 1";
  1663. $playerResult = db_query($playerQuery);
  1664. $playerObject = mysqli_fetch_object($playerResult);
  1665. $numofrows = mysqli_num_rows($playerResult);
  1666. $var->dns = $_SESSION["CFG"]["dns"];
  1667. $var->wwwroot = $_SESSION["CFG"]["wwwroot"];
  1668. $var->support = $_SESSION["CFG"]["support"];
  1669. //Get the first player of team 1
  1670. $var->firstname1 = $playerObject->firstname;
  1671. $var->lastname1 = $playerObject->lastname;
  1672. $var->fullname1 = $playerObject->firstname . " " . $playerObject->lastname;
  1673. //Get the second player of team 1
  1674. $playerObject = mysqli_fetch_object($playerResult);
  1675. $var->firstname2 = $playerObject->firstname;
  1676. $var->lastname2 = $playerObject->lastname;
  1677. $var->fullname2 = $playerObject->firstname . " " . $playerObject->lastname;
  1678. //Get the first player of team 2
  1679. $playerObject = mysqli_fetch_object($playerResult);
  1680. $var->firstname3 = $playerObject->firstname;
  1681. $var->lastname3 = $playerObject->lastname;
  1682. $var->fullname3 = $playerObject->firstname . " " . $playerObject->lastname;
  1683. //Get the second player of team 2
  1684. $playerObject = mysqli_fetch_object($playerResult);
  1685. $var->firstname4 = $playerObject->firstname;
  1686. $var->lastname4 = $playerObject->lastname;
  1687. $var->fullname4 = $playerObject->firstname . " " . $playerObject->lastname;
  1688. $clubfullname = get_clubname();
  1689. $var->clubfullname = $clubfullname;
  1690. $var->clubadminemail = "player.mailer@sportsynergy.net";
  1691. // Set the Subject
  1692. if ($isNewReservation) {
  1693. $subject = "Court Reservation Notice - ".get_clubname() ;
  1694. } else {
  1695. $subject = "Updated Court Reservation Notice - ".get_clubname();
  1696. }
  1697. //Check to see if there is a single wanting to play
  1698. $extraPlayerQuery = "SELECT reservationdetails.userid, users.firstname, users.lastname, users.email
  1699. FROM tblReservations reservations, tblkpUserReservations reservationdetails, tblUsers users
  1700. WHERE reservations.reservationid = reservationdetails.reservationid
  1701. AND reservationdetails.userid = users.userid
  1702. AND reservationdetails.reservationid=$resid
  1703. AND reservationdetails.usertype=0";
  1704. $extraPlayerResult = db_query($extraPlayerQuery);
  1705. $extraPlayerobj = mysqli_fetch_object($extraPlayerResult);
  1706. //Prepare and send emails to single player where there is just one player in the whole reservation
  1707. if (mysqli_num_rows($extraPlayerResult) == 1 && mysqli_num_rows($playerResult) == 0) {
  1708. if (isDebugEnabled(1)) logMessage("applicationlib.confirm_doubles: send emails to single player where there is only one");
  1709. $var->partner = $extraPlayerobj->firstname . " " . $extraPlayerobj->lastname;
  1710. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/confirm_doubles_looking_for_three.php", $var);
  1711. if (isDebugEnabled(1)) logMessage($emailbody);
  1712. // Provide Content
  1713. $content = new Object;
  1714. $content->line1 = $emailbody;
  1715. $content->clubname = get_clubname();
  1716. $to_email = "$extraPlayerobj->email";
  1717. $to_emails = array(
  1718. $to_email => array(
  1719. 'name' => $extraPlayerobj->firstname
  1720. )
  1721. );
  1722. //Send the email
  1723. sendgrid_email($subject, $to_emails, $content, "Confirm Doubles");
  1724. }
  1725. //Prepare and send emails to single players where there is more than one person looking for a partner
  1726. elseif (mysqli_num_rows($extraPlayerResult) == 2) {
  1727. if (isDebugEnabled(1)) logMessage("applicationlib.confirm_doubles: send out emails to single players where more than one is looking");
  1728. $var->fullname1 = getFullNameForUserId($extraPlayerobj->userid);
  1729. //Get the next player
  1730. $extraPlayerobj = mysqli_fetch_object($extraPlayerResult);
  1731. $var->fullname2 = getFullNameForUserId($extraPlayerobj->userid);
  1732. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/confirm_doubles_for_players_looking.php", $var);
  1733. //Reset Counter
  1734. if (mysqli_num_rows($extraPlayerResult) > 0) mysqli_data_seek($extraPlayerResult, 0);
  1735. $to_emails = array();
  1736. if (isDebugEnabled(1)) logMessage($emailbody);
  1737. $to_email = "$extraPlayerobj->email";
  1738. $to_emails[$to_email] = array(
  1739. 'name' => $extraPlayerobj->firstname
  1740. );
  1741. //Get next player
  1742. $extraPlayerobj = mysqli_fetch_object($extraPlayerResult);
  1743. $to_email = "$extraPlayerobj->email";
  1744. $to_emails[$to_email] = array(
  1745. 'name' => $extraPlayerobj->firstname
  1746. );
  1747. // Provide Content
  1748. $content = new Object;
  1749. $content->line1 = $emailbody;
  1750. $content->clubname = get_clubname();
  1751. //Send the email
  1752. sendgrid_email($subject, $to_emails, $content, "Confirm Doubles");
  1753. }
  1754. //Prepare and send emails to single player where there is only one person needing a partner
  1755. elseif (mysqli_num_rows($extraPlayerResult) == 1) {
  1756. if (isDebugEnabled(1)) logMessage("applicationlib.confirm_doubles: send out emails where there is only one person needing a partner");
  1757. $var->partner = $extraPlayerobj->firstname . " " . $extraPlayerobj->lastname;
  1758. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/confirm_double_for_player_looking.php", $var);
  1759. if (isDebugEnabled(1)) logMessage($emailbody);
  1760. $to_emails = array();
  1761. $to_email = "$extraPlayerobj->email";
  1762. $to_emails = array(
  1763. $to_email => array(
  1764. 'name' => $extraPlayerobj->firstname
  1765. )
  1766. );
  1767. // Provide Content
  1768. $content = new Object;
  1769. $content->line1 = $emailbody;
  1770. $content->clubname = get_clubname();
  1771. //Send the email
  1772. sendgrid_email($subject, $to_emails, $content, "Confirm Doubles");
  1773. }
  1774. //Now Send emails out to players that acutally are in a team
  1775. else {
  1776. // when only two rows returned this is a team looking for another team.
  1777. if ($numofrows == 2) {
  1778. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/confirm_doubles_for_team_looking.php", $var);
  1779. }
  1780. //Send out emails to four players, the variables were set earlier in this function
  1781. else {
  1782. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/confirm_doubles.php", $var);
  1783. }
  1784. //Send out emails to the teams
  1785. //Reset the result pointer to the begining
  1786. if (mysqli_num_rows($playerResult) > 0) mysqli_data_seek($playerResult, 0);
  1787. $to_emails = array();
  1788. while ($playerObject = mysqli_fetch_object($playerResult)) {
  1789. if (isDebugEnabled(1)) logMessage($emailbody);
  1790. $to_email = "$playerObject->email";
  1791. $to_emails[$to_email] = array(
  1792. 'name' => $playerObject->firstname
  1793. );
  1794. }
  1795. $content = new Object;
  1796. $content->line1 = $emailbody;
  1797. $content->clubname = get_clubname();
  1798. //Send the email
  1799. sendgrid_email($subject, $to_emails, $content, "Confirm Doubles");
  1800. }
  1801. }
  1802. /**
  1803. *
  1804. * Enter description here ...
  1805. * @param unknown_type $resid
  1806. */
  1807. function cancel_doubles($resid) {
  1808. $rquery = "SELECT courts.courtname, reservations.time, users.firstname, users.lastname, users.email, courts.courtid, reservations.matchtype, matchtype.name
  1809. FROM tblCourts courts, tblReservations reservations, tblUsers users, tblkpUserReservations reservationdetails, tblUserRankings rankings, tblkpTeams teamdetails, tblMatchType matchtype, tblClubUser clubuser
  1810. WHERE reservations.reservationid = reservationdetails.reservationid
  1811. AND teamdetails.teamid = reservationdetails.userid
  1812. AND users.userid = teamdetails.userid
  1813. AND rankings.userid = reservationdetails.userid
  1814. AND courts.courtid = reservations.courtid
  1815. AND reservations.matchtype = matchtype.id
  1816. AND reservations.reservationid=$resid
  1817. AND users.userid = clubuser.userid
  1818. AND clubuser.clubid=" . get_clubid() . "
  1819. AND reservationdetails.usertype=1
  1820. AND rankings.usertype=1";
  1821. $rresult = db_query($rquery);
  1822. $robj = mysqli_fetch_object($rresult);
  1823. /* email the user with the new account information */
  1824. $var = new Object;
  1825. $var->courtname = $robj->courtname;
  1826. $var->time = gmdate("l F j g:i a", $robj->time);
  1827. $var->timestamp = $robj->time;
  1828. $var->dns = $_SESSION["CFG"]["dns"];
  1829. $var->wwwroot = $_SESSION["CFG"]["wwwroot"];
  1830. $var->courtid = $robj->courtid;
  1831. $var->support = $_SESSION["CFG"]["support"];
  1832. $var->matchtype = $robj->name;
  1833. //Get the first player of team 1
  1834. $var->firstname1 = $robj->firstname;
  1835. $var->lastname1 = $robj->lastname;
  1836. $var->fullname1 = $robj->firstname . " " . $robj->lastname;
  1837. //Get the second player of team 1
  1838. $robj = mysqli_fetch_object($rresult);
  1839. $var->firstname2 = $robj->firstname;
  1840. $var->lastname2 = $robj->lastname;
  1841. $var->fullname2 = $robj->firstname . " " . $robj->lastname;
  1842. //Get the first player of team 2
  1843. $robj = mysqli_fetch_object($rresult);
  1844. $var->firstname3 = $robj->firstname;
  1845. $var->lastname3 = $robj->lastname;
  1846. $var->fullname3 = $robj->firstname . " " . $robj->lastname;
  1847. //Get the second player of team 2
  1848. $robj = mysqli_fetch_object($rresult);
  1849. $var->firstname4 = $robj->firstname;
  1850. $var->lastname4 = $robj->lastname;
  1851. $var->fullname4 = $robj->firstname . " " . $robj->lastname;
  1852. $clubfullname = get_clubname();
  1853. $var->clubfullname = $clubfullname;
  1854. $var->clubadminemail = "PlayerMailer@sportsynergy.net";
  1855. if (mysqli_num_rows($rresult) == 4) {
  1856. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/cancel_doubles.php", $var);
  1857. } else {
  1858. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/cancel_doubles_looking.php", $var);
  1859. }
  1860. //Reset the result pointer to the begining
  1861. mysqli_data_seek($rresult, 0);
  1862. $to_emails = array();
  1863. while ($emailidrow = db_fetch_row($rresult)) {
  1864. $to_emails[$emailidrow[4]] = array(
  1865. 'name' => $emailidrow[2]
  1866. );
  1867. }
  1868. $content = new Object;
  1869. $content->line1 = $emailbody;
  1870. $content->clubname = get_clubname();
  1871. $template = get_sitecode();
  1872. $subject = "Court Cancellation Notice - ".get_clubname();
  1873. //Send the email
  1874. sendgrid_email($subject, $to_emails, $content, "Cancel Doubles");
  1875. }
  1876. /**
  1877. * Sends out emails to the players involved.
  1878. * @param unknown_type $wUserid
  1879. * @param unknown_type $lUserid
  1880. * @param unknown_type $wor
  1881. * @param unknown_type $wnr
  1882. * @param unknown_type $lor
  1883. * @param unknown_type $lnr
  1884. * @param unknown_type $score
  1885. * @param unknown_type $matchtype
  1886. */
  1887. function report_scores_singles_simple($wUserid, $lUserid, $wor, $wnr, $lor, $lnr, $score, $matchtype) {
  1888. global $bad, $not_bad, $close;
  1889. $rquery = "SELECT users.firstname, users.lastname, users.email
  1890. FROM tblUsers users
  1891. WHERE users.userid = $wUserid
  1892. OR users.userid = $lUserid";
  1893. $rresult = db_query($rquery);
  1894. $robj = mysqli_fetch_object($rresult);
  1895. /* email the user with the new account information */
  1896. $var = new Object;
  1897. if ($score == 0) {
  1898. $rand_key = array_rand($bad,1);
  1899. $var->howbad = $bad[$rand_key];
  1900. $var->loserscore = 0;
  1901. } elseif ($score == 2) {
  1902. $rand_key = array_rand($close,1);
  1903. $var->howbad = $close[$rand_key];
  1904. $var->loserscore = 2;
  1905. } else {
  1906. $rand_key = array_rand($not_bad,1);
  1907. $var->howbad = $not_bad[$rand_key];
  1908. $var->loserscore = 1;
  1909. }
  1910. $var->support = $_SESSION["CFG"]["support"];
  1911. $var->winnersold = $wor;
  1912. $var->winnersnew = round($wnr, 4);
  1913. $var->losersold = $lor;
  1914. $var->losersnew = round($lnr, 4);
  1915. //Get the first player
  1916. $var->winnerfull = getFullNameForUserId($wUserid);
  1917. //Get the next One
  1918. $var->loserfull = getFullNameForUserId($lUserid);
  1919. $var->loserscore = $score;
  1920. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/report_scores_singles_simple.php", $var);
  1921. $emailbody = nl2br($emailbody);
  1922. //Reset the result pointer to the begining
  1923. mysqli_data_seek($rresult, 0);
  1924. $to_emails = array();
  1925. while ($emailidrow = db_fetch_row($rresult)) {
  1926. $to_emails[$emailidrow[2]] = array(
  1927. 'name' => $emailidrow[0]
  1928. );
  1929. }
  1930. $content = new Object;
  1931. $content->line1 = $emailbody;
  1932. $content->clubname = get_clubname();
  1933. $template = get_sitecode();
  1934. $subject = "Score Report - ".get_clubname();
  1935. //Send the email
  1936. sendgrid_email($subject, $to_emails, $content, "Report Singles Score");
  1937. $description = "$var->winnerfull $var->howbad $var->loserfull in a $matchtype match 3-$score ";
  1938. logSiteActivity(get_siteid() , $description);
  1939. }
  1940. /**
  1941. *
  1942. * Enter description here ...
  1943. * @param unknown_type $resid
  1944. * @param unknown_type $wor
  1945. * @param unknown_type $wnr
  1946. * @param unknown_type $lor
  1947. * @param unknown_type $lnr
  1948. * @param unknown_type $score
  1949. */
  1950. function report_scores_singles($resid, $wor, $wnr, $lor, $lnr, $score) {
  1951. global $bad, $not_bad, $close;
  1952. $rquery = "SELECT DISTINCTROW courts.courtname, reservations.time, users.firstname, users.lastname, users.email, courts.courtid, reservationdetails.outcome, reservations.matchtype, users.gender, matchtype.name
  1953. FROM tblCourts courts, tblReservations reservations, tblUsers users, tblkpUserReservations reservationdetails, tblUserRankings rankings, tblMatchType matchtype, tblClubUser clubuser
  1954. WHERE courts.courtid = reservations.courtid
  1955. AND users.userid = rankings.userid
  1956. AND users.userid = reservationdetails.userid
  1957. AND reservations.reservationid = reservationdetails.reservationid
  1958. AND reservations.matchtype = matchtype.id
  1959. AND reservations.reservationid=$resid
  1960. AND users.userid = clubuser.userid
  1961. AND clubuser.clubid=" . get_clubid() . "
  1962. ORDER BY reservationdetails.outcome DESC";
  1963. $rresult = db_query($rquery);
  1964. $robj = mysqli_fetch_object($rresult);
  1965. /* email the user with the new account information */
  1966. $var = new Object;
  1967. if ($robj->gender == 1) {
  1968. $winnersex = "him";
  1969. } else {
  1970. $winnersex = "her";
  1971. }
  1972. $robj = mysqli_fetch_object($rresult);
  1973. if ($robj->gender == 1) {
  1974. $losersex = "he";
  1975. } else {
  1976. $losersex = "she";
  1977. }
  1978. mysqli_data_seek($rresult, 0);
  1979. $robj = mysqli_fetch_object($rresult);
  1980. if ($score == 0) {
  1981. $rand_key = array_rand($bad,1);
  1982. $var->howbad1 = $bad[$rand_key];
  1983. $var->loserscore = 0;
  1984. } elseif ($score == 2) {
  1985. $rand_key = array_rand($not_bad,1);
  1986. $var->howbad1 = $not_bad[$rand_key];
  1987. $var->loserscore = 2;
  1988. } else {
  1989. $rand_key = array_rand($close,1);
  1990. $var->howbad = $close[$rand_key];
  1991. $var->loserscore = 1;
  1992. }
  1993. $var->courtname = $robj->courtname;
  1994. $var->matchtype = $robj->name;
  1995. $var->time = gmdate("l F j g:i a", $robj->time);
  1996. $var->date = gmdate("l F j", $robj->time);
  1997. $var->hour = gmdate("g:i a", $robj->time);
  1998. $var->timestamp = $robj->time;
  1999. $var->support = $_SESSION["CFG"]["support"];
  2000. $var->courtid = $robj->courtid;
  2001. $var->winnersold = $wor;
  2002. $var->winnersnew = round($wnr, 4);
  2003. $var->losersold = $lor;
  2004. $var->losersnew = round($lnr, 4);
  2005. //Get the first player
  2006. $var->winnerfname = $robj->firstname;
  2007. $var->winnerlname = $robj->lastname;
  2008. $var->winnerfull = $robj->firstname . " " . $robj->lastname;
  2009. //Get the second player
  2010. $robj = mysqli_fetch_object($rresult);
  2011. $var->loserfname = $robj->firstname;
  2012. $var->loserlname = $robj->lastname;
  2013. $var->loserfull = $robj->firstname . " " . $robj->lastname;
  2014. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/report_scores_singles.php", $var);
  2015. //convert newlines
  2016. $emailbody = nl2br($emailbody);
  2017. //Reset the result pointer to the begining
  2018. mysqli_data_seek($rresult, 0);
  2019. $to_emails = array();
  2020. while ($emailidrow = db_fetch_row($rresult)) {
  2021. $to_emails[$emailidrow[4]] = array(
  2022. 'name' => $emailidrow[2]
  2023. );
  2024. }
  2025. $content = new Object;
  2026. $content->line1 = $emailbody;
  2027. $content->clubname = get_clubname();
  2028. $template = get_sitecode();
  2029. $subject = "Score Report - ".get_clubname();
  2030. //Send the email
  2031. sendgrid_email($subject, $to_emails, $content, "Report Singles Score");
  2032. $description = "$var->winnerfull defeated $var->loserfull in a $var->matchtype match 3-$score on $var->courtname $var->date at $var->hour";
  2033. logSiteActivity(get_siteid() , $description);
  2034. }
  2035. /**
  2036. *
  2037. * Enter description here ...
  2038. * @param unknown_type $wid
  2039. * @param unknown_type $lid
  2040. * @param unknown_type $wor
  2041. * @param unknown_type $wnr
  2042. * @param unknown_type $lor
  2043. * @param unknown_type $lnr
  2044. */
  2045. function report_scores_singlesbox($wid, $lid, $wor, $wnr, $lor, $lnr) {
  2046. $winnernamequery = "SELECT tblUsers.firstname, tblUsers.lastname, tblUsers.email
  2047. FROM tblUsers
  2048. WHERE (((tblUsers.userid)=$wid))";
  2049. $wresult = db_query($winnernamequery);
  2050. $wobj = mysqli_fetch_object($wresult);
  2051. $losernamequery = "SELECT tblUsers.firstname, tblUsers.lastname, tblUsers.email
  2052. FROM tblUsers
  2053. WHERE (((tblUsers.userid)=$lid))";
  2054. $lresult = db_query($losernamequery);
  2055. $lobj = mysqli_fetch_object($lresult);
  2056. /* email the user with the new account information */
  2057. $var = new Object;
  2058. $var->support = $_SESSION["CFG"]["support"];
  2059. $var->winnersold = $wor;
  2060. $var->winnersnew = round($wnr, 4);
  2061. $var->losersold = $lor;
  2062. $var->losersnew = round($lnr, 4);
  2063. //Get the winner user information
  2064. $var->winnerfname = $wobj->firstname;
  2065. $var->winnerlname = $wobj->lastname;
  2066. $var->winnerfull = $wobj->firstname . " " . $wobj->lastname;
  2067. //Get the loser user information
  2068. $var->loserfname = $lobj->firstname;
  2069. $var->loserlname = $lobj->lastname;
  2070. $var->loserfull = $lobj->firstname . " " . $lobj->lastname;
  2071. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/report_scores_singlesbox.php", $var);
  2072. $content = new Object;
  2073. $content->line1 = $emailbody;
  2074. $content->clubname = get_clubname();
  2075. $template = get_sitecode();
  2076. $subject = "Score Report - ".get_clubname();
  2077. $winner_email = array(
  2078. $wobj->email => array(
  2079. 'name' => $wobj->firstname
  2080. )
  2081. );
  2082. //Send the email
  2083. sendgrid_email($subject, $winner_email, $content, "Report Singles Box");
  2084. //Send the email
  2085. $loser_email = array(
  2086. $lobj->email => array(
  2087. 'name' => $lobj->firstname
  2088. )
  2089. );
  2090. sendgrid_email($subject, $loser_email, $content, "Report Singles Box");
  2091. }
  2092. /**
  2093. * Sends out emails to the players involved.
  2094. * This is used for the admin records scores when there isn't a reservation id involved
  2095. * @param unknown_type $wTeamid
  2096. * @param unknown_type $lTeamid
  2097. * @param unknown_type $wor
  2098. * @param unknown_type $wnr
  2099. * @param unknown_type $lor
  2100. * @param unknown_type $lnr
  2101. * @param unknown_type $score
  2102. * @param unknown_type $matchtype
  2103. */
  2104. function report_scores_doubles_simple($wTeamid, $lTeamid, $wor, $wnr, $lor, $lnr, $score, $matchtype) {
  2105. global $bad, $not_bad, $close;
  2106. $rquery = "SELECT users.firstname, users.lastname, users.email
  2107. FROM tblUsers users, tblkpTeams teamdetails
  2108. WHERE users.userid = teamdetails.userid
  2109. AND users.enddate IS NULL
  2110. AND (teamdetails.teamid = $wTeamid
  2111. OR teamdetails.teamid = $lTeamid)";
  2112. $rresult = db_query($rquery);
  2113. $robj = mysqli_fetch_object($rresult);
  2114. /* email the user with the new account information */
  2115. $var = new Object;
  2116. if ($score == 0) {
  2117. $rand_key = array_rand($bad,1);
  2118. $var->howbad = $bad[$rand_key];
  2119. $var->loserscore = 0;
  2120. } elseif ($score == 2) {
  2121. $rand_key = array_rand($close,1);
  2122. $var->howbad = $close[$rand_key];
  2123. $var->loserscore = 2;
  2124. } else {
  2125. $rand_key = array_rand($not_bad,1);
  2126. $var->howbad = $not_bad[$rand_key];
  2127. $var->loserscore = 1;
  2128. }
  2129. $var->support = $_SESSION["CFG"]["support"];
  2130. $var->winnersold = $wor;
  2131. $var->winnersnew = round($wnr, 4);
  2132. $var->losersold = $lor;
  2133. $var->losersnew = round($lnr, 4);
  2134. //Get the first player
  2135. $var->winner = getFullNamesForTeamId($wTeamid);
  2136. //Get the next One
  2137. $robj = mysqli_fetch_object($rresult);
  2138. $var->loser = getFullNamesForTeamId($lTeamid);
  2139. $var->loserscore = $score;
  2140. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/report_scores_doubles_simple.php", $var);
  2141. $emailbody = nl2br($emailbody);
  2142. //Reset the result pointer to the begining
  2143. mysqli_data_seek($rresult, 0);
  2144. $to_emails = array();
  2145. while ($emailidrow = db_fetch_row($rresult)) {
  2146. $to_emails[$emailidrow[2]] = array(
  2147. 'name' => $emailidrow[0]
  2148. );
  2149. }
  2150. // Provide Content
  2151. $content = new Object;
  2152. $content->line1 = $emailbody;
  2153. $content->clubname = get_clubname();
  2154. $template = get_sitecode();
  2155. $subject = "Score Report - ".get_clubname();
  2156. //Send the email
  2157. sendgrid_email($subject, $to_emails, $content, "Report Doubles Box");
  2158. $description = "$var->winner $var->howbad $var->loser in a $matchtype match 3-$score ";
  2159. logSiteActivity(get_siteid() , $description);
  2160. }
  2161. /**
  2162. *
  2163. * Enter description here ...
  2164. * @param unknown_type $resid
  2165. * @param unknown_type $wor
  2166. * @param unknown_type $wnr
  2167. * @param unknown_type $lor
  2168. * @param unknown_type $lnr
  2169. * @param unknown_type $score
  2170. */
  2171. function report_scores_doubles($resid, $wor, $wnr, $lor, $lnr, $score) {
  2172. global $bad, $not_bad, $close;
  2173. $rquery = "SELECT DISTINCT courts.courtname, reservations.time, users.firstname, users.lastname, users.email, courts.courtid, reservationdetails.outcome, reservations.matchtype, matchtype.name
  2174. FROM tblCourts courts, tblReservations reservations, tblUsers users, tblkpUserReservations reservationdetails, tblkpTeams teamdetails, tblMatchType matchtype,tblClubUser clubuser
  2175. WHERE reservations.reservationid = reservationdetails.reservationid
  2176. AND teamdetails.teamid = reservationdetails.userid
  2177. AND users.userid = teamdetails.userid
  2178. AND courts.courtid = reservations.courtid
  2179. AND reservations.matchtype = matchtype.id
  2180. AND reservationdetails.reservationid=$resid
  2181. AND users.userid = clubuser.userid
  2182. AND clubuser.clubid=" . get_clubid() . "
  2183. ORDER BY reservationdetails.outcome DESC";
  2184. $rresult = db_query($rquery);
  2185. $robj = mysqli_fetch_object($rresult);
  2186. // A little defense for a problem where teams don't have rankings
  2187. if( mysqli_num_rows($rresult) < 4 ){
  2188. if (isDebugEnabled(2)) logMessage("applicationlib.report_scores_doubles: there is some bad things happening for reservation $resid");
  2189. return;
  2190. }
  2191. /* email the user with the new account information */
  2192. $var = new Object;
  2193. #bad/not_bad/close
  2194. if ($score == 0) {
  2195. $rand_key = array_rand($bad,1);
  2196. $var->howbad = $bad[$rand_key];
  2197. $var->loserscore = 0;
  2198. } elseif ($score == 2) {
  2199. $rand_key = array_rand($close,1);
  2200. $var->howbad = $close[$rand_key];
  2201. $var->loserscore = 2;
  2202. } else {
  2203. $rand_key = array_rand($not_bad,1);
  2204. $var->howbad = $not_bad[$rand_key];
  2205. $var->loserscore = 1;
  2206. }
  2207. $var->courtname = $robj->courtname;
  2208. $var->matchtype = $robj->name;
  2209. $var->time = gmdate("l F j g:i a", $robj->time);
  2210. $var->timestamp = $robj->time;
  2211. $var->dns = $_SESSION["CFG"]["dns"];
  2212. $var->wwwroot = $_SESSION["CFG"]["wwwroot"];
  2213. $var->courtid = $robj->courtid;
  2214. $var->support = $_SESSION["CFG"]["support"];
  2215. $var->winnersold = $wor;
  2216. $var->winnersnew = round($wnr, 4);
  2217. $var->losersold = $lor;
  2218. $var->losersnew = round($lnr, 4);
  2219. $var->date = gmdate("l F j", $robj->time);
  2220. $var->hour = gmdate("g:i a", $robj->time);
  2221. //Get the first player of team 1
  2222. $var->firstname1 = $robj->firstname;
  2223. $var->lastname1 = $robj->lastname;
  2224. $var->fullname1 = $robj->firstname . " " . $robj->lastname;
  2225. //Get the second player of team 1
  2226. $robj = mysqli_fetch_object($rresult);
  2227. $var->firstname2 = $robj->firstname;
  2228. $var->lastname2 = $robj->lastname;
  2229. $var->fullname2 = $robj->firstname . " " . $robj->lastname;
  2230. //Get the first player of team 2
  2231. $robj = mysqli_fetch_object($rresult);
  2232. $var->firstname3 = $robj->firstname;
  2233. $var->lastname3 = $robj->lastname;
  2234. $var->fullname3 = $robj->firstname . " " . $robj->lastname;
  2235. //Get the second player of team 2
  2236. $robj = mysqli_fetch_object($rresult);
  2237. $var->firstname4 = $robj->firstname;
  2238. $var->lastname4 = $robj->lastname;
  2239. $var->fullname4 = $robj->firstname . " " . $robj->lastname;
  2240. $emailbody = read_template($_SESSION["CFG"]["templatedir"] . "/email/report_scores_doubles.php", $var);
  2241. $emailbody = nl2br($emailbody);
  2242. //Reset the result pointer to the begining
  2243. mysqli_data_seek($rresult, 0);
  2244. $to_emails = array();
  2245. while ($emailidrow = db_fetch_row($rresult)) {
  2246. $to_emails[$emailidrow[4]] = array(
  2247. 'name' => $emailidrow[2]
  2248. );
  2249. }
  2250. // Provide Content
  2251. $content = new Object;
  2252. $content->line1 = $emailbody;
  2253. $content->clubname = get_clubname();
  2254. $template = get_sitecode();
  2255. $subject = "Score Report - ".get_clubname();
  2256. //Send the email
  2257. sendgrid_email($subject, $to_emails, $content, "Report Doubles Box");
  2258. $description = "$var->fullname1 and $var->fullname2 $var->howbad $var->fullname3 and $var->fullname4 in a $var->matchtype match 3-$score on $var->courtname $var->date at $var->hour";
  2259. logSiteActivity(get_siteid() , $description);
  2260. }
  2261. /**
  2262. * ??? required parameters: reservationid score
  2263. * @param unknown_type $frm
  2264. * @param unknown_type $source
  2265. */
  2266. function record_score(&$frm, $source) {
  2267. /* Record score
  2268. // The winner userid is passed in the post vars, the loser is passed
  2269. // in either the player1 or player2 post vars. Also, the outcome is
  2270. // either a 0 which is a 3-0 match score, a 1 which is a 3-1 match
  2271. // score or finally a 2 which is a 3-2 match score.
  2272. // Set the winner and loser variables so we know who is who
  2273. // If the boxid variable is set this is being called from
  2274. // the web ladder or from a reservation was made as a league
  2275. // reservation. In any event we will figure out who who with
  2276. // the fancy get_matchresults.
  2277. // 03/27/2003 John now suggested that the box league matches count for
  2278. // twice that of a practice match
  2279. // 10/01/2005 John now suggested that the challenge match count for thrice
  2280. // thhat of a practice match.
  2281. */
  2282. $results = get_matchresults($frm['winner'], $frm['Player1'], $frm['Player2']);
  2283. $winner = $results['winner'];
  2284. $loser = $results['loser'];
  2285. $gameswon = $frm['gameswon'];
  2286. if (isDebugEnabled(1)) logMessage("applicationlib.record_score: source is $source and gameswon: $gameswon" );
  2287. // Update the winners outcome
  2288. $winnersquery = "UPDATE tblkpUserReservations SET outcome='$frm[gameswon]'
  2289. WHERE reservationid='$frm[reservationid]'
  2290. AND userid=$winner";
  2291. $winnerresult = db_query($winnersquery);
  2292. // Update the losers outcome
  2293. $loserssquery = "UPDATE tblkpUserReservations SET outcome='$frm[score]'
  2294. WHERE reservationid='$frm[reservationid]'
  2295. AND userid=$loser";
  2296. $losersresult = db_query($loserssquery);
  2297. // Get the courttypeid from tblReservations
  2298. $ctidquery = "SELECT courts.courttypeid, reservations.reservationid, reservations.usertype, reservations.matchtype
  2299. FROM tblCourts courts, tblReservations reservations
  2300. WHERE courts.courtid = reservations.courtid
  2301. AND reservations.reservationid='$frm[reservationid]'";
  2302. $ctidresult = db_query($ctidquery);
  2303. $ctidarray = db_fetch_array($ctidresult);
  2304. $usertypeval = $ctidarray[2];
  2305. /**
  2306. * Adjust the rankings
  2307. */
  2308. if ($usertypeval == 1) {
  2309. // Look up the individuals ranking for members of winning team
  2310. // (this will be averaged to calculate
  2311. $winnerResult = getUserIdsForTeamIdWithCourtType($winner, $ctidarray[0]);
  2312. $playerRow = mysqli_fetch_array($winnerResult);
  2313. $winnerRanking = $playerRow['ranking'];
  2314. $playerRow = mysqli_fetch_array($winnerResult);
  2315. $winnerRanking+= $playerRow['ranking'];
  2316. $winnerRanking = $winnerRanking / 2;
  2317. if (isDebugEnabled(1)) logMessage("applicationlib.record_scores: Team Id $winner has a ranking of $winnerRanking");
  2318. $loserResult = getUserIdsForTeamIdWithCourtType($loser, $ctidarray[0]);
  2319. $playerRow = mysqli_fetch_array($loserResult);
  2320. $loserRanking = $playerRow['ranking'];
  2321. $playerRow = mysqli_fetch_array($loserResult);
  2322. $loserRanking+= $playerRow['ranking'];
  2323. $loserRanking = $loserRanking / 2;
  2324. if (isDebugEnabled(1)) logMessage("applicationlib.record_scores: Team Id $loser has a ranking of $loserRanking");
  2325. // Calculate the Rankings
  2326. $rankingArray = calculateRankings($winnerRanking, $loserRanking);
  2327. //If the match type is a two (challenge match) count the match two times
  2328. if ($ctidarray[3] == 2) {
  2329. $rankingArray = calculateRankings($rankingArray['winner'], $rankingArray['loser']);
  2330. }
  2331. //For winner team
  2332. mysqli_data_seek($winnerResult, 0);
  2333. mysqli_data_seek($loserResult, 0);
  2334. $winners = array();
  2335. $playerRow = mysqli_fetch_array($winnerResult);
  2336. array_push($winners, $playerRow['userid']);
  2337. $playerRow = mysqli_fetch_array($winnerResult);
  2338. array_push($winners, $playerRow['userid']);
  2339. $winnerAdjustment = $rankingArray['winner'] - $winnerRanking;
  2340. $playerOneRankQuery = "SELECT rankings.ranking
  2341. FROM tblUserRankings rankings
  2342. WHERE rankings.userid = $winners[0]
  2343. AND rankings.courttypeid = '$ctidarray[0]'
  2344. AND rankings.usertype = 0";
  2345. $playerOneRankResult = db_query($playerOneRankQuery);
  2346. $playerOneRankingArray = mysqli_fetch_array($playerOneRankResult);
  2347. $playerOneRanking = $playerOneRankingArray[0];
  2348. $playerOneNewRanking = $playerOneRanking + $winnerAdjustment;
  2349. $playerOneAdjustment = db_query("
  2350. UPDATE tblUserRankings
  2351. SET ranking = $playerOneNewRanking
  2352. WHERE userid = '$winners[0]'
  2353. AND courttypeid = '$ctidarray[0]'");
  2354. $playerTwoRankQuery = "SELECT rankings.ranking
  2355. FROM tblUserRankings rankings
  2356. WHERE rankings.userid = $winners[1]
  2357. AND rankings.courttypeid = '$ctidarray[0]'
  2358. AND rankings.usertype = 0";
  2359. $playerTwoRankResult = db_query($playerTwoRankQuery);
  2360. $playerTwoRankingArray = mysqli_fetch_array($playerTwoRankResult);
  2361. $playerTwoRanking = $playerTwoRankingArray[0];
  2362. $playerTwoNewRanking = $playerTwoRanking + $winnerAdjustment;
  2363. $playerOneAdjustment = db_query("
  2364. UPDATE tblUserRankings
  2365. SET ranking = $playerTwoNewRanking
  2366. WHERE userid = '$winners[1]'
  2367. AND courttypeid = '$ctidarray[0]'");
  2368. //For loser team
  2369. $losers = array();
  2370. $playerRow = mysqli_fetch_array($loserResult);
  2371. array_push($losers, $playerRow['userid']);
  2372. $playerRow = mysqli_fetch_array($loserResult);
  2373. array_push($losers, $playerRow['userid']);
  2374. $loserAdjustment = $loserRanking - $rankingArray['loser'];
  2375. $playerThreeRankQuery = "SELECT rankings.ranking
  2376. FROM tblUserRankings rankings
  2377. WHERE rankings.userid = $losers[0]
  2378. AND rankings.courttypeid = '$ctidarray[0]'
  2379. AND rankings.usertype = 0";
  2380. $playerThreeRankResult = db_query($playerThreeRankQuery);
  2381. $playerThreeRankingArray = mysqli_fetch_array($playerThreeRankResult);
  2382. $playerThreeRanking = $playerThreeRankingArray[0];
  2383. $playerThreeNewRanking = $playerThreeRanking - $loserAdjustment;
  2384. $playerThreeAdjustment = db_query("
  2385. UPDATE tblUserRankings
  2386. SET ranking = $playerThreeNewRanking
  2387. WHERE userid = '$losers[0]'
  2388. AND courttypeid = '$ctidarray[0]'");
  2389. $playerFourRankQuery = "SELECT rankings.ranking
  2390. FROM tblUserRankings rankings
  2391. WHERE rankings.userid = $losers[1]
  2392. AND rankings.courttypeid = '$ctidarray[0]'
  2393. AND rankings.usertype = 0";
  2394. $playerFourRankResult = db_query($playerFourRankQuery);
  2395. $playerFourRankingArray = mysqli_fetch_array($playerFourRankResult);
  2396. $playerFourRanking = $playerFourRankingArray[0];
  2397. $playerFourNewRanking = $playerFourRanking - $loserAdjustment;
  2398. $playerOneAdjustment = db_query("
  2399. UPDATE tblUserRankings
  2400. SET ranking = $playerFourNewRanking
  2401. WHERE userid = '$losers[1]'
  2402. AND courttypeid = '$ctidarray[0]'");
  2403. }
  2404. //Singles
  2405. elseif ($usertypeval == 0) {
  2406. $winneridquery = "SELECT rankings.ranking, users.firstname, users.lastname
  2407. FROM tblUsers users, tblUserRankings rankings
  2408. WHERE users.userid = rankings.userid
  2409. AND rankings.userid=$winner
  2410. AND rankings.courttypeid=$ctidarray[0]
  2411. AND users.enddate IS NULL
  2412. AND rankings.usertype=0";
  2413. $winneridresult = db_query($winneridquery);
  2414. $winneridarray = db_fetch_array($winneridresult);
  2415. $loseridquery = "SELECT rankings.ranking, users.firstname, users.lastname
  2416. FROM tblUsers users, tblUserRankings rankings
  2417. WHERE users.userid = rankings.userid
  2418. AND rankings.userid=$loser
  2419. AND rankings.courttypeid=$ctidarray[0]
  2420. AND users.enddate IS NULL
  2421. AND rankings.usertype=0";
  2422. $loseridresult = db_query($loseridquery);
  2423. $loseridarray = db_fetch_array($loseridresult);
  2424. $rankingArray = calculateRankings($winneridarray[0], $loseridarray[0]);
  2425. if ($ctidarray[3] == 2) {
  2426. $rankingArray = calculateRankings($rankingArray['winner'], $rankingArray['loser']);
  2427. }
  2428. $newWinnerRanking = $rankingArray['winner'];
  2429. $newLoserRanking = $rankingArray['loser'];
  2430. // Update the winners ranking
  2431. $losersrankq = db_query("
  2432. UPDATE tblUserRankings
  2433. SET ranking = $newWinnerRanking
  2434. WHERE userid = '$winner'
  2435. AND courttypeid = '$ctidarray[0]'");
  2436. // Update the losers ranking
  2437. $winnrsrankq = db_query("
  2438. UPDATE tblUserRankings
  2439. SET ranking = $newLoserRanking
  2440. WHERE userid = '$loser'
  2441. AND courttypeid = '$ctidarray[0]'
  2442. ");
  2443. }
  2444. /**
  2445. * Write out the message
  2446. */
  2447. if ($usertypeval == 1) {
  2448. $wteamnamequery = "SELECT users.firstname, users.lastname
  2449. FROM tblUsers users, tblkpTeams teamdetails
  2450. WHERE users.userid = teamdetails.userid
  2451. AND teamdetails.teamid=$winner
  2452. ORDER BY users.userid";
  2453. $wteamnameresult = db_query($wteamnamequery);
  2454. $wteamnamearray = db_fetch_array($wteamnameresult);
  2455. //Get the players first and last names of the losing team
  2456. $lteamnamequery = "SELECT users.firstname, users.lastname
  2457. FROM tblUsers users, tblkpTeams teamdetails
  2458. WHERE users.userid = teamdetails.userid
  2459. AND teamdetails.teamid=$loser
  2460. ORDER BY users.userid";
  2461. $lteamnameresult = db_query($lteamnamequery);
  2462. $lteamnamearray = db_fetch_array($lteamnameresult);
  2463. echo "<span class=bigbanner> Congratulations $wteamnamearray[0] $wteamnamearray[1] and ";
  2464. // And now get the next partner
  2465. $wteamnamearray = db_fetch_array($wteamnameresult);
  2466. echo "$wteamnamearray[0] $wteamnamearray[1]!</span><br><br>";
  2467. // Set the array pointer back to the front.
  2468. unset($wteamnameresult);
  2469. $wteamnameresult = db_query($wteamnamequery);
  2470. $wteamnamearray = db_fetch_array($wteamnameresult);
  2471. echo "<div class=normal>$wteamnamearray[0] $wteamnamearray[1]'s ranking went up by " . round($winnerAdjustment, 4) . " to " . round($playerOneNewRanking, 4) . "</div>";
  2472. $wteamnamearray = db_fetch_array($wteamnameresult);
  2473. echo "<div class=normal>$wteamnamearray[0] $wteamnamearray[1]'s ranking went up by " . round($winnerAdjustment, 4) . " to " . round($playerTwoNewRanking, 4) . "</div>";
  2474. echo "<br>";
  2475. echo "<div class=normal> $lteamnamearray[0] $lteamnamearray[1]'s ranking went down by " . round($winnerAdjustment, 4) . " to " . round($playerThreeRanking, 4) . "</div>";
  2476. $lteamnamearray = db_fetch_array($lteamnameresult);
  2477. echo "<div class=normal> $lteamnamearray[0] $lteamnamearray[1]'s ranking went down by " . round($winnerAdjustment, 4) . " to " . round($playerFourRanking, 4) . "</div>";
  2478. ?>
  2479. <div>
  2480. <? if( isset($source) && $source == "ladder"){ ?>
  2481. <a href="<?=$_SESSION["CFG"]["wwwroot"]?>/users/player_ladder.php">Back
  2482. to the ladder</a>
  2483. <? } else { ?>
  2484. <a href="<?=$_SESSION["CFG"]["wwwroot"]?>/clubs/<?=get_sitecode()?>">Back
  2485. to the scheduler</a>
  2486. <? } ?>
  2487. </div>
  2488. <?
  2489. //Send out the emails
  2490. report_scores_doubles($frm['reservationid'], $winnerRanking, $rankingArray['winner'], $loserRanking, $rankingArray['loser'], $frm['score']);
  2491. } else { ?>
  2492. <table cellspacing="0" cellpadding="0" border="0" width="710"
  2493. align="center">
  2494. <tr>
  2495. <td class="normal"><font class="bigbanner"> Congratulations <?=$winneridarray[1]?>
  2496. <?=$winneridarray[2] ?>!!
  2497. </font><br> <br> <?= $winneridarray[1]?> <?=$winneridarray[2]?>'s
  2498. rating rose from <?=$winneridarray[0]?> to <?=round($newWinnerRanking,4)?>
  2499. <br> <?=$loseridarray[1]?> <?=$loseridarray[2]?>'s rating fell from <?=$loseridarray[0]?>
  2500. to <?=round($newLoserRanking,4)?> <br>
  2501. <td>
  2502. <tr>
  2503. <tr>
  2504. <td class="normal"><br /> <?
  2505. if( isset($source) && $source == "ladder"){?> <a
  2506. href="<?=$_SESSION["CFG"]["wwwroot"]?>/users/player_ladder.php">Back
  2507. to the ladder</a> <? } else { ?> <a
  2508. href="<?=$_SESSION["CFG"]["wwwroot"]?>/clubs/<?=get_sitecode()?>">Back
  2509. to the scheduler</a> <? } ?>
  2510. <td>
  2511. <tr>
  2512. </table>
  2513. <?
  2514. //Send out the emails
  2515. report_scores_singles($frm['reservationid'], $winneridarray[0], $rankingArray['winner'], $loseridarray[0], $rankingArray['loser'], $frm['score']);
  2516. }
  2517. }
  2518. /*
  2519. This is done using the USSRA rating system. This is calculated using the
  2520. following formula:
  2521. --------------------------------------------------------------------------
  2522. WRO= Winner's old rating
  2523. LRO = Loser's old rating
  2524. K = constant = .1
  2525. D = denominator = .5
  2526. PW = Probability that the winner would win = (1/power(10,(-(WRO-LRO)/D))+1))
  2527. PL = Probability that the lose would win = (1/Power(10,(-(LRO-WRO)/D))+1))
  2528. WRN = Winners's new raing = (WRO+K*(1-PW))
  2529. LRN = Loser's new rating = (LRO+K*K(0-PL)
  2530. --------------------------------------------------------------------------
  2531. This is using infomration found at www.us-squash.org **/
  2532. function calculateRankings($winnerOldRanking, $losersOldRanking) {
  2533. $wro = $winnerOldRanking;
  2534. $lro = $losersOldRanking;
  2535. $k = .1;
  2536. $d = .5;
  2537. $pw = (1 / (pow(10, (- ($wro - $lro) / $d)) +1));
  2538. $pl = (1 / (pow(10, (- ($lro - $wro) / $d)) +1));
  2539. $wrn = ($wro + $k * (1 - $pw));
  2540. $lrn = ($lro + $k * (0 - $pl));
  2541. return array (
  2542. "winner" => $wrn,
  2543. "loser" => $lrn
  2544. );
  2545. }
  2546. /*
  2547. * This is the function used by the box leagues to record how many
  2548. * matches people have played. First we read in the previous games
  2549. * played value for both the person calling this function as
  2550. * well as the person's opponent.
  2551. *
  2552. * @param unknown_type $playerOneId
  2553. * @param unknown_type $playerTwoId
  2554. * @param unknown_type $boxId
  2555. */
  2556. function update_gamesplayed($playerOneId, $playerTwoId, $boxId) {
  2557. if(isDebugEnabled(1) ) logMessage("applicationlib.update_gamesplayed: playerone: $playerOneId, playerTwoId $playerTwoId, boxid: $boxId");
  2558. $boxgamesplayedquery = "SELECT tblkpBoxLeagues.boxid, tblkpBoxLeagues.userid, tblkpBoxLeagues.games
  2559. FROM tblkpBoxLeagues
  2560. WHERE (((tblkpBoxLeagues.userid)=$playerOneId
  2561. Or (tblkpBoxLeagues.userid)=$playerTwoId)
  2562. AND ((tblkpBoxLeagues.boxid)=$boxId))";
  2563. $boxgamesplayedresult = db_query($boxgamesplayedquery);
  2564. while ($boxgamesplayedarray = mysqli_fetch_row($boxgamesplayedresult)) {
  2565. $onemoregame = $boxgamesplayedarray[2] + 1;
  2566. $updategames = db_query("UPDATE tblkpBoxLeagues
  2567. SET games = '$onemoregame'
  2568. WHERE userid = '$boxgamesplayedarray[1]'
  2569. AND boxid = '$boxgamesplayedarray[0]'
  2570. ");
  2571. }
  2572. }
  2573. /************************************************************************************************************************/
  2574. function update_streakval(& $frm) {
  2575. // Get the courttypeid from tblReservations
  2576. $ctidquery = "SELECT courts.courttypeid, reservations.reservationid, reservations.usertype
  2577. FROM tblCourts courts, tblReservations reservations
  2578. WHERE courts.courtid = reservations.courtid
  2579. AND reservations.reservationid='$frm[reservationid]'";
  2580. $ctidresult = db_query($ctidquery);
  2581. $ctidarray = db_fetch_array($ctidresult);
  2582. if (isset ($frm['boxid'])) {
  2583. $results = get_matchresults($frm['winner'], $frm['Player1'], $frm['Player2']);
  2584. $winner = $results['winner'];
  2585. $loser = $results['loser'];
  2586. } else {
  2587. $winner = $frm['winner'];
  2588. if ($frm['Player1'] == $frm['winner']) {
  2589. $loser = $frm['Player2'];
  2590. } else {
  2591. $loser = $frm['Player1'];
  2592. }
  2593. }
  2594. // End the streak for the loser
  2595. $endStreakQuery = " UPDATE tblUserRankings
  2596. SET hot = '0'
  2597. WHERE userid = '$loser'
  2598. AND courttypeid = '$ctidarray[0]'";
  2599. $endStreakResult = db_query($endStreakQuery);
  2600. //See if this puts the winner on a streak
  2601. $streakquery = "SELECT outcome
  2602. FROM tblkpUserReservations
  2603. WHERE userid=$winner
  2604. ORDER BY reservationid desc limit 0,5";
  2605. $streakresult = db_query($streakquery);
  2606. $numberOfWins = 0;
  2607. while ($streakval = mysqli_fetch_array($streakresult)) {
  2608. $numberOfWins += $streakval['outcome'];
  2609. }
  2610. // If the streakval is greater than
  2611. if ($numberOfWins > 10) {
  2612. $updateQuery = "UPDATE tblUserRankings
  2613. SET hot = '1'
  2614. WHERE userid = '$winner'
  2615. AND courttypeid = '$ctidarray[0]'";
  2616. $qid = db_query($updateQuery);
  2617. }
  2618. }
  2619. /***********************************************************************************************************************
  2620. *
  2621. * This is called in the report scores function which may or maynot be reporting the score of
  2622. * a box league match, if if is a bax league match it may or maynot be done through the same page
  2623. * one being the report scores link, the other through the reservation. We will look for the outcome
  2624. * http_post_var to determine this one.
  2625. *
  2626. * */
  2627. function get_matchresults($winner, $player1, $player2) {
  2628. if ($player1 == $winner) {
  2629. $loser = $player2;
  2630. } else {
  2631. $loser = $player1;
  2632. }
  2633. $results = array (
  2634. "winner" => $winner,
  2635. "loser" => $loser
  2636. );
  2637. return $results;
  2638. }
  2639. /************************************************************************************************************************/
  2640. function update_ladderscore($losersgamepoints, $boxid, $winner, $player1, $player2) {
  2641. if(isDebugEnabled(1) ) logMessage("applicationlib.update_ladderscore: losersgamepoints: $losersgamepoints\nboxid: $boxid\nwinner: $winner\nplayer1: $player1\nplayer2: $player2");
  2642. // Per John OBrien on 10/10/2002 the box leagues players are to be ranked in the
  2643. // box league with a box league score. For every match recorded through the boxleague
  2644. // the players score is incremented one for winning plus one for playing. As for the loser
  2645. // their score is only increment one for playing.
  2646. /* 11/22/2002 - alright. one more LAST change to the way this fricking scoring works.
  2647. if A beats B (3-2) A is supposed to get FIVE points: one point
  2648. for showing up,one point for each game, and one point for the win
  2649. */
  2650. //We are not going to use the box results for now since all scores are reported through the reservation
  2651. $results = get_matchresults($winner, $player1, $player2);
  2652. //Dont really understand why we have to trim these, i guess its not really that important.
  2653. $winner = $results['winner'];
  2654. $winner = rtrim ($winner);
  2655. $loser = $results['loser'];
  2656. $loser = rtrim ($loser);
  2657. $pointsforshowing = 1;
  2658. $winnersgamepoints = 3;
  2659. if($losersgamepoints == 0){
  2660. $bonuspoint = 2;
  2661. }
  2662. else if($losersgamepoints == 1){
  2663. $bonuspoint = 1;
  2664. }
  2665. else {
  2666. $bonuspoint = 0;
  2667. }
  2668. //First we need to get the score for each player from the database.
  2669. $ladderscorequery = "SELECT tblkpBoxLeagues.boxid, tblkpBoxLeagues.userid, tblkpBoxLeagues.score
  2670. FROM tblkpBoxLeagues
  2671. WHERE tblkpBoxLeagues.boxid='$boxid'
  2672. AND (tblkpBoxLeagues.userid=$loser OR tblkpBoxLeagues.userid=$winner)";
  2673. $ladderscoreresult = db_query($ladderscorequery);
  2674. while ($ladderscorearray= db_fetch_array($ladderscoreresult)) {
  2675. //First off we are going to increment the score for each player
  2676. $resultbox = $ladderscorearray[0];
  2677. $resultuser = $ladderscorearray[1];
  2678. $resultscore = $ladderscorearray[2];
  2679. if(isDebugEnabled(1) ) logMessage("applicationlib.update_ladderscore: updating ladder score for $resultuser where loser is $loser and winner is $winner.");
  2680. $newwinnerscore = $resultscore + $pointsforshowing + $winnersgamepoints + $bonuspoint;
  2681. $newloserscore = $resultscore + $losersgamepoints + $pointsforshowing;
  2682. //Give the loser props...for trying
  2683. if ($resultuser == $loser) {
  2684. if(isDebugEnabled(1) ) logMessage("applicationlib.update_ladderscore: updating ladder score for $resultuser to $newloserscore");
  2685. $qid = db_query("UPDATE tblkpBoxLeagues
  2686. SET score = $newloserscore
  2687. WHERE boxid = '$boxid'
  2688. AND userid = '$resultuser'");
  2689. }
  2690. //Now we have to give the winner props..for winning
  2691. if ($resultuser == $winner) {
  2692. if(isDebugEnabled(1) ) logMessage("applicationlib.update_ladderscore: updating ladder score for $resultuser to $newwinnerscore");
  2693. $qid = db_query("UPDATE tblkpBoxLeagues
  2694. SET score = $newwinnerscore
  2695. WHERE boxid = '$boxid'
  2696. AND userid = '$resultuser'");
  2697. }
  2698. }
  2699. }
  2700. /************************************************************************************************************************/
  2701. //Returns the day number of the week
  2702. function getDOW($thisday) {
  2703. $daynumber = 0;
  2704. if ($thisday == "Sunday") {
  2705. $daynumber = 0;
  2706. }
  2707. elseif ($thisday == "Monday") {
  2708. $daynumber = 1;
  2709. }
  2710. elseif ($thisday == "Tuesday") {
  2711. $daynumber = 2;
  2712. }
  2713. elseif ($thisday == "Wednesday") {
  2714. $daynumber = 3;
  2715. }
  2716. elseif ($thisday == "Thursday") {
  2717. $daynumber = 4;
  2718. }
  2719. elseif ($thisday == "Friday") {
  2720. $daynumber = 5;
  2721. }
  2722. elseif ($thisday == "Saturday") {
  2723. $daynumber = 6;
  2724. }
  2725. return $daynumber;
  2726. }
  2727. /*
  2728. *******************************************************************************************************
  2729. ** getTeamIDForCurrentUser
  2730. *******************************************************************************************************
  2731. */
  2732. function getTeamIDForCurrentUser($sportid, $partner) {
  2733. if(isDebugEnabled(1) ) logMessage("applicationlib.getTeamIDForCurrentUser($sportid, $partner)");
  2734. //find teams for current user
  2735. $currentuserteamquery = "SELECT teamdetails.teamid
  2736. FROM tblTeams teams, tblkpTeams teamdetails
  2737. WHERE teams.teamid = teamdetails.teamid
  2738. AND teamdetails.userid=" . get_userid();
  2739. // run the query on the database
  2740. $currentuserteamresult = db_query($currentuserteamquery);
  2741. //Build an single dimensional array for current user teams
  2742. $currentUserStack = array ();
  2743. while ($currentuserteamarray = mysqli_fetch_array($currentuserteamresult)) {
  2744. array_push($currentUserStack, $currentuserteamarray['teamid']);
  2745. }
  2746. //find teams for current users partner
  2747. $currentuserpartnerteamquery = "SELECT teamdetails.teamid
  2748. FROM tblTeams teams, tblkpTeams teamdetails
  2749. WHERE teams.teamid = teamdetails.teamid
  2750. AND teamdetails.userid=$partner";
  2751. // run the query on the database
  2752. $currentuserpartnerteamresult = db_query($currentuserpartnerteamquery);
  2753. //Build an single dimensional array for current users partners teams
  2754. $currentUserPartnerStack = array ();
  2755. while ($currentuserpartnerteamarray = mysqli_fetch_array($currentuserpartnerteamresult)) {
  2756. array_push($currentUserPartnerStack, $currentuserpartnerteamarray['teamid']);
  2757. }
  2758. $teamexistsarray = array_intersect($currentUserStack, $currentUserPartnerStack);
  2759. //print "This is my teamarray: $teamexistsarray[0]";
  2760. if (count($teamexistsarray) > 0) {
  2761. //found a team
  2762. $teamid = current($teamexistsarray);
  2763. } else {
  2764. //had to make a team
  2765. $teamidarray = makeTeamForCurrentUser($sportid, $partner);
  2766. $teamid = $teamidarray[1];
  2767. }
  2768. return $teamid;
  2769. }
  2770. /**
  2771. * Returns the player names for a team
  2772. *
  2773. * @param $teamid
  2774. */
  2775. function getFullnameForTeamPlayers($teamid){
  2776. $query = "SELECT users.firstname, users.lastname, users.userid, users.email,
  2777. concat_ws(' ', users.firstname, users.lastname) AS fullname
  2778. FROM tblUsers users, tblkpTeams teams
  2779. WHERE users.userid = teams.userid
  2780. AND teams.teamid=$teamid";
  2781. $result = db_query($query);
  2782. $teamnames = array();
  2783. while( $playerarray = mysqli_fetch_array($result) ){
  2784. $player = array('firstname' => $playerarray['firstname'],
  2785. 'lastname' => $playerarray['lastname'],
  2786. 'email' => $playerarray['email'],
  2787. 'userid' => $playerarray['userid'],
  2788. 'fullname' => $playerarray['fullname']);
  2789. $teamnames[] = $player;
  2790. }
  2791. return $teamnames;
  2792. }
  2793. /*
  2794. *******************************************************************************************************
  2795. ** getTeamIDForPlayers
  2796. *******************************************************************************************************
  2797. */
  2798. function getTeamIDForPlayers($sportid, $player1, $player2) {
  2799. //find teams for player 1
  2800. $player1teamquery = "SELECT teamdetails.teamid
  2801. FROM tblTeams teams, tblkpTeams teamdetails
  2802. WHERE teams.teamid = teamdetails.teamid
  2803. AND teamdetails.userid=$player1";
  2804. // run the query on the database
  2805. $player1teamresult = db_query($player1teamquery);
  2806. //Build an single dimensional array for player ones teams
  2807. $playerOnesTeamsStack = array ();
  2808. while ($player1teamarray = mysqli_fetch_array($player1teamresult)) {
  2809. array_push($playerOnesTeamsStack, $player1teamarray['teamid']);
  2810. }
  2811. //find teams for player 2
  2812. $player2teamquery = "SELECT teamdetails.teamid
  2813. FROM tblTeams teams, tblkpTeams teamdetails
  2814. WHERE teams.teamid = teamdetails.teamid
  2815. AND teamdetails.userid=$player2";
  2816. // run the query on the database
  2817. $player2teamresult = db_query($player2teamquery);
  2818. //Build an single dimensional array for player ones teams
  2819. $playerTwosTeamsStack = array ();
  2820. while ($player2teamarray = mysqli_fetch_array($player2teamresult)) {
  2821. array_push($playerTwosTeamsStack, $player2teamarray['teamid']);
  2822. }
  2823. $teamexistsarray = array_intersect($playerOnesTeamsStack, $playerTwosTeamsStack);
  2824. $numofrows = count($teamexistsarray);
  2825. //Where this is one player1 and player2 are different people
  2826. if (count($teamexistsarray) == 1) {
  2827. //found a team
  2828. $teamid = current($teamexistsarray);
  2829. }
  2830. /* This will happen when a team is needed for the same person
  2831. * only really application for club guest and club member teams
  2832. */
  2833. elseif (count($teamexistsarray) > 1) {
  2834. $teamid = findSelfTeam($teamexistsarray);
  2835. //Set up the double member teams (where allowed)
  2836. //this will only need to be done once per double
  2837. //member team.
  2838. if(!isset($teamid)){
  2839. $teamidarray = makeTeamForPlayers($sportid, $player1, $player2);
  2840. $teamid = $teamidarray[1];
  2841. }
  2842. } else {
  2843. //had to make a team
  2844. $teamidarray = makeTeamForPlayers($sportid, $player1, $player2);
  2845. $teamid = $teamidarray[1];
  2846. }
  2847. return $teamid;
  2848. }
  2849. /************************************************************************************************************************/
  2850. function isCurrentUserOnTeam($teamid) {
  2851. $imOnTheTeam = 0;
  2852. $query = "SELECT tblkpTeams.userid
  2853. FROM tblkpTeams
  2854. WHERE tblkpTeams.teamid=$teamid";
  2855. // run the query on the database
  2856. $result = db_query($query);
  2857. if( mysqli_num_rows($result)< 2){
  2858. return 0;
  2859. }
  2860. $playeroneArray = mysqli_fetch_array($result);
  2861. $playerone = $playeroneArray[0];
  2862. $playertwoArray = mysqli_fetch_array($result);
  2863. $playertwo = $playertwoArray[0];
  2864. if (get_userid() == $playerone || get_userid() == $playertwo) {
  2865. $imOnTheTeam = 1;
  2866. if( isDebugEnabled(1) ) logMessage("applicationlib.isCurrentUserOnTeam: Current User is on team");
  2867. }
  2868. return $imOnTheTeam;
  2869. }
  2870. /************************************************************************************************************************/
  2871. /* Load in the clubs availble sports */
  2872. function load_avail_sports() {
  2873. $sportquery = "SELECT DISTINCT courts.courttypeid, courttype.courttypename, courttype.reservationtype
  2874. FROM tblCourts courts, tblCourtType courttype
  2875. INNER JOIN tblSportType ON courttype.sportid = tblSportType.sportid
  2876. WHERE courts.courttypeid = courttype.courttypeid
  2877. AND tblSportType.sportname <> 'Equipment'
  2878. AND courts.siteid=".get_siteid();
  2879. $sportresult = db_query($sportquery);
  2880. return $sportresult;
  2881. }
  2882. /************************************************************************************************************************/
  2883. /* Load in the clubs availble timezones */
  2884. function load_avail_timezones() {
  2885. $tzquery = "SELECT tz.name, tz.offset
  2886. FROM tblTimezones tz";
  2887. $tzresult = db_query($tzquery);
  2888. return $tzresult;
  2889. }
  2890. /************************************************************************************************************************/
  2891. /* This will retrieve the availabe sites*/
  2892. function load_avail_sites() {
  2893. $getAllClubSitesQuery = "SELECT * from tblClubSites WHERE clubid = " . get_clubid() . "";
  2894. $getAllClubSitesResult = db_query($getAllClubSitesQuery);
  2895. return $getAllClubSitesResult;
  2896. }
  2897. /************************************************************************************************************************/
  2898. /* This will retrieve the site parameters */
  2899. function load_parameter_options($parameterid){
  2900. if( isDebugEnabled(1) ) logMessage("applicationlib.load_parameter_options for parameter: ". $parameterId );
  2901. $query = "SELECT parameteroption.optionname, parameteroption.optionvalue
  2902. FROM tblParameterOptions parameteroption
  2903. WHERE parameteroption.parameterid = $parameterid";
  2904. $result = db_query($query);
  2905. return $result;
  2906. }
  2907. /************************************************************************************************************************/
  2908. /* This will retrieve the site parameters */
  2909. function load_site_parameters() {
  2910. if( isDebugEnabled(1) ) logMessage("applicationlib.load_site_parameters for site: ". get_siteid());
  2911. $getAllClubSitesQuery = "SELECT parameter.parameterid, parameter.parameterlabel, parametertype.parametertypename, parameteraccesstype.parameteraccesstypename
  2912. FROM tblParameter parameter, tblParameterType parametertype, tblParameterAccess parameteraccess, tblParameterAccessType parameteraccesstype
  2913. WHERE parameter.parametertypeid = parametertype.parametertypeid
  2914. AND parameteraccess.parameterid = parameter.parameterid
  2915. AND parameteraccess.roleid = ".get_roleid()."
  2916. AND parameteraccess.parameteraccesstypeid = parameteraccesstype.parameteraccesstypeid
  2917. AND parameter.siteid = " . get_siteid() . "
  2918. ORDER BY parameter.parameterid";
  2919. $getAllClubSitesResult = db_query($getAllClubSitesQuery);
  2920. return $getAllClubSitesResult;
  2921. }
  2922. /************************************************************************************************************************/
  2923. /* This will retrieve the site parameter */
  2924. function load_site_parameter($parameterid, $userid) {
  2925. if( isDebugEnabled(1) ) logMessage("applicationlib.load_site_parameter: $parameterid for user $userid" );
  2926. $query = "SELECT parametervalue.parametervalue
  2927. FROM tblParameterValue parametervalue
  2928. WHERE parametervalue.userid = $userid
  2929. AND parametervalue.parameterid = $parameterid
  2930. AND parametervalue.enddate IS NULL";
  2931. $result = db_query($query);
  2932. if( mysqli_num_rows($result) > 0 ){
  2933. $resultArray = mysqli_fetch_array($result);
  2934. return $resultArray[0];
  2935. }else{
  2936. return "";
  2937. }
  2938. }
  2939. /************************************************************************************************************************/
  2940. /* This will retrieve the site parameter option name*/
  2941. function load_parameter_option_name($parameterid, $optionvalue) {
  2942. if( isDebugEnabled(1) ) logMessage("applicationlib.load_parameter_option_name: $parameterid for user $optionvalue" );
  2943. $query = "SELECT parameteroption.optionname
  2944. FROM tblParameterOptions parameteroption
  2945. WHERE parameteroption.parameterid = '$parameterid'
  2946. AND parameteroption.optionvalue = '$optionvalue'";
  2947. $result = db_query($query);
  2948. if( mysqli_num_rows($result) > 0 ){
  2949. $resultArray = mysqli_fetch_array($result);
  2950. return $resultArray[0];
  2951. }else{
  2952. return "";
  2953. }
  2954. }
  2955. /************************************************************************************************************************/
  2956. /* This will retrieve the users profile*/
  2957. function load_user_profile($userid) {
  2958. $qid = db_query("SELECT users.userid,
  2959. users.username,
  2960. users.firstname,
  2961. users.lastname,
  2962. users.email,
  2963. users.homephone,
  2964. users.workphone,
  2965. users.cellphone,
  2966. users.pager,
  2967. clubuser.recemail,
  2968. clubuser.roleid,
  2969. users.useraddress,
  2970. clubuser.enable,
  2971. clubuser.msince,
  2972. clubuser.memberid,
  2973. users.gender,
  2974. clubuser.lastlogin
  2975. FROM tblUsers users, tblClubUser clubuser
  2976. WHERE users.userid = $userid
  2977. AND clubuser.userid = users.userid");
  2978. return db_fetch_array($qid);
  2979. }
  2980. /************************************************************************************************************************/
  2981. /* This will retrieve the registered sports*/
  2982. function load_registered_sports($userid) {
  2983. $registeredSportsQuery = "SELECT rankings.courttypeid, rankings.ranking,courttype.courttypename,courttype.reservationtype
  2984. FROM tblUserRankings rankings, tblCourtType courttype
  2985. WHERE rankings.courttypeid = courttype.courttypeid
  2986. AND rankings.userid=$userid
  2987. AND rankings.usertype=0";
  2988. $registeredSportsResult = db_query($registeredSportsQuery);
  2989. if( isDebugEnabled(1) ) logMessage("applicationlib: found ". mysqli_num_rows($registeredSportsResult). " registered sports for user: ". $userid);
  2990. return $registeredSportsResult;
  2991. }
  2992. /************************************************************************************************************************/
  2993. function load_auth_sites($userid) {
  2994. $authSitesQuery = "SELECT siteauth.siteid,clubsites.sitename
  2995. FROM tblkupSiteAuth siteauth, tblClubSites clubsites
  2996. WHERE clubsites.siteid = siteauth.siteid
  2997. AND siteauth.userid = $userid
  2998. AND clubsites.clubid = ". get_clubid();
  2999. $authSitesResult = db_query($authSitesQuery);
  3000. return $authSitesResult;
  3001. }
  3002. /************************************************************************************************************************/
  3003. /*
  3004. This is used to get the courttype for singles courttypes.
  3005. */
  3006. function get_singlesCourtTypesForSite($currentSiteId) {
  3007. $courttypeQuery = "SELECT DISTINCT courttype.courttypeid, courttype.courttypename
  3008. FROM tblCourtType courttype
  3009. INNER JOIN tblCourts courts ON courts.courttypeid = courttype.courttypeid
  3010. WHERE courts.siteid = $currentSiteId
  3011. AND (courttype.reservationtype = 0
  3012. OR courttype.reservationtype = 1)";
  3013. return db_query($courttypeQuery);
  3014. }
  3015. /************************************************************************************************************************/
  3016. /*
  3017. This is used to get the courttype for doubles courttypes.
  3018. */
  3019. function get_doublesCourtTypesForSite($currentSiteId) {
  3020. $courttypeQuery = "SELECT DISTINCT courttype.courttypeid, courttype.courttypename
  3021. FROM tblCourtType courttype
  3022. INNER JOIN tblCourts ON courttype.courttypeid = tblCourts.courttypeid
  3023. WHERE tblCourts.siteid = $currentSiteId
  3024. AND (courttype.reservationtype = 2
  3025. OR courttype.reservationtype = 1)
  3026. ORDER BY courttype.courttypeid";
  3027. return db_query($courttypeQuery);
  3028. }
  3029. /*
  3030. Gets the matchscores for each court types at a site
  3031. */
  3032. function get_singlesMatchscoresForSite($siteid){
  3033. $query = "SELECT DISTINCT tblCourts.courttypeid,gameswon, gameslost
  3034. FROM tblMatchScore
  3035. INNER JOIN tblCourts ON tblMatchScore.courttypeid = tblCourts.courttypeid
  3036. INNER JOIN tblCourtType courttype ON tblCourts.courttypeid = courttype.courttypeid
  3037. AND (courttype.reservationtype = 0
  3038. OR courttype.reservationtype = 1)
  3039. WHERE tblCourts.siteid = $siteid";
  3040. return db_query($query);
  3041. }
  3042. /*
  3043. Gets the matchscores for each court types at a site
  3044. */
  3045. function get_doublesMatchscoresForSite($siteid){
  3046. $query = "SELECT DISTINCT tblCourts.courttypeid,gameswon, gameslost
  3047. FROM tblMatchScore
  3048. INNER JOIN tblCourts ON tblMatchScore.courttypeid = tblCourts.courttypeid
  3049. INNER JOIN tblCourtType courttype ON tblCourts.courttypeid = courttype.courttypeid
  3050. AND (courttype.reservationtype = 2
  3051. OR courttype.reservationtype = 1)
  3052. WHERE tblCourts.siteid = $siteid";
  3053. return db_query($query);
  3054. }
  3055. /*
  3056. This returns all of the match scores
  3057. **/
  3058. function getAllMatchScores(){
  3059. $query = "SELECT courttypeid, gameswon, gameslost
  3060. FROM clubpro_main.tblMatchScore";
  3061. return db_query($query);
  3062. }
  3063. /************************************************************************************************************************/
  3064. /*
  3065. Gets the available court types for the site
  3066. */
  3067. function get_courtTypeForCourt($court) {
  3068. $courttypeQuery = "SELECT tblCourts.courttypeid
  3069. FROM tblCourts
  3070. WHERE (((tblCourts.courtid)=$court))";
  3071. $courttypeResult = db_query($courttypeQuery);
  3072. $resultArray = mysqli_fetch_array($courttypeResult);
  3073. return $resultArray[0];
  3074. }
  3075. /*
  3076. ***********************************************************************************************************************
  3077. */
  3078. /* returns the court type for the given reservationid */
  3079. function get_courtTypeForReservationId($resid) {
  3080. $matchtypequery = "SELECT courts.courttypeid
  3081. FROM tblReservations reservation, tblCourts courts
  3082. WHERE reservation.courtid = courts.courtid
  3083. AND reservation.reservationid=$resid";
  3084. $matchtyperesult = db_query($matchtypequery);
  3085. $matchtypevalueArray = mysqli_fetch_array($matchtyperesult);
  3086. $matchtypevalue = $matchtypevalueArray[0];
  3087. return $matchtypevalue;
  3088. }
  3089. /************************************************************************************************************************/
  3090. /*
  3091. This is by all player selection dropdowns. It makes sure the player is authorized for the site
  3092. and also has a ranking for the sport.
  3093. */
  3094. function get_all_players_dropdown($currentCourtSiteID) {
  3095. $query = "SELECT DISTINCT users.userid, users.firstname, users.lastname
  3096. FROM tblUsers users, tblUserRankings rankings, tblkupSiteAuth siteauth, tblClubUser clubuser
  3097. WHERE users.userid = rankings.userid
  3098. AND users.userid = siteauth.userid
  3099. AND clubuser.roleid!= 4
  3100. AND users.userid = clubuser.userid
  3101. AND clubuser.clubid=" . get_clubid() . "
  3102. AND users.lastname != 'Guest'
  3103. AND users.firstname != 'Club'
  3104. AND siteauth.siteid=$currentCourtSiteID
  3105. AND users.userid != " . get_userid() . "
  3106. AND clubuser.enable='y'
  3107. AND clubuser.enddate IS NULL
  3108. ORDER BY users.lastname";
  3109. return db_query($query);
  3110. }
  3111. /************************************************************************************************************************/
  3112. /*
  3113. This is by all player selection dropdowns. It makes sure the player is authorized for the site
  3114. and also has a ranking for the sport.
  3115. */
  3116. function get_player_dropdown($currentCourtSiteID, $courtid) {
  3117. $query = "SELECT DISTINCT users.userid, users.firstname, users.lastname
  3118. FROM tblUsers users, tblUserRankings rankings, tblkupSiteAuth siteauth, tblClubUser clubuser
  3119. WHERE users.userid = rankings.userid
  3120. AND users.userid = siteauth.userid
  3121. AND clubuser.roleid!= 4
  3122. AND users.userid = clubuser.userid
  3123. AND clubuser.clubid=" . get_clubid() . "
  3124. AND users.lastname != 'Guest'
  3125. AND users.firstname != 'Club'
  3126. AND siteauth.siteid=$currentCourtSiteID
  3127. AND users.userid != " . get_userid() . "
  3128. AND rankings.courttypeid=" . get_courtTypeForCourt($courtid) . "
  3129. AND rankings.usertype=0
  3130. AND clubuser.enable='y'
  3131. AND clubuser.enddate IS NULL
  3132. ORDER BY users.lastname";
  3133. return db_query($query);
  3134. }
  3135. /************************************************************************************************************************/
  3136. /*
  3137. This is by all player selection dropdowns. It makes sure the player is authorized for the site
  3138. and also has a ranking for the sport.
  3139. */
  3140. function get_player_dropdown_withme($currentCourtSiteID, $courtid) {
  3141. $query = "SELECT DISTINCT users.userid, users.firstname, users.lastname
  3142. FROM tblUsers users, tblUserRankings rankings, tblkupSiteAuth siteauth, tblClubUser clubuser
  3143. WHERE users.userid = rankings.userid
  3144. AND users.userid = siteauth.userid
  3145. AND clubuser.roleid!= 4
  3146. AND users.userid = clubuser.userid
  3147. AND clubuser.clubid=" . get_clubid() . "
  3148. AND siteauth.siteid=$currentCourtSiteID
  3149. AND rankings.courttypeid=" . get_courtTypeForCourt($courtid) . "
  3150. AND rankings.usertype=0
  3151. AND clubuser.enable='y'
  3152. AND clubuser.enddate IS NULL
  3153. ORDER BY users.lastname";
  3154. return db_query($query);
  3155. }
  3156. /************************************************************************************************************************/
  3157. /*
  3158. This is by all player selection dropdowns. It makes sure the player is authorized for the site
  3159. and also has a ranking for the sport. **Important: THis does not exlude club guest from being displayed
  3160. and really is only used to generate the list of members for modifing a doubles reservation.
  3161. */
  3162. function get_player_dropdown_with_current($currentCourtSiteID, $courtid) {
  3163. $query = "SELECT DISTINCT users.userid, users.firstname, users.lastname
  3164. FROM tblUsers users, tblUserRankings rankings, tblkupSiteAuth siteauth,tblClubUser clubuser
  3165. WHERE users.userid = rankings.userid
  3166. AND users.userid = siteauth.userid
  3167. AND clubuser.roleid!= 4
  3168. AND users.userid = clubuser.userid
  3169. AND clubuser.clubid=" . get_clubid() . "
  3170. AND siteauth.siteid=$currentCourtSiteID
  3171. AND rankings.courttypeid=" . get_courtTypeForCourt($courtid) . "
  3172. AND rankings.usertype=0
  3173. AND clubuser.enddate IS NULL
  3174. ORDER BY users.lastname";
  3175. return db_query($query);
  3176. }
  3177. /************************************************************************************************************************/
  3178. /*
  3179. This will the the hisotry of the games played between the current user and the userid passed in. This will figure out the
  3180. sports the two users have in common as well as the win loss hisotryAn array
  3181. will be returned that will look like this:
  3182. [0] wins of userid 1 against user 2 for specified sport
  3183. [1] wins of userid 2 against user 1 for specified sport
  3184. [2] winning percentage of user 1 vs user 2 for specified sport
  3185. */
  3186. function get_record_history($userid1, $userid2, $courttypeid) {
  3187. if( isDebugEnabled(1) ) logMessage("applicationlib.get_record_history: getting the record history for userid: ".$userid1." and userid: ". $userid2." for court type: ". $courttypeid);
  3188. // 1. get all resevationsids for user 1
  3189. // 2. get all reservationids for user 2
  3190. // for like reservations record user1 wins and user two wins
  3191. $userOneWins = 0;
  3192. $userTwoWins = 0;
  3193. //Get the first user
  3194. $userOneReservationsQuery = "SELECT reservations.reservationid
  3195. FROM tblkpUserReservations reservationdetails, tblReservations reservations, tblCourts courts
  3196. WHERE reservationdetails.reservationid = reservations.reservationid
  3197. AND reservations.courtid = courts.courtid
  3198. AND courts.courttypeid=$courttypeid
  3199. AND reservationdetails.userid=$userid1";
  3200. $userOneReservationsResult = db_query($userOneReservationsQuery);
  3201. $userOneArray = return_array($userOneReservationsResult);
  3202. //Now get the second user
  3203. $userTwoReservationsQuery = "SELECT reservations.reservationid
  3204. FROM tblkpUserReservations reservationdetails, tblReservations reservations, tblCourts courts
  3205. WHERE reservationdetails.reservationid = reservations.reservationid
  3206. AND reservations.courtid = courts.courtid
  3207. AND courts.courttypeid=$courttypeid
  3208. AND reservationdetails.userid=$userid2";
  3209. $userTwoReservationsResult = db_query($userTwoReservationsQuery);
  3210. $userTwoArray = return_array($userTwoReservationsResult);
  3211. $usersMatches = array_intersect($userOneArray, $userTwoArray);
  3212. for ($i = 0; $i < count($usersMatches); $i++) {
  3213. $reservationid = current($usersMatches);
  3214. $matchResultsQuery = "SELECT tblkpUserReservations.outcome, tblkpUserReservations.userid
  3215. FROM tblkpUserReservations
  3216. WHERE (((tblkpUserReservations.reservationid)=$reservationid))
  3217. ORDER BY tblkpUserReservations.outcome DESC ";
  3218. $matchResultsResult = db_query($matchResultsQuery);
  3219. $firstRecordArray = mysqli_fetch_array($matchResultsResult);
  3220. //If outcome is not zero we know that the match was scored
  3221. if ($firstRecordArray['outcome'] != 0) {
  3222. if ($firstRecordArray['userid'] == $userid1) {
  3223. ++ $userOneWins;
  3224. } else
  3225. if ($firstRecordArray['userid'] == $userid2) {
  3226. ++ $userTwoWins;
  3227. }
  3228. }
  3229. next($usersMatches);
  3230. }
  3231. //Don't divide by zero
  3232. if ($userOneWins != 0) {
  3233. $userOnePercentage = $userOneWins / ($userOneWins + $userTwoWins);
  3234. $userOnePercentageFormated = sprintf("%01.2f", $userOnePercentage * 100);
  3235. } else {
  3236. $userOnePercentageFormated = "0.00";
  3237. }
  3238. if( isDebugEnabled(1) ) logMessage("applicationlib.get_record_history: Got the record userOneWins:".$userOneWins." userTwoWins:".$userTwoWins." and percentage: ". $userOnePercentageFormated);
  3239. return array (
  3240. $userOneWins,
  3241. $userTwoWins,
  3242. $userOnePercentageFormated
  3243. );
  3244. }
  3245. /************************************************************************************************************************/
  3246. /*
  3247. This function takes in a single dimension sql result and returns an array of its values
  3248. */
  3249. function return_array($sqlResult) {
  3250. $stack = array ();
  3251. while ($record = mysqli_fetch_array($sqlResult)) {
  3252. array_push($stack, $record[0]);
  3253. }
  3254. return $stack;
  3255. }
  3256. /************************************************************************************************************************/
  3257. /*
  3258. This function returns all of the months
  3259. */
  3260. function get_months() {
  3261. $monthArray = array (
  3262. "January",
  3263. "February",
  3264. "March",
  3265. "April",
  3266. "May",
  3267. "June",
  3268. "July",
  3269. "August",
  3270. "September",
  3271. "October",
  3272. "November",
  3273. "December"
  3274. );
  3275. return $monthArray;
  3276. }
  3277. /************************************************************************************************************************/
  3278. /*
  3279. This function returns true if nobody has that email address.
  3280. @retun the clubuserid of the offending email address
  3281. */
  3282. function verifyEmailUniqueOutsideClub($email, $userid, $clubid ) {
  3283. if( isDebugEnabled(1) ) logMessage("applicationlib.verifyEmailUniqueOutsideClub: $email, $userid and $clubid");
  3284. $qid = db_query("SELECT users.userid, clubuser.id
  3285. FROM tblUsers users, tblClubUser clubuser
  3286. WHERE users.email = '$email'
  3287. AND users.enddate is NULL
  3288. AND users.userid = clubuser.userid
  3289. and clubuser.clubid != $clubid
  3290. AND clubuser.enddate IS NULL");
  3291. while ($row = mysqli_fetch_array($qid)) {
  3292. if ($row['userid'] != $userid) {
  3293. return $row['id'];
  3294. }
  3295. }
  3296. return;
  3297. }
  3298. /************************************************************************************************************************/
  3299. /*
  3300. This function returns true if nobody has that email address.
  3301. @retun the clubuserid of the offending email address
  3302. */
  3303. function verifyEmailUniqueAtClub($email, $userid, $clubid ) {
  3304. if( isDebugEnabled(1) ) logMessage("applicationlib.verifyEmailUniqueAtClub: $email, $userid and $clubid");
  3305. $qid = db_query("SELECT users.userid, clubuser.id
  3306. FROM tblUsers users, tblClubUser clubuser
  3307. WHERE users.email = '$email'
  3308. AND users.enddate is NULL
  3309. AND users.userid = clubuser.userid
  3310. AND clubuser.clubid = $clubid
  3311. AND clubuser.enddate IS NULL");
  3312. while ($row = mysqli_fetch_array($qid)) {
  3313. if ($row['userid'] != $userid) {
  3314. return $row['id'];
  3315. }
  3316. }
  3317. return;
  3318. }
  3319. /**
  3320. *
  3321. * @param $email
  3322. * @param $clubid
  3323. */
  3324. function isEmailUniqueAtClub($email, $clubid){
  3325. if( isDebugEnabled(1) ) logMessage("applicationlib.isEmailUniqueAtClub: $email and $clubid");
  3326. $qid = db_query("SELECT users.userid, clubuser.id
  3327. FROM tblUsers users, tblClubUser clubuser
  3328. WHERE users.email = '$email'
  3329. AND users.enddate is NULL
  3330. AND users.userid = clubuser.userid
  3331. AND clubuser.clubid = $clubid
  3332. AND clubuser.enddate IS NULL");
  3333. if( mysqli_num_rows($qid)>0){
  3334. return false;
  3335. }else{
  3336. return true;
  3337. }
  3338. }
  3339. /************************************************************************************************************************/
  3340. /*
  3341. Just do some really basic validity checks on an email address
  3342. */
  3343. function is_email_valid($emailaddress) {
  3344. if (filter_var(trim($emailaddress), FILTER_VALIDATE_EMAIL)) {
  3345. return TRUE;
  3346. }
  3347. return FALSE;
  3348. }
  3349. /************************************************************************************************************************/
  3350. /*
  3351. This function returns a list of players for admin searches
  3352. */
  3353. function get_admin_player_search($searchname) {
  3354. $playerquery = "SELECT users.firstname, users.lastname, users.username, users.email, users.workphone, users.homephone, users.userid, clubuser.msince, users.cellphone, clubuser.memberid, clubuser.enable
  3355. FROM tblUsers users, tblClubUser clubuser
  3356. WHERE users.userid = clubuser.userid
  3357. AND clubuser.clubid =" . get_clubid() . "
  3358. AND (users.firstname Like '$searchname%'
  3359. OR users.lastname Like '$searchname%'
  3360. OR clubuser.memberid Like '$searchname%'
  3361. )
  3362. AND clubuser.enddate is NULL
  3363. ORDER BY users.lastname";
  3364. return db_query($playerquery);
  3365. }
  3366. /************************************************************************************************************************/
  3367. /*
  3368. This function returns a list of players for player searches
  3369. */
  3370. function get_player_search($searchname) {
  3371. $playerquery = "SELECT user.userid, user.firstname, user.lastname, user.email, user.workphone, user.homephone, user.cellphone
  3372. FROM tblUsers user, tblClubUser clubuser
  3373. WHERE user.userid = clubuser.userid
  3374. AND clubuser.clubid=" . get_clubid() . "
  3375. AND (user.firstname Like '$searchname%'
  3376. OR user.lastname Like '$searchname%')
  3377. AND clubuser.enable='y'
  3378. AND clubuser.roleid != 4
  3379. AND clubuser.enddate IS NULL
  3380. ORDER BY user.lastname";
  3381. return db_query($playerquery);
  3382. }
  3383. /************************************************************************************************************************/
  3384. /*
  3385. This function decides is the box is expired
  3386. */
  3387. function isBoxExpired($time, $boxnum) {
  3388. $expired = FALSE;
  3389. if ($boxnum > 0) {
  3390. //get the box endtimestamp
  3391. $expiredQuery = "SELECT enddatestamp FROM tblBoxLeagues where boxid = $boxnum";
  3392. $expiredResult = db_query($expiredQuery);
  3393. $boxtimeArray = mysqli_fetch_array($expiredResult);
  3394. $boxtime = $boxtimeArray[0];
  3395. $boxplus = $boxtime +86400;
  3396. //give them the whole day
  3397. if ($time > $boxtime +86400) {
  3398. $expired = TRUE;
  3399. }
  3400. }
  3401. return $expired;
  3402. }
  3403. /************************************************************************************************************************/
  3404. /*
  3405. Since it was finally decided to limit the the number of boxes someone can play in at one time to.....well...one, we now
  3406. have at our disposal the getBoxIdForUser function which will return the boxid for the userid passed in. If a user
  3407. is not is a box at all -1 will be retuned.
  3408. */
  3409. function getBoxIdForUser($userid) {
  3410. $boxUserQuery = "SELECT boxid from tblkpBoxLeagues where userid = $userid";
  3411. $boxUserResult = db_query($boxUserQuery);
  3412. if (mysqli_num_rows($boxUserResult) > 0) {
  3413. $boxidArray = mysqli_fetch_array($boxUserResult);
  3414. $boxid = $boxidArray[0];
  3415. } else {
  3416. $boxid = -1;
  3417. }
  3418. return $boxid;
  3419. }
  3420. /************************************************************************************************************************/
  3421. /*
  3422. This will check to see if the the two users have played each other. We are not going to do alot of validation here so
  3423. its important to make sure that these are two VALID box leage players before calling this.
  3424. */
  3425. function getBoxReservation($userid1, $userid2, $boxid) {
  3426. $hasPlayedWith = FALSE;
  3427. $p1stack = array ();
  3428. $p2stack = array ();
  3429. //find box matches for player one
  3430. $findHistoryQuery1 = "SELECT reservations.reservationid
  3431. FROM tblkpUserReservations reservationdetails, tblReservations reservations, tblBoxHistory boxhistory
  3432. WHERE reservationdetails.reservationid = reservations.reservationid
  3433. AND reservations.reservationid = boxhistory.reservationid
  3434. AND boxhistory.boxid=$boxid
  3435. AND reservationdetails.userid=$userid1";
  3436. $findHistoryResult1 = db_query($findHistoryQuery1);
  3437. while ($findHistoryArray1 = db_fetch_array($findHistoryResult1)) {
  3438. array_push($p1stack, $findHistoryArray1[0]);
  3439. }
  3440. //find box matches for player two
  3441. $findHistoryQuery2 = "SELECT reservations.reservationid
  3442. FROM tblkpUserReservations reservationdetails, tblReservations reservations, tblBoxHistory boxhistory
  3443. WHERE reservationdetails.reservationid = reservations.reservationid
  3444. AND reservations.reservationid = boxhistory.reservationid
  3445. AND boxhistory.boxid=$boxid
  3446. AND reservationdetails.userid=$userid2";
  3447. $findHistoryResult2 = db_query($findHistoryQuery2);
  3448. while ($findHistoryArray2 = db_fetch_array($findHistoryResult2)) {
  3449. array_push($p2stack, $findHistoryArray2[0]);
  3450. }
  3451. $playersintersect = array_intersect($p1stack, $p2stack);
  3452. return $playersintersect[0];
  3453. }
  3454. /**
  3455. * Real Simple. Returns true if the reservation has already been scored, meaning
  3456. * something has been entered in the outcome.
  3457. */
  3458. function hasPlayedBoxWith($userid1, $userid2, $boxid){
  3459. $reservationId = getBoxReservation($userid1, $userid2, $boxid);
  3460. if( isset($reservationId) ){
  3461. return true;
  3462. }
  3463. else{
  3464. return false;
  3465. }
  3466. }
  3467. /************************************************************************************************************************/
  3468. /*
  3469. This will retireive the sitecode
  3470. */
  3471. function get_sitecode() {
  3472. $siteid = $_SESSION["siteprefs"]["siteid"];
  3473. //special case when system console is loaded
  3474. if($siteid == 0){
  3475. return "system";
  3476. }
  3477. return $_SESSION["siteprefs"]["sitecode"];
  3478. }
  3479. /************************************************************************************************************************/
  3480. /*
  3481. This function returns a list of players for player searches
  3482. */
  3483. function get_allclubs_dropdown() {
  3484. $playerquery = "SELECT *
  3485. FROM tblClubs
  3486. WHERE enable=1 ";
  3487. return db_query($playerquery);
  3488. }
  3489. /************************************************************************************************************************/
  3490. /*
  3491. This function returns a list of players for player searches
  3492. */
  3493. function get_allsites_dropdown() {
  3494. $playerquery = "SELECT tblClubSites.*, tblClubs.clubname
  3495. FROM tblClubSites
  3496. INNER JOIN tblClubs ON tblClubSites.clubid = tblClubs.clubid";
  3497. return db_query($playerquery);
  3498. }
  3499. /************************************************************************************************************************/
  3500. /*
  3501. This function returns a list of players for player searches
  3502. */
  3503. function getMonthName($month) {
  3504. if ($month == "1") {
  3505. $monthName = "January";
  3506. }
  3507. elseif ($month == "2") {
  3508. $monthName = "Februray";
  3509. }
  3510. elseif ($month == "3") {
  3511. $monthName = "March";
  3512. }
  3513. elseif ($month == "4") {
  3514. $monthName = "April";
  3515. }
  3516. elseif ($month == "5") {
  3517. $monthName = "May";
  3518. }
  3519. elseif ($month == "6") {
  3520. $monthName = "June";
  3521. }
  3522. elseif ($month == "7") {
  3523. $monthName = "July";
  3524. }
  3525. elseif ($month == "8") {
  3526. $monthName = "August";
  3527. }
  3528. elseif ($month == "9") {
  3529. $monthName = "September";
  3530. }
  3531. elseif ($month == "10") {
  3532. $monthName = "October";
  3533. }
  3534. elseif ($month == "11") {
  3535. $monthName = "November";
  3536. }
  3537. elseif ($month == "12") {
  3538. $monthName = "December";
  3539. }
  3540. return $monthName;
  3541. }
  3542. /************************************************************************************************************************/
  3543. /*
  3544. This function returns a the two userid for the team specified
  3545. */
  3546. function getUserIdsForTeamId($teamid) {
  3547. $playersQuery = "SELECT teamdetails.userid, users.firstname, users.lastname
  3548. FROM tblkpTeams teamdetails, tblUsers users
  3549. WHERE teamdetails.teamid=$teamid
  3550. AND teamdetails.userid = users.userid
  3551. ORDER BY users.userid";
  3552. $playersResult = db_query($playersQuery);
  3553. return $playersResult;
  3554. }
  3555. /************************************************************************************************************************/
  3556. /*
  3557. This function returns a the two userid for the team specified
  3558. */
  3559. function getUserIdsForTeamIdWithCourtType($teamid, $courtTypeId) {
  3560. $playersQuery = "SELECT teamdetails.userid, users.firstname, users.lastname, rankings.ranking
  3561. FROM tblkpTeams teamdetails, tblUsers users, tblUserRankings rankings
  3562. WHERE teamdetails.teamid=$teamid
  3563. AND teamdetails.userid = users.userid
  3564. AND rankings.userid = users.userid
  3565. AND rankings.usertype = 0
  3566. AND rankings.courttypeid = $courtTypeId
  3567. ORDER BY users.userid";
  3568. $playersResult = db_query($playersQuery);
  3569. return $playersResult;
  3570. }
  3571. /************************************************************************************************************************/
  3572. /*
  3573. This will return true if the user specified is a club guest and false if not.
  3574. */
  3575. function isClubGuest($userid) {
  3576. if($userid=="" || empty($userid) ){
  3577. return false;
  3578. }
  3579. $isClubGuest = FALSE;
  3580. $isClubGuestQuery = "SELECT firstname, lastname from tblUsers
  3581. WHERE userid = $userid";
  3582. $isClubGuestResult = db_query($isClubGuestQuery);
  3583. $isClubGuestArray = mysqli_fetch_array($isClubGuestResult);
  3584. if ($isClubGuestArray['firstname'] == "Club" && $isClubGuestArray['lastname'] == "Guest") {
  3585. $isClubGuest = TRUE;
  3586. }
  3587. return $isClubGuest;
  3588. }
  3589. /**
  3590. * Used to determine if a player has been selected in a drop down.
  3591. */
  3592. function isPlayerSpecified($userid){
  3593. if($userid ==""){
  3594. return false;
  3595. }
  3596. return true;
  3597. }
  3598. /*
  3599. * This will return true if the passed in user has a roleid is 2 or Program administrator
  3600. */
  3601. function isProgramAdmin($userid) {
  3602. //This damn thing might be empty, fine, I'll check it
  3603. if (empty ($userid))
  3604. return false;
  3605. $query = "SELECT clubuser.roleid
  3606. FROM tblClubUser clubuser
  3607. WHERE clubuser.userid = $userid";
  3608. $result = db_query($query);
  3609. $array = mysqli_fetch_array($result);
  3610. if ($array['roleid'] == 2) {
  3611. return true;
  3612. } else {
  3613. return false;
  3614. }
  3615. }
  3616. /*
  3617. * Figures out if this is a CLub Member
  3618. */
  3619. function isClubMember($userid) {
  3620. if(empty($userid)){
  3621. return false;
  3622. }
  3623. $query = "SELECT users.firstname, users.lastname
  3624. FROM tblUsers users
  3625. WHERE users.userid = $userid";
  3626. $result = db_query($query);
  3627. $array = mysqli_fetch_array($result);
  3628. if ($array['firstname'] == "Club" && $array['lastname'] == "Member") {
  3629. return true;
  3630. } else {
  3631. return false;
  3632. }
  3633. }
  3634. /*
  3635. * Figures out if this is a CLub Member (just based on the name)
  3636. */
  3637. function isClubMemberName($username) {
  3638. if ($username == "Club Member") {
  3639. return true;
  3640. } else {
  3641. return false;
  3642. }
  3643. }
  3644. /*
  3645. * Figures out if this is a CLub Gueset (just based on the name)
  3646. */
  3647. function isClubGuestName($username) {
  3648. if ($username == "Club Guest") {
  3649. return true;
  3650. } else {
  3651. return false;
  3652. }
  3653. }
  3654. /************************************************************************************************************************/
  3655. /*
  3656. Validates the Skill Range Policies
  3657. Only support singles court types for now
  3658. */
  3659. function validateSkillPolicies($opponentid, $currentuserid, $courtid, $courttype, $time) {
  3660. if( isDebugEnabled(1) ) logMessage("applicationlib.validateSkillPolicies: Validating Skill Range Policies: opponent: $opponentid, Current User: $currentuserid, courtid = $courtid, time= $time Court Type: $courttype ");
  3661. //Make an exception for the club guest
  3662. if (isClubGuest($opponentid)) {
  3663. return TRUE;
  3664. }
  3665. $result = load_skill_policies(get_siteid());
  3666. while ($row = mysqli_fetch_array($result)) {
  3667. $starttime = $row['starttime'];
  3668. $endtime = $row['endtime'];
  3669. $startTimeArray = explode(":", $starttime);
  3670. $endTimeArray = explode(":", $endtime);
  3671. $starthour = $startTimeArray[0];
  3672. $endhour = $endTimeArray[0];
  3673. //Check to see if court applies
  3674. if ($row['courtid'] == $courtid || $row['courtid'] == NULL) {
  3675. //Check to see if Day applies
  3676. $dow = gmdate("w", $time);
  3677. if ($row['dayid'] == $dow || $row['dayid'] == NULL) {
  3678. //Check to see if this is within the window
  3679. if (withinWindow(gmdate("H", $time), $starthour, $endhour)) {
  3680. //Check for a Singles Reservations
  3681. if ($courttype == 'singles' || $courttype == 'doubles') {
  3682. //Check individual ranking
  3683. $individualQuery = "SELECT rankings.ranking
  3684. FROM tblUserRankings rankings,
  3685. tblCourtType courttype,
  3686. tblCourts courts
  3687. WHERE (
  3688. rankings.userid =$opponentid
  3689. OR rankings.userid =$currentuserid
  3690. )
  3691. AND rankings.courttypeid = courttype.courttypeid
  3692. AND courts.courttypeid = courttype.courttypeid
  3693. AND courts.courtid = $courtid
  3694. AND rankings.usertype =0";
  3695. $individualQueryResult = db_query($individualQuery);
  3696. //Make sure both users have a rankings
  3697. if (mysqli_num_rows($individualQueryResult) != 2) {
  3698. if( isDebugEnabled(1) ) logMessage("applicationlib.validateSkillPolicies: One of these two players doesn't have a ranking ");
  3699. return FALSE;
  3700. }
  3701. $ranking1Array = mysqli_fetch_array($individualQueryResult);
  3702. $ranking1 = $ranking1Array[0];
  3703. //mysqli_data_seek($individualQueryResult,1);
  3704. $ranking2Array = mysqli_fetch_array($individualQueryResult);
  3705. $ranking2 = $ranking2Array[0];
  3706. //Do the calculation
  3707. if ((abs($ranking1 - $ranking2) > $row['skillrange'])) {
  3708. if( isDebugEnabled(1) ) logMessage("applicationlib.validateSkillPolicies: ".abs($ranking1 - $ranking2) ." is greater than the skill range of ".$row['skillrange'].". Not letting this happen.");
  3709. return FALSE;
  3710. }
  3711. else{
  3712. if( isDebugEnabled(1) ) logMessage("applicationlib.validateSkillPolicies: ".abs($ranking1 - $ranking2) ." is less than the skill range of ".$row['skillrange'].". This is ok.");
  3713. }
  3714. } //end of check
  3715. } //endif within window
  3716. } //endif day validiation
  3717. } //endif court validiation
  3718. } //end main while loop
  3719. if( isDebugEnabled(1) ) logMessage("applicationlib.validateSkillPolicies: Everything looks ok with this reservation ");
  3720. return TRUE;
  3721. }
  3722. /************************************************************************************************************************/
  3723. /*
  3724. This will return TRUE if the resevation is being made in a primetime window I realize that this appears really complicated,
  3725. but really its not that bad.
  3726. court id- the court id
  3727. time - the time
  3728. opponent - the opponent. Used for validating allow looking for a match
  3729. *
  3730. */
  3731. function validateSchedulePolicies($courtid, $time, $opponent) {
  3732. if( isDebugEnabled(1) ) logMessage("applicationlib.validateSchedulePolicies: Validating Scheduling Policies: courtid = $courtid, time= $time, partner= $opponent ");
  3733. $result = load_reservation_policies(get_siteid());
  3734. while ($row = mysqli_fetch_array($result)) {
  3735. $starttime = $row['starttime'];
  3736. $endtime = $row['endtime'];
  3737. $startTimeArray = explode(":", $starttime);
  3738. $endTimeArray = explode(":", $endtime);
  3739. $starthour = $startTimeArray[0];
  3740. $endhour = $endTimeArray[0];
  3741. //Check to see if court applies
  3742. if ($row['courtid'] == $courtid || $row['courtid'] == NULL) {
  3743. //Check to see if Day applies
  3744. $dow = gmdate("w", $time);
  3745. if ($row['dayid'] == $dow || $row['dayid'] == NULL) {
  3746. //Check to see if this is within the window
  3747. if (withinWindow(gmdate("H", $time), $starthour, $endhour)) {
  3748. //When $row['courtid'] that means we have to check all courts
  3749. if ($row['courtid'] == NULL || $row['courtid'] == $courtid) {
  3750. //Check to see if they exceeded window
  3751. if ($row['schedulelimit'] <= getAllReservationsMadeToday($starthour, $endhour, $time)) {
  3752. $message = "Policy '".$row['policyname']."' doesn't allow more than ".$row['schedulelimit']. " reservations per day";
  3753. if( isDebugEnabled(1) ) logMessage($message);
  3754. return $message;
  3755. }
  3756. //Checking looking for match
  3757. // if the partner is set and empty that means its a no specified opponent from the singles, if its not
  3758. //set and not defined that means this is being run on a doubles reservation in which case we do not apply
  3759. // allow looking for match policies.
  3760. if( $row['allowlooking']=='n' && isset($opponent)){
  3761. if( isDebugEnabled(1) ) logMessage("applicationlib.validateSchedulePolicies: this policy doesn't allow looking for a match");
  3762. $message = "Policy called '".$row['policyname']."' doesn't allow players looking for a match";
  3763. if( isDebugEnabled(1) ) logMessage($message);
  3764. return $message;
  3765. }
  3766. // Checking the back to back policies.
  3767. if( $row['allowback2back']=='n' ){
  3768. if( isDebugEnabled(1) ) logMessage("applicationlib.validateSchedulePolicies: this policy doesn't allow back2back, looking into this.");
  3769. $courtDuration = getCourtDuration($courtid, $time, $dow );
  3770. $previousReservationTime = $time - ($courtDuration * 60 * 60);
  3771. if( isInReservation($courtid, $previousReservationTime, get_userid() ) ){
  3772. $message = "A policy called '".$row['policyname']."' doesn't allow back to back reservations.";
  3773. if( isDebugEnabled(1) ) logMessage($message);
  3774. return $message;
  3775. }
  3776. $nextReservationTime = $time + ($courtDuration * 60 * 60);
  3777. if( isInReservation($courtid, $nextReservationTime, get_userid() ) ){
  3778. $message = "A policy called '".$row['policyname']."' doesn't allow back to back reservations.";
  3779. if( isDebugEnabled(1) ) logMessage($message);
  3780. return $message;
  3781. }
  3782. }
  3783. } else {
  3784. //Check to see if they exceeded window
  3785. if ($row['schedulelimit'] <= getCourtReservationsMadeToday($courtid, $starthour, $endhour, $time)) {
  3786. $message = "Policy '".$row['policyname']."' doesn't allow more than ".$row['schedulelimit']. " reservations per day";
  3787. if( isDebugEnabled(1) ) logMessage($message);
  3788. return $message;
  3789. }
  3790. }
  3791. }
  3792. }
  3793. }
  3794. }
  3795. return '';
  3796. }
  3797. /************************************************************************************************************************/
  3798. /*
  3799. This will return TRUE if the resevation is being made in a window
  3800. */
  3801. function withinWindow($reservationtime, $starthour, $endhour) {
  3802. ;
  3803. //When starttime is null, endtime should also be NULL which means that it does not specify a window,all applies.
  3804. if ($starthour == NULL) {
  3805. return TRUE;
  3806. }
  3807. if ($starthour <= $reservationtime && $endhour > $reservationtime) {
  3808. return TRUE;
  3809. }
  3810. return FALSE;
  3811. }
  3812. /************************************************************************************************************************/
  3813. /*
  3814. */
  3815. function getAllReservationsMadeToday($starthour, $endhour, $time) {
  3816. //Then Check all day
  3817. if ($starthour == NULL) {
  3818. return countNumberOfAllResevationsMadeToday($time);
  3819. } else {
  3820. return countNumberOfAllResevationsMadeTodayInWindow($starthour, $endhour, $time);
  3821. }
  3822. }
  3823. /************************************************************************************************************************/
  3824. /*
  3825. */
  3826. function getCourtReservationsMadeToday($courtid, $starthour, $endhour, $time) {
  3827. //Then Check all day
  3828. if ($starthour == NULL) {
  3829. return countNumberOfCourtResevationsMadeToday($courtid, $time);
  3830. } else {
  3831. return countNumberOfCourtResevationsMadeTodayInWindow($courtid, $starthour, $endhour, $time);
  3832. }
  3833. }
  3834. /************************************************************************************************************************/
  3835. /*
  3836. */
  3837. function countNumberOfAllResevationsMadeToday($time) {
  3838. if( isDebugEnabled(1) ) logMessage("applicationlib.countNumberOfAllResevationsMadeToday: checking to see if reservations are made for time: $time");
  3839. //For each court in the site
  3840. $courtQuery = "Select courts.courtid from tblCourts courts where courts.siteid=".get_siteid();
  3841. $courtResult = db_query($courtQuery);
  3842. $totalReservations = 0;
  3843. //Get Teams
  3844. $userid = get_userid();
  3845. $teams = getTeamsForUser($userid);
  3846. while($courtidArray = mysqli_fetch_array($courtResult)){
  3847. $courtid = $courtidArray['courtid'];
  3848. //Have to get the open/close time for today
  3849. $starttime = getOpenTimeToday($time, $courtid);
  3850. $endtime = getCloseTimeToday($time, $courtid);
  3851. $singlesQuery = "SELECT count(reservations.time)
  3852. FROM tblReservations reservations, tblkpUserReservations details
  3853. WHERE reservations.reservationid = details.reservationid
  3854. AND details.userid = " . get_userid() . "
  3855. AND reservations.enddate is NULL
  3856. AND reservations.usertype = 0
  3857. AND reservations.courtid=$courtid
  3858. AND reservations.time >= $starttime
  3859. AND reservations.time < $endtime";
  3860. $singlesResult = db_query($singlesQuery);
  3861. $singlesResultArray = mysqli_fetch_array($singlesResult);
  3862. $totalReservations += $singlesResultArray[0];
  3863. //Now get the number of doubles reservations
  3864. /*
  3865. 1.) Get the the court type ids for the site doubles or multi reservationtype
  3866. 2.) For each one, get the list of teams ids
  3867. 3.) Look for all reservations with team id
  3868. 4.) Count them.
  3869. */
  3870. if(mysqli_num_rows($teams) > 0 ){
  3871. $teamINClause = "";
  3872. //Reset the teams
  3873. mysqli_data_seek($teams,0);
  3874. for ($i = 0; $i < mysqli_num_rows($teams); ++ $i) {
  3875. $team = mysqli_fetch_array($teams);
  3876. if ($i != 0) {
  3877. $teamINClause .= ",";
  3878. }
  3879. $teamINClause .= "$team[teamid]";
  3880. }
  3881. $doublesQuery = "SELECT count(reservations.time)
  3882. FROM tblReservations reservations, tblkpUserReservations details, tblCourts courts
  3883. WHERE reservations.reservationid = details.reservationid
  3884. AND reservations.usertype = 1
  3885. AND courts.courtid=$courtid
  3886. AND reservations.time >= $starttime
  3887. AND reservations.time < $endtime
  3888. AND details.userid IN ($teamINClause)
  3889. AND reservations.enddate IS NULL";
  3890. $doublesResult = db_query($doublesQuery);
  3891. $doublesResultArray = mysqli_fetch_array($doublesResult);
  3892. $totalReservations += $doublesResultArray[0];
  3893. }
  3894. }
  3895. return $totalReservations;
  3896. }
  3897. /************************************************************************************************************************/
  3898. /*
  3899. This will return TRUE if the resevation is being made in a window
  3900. */
  3901. function countNumberOfAllResevationsMadeTodayInWindow($starthour, $endhour, $time) {
  3902. $starttime = getTimeToday($starthour, $time);
  3903. $endtime = getTimeToday($endhour, $time);
  3904. $totalReservations = 0;
  3905. $singlesQuery = "SELECT count(reservations.time)
  3906. FROM tblReservations reservations, tblkpUserReservations details
  3907. WHERE reservations.reservationid = details.reservationid
  3908. AND reservations.usertype = 0
  3909. AND reservations.enddate IS NULL
  3910. AND details.userid = " . get_userid() . "
  3911. AND reservations.time >= $starttime
  3912. AND reservations.time < $endtime";
  3913. $singlesResult = db_query($singlesQuery);
  3914. $singlesResultArray = mysqli_fetch_array($singlesResult);
  3915. $totalReservations = $singlesResultArray[0];
  3916. //Now get the number of doubles reservations
  3917. /*
  3918. 1.) Get the the court type ids for the site doubles or multi reservationtype
  3919. 2.) For each one, get the list of teams ids
  3920. 3.) Look for all reservations with team id
  3921. 4.) Count them.
  3922. */
  3923. $teamINClause = "";
  3924. $userid = get_userid();
  3925. $teams = getTeamsForUser($userid);
  3926. $rows = mysqli_num_rows($teams);
  3927. for ($i = 0; $i < $rows; ++ $i) {
  3928. $team = mysqli_fetch_array($teams);
  3929. if ($i != 0) {
  3930. $teamINClause .= ",";
  3931. }
  3932. $teamINClause .= "$team[teamid]";
  3933. }
  3934. // If this person is on a team, set.
  3935. if($rows > 0 ){
  3936. $doublesQuery = "SELECT count(reservations.time)
  3937. FROM tblReservations reservations, tblkpUserReservations details
  3938. WHERE reservations.reservationid = details.reservationid
  3939. AND reservations.usertype = 1
  3940. AND reservations.enddate IS NULL
  3941. AND reservations.time >= $starttime
  3942. AND reservations.time < $endtime
  3943. AND details.userid IN ($teamINClause)";
  3944. $doublesResult = db_query($doublesQuery);
  3945. $doublesResultArray = mysqli_fetch_array($doublesResult);
  3946. $totalReservations += $doublesResultArray[0];
  3947. }
  3948. return $totalReservations;
  3949. }
  3950. /************************************************************************************************************************/
  3951. /*
  3952. */
  3953. function countNumberOfCourtResevationsMadeToday($courtid, $time) {
  3954. $starttime = getOpenTimeToday($time, $courtid);
  3955. $endtime = getCloseTimeToday($time, $courtid);
  3956. if( isDebugEnabled(1) ) logMessage("applicationlib.countNumberOfCourtResevationsMadeToday: checking to see if reservations are made: $courtid and $time");
  3957. $singlesQuery = "SELECT count(reservations.time)
  3958. FROM tblReservations reservations, tblkpUserReservations details
  3959. WHERE reservations.reservationid = details.reservationid
  3960. AND reservations.usertype = 0
  3961. AND reservations.enddate IS NULL
  3962. AND details.userid = " . get_userid() . "
  3963. AND reservations.time > $starttime
  3964. AND reservations.time < $endtime";
  3965. $singlesResult = db_query($singlesQuery);
  3966. $singlesResultArray = mysqli_fetch_array($singlesResult);
  3967. $totalReservations = $singlesResultArray[0];
  3968. //Now get the number of doubles reservations
  3969. /*
  3970. 1.) Get the the court type ids for the site doubles or multi reservationtype
  3971. 2.) For each one, get the list of teams ids
  3972. 3.) Look for all reservations with team id
  3973. 4.) Count them.
  3974. */
  3975. $teamINClause = "";
  3976. $userid = get_userid();
  3977. $teams = getTeamsForUser($userid);
  3978. $rows = mysqli_num_rows($teams);
  3979. for ($i = 0; $i < $rows; ++ $i) {
  3980. $team = mysqli_fetch_array($teams);
  3981. if ($i != 0) {
  3982. $teamINClause .= ",";
  3983. }
  3984. $teamINClause .= "$team[teamid]";
  3985. }
  3986. if($rows > 0){
  3987. $doublesQuery = "SELECT count(reservations.time)
  3988. FROM tblReservations reservations, tblkpUserReservations details
  3989. WHERE reservations.reservationid = details.reservationid
  3990. AND reservations.usertype = 1
  3991. AND reservations.enddate IS NULL
  3992. AND reservations.time >= $starttime
  3993. AND reservations.time < $endtime
  3994. AND details.userid IN ($teamINClause)";
  3995. $doublesResult = db_query($doublesQuery);
  3996. $doublesResultArray = mysqli_fetch_array($doublesResult);
  3997. $totalReservations += $doublesResultArray[0];
  3998. }
  3999. return $totalReservations;
  4000. }
  4001. /************************************************************************************************************************/
  4002. /*
  4003. */
  4004. function countNumberOfCourtResevationsMadeTodayInWindow($starthour, $endhour, $time) {
  4005. $starttime = getTimeToday($starthour, $time);
  4006. $endtime = getTimeToday($endhour, $time);
  4007. if( isDebugEnabled(1) ) logMessage("applicationlib.countNumberOfCourtResevationsMadeTodayInWindow: checking to see if reservations are made: starthour: $starthour endhour: $endhour and time: $time");
  4008. $singlesQuery = "SELECT count(reservations.time)
  4009. FROM tblReservations reservations, tblkpUserReservations details
  4010. WHERE reservations.reservationid = details.reservationid
  4011. AND reservations.usertype = 0
  4012. AND reservations.enddate IS NULL
  4013. AND details.userid = " . get_userid() . "
  4014. AND reservations.time > $starttime
  4015. AND reservations.time < $endtime";
  4016. $singlesResult = db_query($singlesQuery);
  4017. $singlesResultArray = mysqli_fetch_array($singlesResult);
  4018. $totalReservations = $singlesResultArray[0];
  4019. //Now get the number of doubles reservations
  4020. /*
  4021. 1.) Get the the court type ids for the site doubles or multi reservationtype
  4022. 2.) For each one, get the list of teams ids
  4023. 3.) Look for all reservations with team id
  4024. 4.) Count them.
  4025. */
  4026. $teamINClause = "";
  4027. $userid = get_userid();
  4028. $teams = getTeamsForUser($userid);
  4029. $rows = mysqli_num_rows($teams);
  4030. for ($i = 0; $i < $rows; ++ $i) {
  4031. $team = mysqli_fetch_array($teams);
  4032. if ($i != 0) {
  4033. $teamINClause .= ",";
  4034. }
  4035. $teamINClause .= "$team[teamid]";
  4036. }
  4037. if($rows > 0 ){
  4038. $doublesQuery = "SELECT count(reservations.time)
  4039. FROM tblReservations reservations, tblkpUserReservations details
  4040. WHERE reservations.reservationid = details.reservationid
  4041. AND reservations.usertype = 1
  4042. AND reservations.enddate IS NULL
  4043. AND reservations.time >= $starttime
  4044. AND reservations.time < $endtime
  4045. AND details.userid IN ($teamINClause)";
  4046. $doublesResult = db_query($doublesQuery);
  4047. $doublesResultArray = mysqli_fetch_array($doublesResult);
  4048. $totalReservations += $doublesResultArray[0];
  4049. }
  4050. return $totalReservations;
  4051. }
  4052. /************************************************************************************************************************/
  4053. /*
  4054. */
  4055. function getTeamsForUser($userid) {
  4056. /*
  4057. 1.) Get the the court type ids for the site doubles or multi reservationtype
  4058. 2.) For each one, get the list of teams ids
  4059. */
  4060. $teamsQuery = "SELECT teamdetails.teamid
  4061. FROM tblkpTeams teamdetails
  4062. WHERE teamdetails.userid = $userid";
  4063. return db_query($teamsQuery);;
  4064. }
  4065. /************************************************************************************************************************/
  4066. /*
  4067. */
  4068. function getOpenTimeToday($time, $courtid) {
  4069. $day = gmdate("j", $time);
  4070. $month = gmdate("n", $time);
  4071. $year = gmdate("Y", $time);
  4072. $dow = gmdate("w", $time);
  4073. // int hour, int minute, int second, int month, int day, int year
  4074. $query = "SELECT hours.opentime
  4075. FROM tblCourtHours hours
  4076. WHERE hours.courtid=$courtid
  4077. AND hours.dayid=$dow";
  4078. $result = db_query($query);
  4079. $resultArray = mysqli_fetch_array($result);
  4080. $opentime = $resultArray[0];
  4081. $openTimeArray = explode(":", $opentime);
  4082. $timestamp = gmmktime($openTimeArray[0], 0, 0, $month, $day, $year);
  4083. return $timestamp;
  4084. }
  4085. /************************************************************************************************************************/
  4086. /*
  4087. */
  4088. function getCloseTimeToday($time, $courtid) {
  4089. $day = gmdate("j", $time);
  4090. $month = gmdate("n", $time);
  4091. $year = gmdate("Y", $time);
  4092. $dow = gmdate("w", $time);
  4093. // int hour, int minute, int second, int month, int day, int year
  4094. $query = "SELECT hours.closetime
  4095. FROM tblCourtHours hours
  4096. WHERE hours.courtid=$courtid
  4097. AND hours.dayid=$dow";
  4098. $result = db_query($query);
  4099. $resultArray = mysqli_fetch_array($result);
  4100. $closetime = $resultArray[0];
  4101. $closeTimeArray = explode(":", $closetime);
  4102. $timestamp = gmmktime($closeTimeArray[0], 0, 0, $month, $day, $year);
  4103. return $timestamp;
  4104. }
  4105. /************************************************************************************************************************/
  4106. /*
  4107. */
  4108. function getDurationToday($time, $courtid) {
  4109. $day = gmdate("j", $time);
  4110. $month = gmdate("n", $time);
  4111. $year = gmdate("Y", $time);
  4112. $dow = gmdate("w", $time);
  4113. // int hour, int minute, int second, int month, int day, int year
  4114. $query = "SELECT hours.duration
  4115. FROM tblCourtHours hours
  4116. WHERE hours.courtid=$courtid
  4117. AND hours.dayid=$dow";
  4118. $result = db_query($query);
  4119. $resultArray = mysqli_fetch_array($result);
  4120. return $resultArray[0];
  4121. }
  4122. /************************************************************************************************************************/
  4123. /*
  4124. */
  4125. function getTimeToday($hour, $time) {
  4126. $day = gmdate("j", $time);
  4127. $minute = gmdate("i", $time);
  4128. $month = gmdate("n", $time);
  4129. $year = gmdate("Y", $time);
  4130. $timestamp = gmmktime($hour, $minute, 0, $month, $day, $year);
  4131. return $timestamp;
  4132. }
  4133. /*****************************************************************/
  4134. /*
  4135. Will load the windows
  4136. */
  4137. function load_reservation_policies($siteid) {
  4138. $query = "SELECT policy.policyname,
  4139. policy.policyid,
  4140. policy.description,
  4141. policy.schedulelimit,
  4142. policy.dayid,
  4143. policy.courtid,
  4144. policy.siteid,
  4145. policy.starttime,
  4146. policy.endtime,
  4147. policy.allowlooking,
  4148. policy.allowback2back
  4149. FROM tblSchedulingPolicy policy
  4150. WHERE policy.siteid = $siteid";
  4151. return db_query($query);
  4152. }
  4153. /*****************************************************************/
  4154. /*
  4155. */
  4156. function load_reservation_policy($policyid) {
  4157. $query = "SELECT policy.policyname,
  4158. policy.policyid,
  4159. policy.description,
  4160. policy.schedulelimit,
  4161. policy.dayid,
  4162. policy.courtid,
  4163. policy.siteid,
  4164. policy.starttime,
  4165. policy.endtime,
  4166. policy.allowlooking,
  4167. policy.allowback2back
  4168. FROM tblSchedulingPolicy policy
  4169. WHERE policy.policyid = $policyid";
  4170. $result = db_query($query);
  4171. return mysqli_fetch_array($result);
  4172. }
  4173. /*****************************************************************/
  4174. /*
  4175. Will load the windows
  4176. */
  4177. function load_skill_policies($siteid) {
  4178. $query = "SELECT policy.policyname,
  4179. policy.policyid,
  4180. policy.description,
  4181. policy.skillrange,
  4182. policy.dayid,
  4183. policy.courtid,
  4184. policy.starttime,
  4185. policy.endtime
  4186. FROM tblSkillRangePolicy policy
  4187. WHERE policy.siteid = $siteid";
  4188. return db_query($query);
  4189. }
  4190. /**
  4191. *
  4192. * @param $eventid
  4193. */
  4194. function load_court_event($eventid){
  4195. $query = "SELECT events.eventname,
  4196. events.playerlimit,events.eventid
  4197. FROM tblEvents events
  4198. WHERE events.eventid = $eventid";
  4199. $result = db_query($query);
  4200. return mysqli_fetch_array($result);
  4201. }
  4202. /**
  4203. *
  4204. * @param $eventid
  4205. */
  4206. function load_court_events($siteid){
  4207. $query = "SELECT events.eventid, events.eventname,
  4208. events.playerlimit
  4209. FROM tblEvents events
  4210. WHERE events.siteid = $siteid
  4211. ORDER BY events.eventname";
  4212. $result = db_query($query);
  4213. if( isDebugEnabled(1) ) logMessage("applicationlib.load_court_events: loading court events for site $siteid. Found ". mysqli_num_rows($result) . " in all");
  4214. return db_query($query);
  4215. }
  4216. /*****************************************************************/
  4217. /*
  4218. Will load the windows
  4219. */
  4220. function load_skill_range_policy($policyid) {
  4221. $query = "SELECT policy.policyid,
  4222. policy.policyname,
  4223. policy.description,
  4224. policy.skillrange,
  4225. policy.dayid,
  4226. policy.courtid,
  4227. policy.siteid,
  4228. policy.starttime,
  4229. policy.endtime
  4230. FROM tblSkillRangePolicy policy
  4231. WHERE policy.policyid = $policyid";
  4232. $result = db_query($query);
  4233. return mysqli_fetch_array($result);
  4234. }
  4235. /**
  4236. * Returns a court duration given a court id and time
  4237. * @return current court duration in minutes.
  4238. *
  4239. * This does not support hours exceptions!!
  4240. */
  4241. function getCourtDuration($courtid, $time, $dow){
  4242. $query = "SELECT duration
  4243. FROM tblCourtHours hours
  4244. WHERE courtid = $courtid
  4245. AND dayid = $dow";
  4246. $result = db_query($query);
  4247. $resultArray = mysqli_fetch_array($result);
  4248. return $resultArray[0];
  4249. }
  4250. /**
  4251. *
  4252. * @return boolean
  4253. *
  4254. * Only works for singles reservations at the moment
  4255. *
  4256. */
  4257. function isInReservation($courtid, $time, $userid){
  4258. $query = "SELECT 1 FROM tblReservations reservation, tblkpUserReservations reservationdetails
  4259. WHERE reservation.reservationid = reservationdetails.reservationid
  4260. AND reservation.courtid = $courtid
  4261. AND reservation.time = $time
  4262. AND reservation.usertype=0
  4263. AND reservationdetails.userid = $userid";
  4264. $result = db_query($query);
  4265. if(mysqli_num_rows($result) > 0 ){
  4266. return TRUE;
  4267. }else{
  4268. return FALSE;
  4269. }
  4270. }
  4271. /**
  4272. * This should only be set in the clubpro/admin.php
  4273. */
  4274. function isSystemAdministrationConsole(){
  4275. if( isset($_SESSION["siteprefs"]["clubid"]) && $_SESSION["siteprefs"]["clubid"] == 0 ){
  4276. return true;
  4277. }
  4278. else{
  4279. return false;
  4280. }
  4281. }
  4282. /**
  4283. * Returns the club site ladders for a given siteid
  4284. *
  4285. * @param unknown_type $siteid
  4286. */
  4287. function getClubSiteLadders($siteid){
  4288. if( isDebugEnabled(1) ) logMessage("applicationlib.getClubSiteLadders: getting the ladders configured for site for court: $siteid");
  4289. $array = array();
  4290. $query = "SELECT ladders.name, ladders.courttypeid
  4291. FROM tblClubSiteLadders ladders
  4292. WHERE ladders.siteid = $siteid
  4293. AND ladders.enddate IS NULL";
  4294. $qid = db_query($query);
  4295. while( $ladder = db_fetch_array($qid) ){
  4296. $array[] = $ladder;
  4297. }
  4298. return $array;
  4299. }
  4300. /*****************************************************************/
  4301. /*
  4302. Retreives all site preferences
  4303. */
  4304. function getSitePreferencesForCourt($courtid) {
  4305. $query = "SELECT
  4306. sites.sitecode,
  4307. sites.siteid,
  4308. sites.allowselfcancel,
  4309. sites.clubid,
  4310. sites.daysahead,
  4311. sites.enableautologin,
  4312. sites.displaytime,
  4313. sites.allowsoloreservations,
  4314. sites.rankingadjustment,
  4315. sites.allowselfscore,
  4316. sites.enable,
  4317. sites.isliteversion,
  4318. sites.allowallsiteadvertising,
  4319. sites.allowplayerslooking,
  4320. sites.allownearrankingadvertising,
  4321. sites.enableguestreservation,
  4322. sites.displaysitenavigation,
  4323. sites.rankingscheme,
  4324. sites.displayrecentactivity,
  4325. sites.challengerange,
  4326. sites.facebookurl,
  4327. sites.reminders,
  4328. sites.displaycourttype,
  4329. clubs.clubname,
  4330. clubs.timezone,
  4331. sites.showplayernames,
  4332. sites.requirelogin
  4333. FROM tblClubSites sites, tblCourts courts, tblClubs clubs
  4334. WHERE sites.siteid = courts.siteid
  4335. AND sites.clubid = clubs.clubid
  4336. AND courts.courtid = $courtid";
  4337. $qid = db_query($query);
  4338. $array = db_fetch_array($qid);
  4339. $anyboxesquery = "SELECT tblBoxLeagues.boxid
  4340. FROM tblBoxLeagues
  4341. WHERE tblBoxLeagues.siteid=".$array['siteid'];
  4342. $anyboxesresult = db_query($anyboxesquery);
  4343. if(mysqli_num_rows($anyboxesresult)>0){
  4344. $array['boxenabled'] = 'true';
  4345. }else{
  4346. $array['boxenabled'] = 'false';
  4347. }
  4348. return $array;
  4349. }
  4350. /*****************************************************************/
  4351. /*
  4352. Retreives all site preferences
  4353. */
  4354. function getSitePreferences($siteid) {
  4355. $query = "SELECT
  4356. sites.sitecode,
  4357. sites.siteid,
  4358. sites.allowselfcancel,
  4359. sites.clubid,
  4360. sites.daysahead,
  4361. sites.enableautologin,
  4362. sites.displaytime,
  4363. sites.allowsoloreservations,
  4364. sites.rankingadjustment,
  4365. sites.allowselfscore,
  4366. sites.enable,
  4367. sites.isliteversion,
  4368. sites.allowallsiteadvertising,
  4369. sites.allowplayerslooking,
  4370. sites.allownearrankingadvertising,
  4371. sites.enableguestreservation,
  4372. sites.displaysitenavigation,
  4373. sites.displayrecentactivity,
  4374. sites.rankingscheme,
  4375. sites.challengerange,
  4376. sites.facebookurl,
  4377. sites.reminders,
  4378. sites.displaycourttype,
  4379. clubs.clubname,
  4380. clubs.timezone,
  4381. sites.showplayernames,
  4382. sites.requirelogin
  4383. FROM tblClubSites sites, tblClubs clubs
  4384. WHERE sites.siteid = '$siteid'
  4385. AND sites.clubid = clubs.clubid";
  4386. $qid = db_query($query);
  4387. $array = db_fetch_array($qid);
  4388. $anyboxesquery = "SELECT tblBoxLeagues.boxid
  4389. FROM tblBoxLeagues
  4390. WHERE tblBoxLeagues.siteid=$siteid";
  4391. $anyboxesresult = db_query($anyboxesquery);
  4392. if(mysqli_num_rows($anyboxesresult)>0){
  4393. $array['boxenabled'] = 'true';
  4394. }else{
  4395. $array['boxenabled'] = 'false';
  4396. }
  4397. // This only matters if the user is logged in.
  4398. if( is_logged_in() ){
  4399. // Get user parameters
  4400. $query = "SELECT tblPreferencesOverride.preference, tblPreferencesOverride.override FROM clubpro_main.tblParameterValue
  4401. INNER JOIN tblParameterOptions on tblParameterValue.parametervalue = tblParameterOptions.optionvalue
  4402. INNER JOIN tblPreferencesOverride ON tblParameterOptions.parameteroptionid = tblPreferencesOverride.parameteroptionid
  4403. WHERE userid = ". get_userid();
  4404. $qid = db_query($query);
  4405. while( $override = db_fetch_array($qid) ){
  4406. if( isDebugEnabled(1) ) logMessage("applicationlib.getSitePreferences: Found override: ". $override['preference']);
  4407. $array[$override['preference']] = $override['override'];
  4408. }
  4409. }
  4410. return $array;
  4411. }
  4412. /*
  4413. * Retreives all site attributes. Unlike a preference, these are derived.
  4414. *
  4415. * Others can be added
  4416. *
  4417. * Current site attributes are: COURT_SPORT
  4418. */
  4419. function getSiteAttributes($siteid){
  4420. $attributeArray = array();
  4421. $court_sport = "court_sport";
  4422. $web_ladder = "web_ladder";
  4423. /*
  4424. * If the site contains any of the supported sports:
  4425. * + Tenns (5)
  4426. * + Badmitton (3)
  4427. * + Squash (4)
  4428. * + Racquetball (6)
  4429. *
  4430. */
  4431. $sportQuery = "SELECT DISTINCT 1 from tblCourts courts, tblCourtType courttype
  4432. WHERE courts.courttypeid = courttype.courttypeid
  4433. AND courts.siteid = $siteid
  4434. AND (courttype.sportid = 5 OR courttype.sportid = 3 OR courttype.sportid = 4 OR courttype.sportid = 6)";
  4435. $$sportResult = db_query($sportQuery);
  4436. if(mysqli_num_rows($$sportResult) > 0){
  4437. array_push($attributeArray, $court_sport);
  4438. }
  4439. /*
  4440. * If the site has an assigned box league.
  4441. */
  4442. $anyboxesquery = "SELECT tblBoxLeagues.boxid
  4443. FROM tblBoxLeagues
  4444. WHERE (((tblBoxLeagues.siteid)=$siteid))";
  4445. $anyboxesresult = db_query($anyboxesquery);
  4446. if(mysqli_num_rows($anyboxesresult)>0){
  4447. array_push($attributeArray, $web_ladder);
  4448. }
  4449. return $attributeArray;
  4450. }
  4451. /**
  4452. * Simply checks the existence of the court attribute
  4453. * Store this as a session varaible
  4454. * @return boolean
  4455. */
  4456. function isSiteBoxLeageEnabled(){
  4457. return $_SESSION["siteprefs"]["boxenabled"]=='true'?true:false;
  4458. }
  4459. /**
  4460. * Gets the usertype of a reservation (1=Doubles, 0=Singles)
  4461. *
  4462. * @param unknown_type $reservationID
  4463. * @return boolean
  4464. */
  4465. function isDoublesReservation($reservationID){
  4466. $query = "SELECT reservations.usertype
  4467. FROM tblReservations reservations
  4468. WHERE reservations.reservationid = $reservationID";
  4469. $qid = db_query($query);
  4470. $usertypeArray = mysqli_fetch_array($qid);
  4471. $usertype = $usertypeArray[0];
  4472. return $usertype==1 ? true: false;
  4473. }
  4474. /**
  4475. * Adds name value pairs to an array and return how many were added.
  4476. *
  4477. * @param unknown_type $arr
  4478. * @return number
  4479. */
  4480. function array_push_associative(&$arr) {
  4481. $args = func_get_args();
  4482. $ret = 0;
  4483. foreach ($args as $arg) {
  4484. if (is_array($arg)) {
  4485. foreach ($arg as $key => $value) {
  4486. $arr[$key] = $value;
  4487. $ret++;
  4488. }
  4489. }else{
  4490. $arr[$arg] = "";
  4491. }
  4492. }
  4493. return $ret;
  4494. }
  4495. /**
  4496. * Will return true if is club administrator and is in the reservation
  4497. *
  4498. * @param unknown_type $courtid
  4499. * @param unknown_type $time
  4500. * @return boolean
  4501. */
  4502. function isCAButNotinReservation($courtid, $time){
  4503. $isCA = FALSE;
  4504. $isGuestMatch = FALSE;
  4505. $isInReservation = FALSE;
  4506. if(get_roleid()==2){
  4507. $isCA = TRUE;
  4508. }
  4509. $getCourtInfoQuery = "SELECT *
  4510. FROM tblReservations
  4511. WHERE tblReservations.courtid = '$courtid'
  4512. AND tblReservations.time = '$time'";
  4513. $getCourtInfoResults = db_query($getCourtInfoQuery);
  4514. $getCourtInfoArray = mysqli_fetch_array($getCourtInfoResults);
  4515. //Check if this is a guest reservation
  4516. if($getCourtInfoArray['guesttype']==1){
  4517. $isGuestMatch = TRUE;
  4518. }
  4519. //Check singles reservation
  4520. elseif($getCourtInfoArray['usertype']==0){
  4521. $userlookupQuery = "SELECT tblkpUserReservations.userid
  4522. FROM tblkpUserReservations
  4523. INNER JOIN tblReservations ON tblkpUserReservations.reservationid = tblReservations.reservationid
  4524. WHERE (((tblReservations.time)=$time)
  4525. AND ((tblReservations.courtid)=$courtid))";
  4526. $userlookupResult = db_query($userlookupQuery);
  4527. while($userlookupArray = mysqli_fetch_array($userlookupResult)){
  4528. if($userlookupArray['userid']==get_userid()){
  4529. $isInReservation = TRUE;
  4530. }
  4531. }
  4532. }
  4533. //Check doubles reservation with teams
  4534. elseif($getCourtInfoArray['usertype']==1){
  4535. $doublesQuery = "SELECT tblkpUserReservations.userid, tblkpUserReservations.usertype
  4536. FROM tblkpUserReservations
  4537. INNER JOIN tblReservations ON tblkpUserReservations.reservationid = tblReservations.reservationid
  4538. WHERE (((tblReservations.time)=$time)
  4539. AND ((tblReservations.courtid)=$courtid))";
  4540. $doublesResult = db_query($doublesQuery);
  4541. while($doublesArray = mysqli_fetch_array($doublesResult)){
  4542. if($doublesArray['usertype']==0){
  4543. if($doublesArray['userid']==get_userid()){
  4544. $isInReservation = TRUE;
  4545. }
  4546. }//end if
  4547. elseif($doublesArray['usertype']==1){
  4548. if(isCurrentUserOnTeam($doublesArray['userid'])==1){
  4549. $isInReservation = TRUE;
  4550. } //endif
  4551. }//end elseif
  4552. }//end while
  4553. }
  4554. if(($isCA && !$isInReservation) || ($isCA && $isGuestMatch)){
  4555. return TRUE;
  4556. }
  4557. else{
  4558. return FALSE;
  4559. }
  4560. }
  4561. /**
  4562. * This will check to see if on either a singles reservation or a doubles
  4563. * reservation the user attempting to cancel the court in doing so where
  4564. * someone is looking for a match. As a general rule we are only allowing
  4565. * members of an incomplete reservation (and desk users) to cancel the court.
  4566. *
  4567. * @param unknown_type $courtid
  4568. * @param unknown_type $time
  4569. * @return boolean
  4570. */
  4571. function isUserInPartialReservationSingles($courtid, $time){
  4572. $isOnlyUserInReservation = FALSE;
  4573. $isInReservation = FALSE;
  4574. $isOnlyOnePlayer = FALSE;
  4575. $userlookupQuery = "SELECT tblkpUserReservations.userid
  4576. FROM tblkpUserReservations
  4577. INNER JOIN tblReservations ON tblkpUserReservations.reservationid = tblReservations.reservationid
  4578. WHERE (((tblReservations.time)=$time)
  4579. AND ((tblReservations.courtid)=$courtid))";
  4580. $userlookupResult = db_query($userlookupQuery);
  4581. while($userlookupArray = mysqli_fetch_array($userlookupResult)){
  4582. if($userlookupArray['userid']==get_userid()){
  4583. $isInReservation = TRUE;
  4584. }
  4585. if($userlookupArray['userid']==0){
  4586. $isOnlyOnePlayer = TRUE;
  4587. }
  4588. }
  4589. if($isInReservation && $isOnlyOnePlayer){
  4590. $isOnlyUserInReservation = TRUE;
  4591. }
  4592. // Or if tblkpUserReservations are of different usertypes then we kn
  4593. return $isOnlyUserInReservation;
  4594. }
  4595. /**
  4596. * This will check to see if on either a singles reservation or a
  4597. * doubles reservation the user attempting to cancel the court in
  4598. * doing so where someone is looking for a match. As a general
  4599. * rule we are only allowing members of an incomplete reservation
  4600. * s(and desk users) to cancel the court.
  4601. *
  4602. * @param unknown_type $courtid
  4603. * @param unknown_type $time
  4604. * @return boolean
  4605. */
  4606. function isUserInPartialReservationDoubles($courtid, $time){
  4607. $isInReservation = FALSE;
  4608. $doesDoublesReservationNeedAPlayer = FALSE;
  4609. $isUserInPartialReservationDoubles = FALSE;
  4610. $doublesReservationLookingForTeam = FALSE;
  4611. $isOnDoublesTeam = FALSE;
  4612. $isInDoublesReservation = FALSE;
  4613. $usertype = 0;
  4614. $userlookupQuery = "SELECT tblkpUserReservations.userid, tblkpUserReservations.usertype
  4615. FROM tblkpUserReservations
  4616. INNER JOIN tblReservations ON tblkpUserReservations.reservationid = tblReservations.reservationid
  4617. WHERE (((tblReservations.time)=$time)
  4618. AND ((tblReservations.courtid)=$courtid))";
  4619. $userlookupResult = db_query($userlookupQuery);
  4620. while($reservationUser = mysqli_fetch_array($userlookupResult)){
  4621. //First check to see if current user is the one looking for a match
  4622. //if($reservationUser[usertype]==0 && $reservationUser[userid]==get_userid()){
  4623. //$isInDoublesReservation = TRUE;
  4624. //}
  4625. //Now check if the current user is in one of the teams
  4626. if($reservationUser['usertype']==1 && isCurrentUserOnTeam($reservationUser['userid'])){
  4627. $isInDoublesReservation = TRUE;
  4628. $isOnDoublesTeam = TRUE;
  4629. }
  4630. //We want to check for doubles reservations looking for a team
  4631. if($reservationUser['userid'] == 0){
  4632. $doublesReservationLookingForTeam = TRUE;
  4633. }
  4634. // print "This is the value of reservationUser[usertype] $reservationUser[usertype]";
  4635. $usertype = $usertype + $reservationUser['usertype'];
  4636. }
  4637. //For a complete doubles reservation the usertypes should add up to 2 (1+1), for a complete singles reservation
  4638. // the usertype should add up to 0 (0+0)
  4639. if($usertype == 1){
  4640. $doesDoublesReservationNeedAPlayer = TRUE;
  4641. }
  4642. //If Both are true then set $isInDoublesReservation to TRUE, then we have established that
  4643. //the current user is in the reservation somehow (either by himself or on a team) and that
  4644. //the this is a doubles reservation that
  4645. if($doesDoublesReservationNeedAPlayer && $isInDoublesReservation){
  4646. $isUserInPartialReservationDoubles = TRUE;
  4647. }
  4648. //Finally we have to check for the scenerio of someone on a team looking for anothher team. If
  4649. // this person attempts to cancel the court they too should only have the option of canceling
  4650. // (not modifying)
  4651. if($doublesReservationLookingForTeam && $isOnDoublesTeam == TRUE){
  4652. $isUserInPartialReservationDoubles = TRUE;
  4653. }
  4654. return $isUserInPartialReservationDoubles;
  4655. }
  4656. /**
  4657. * This will return the full name of a user for a given userid (first name, last name)
  4658. *
  4659. * @param int $userId
  4660. * @return String Users Name (first name, last name)
  4661. */
  4662. function getFullNameForUserId($userId){
  4663. //this may not be set
  4664. if( !isset($userId)) return;
  4665. $userResult = getFullNameResultForUserId($userId);
  4666. $userArray = mysqli_fetch_array($userResult);
  4667. $fullname = "";
  4668. //For faster results using indexes
  4669. if( mysqli_num_rows($userResult) > 0){
  4670. $fullname = "$userArray[0] $userArray[1]";
  4671. }
  4672. return $fullname;
  4673. }
  4674. /*
  4675. This will return the full name of a and espcaes ', ", and a few others. Use when putting
  4676. output in database.
  4677. */
  4678. function getFullNameForUserIdWithEscapes($userId){
  4679. $fullname = getFullNameForUserId($userId);
  4680. return addslashes($fullname);
  4681. }
  4682. /**
  4683. *
  4684. * Enter description here ...
  4685. * @param unknown_type $userId
  4686. */
  4687. function getFullNameResultForUserId($userId){
  4688. $userQuery = "SELECT tblUsers.firstname, tblUsers.lastname
  4689. FROM tblUsers
  4690. WHERE tblUsers.userid=$userId";
  4691. return db_query($userQuery);
  4692. }
  4693. /**
  4694. * Returns the the names of the players in the team specified
  4695. */
  4696. function getFullNamesForTeamId($teamId){
  4697. $teamsQuery = "SELECT teamdetails.userid
  4698. FROM tblkpTeams teamdetails
  4699. WHERE teamdetails.teamid = $teamId";
  4700. $teamResult = db_query($teamsQuery);
  4701. $playerOneArray = mysqli_fetch_array($teamResult);
  4702. $playerOne = $playerOneArray[0];
  4703. $playerTwoArray = mysqli_fetch_array($teamResult);
  4704. $playerTwo = $playerTwoArray[0];
  4705. return getFullNameForUserId($playerOne)." and ".getFullNameForUserId($playerTwo);
  4706. }
  4707. /**
  4708. * Returns the events for the site.
  4709. */
  4710. function get_site_events($siteid){
  4711. if( isDebugEnabled(1) ) logMessage("applicationlib.get_site_events: Getting events for site $siteid");
  4712. $query = "SELECT eventid, eventname
  4713. FROM tblEvents
  4714. WHERE siteid = $siteid";
  4715. return db_query($query);
  4716. }
  4717. /**
  4718. * Simply determins if the time past occured before the current time
  4719. */
  4720. function isInPast($time){
  4721. $clubquery = "SELECT timezone from tblClubs WHERE clubid='".get_clubid()."'";
  4722. $clubresult = db_query($clubquery);
  4723. $clubobj = db_fetch_array($clubresult);
  4724. $tzdelta = $clubobj[timezone]*3600;
  4725. $curtime = mktime()+$tzdelta;
  4726. if($time<$curtime){
  4727. return true;
  4728. }
  4729. else{
  4730. return false;
  4731. }
  4732. }
  4733. /**
  4734. * Logs Stuff
  4735. *
  4736. * TODO: addin a light-logrotate class
  4737. *
  4738. * @param String $message
  4739. */
  4740. function logMessage($message){
  4741. date_default_timezone_set('GMT');
  4742. if( !isset($_SESSION["CFG"]["logFile"])){
  4743. die("This thing isn't configured right, try specifing a log file in application.lib");
  4744. }
  4745. $fp = fopen ($_SESSION["CFG"]["logFile"], "a+");
  4746. fwrite($fp,date("r",mktime()).": ".$message."\n");
  4747. fclose($fp);
  4748. }
  4749. /**
  4750. * Set in the application.php
  4751. */
  4752. function isDebugEnabled($level){
  4753. global $APP_DEBUG;
  4754. if( isset($APP_DEBUG) && $APP_DEBUG <=$level){
  4755. return true;
  4756. }
  4757. else{
  4758. return false;
  4759. }
  4760. }
  4761. /**
  4762. * For sendout out debug mails
  4763. */
  4764. function isMailDebugEnabled($level){
  4765. global $MAIL_DEBUG;
  4766. if( isset($MAIL_DEBUG) && $MAIL_DEBUG <=$level){
  4767. return true;
  4768. }
  4769. else{
  4770. return false;
  4771. }
  4772. }
  4773. /**
  4774. * Will display either today, a day ago, three days, four days,
  4775. * five days, six days, a week, more than a week ago
  4776. */
  4777. function determineLastLoginText($theTimeTheyLastLoggedIn, $clubid){
  4778. $clubquery = "SELECT timezone from tblClubs WHERE clubid=$clubid";
  4779. $clubresult = db_query($clubquery);
  4780. $timezonevalArray = mysqli_fetch_array($clubresult);
  4781. $timezoneval = $timezonevalArray[0];
  4782. $tzdelta = $timezoneval*3600;
  4783. $theTimeItIsRightNow = mktime()+$tzdelta;
  4784. $timeSinceLastLogin = $theTimeItIsRightNow - $theTimeTheyLastLoggedIn;
  4785. if( $timeSinceLastLogin < 86400 ){
  4786. $timeSinceLastLoginString = "Within the last day";
  4787. }
  4788. elseif($timeSinceLastLogin < (86400 * 2) ){
  4789. $timeSinceLastLoginString = "Two days ago";
  4790. }
  4791. elseif( $timeSinceLastLogin < (86400 * 3) ){
  4792. $timeSinceLastLoginString = "Three days ago";
  4793. }
  4794. elseif( $timeSinceLastLogin < (86400 * 4) ){
  4795. $timeSinceLastLoginString = "Four days ago";
  4796. }
  4797. elseif( $timeSinceLastLogin < (86400 * 5) ){
  4798. $timeSinceLastLoginString = "Five days ago";
  4799. }
  4800. elseif( $timeSinceLastLogin < (86400 * 6 ) ){
  4801. $timeSinceLastLoginString = "Six days ago";
  4802. }
  4803. else{
  4804. $timeSinceLastLoginString = "More than a week ago";
  4805. }
  4806. return $timeSinceLastLoginString;
  4807. }
  4808. /**
  4809. * A simple Twitter status display script.
  4810. * Useful as a status badge for JavaScript non-compliant browsers, where the
  4811. * insertion of the status message must be performed on the server.
  4812. *
  4813. * Example: echo(getTwitterStatus(637073, "\\0"));
  4814. *
  4815. * @author Manas Tungare, manas@tungare.name
  4816. * @version 1.0
  4817. * @copyright Manas Tungare, 2007.
  4818. * @license Creative Commons Attribution ShareAlike 3.0.
  4819. */
  4820. /**
  4821. * Retrieves Twitter status from the Twitter server, parses it, and
  4822. * linkifies any URLs present.
  4823. *
  4824. * This code is a textbook example of optimizing at the cost of maintainability
  4825. * and reliability. It is utterly susceptible to changes in the XML format
  4826. * (that would otherwise be nicely handled by an XML parser.) But XML itself is
  4827. * an insanely heavy markup format, and this code neatly teases out the
  4828. * interesting bits while ignoring the rest. It was written for performance,
  4829. * not elegance. (Though, some would argue about elegance through sheer
  4830. * simplicity, but I digress.) :-)
  4831. *
  4832. * @return string Current status message of given user.
  4833. * @param userNumber Your user number; not to be confused with your user id.
  4834. * @param linkText Configurable anchor text for linkified URLs
  4835. * "\\0" : if you want the entire URL to show up.
  4836. * "\\1" : to show only the domain name (slashdot-style).
  4837. * "blah" : Anything else inserts that text verbatim.
  4838. */
  4839. function getTwitterStatus($userNumber, $linkText) {
  4840. $url = "http://twitter.com/statuses/user_timeline/" . $userNumber .
  4841. ".xml?count=$count";
  4842. $feed = "";
  4843. // Fetch feed, read it all into a string.
  4844. // TODO(manas) Cache me if you can.
  4845. $file = fopen($url, "r");
  4846. if (!is_resource($file)) {
  4847. return ("Unable to connect to Twitter!");
  4848. }
  4849. while (!feof($file)) {
  4850. $feed .= fgets($file, 4096);
  4851. }
  4852. fclose ($file);
  4853. // Parse, obtain created_at time, format it nicely.
  4854. $created_at = array();
  4855. preg_match("/<created_at>(.*?)<\/created_at>/", $feed, $created_at);
  4856. $relative_time = niceTime(strtotime(str_replace("+0000", "",
  4857. $created_at[1])));
  4858. // Parse it to extract the <text> element.
  4859. $text = array();
  4860. preg_match("/<text>(.*?)<\/text>/", $feed, $text);
  4861. $status = preg_replace("/http:\/\/(.*?)\/[^ ]*/",
  4862. '<a href="\\0">'.$linkText.'</a>', $text[1]);
  4863. // Linkify URLs
  4864. //return $status . " &mdash; " . $relative_time;
  4865. return $status ;
  4866. }
  4867. /**
  4868. * Formats a timestamp nicely with an adaptive "x units of time ago" message.
  4869. * Based on the original Twitter JavaScript badge. Only handles past dates.
  4870. * @return string Nicely-formatted message for the timestamp.
  4871. * @param $time Output of strtotime() on your choice of timestamp.
  4872. */
  4873. function niceTime($time) {
  4874. $delta = time() - $time;
  4875. if ($delta < 60) {
  4876. return 'less than a minute ago.';
  4877. } else if ($delta < 120) {
  4878. return 'about a minute ago.';
  4879. } else if ($delta < (45 * 60)) {
  4880. return floor($delta / 60) . ' minutes ago.';
  4881. } else if ($delta < (90 * 60)) {
  4882. return 'about an hour ago.';
  4883. } else if ($delta < (24 * 60 * 60)) {
  4884. return 'about ' . floor($delta / 3600) . ' hours ago.';
  4885. } else if ($delta < (48 * 60 * 60)) {
  4886. return '1 day ago.';
  4887. } else {
  4888. return floor($delta / 86400) . ' days ago.';
  4889. }
  4890. }
  4891. /**
  4892. * Goes out to the database and gets the footer message
  4893. */
  4894. function getFooterMessage(){
  4895. $footerMessageQuery = "SELECT text from tblFooterMessage WHERE enddate is NULL";
  4896. $footMessageResult = db_query($footerMessageQuery);
  4897. if( mysqli_num_rows($footMessageResult) > 0){
  4898. $footer_obj = mysqli_fetch_object($footMessageResult);
  4899. return $footer_obj->text;
  4900. }
  4901. else{
  4902. return;
  4903. }
  4904. }
  4905. /**
  4906. *
  4907. * @param $siteId
  4908. */
  4909. function getRecentSiteActivity($siteid){
  4910. $query = "SELECT activity.description, activity.activitydate
  4911. FROM tblSiteActivity activity
  4912. WHERE siteid = $siteid AND enddate is NULL
  4913. ORDER BY activity.activitydate DESC LIMIT 3";
  4914. return db_query($query);
  4915. }
  4916. /**
  4917. * Gets recent activity older than a $startDate
  4918. *
  4919. * @param $siteId
  4920. */
  4921. function getRecentSiteActivityBlock($siteid,$startDate){
  4922. $query = "SELECT activity.description,activity.activitydate from tblSiteActivity activity
  4923. WHERE siteid = $siteid AND enddate is NULL
  4924. AND activity.activitydate < '$startDate'
  4925. ORDER BY activity.activitydate DESC LIMIT 3";
  4926. return db_query($query);
  4927. }
  4928. /**
  4929. * Gets the Club news
  4930. * @param $siteid
  4931. */
  4932. function getClubNews($siteid){
  4933. $query = "SELECT message FROM tblMessages messages
  4934. WHERE siteid = $siteid AND enable = 1 AND messagetypeid = 2
  4935. ORDER BY messages.lastmodified DESC LIMIT 3";
  4936. return db_query($query);
  4937. }
  4938. function getClubEvents($clubid){
  4939. $query = "SELECT events.id, events.name, events.eventdate, events.description
  4940. FROM tblClubEvents events
  4941. WHERE clubid = $clubid
  4942. AND enddate is NULL
  4943. ORDER BY events.eventdate LIMIT 6";
  4944. return db_query($query);
  4945. }
  4946. /**
  4947. * Gets the recent challenges matches
  4948. * @param $siteid
  4949. */
  4950. function getMatchesByType($siteid, $matchtype, $limit){
  4951. if( isDebugEnabled(1) ) logMessage("applicationlib.getMatchesByType: Getting challenge matches $siteid");
  4952. $curresidquery = "SELECT reservations.reservationid, reservations.time, courts.courtname
  4953. FROM tblReservations reservations,tblCourts courts
  4954. WHERE reservations.matchtype = $matchtype
  4955. AND reservations.usertype=0
  4956. AND reservations.enddate IS NULL
  4957. AND courts.courtid = reservations.courtid
  4958. AND courts.siteid = $siteid
  4959. ORDER BY reservations.time DESC LIMIT $limit";
  4960. //print $curresidquery;
  4961. return db_query($curresidquery);
  4962. }
  4963. /**
  4964. *
  4965. * @param unknown_type $clubeventid
  4966. */
  4967. function getClubEventParticipants($clubeventid, $division){
  4968. $query = "SELECT users.userid, users.firstname, users.lastname, partner.userid as 'partnerid', partner.firstname as 'partner firstname', partner.lastname as 'partner lastname', participant.division
  4969. FROM tblClubEventParticipants participant
  4970. INNER JOIN tblUsers users
  4971. ON participant.userid = users.userid
  4972. LEFT JOIN tblUsers partner
  4973. ON participant.partnerid = partner.userid
  4974. AND participant.partnerid IS NOT NULL
  4975. WHERE participant.clubeventid = $clubeventid
  4976. AND participant.enddate is NULL
  4977. ORDER BY case when participant.division = '' or participant.division is null then 1 else 0 end, participant.division, users.lastname;";
  4978. return db_query($query);
  4979. }
  4980. /**
  4981. *
  4982. * @param $siteid
  4983. */
  4984. function logSiteActivity($siteid, $description){
  4985. $description = addslashes($description);
  4986. $query = "INSERT INTO tblSiteActivity (
  4987. activitydate, siteid, description
  4988. ) VALUES (
  4989. now(),
  4990. '$siteid',
  4991. '$description'
  4992. )";
  4993. db_query($query);
  4994. }
  4995. /**
  4996. *
  4997. * @param $dateString
  4998. * The string is in this format yyyy-dd-mm
  4999. */
  5000. function formatDateString($dateString){
  5001. date_default_timezone_set('GMT');
  5002. $dates = explode("-",$dateString);
  5003. $day = $dates[2];
  5004. $month = $dates[1];
  5005. $year = $dates[0];
  5006. $time = mktime(0,0,0,$month,$day,$year);
  5007. return date("l F j", $time);
  5008. }
  5009. /**
  5010. *
  5011. * @param $dateString
  5012. * The string is in this format yyyy-dd-mm
  5013. */
  5014. function formatDateStringSimple($dateString){
  5015. date_default_timezone_set('GMT');
  5016. $dates = explode("-",$dateString);
  5017. $day = $dates[2];
  5018. $month = $dates[1];
  5019. $year = $dates[0];
  5020. $time = mktime(0,0,0,$month,$day,$year);
  5021. return date("n/j/Y", $time);
  5022. }
  5023. /**
  5024. *
  5025. * @param $dateString
  5026. */
  5027. function convertToDateSlashes($dateString){
  5028. if( empty($dateString)){
  5029. return;
  5030. }
  5031. $pos = strpos($dateString, '-');
  5032. if ($pos !== false) {
  5033. $dates = explode("-",$dateString);
  5034. $month = $dates[1];
  5035. $day = $dates[2];
  5036. $year = $dates[0];
  5037. logMessage("applicationlib.convertToDateSlashes: $month/$day/$year");
  5038. return "$month/$day/$year";
  5039. }
  5040. return $dateString;
  5041. }
  5042. /**
  5043. * Get either a Gravatar URL or complete image tag for a specified email address.
  5044. *
  5045. * @param string $email The email address
  5046. * @param string $s Size in pixels, defaults to 80px [ 1 - 512 ]
  5047. * @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
  5048. * @param string $r Maximum rating (inclusive) [ g | pg | r | x ]
  5049. * @param boole $img True to return a complete IMG tag False for just the URL
  5050. * @param array $atts Optional, additional key/value attributes to include in the IMG tag
  5051. * @return String containing either just a URL or a complete image tag
  5052. * @source http://gravatar.com/site/implement/images/php/
  5053. */
  5054. function get_gravatar( $email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array() ) {
  5055. $url = 'https://www.gravatar.com/avatar/';
  5056. $url .= md5( strtolower( trim( $email ) ) );
  5057. $url .= "?s=$s&d=$d&r=$r";
  5058. if ( $img ) {
  5059. $url = '<img src="' . $url . '"';
  5060. foreach ( $atts as $key => $val )
  5061. $url .= ' ' . $key . '="' . $val . '"';
  5062. $url .= ' />';
  5063. }
  5064. return $url;
  5065. }
  5066. $bad = array(
  5067. "trounced",
  5068. "crushed",
  5069. "clobbered",
  5070. "slaughtered",
  5071. "demolished",
  5072. "skunked",
  5073. "humbled",
  5074. "destroyed",
  5075. "wrecked",
  5076. "made mincemeat of",
  5077. "wiped the floor with",
  5078. "pasted",
  5079. "walloped",
  5080. "ran the table against",
  5081. "blitzed",
  5082. "trashed",
  5083. "walked all over",
  5084. "tyrannized",
  5085. "had their way with",
  5086. "sped past");
  5087. $not_bad = array(
  5088. "conquered",
  5089. "triumphed over",
  5090. "confounded",
  5091. "vanquished",
  5092. "overwhelmed",
  5093. "baffled",
  5094. "subdued",
  5095. "derailed",
  5096. "scuttled",
  5097. "stymied",
  5098. "overpowered",
  5099. "foiled",
  5100. "outplayed",
  5101. "frustrated",
  5102. "subjugated",
  5103. "thwarted",
  5104. "stumped",
  5105. "reigned supreme over",
  5106. "eclipsed",
  5107. "held the upper hand with",
  5108. "handled",
  5109. "glided by"
  5110. );
  5111. $close = array(
  5112. "beat",
  5113. "got by",
  5114. "edged",
  5115. "stole by",
  5116. "surmounted",
  5117. "disappointed",
  5118. "narrowly defeated",
  5119. "barely beat",
  5120. "slipped past",
  5121. "held on to beat",
  5122. "inched by",
  5123. "snuck by",
  5124. "overcame",
  5125. "weaseled past",
  5126. "prevailed over",
  5127. "nosed by",
  5128. "shuffled past",
  5129. "crept by",
  5130. "eked out a victory over",
  5131. "squeezed past",
  5132. "battled past"
  5133. );
  5134. ?>