Advertisement
Guest User

Untitled

a guest
Jan 21st, 2017
337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 27.25 KB | None | 0 0
  1. <?php
  2. require_once("Rest.inc.php");
  3.  
  4. class API extends REST {
  5.  
  6. public $data = "";
  7. const demo_version = false;
  8.  
  9. const DB_SERVER = "localhost";
  10. const DB_USER = "viktkob-smm";
  11. const DB_PASSWORD = "WPYf7605B";
  12. const DB = "viktkob-smm_bonus2";
  13. const GOOGLE_API_KEY = "AIzaSyB1i6vJQrLvt2d7KcRsT-KeIWpF_ZGo-mY";
  14.  
  15. private $db = NULL;
  16. private $mysqli = NULL;
  17. public function __construct(){
  18. parent::__construct(); // Init parent contructor
  19. $this->dbConnect(); // Initiate Database connection
  20. }
  21.  
  22. /* Connect to Database */
  23. private function dbConnect(){
  24. $this->mysqli = new mysqli(self::DB_SERVER, self::DB_USER, self::DB_PASSWORD, self::DB);
  25. }
  26.  
  27. /* Dynmically call the method based on the query string */
  28. public function processApi(){
  29. $func = strtolower(trim(str_replace("/","",$_REQUEST['x'])));
  30. if((int)method_exists($this,$func) > 0) {
  31. $this->$func();
  32. } else {
  33. $this->response('processApi - method not exist',404); // If the method not exist with in this class "Page not found".
  34. }
  35. }
  36.  
  37. /* Api Checker */
  38. private function checkResponse(){
  39. if (mysqli_ping($this->mysqli)){
  40. echo "Database Connection : Success";
  41. }else {
  42. echo "Database Connection : Error";
  43. }
  44. }
  45.  
  46. // security for filter manipulate data
  47. private function checkAuthorization(){
  48. $resp = array("status" => 'Failed', "msg" => 'Unauthorized' );
  49. if(isset($this->_header['Token']) && !empty($this->_header['Token'])){
  50. $token = $this->_header['Token'];
  51. $query = "SELECT id FROM users WHERE password='$token' ";
  52. $r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
  53. if($r->num_rows < 1) {
  54. $this->response($this->json($resp), 200);
  55. }
  56. } else {
  57. $this->response($this->json($resp), 200);
  58. }
  59. }
  60.  
  61. /*
  62. * API USED BY ANDROID CLIENT -------------------------------------------------------------------------------------------------------
  63. */
  64.  
  65. //use start android LAZY_LOAD = false
  66. private function getApiClientData(){
  67. if($this->get_request_method() != "GET") $this->response('',406);
  68.  
  69. $query_p = "SELECT * FROM place p ORDER BY p.last_update DESC;";
  70. $query_pc = "SELECT * FROM place_category;";
  71. $query_i = "SELECT DISTINCT * FROM images;";
  72. $p = $this->mysqli->query($query_p) or die($this->mysqli->error.__LINE__);
  73. $pc = $this->mysqli->query($query_pc) or die($this->mysqli->error.__LINE__);
  74. $i = $this->mysqli->query($query_i) or die($this->mysqli->error.__LINE__);
  75. $result["places"] = array();
  76. $result["place_category"] = array();
  77. $result["images"] = array();
  78. while($row = $p->fetch_assoc()){
  79. $result["places"][] = $row;
  80. }
  81. while($row = $pc->fetch_assoc()){
  82. $result["place_category"][] = $row;
  83. }
  84. while($row = $i->fetch_assoc()){
  85. $result["images"][] = $row;
  86. }
  87. $this->response($this->json($result), 200); // send user details
  88. }
  89.  
  90. // use start version 3.0 for android LAZY_LOAD = true
  91. // deprecated on version 5.0
  92. private function getApiClientDataDraft(){
  93. if($this->get_request_method() != "GET") $this->response('',406);
  94. $query_p = "SELECT p.place_id, p.name, p.image, p.lat, p.lng, p.last_update FROM place p ORDER BY p.last_update DESC";
  95. $query_pc = "SELECT * FROM place_category;";
  96. $query_i = "SELECT DISTINCT * FROM images;";
  97. $p = $this->mysqli->query($query_p) or die($this->mysqli->error.__LINE__);
  98. $pc = $this->mysqli->query($query_pc) or die($this->mysqli->error.__LINE__);
  99. $i = $this->mysqli->query($query_i) or die($this->mysqli->error.__LINE__);
  100. $result["places"] = array();
  101. $result["place_category"] = array();
  102. $result["images"] = array();
  103. while($row = $p->fetch_assoc()){
  104. $result["places"][] = $row;
  105. }
  106. while($row = $pc->fetch_assoc()){
  107. $result["place_category"][] = $row;
  108. }
  109. while($row = $i->fetch_assoc()){
  110. $result["images"][] = $row;
  111. }
  112. $this->response($this->json($result), 200); // send user details
  113. }
  114.  
  115. // use start version 5.0
  116. private function listPlaces(){
  117. if($this->get_request_method() != "GET") $this->response('',406);
  118. $limit = isset($this->_request['count']) ? ((int)$this->_request['count']) : 10;
  119. $page = isset($this->_request['page']) ? ((int)$this->_request['page']) : 1;
  120. $draft = isset($this->_request['draft']) ? ((int)$this->_request['draft']) : 0;
  121.  
  122. $offset = ($page * $limit) - $limit;
  123. $count_total = $this->get_count_result("SELECT COUNT(DISTINCT p.place_id) FROM place p");
  124. $query = "SELECT DISTINCT p.place_id, p.name, p.image, p.address, p.phone, p.website, p.description, p.lat, p.lng, p.last_update
  125. FROM place p ORDER BY p.last_update DESC LIMIT $limit OFFSET $offset";
  126. if($draft == 1){
  127. $query = "SELECT DISTINCT p.place_id, p.name, p.image, p.lat, p.lng, p.last_update
  128. FROM place p ORDER BY p.last_update DESC LIMIT $limit OFFSET $offset";
  129. }
  130.  
  131. $places = $this->get_list_result($query);
  132. $object_res = array();
  133. foreach ($places as $r){
  134. $r["categories"] = $this->getCategoriesArrayByPlaceId($r["place_id"]);
  135. if($draft != 1) $r["images"] = $this->getImagesArrayByPlaceId($r["place_id"]);
  136. array_push($object_res, $r);
  137. }
  138. $count = count($places);
  139. $respon = array(
  140. 'status' => 'success', 'count' => $count, 'count_total' => $count_total, 'pages' => $page, 'places' => $object_res
  141. );
  142. $this->response($this->json($respon), 200);
  143. }
  144.  
  145. // use start version 5.0
  146. private function getPlaceDetails(){
  147. if($this->get_request_method() != "GET") $this->response('',406);
  148. if(!isset($this->_request['place_id'])) $this->responseInvalidParam();
  149. $place_id = (int)$this->_request['place_id'];
  150.  
  151. $query = "SELECT * FROM place p WHERE p.place_id=$place_id";
  152. $place = $this->get_result($query);
  153. $place["categories"] = $this->getCategoriesArrayByPlaceId($place["place_id"]);
  154. $place["images"] = $this->getImagesArrayByPlaceId($place["place_id"]);
  155. $respon = array( 'place' => $place );
  156.  
  157. $this->response($this->json($respon), 200);
  158. }
  159.  
  160. /*
  161. * TABLE USERS TRANSACTION --------------------------------------------------------------------------------------------------------------
  162. */
  163. private function login(){
  164. if($this->get_request_method() != "POST") $this->response('',406);
  165.  
  166. $customer = json_decode(file_get_contents("php://input"),true);
  167. $username = $customer["username"];
  168. $password = $customer["password"];
  169. if(!empty($username) and !empty($password)){ // empty checker
  170. $query="SELECT id, name, username, email, password FROM users WHERE password = '".md5($password)."' AND username = '$username' LIMIT 1";
  171. $r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
  172. if($r->num_rows > 0) {
  173. $result = $r->fetch_assoc();
  174. $this->response($this->json($result), 200);
  175. }
  176. $this->response('', 204); // If no records "No Content" status
  177. }
  178. $error = array('status' => "Failed", "msg" => "Invalid Email address or Password");
  179. $this->response($this->json($error), 400);
  180. }
  181.  
  182. private function users(){
  183. if($this->get_request_method() != "GET") $this->response('',406);
  184.  
  185. $id = (int)$this->_request['id'];
  186. $query="SELECT id, name, username, email FROM users WHERE id=$id";
  187. $this->get_one($query);
  188. }
  189.  
  190. private function updateUsers(){
  191. if($this->get_request_method() != "POST") $this->response('',406);
  192.  
  193. if(self::demo_version){
  194. $m = array('status' => "failed", "msg" => "Ops, this is demo version", "data" => null);
  195. $this->response($this->json($m),200);
  196. }
  197.  
  198. $this->checkAuthorization();
  199. $users = json_decode(file_get_contents("php://input"),true);
  200. if(!isset($users['id'])) $this->responseInvalidParam();
  201.  
  202. $id = (int)$users['id'];
  203. $password = $users['users']['password'];
  204. if($password == '*****'){
  205. $column_names = array('id', 'name', 'username', 'email');
  206. }else{
  207. $users['users']['password'] = md5($password);
  208. $column_names = array('id', 'name', 'username', 'email', 'password');
  209. }
  210. $table_name = 'users';
  211. $pk = 'id';
  212. $this->post_update($id, $users, $pk, $column_names, $table_name);
  213. }
  214.  
  215. private function insertUser(){
  216. if($this->get_request_method() != "POST") $this->response('',406);
  217.  
  218. if(self::demo_version){
  219. $m = array('status' => "failed", "msg" => "Ops, this is demo version", "data" => null);
  220. $this->response($this->json($m),200);
  221. }
  222. $this->checkAuthorization();
  223. $users = json_decode(file_get_contents("php://input"),true);
  224.  
  225. $users['password'] = md5($users['password']);
  226. $column_names = array('name', 'username', 'email', 'password');
  227. $table_name = 'users';
  228. $pk = 'id';
  229. $this->post_one($users, $pk, $column_names, $table_name);
  230. }
  231.  
  232. /*
  233. * TABLE PLACES TRANSACTION ---------------------------------------------------------------------------------------------------------
  234. */
  235. private function getPlaces(){
  236. if($this->get_request_method() != "GET") $this->response('',406);
  237. $param = "";
  238. if(isset($this->_request['cat_id'])) $param = $this->_request['cat_id'];
  239. if($param != ""){
  240. $cat_id = (int)$param;
  241. $query = "SELECT DISTINCT p.* FROM place p, place_category pc WHERE pc.place_id=p.place_id AND pc.cat_id=$cat_id ORDER BY p.last_update DESC;";
  242. }else{
  243. $query = "SELECT * FROM place p ORDER BY p.last_update DESC";
  244. }
  245. $this->get_list($query);
  246. }
  247.  
  248. private function getPlace(){
  249. if($this->get_request_method() != "GET") $this->response('',406);
  250. $place_id = (int)$this->_request['place_id'];
  251. $query="SELECT * FROM place p WHERE p.place_id=$place_id";
  252. $this->get_one($query);
  253. }
  254.  
  255. private function insertPlace(){
  256. if($this->get_request_method() != "POST") $this->response('',406);
  257.  
  258. $this->checkAuthorization();
  259. $place = json_decode(file_get_contents("php://input"),true);
  260. if(!isset($place) ) $this->responseInvalidParam();
  261.  
  262. $column_names = array('name', 'image', 'address', 'phone','website','description','lat','lng','last_update');
  263. $table_name = 'place';
  264. $pk = 'place_id';
  265. $this->post_one($place, $pk, $column_names, $table_name);
  266. }
  267.  
  268. private function updatePlace(){
  269. if($this->get_request_method() != "POST") $this->response('',406);
  270.  
  271. $this->checkAuthorization();
  272. $place = json_decode(file_get_contents("php://input"),true);
  273. if(!isset($place['place_id']))$this->responseInvalidParam();
  274.  
  275. $place_id = (int)$place['place_id'];
  276. $column_names = array('name', 'image', 'address', 'phone','website','description','lat','lng','last_update');
  277. $table_name = 'place';
  278. $pk = 'place_id';
  279. $this->post_update($place_id, $place, $pk, $column_names, $table_name);
  280. }
  281.  
  282. private function deletePlace(){
  283. if($this->get_request_method() != "DELETE") $this->response('',406);
  284.  
  285. $this->checkAuthorization();
  286. if(!isset($this->_request['place_id'])) $this->responseInvalidParam();
  287.  
  288. $place_id = (int)$this->_request['place_id'];
  289. $table_name = 'place';
  290. $pk = 'place_id';
  291. $this->delete_one($place_id, $pk, $table_name);
  292. }
  293.  
  294. private function getPlaceCount(){
  295. if($this->get_request_method() != "GET") $this->response('',406);
  296.  
  297. $param = "";
  298. if(isset($this->_request['cat_id'])){
  299. $param = $this->_request['cat_id'];
  300. }
  301. if($param != ""){
  302. $cat_id = (int)$param;
  303. $query = "SELECT COUNT(DISTINCT p.place_id) FROM place p, category c WHERE p.place_id IN
  304. (SELECT pc.place_id FROM place_category pc WHERE pc.cat_id=$cat_id)";
  305. }else{
  306. $query="SELECT COUNT(p.place_id) FROM place p";
  307. }
  308. $this->get_count($query);
  309. }
  310.  
  311. private function getPlacesByPage(){
  312. if($this->get_request_method() != "GET") $this->response('',406);
  313.  
  314. $limit = (int)$this->_request['limit'];
  315. $offset = ((int)$this->_request['page']) - 1;
  316.  
  317. $param = "";
  318. if(isset($this->_request['cat_id'])){
  319. $param = $this->_request['cat_id'];
  320. }
  321. if($param != ""){
  322. $cat_id = (int)$param;
  323. $query = "SELECT DISTINCT p.* FROM place p, category c WHERE p.place_id IN
  324. (SELECT pc.place_id FROM place_category pc WHERE pc.cat_id=$cat_id)
  325. ORDER BY p.last_update DESC LIMIT $limit OFFSET $offset";
  326. }else{
  327. $query="SELECT DISTINCT * FROM place p ORDER BY p.last_update DESC LIMIT $limit OFFSET $offset";
  328. }
  329.  
  330. $this->get_list($query);
  331. }
  332.  
  333. /*
  334. * TABLE CATEGORY TRANSACTION ----------------------------------------------------------------------------------------------------------
  335. */
  336. private function getCategories(){
  337. if($this->get_request_method() != "GET") $this->response('',406);
  338.  
  339. $query="SELECT * FROM category c ORDER BY c.cat_id ASC";
  340. $this->get_list($query);
  341. }
  342.  
  343. private function getCategory(){
  344. if($this->get_request_method() != "GET") $this->response('',406);
  345.  
  346. $cat_id = (int)$this->_request['cat_id'];
  347. $query="SELECT distinct * FROM category c WHERE c.cat_id=$cat_id";
  348. $this->get_one($query);
  349. }
  350.  
  351. private function getCategoriesByPlaceId(){
  352. if($this->get_request_method() != "GET") $this->response('',406);
  353.  
  354. $place_id = (int)$this->_request['place_id'];
  355. $query = "SELECT DISTINCT c.* FROM category c WHERE c.cat_id IN (SELECT pc.cat_id FROM place_category pc WHERE pc.place_id=$place_id);";
  356. $this->get_list($query);
  357. }
  358.  
  359. /*
  360. * TABLE PLACE_CATEGORY TRANSACTION ----------------------------------------------------------------------------------------------------------
  361. */
  362. private function getPlaceCategories(){
  363. if($this->get_request_method() != "GET") $this->response('',406);
  364.  
  365. $query="SELECT * FROM place_category;";
  366. $this->get_list($query);
  367. }
  368.  
  369. private function placeCategoriesByPlaceId(){
  370. if($this->get_request_method() != "GET") $this->response('',406);
  371.  
  372. $place_id = (int)$this->_request['place_id'];
  373. $query="SELECT * FROM place_category WHERE place_id=".$place_id;
  374. $this->get_list($query);
  375. }
  376.  
  377. private function insertPlaceCategories(){
  378. if($this->get_request_method() != "POST") $this->response('',406);
  379.  
  380. $this->checkAuthorization();
  381. $place_category = json_decode(file_get_contents("php://input"),true);
  382. if(!isset($place_category))$this->responseInvalidParam();
  383.  
  384. $column_names = array('place_id', 'cat_id');
  385. $table_name = 'place_category';
  386. try {
  387. $query="DELETE FROM ".$table_name." WHERE place_id = ".$place_category[0]['place_id'];
  388. $this->mysqli->query($query);
  389. } catch(Exception $e) {}
  390. $this->post_array($place_category, $column_names, $table_name);
  391. }
  392.  
  393. private function getCategoriesArrayByPlaceId($place_id){
  394. $query = "SELECT DISTINCT pc.cat_id, c.name FROM place_category pc, category c WHERE c.cat_id = pc.cat_id AND pc.place_id=".$place_id;
  395. return $this->get_list_result($query);
  396. }
  397.  
  398. /*
  399. * TABLE IMAGES TRANSACTION ----------------------------------------------------------------------------------------------------------
  400. */
  401. private function getImages(){
  402. if($this->get_request_method() != "GET") $this->response('',406);
  403.  
  404. $query="SELECT DISTINCT * FROM images;";
  405. $this->get_list($query);
  406. }
  407.  
  408. private function imagesByPlaceId(){
  409. if($this->get_request_method() != "GET") $this->response('',406);
  410.  
  411. $place_id = (int)$this->_request['place_id'];
  412. $query="SELECT DISTINCT * FROM images i WHERE i.place_id=$place_id";
  413. $this->get_list($query);
  414. }
  415.  
  416. private function insertImages(){
  417. if($this->get_request_method() != "POST") $this->response('',406);
  418.  
  419. $this->checkAuthorization();
  420. $images = json_decode(file_get_contents("php://input"),true);
  421. if(!isset($images))$this->responseInvalidParam();
  422.  
  423. $column_names = array('place_id', 'name');
  424. $table_name = 'images';
  425. try {
  426. $query="DELETE FROM ".$table_name." WHERE place_id = ".$images[0]['place_id'];
  427. $this->mysqli->query($query);
  428. } catch(Exception $e) {}
  429. $this->post_array($images, $column_names, $table_name);
  430. }
  431.  
  432. private function deleteImage(){
  433. if($this->get_request_method() != "DELETE") $this->response('',406);
  434.  
  435. $this->checkAuthorization();
  436. $_name = $this->_request['name'];
  437. $table_name = 'images';
  438. $pk = 'name';
  439. $target_file = "../../uploads/place/" . $_name;
  440. if(file_exists($target_file)){
  441. unlink($target_file);
  442. }
  443. $this->delete_one_str($_name, $pk, $table_name);
  444. }
  445.  
  446. private function getImagesArrayByPlaceId($place_id){
  447. $query = "SELECT DISTINCT i.place_id, i.name FROM images i WHERE i.place_id=".$place_id;
  448. return $this->get_list_result($query);
  449. }
  450.  
  451. /*
  452. * TABLE GCM TRANSACTION ------------------------------------------------------------------------------------------------------
  453. */
  454. private function gcms(){
  455. if($this->get_request_method() != "GET") $this->response('',406);
  456. $query="SELECT DISTINCT g.id, g.device, g.email, g.version, g.regid, g.date_create FROM gcm g ORDER BY g.id DESC";
  457. $this->get_list($query);
  458. }
  459.  
  460. private function allGcmId(){
  461. if($this->get_request_method() != "GET") $this->response('',406);
  462. $query="SELECT DISTINCT g.regid FROM gcm g";
  463. $this->get_list($query);
  464. }
  465.  
  466. private function getGcmCount(){
  467. if($this->get_request_method() != "GET") $this->response('',406);
  468. $query="SELECT COUNT(DISTINCT g.regid) FROM gcm g ORDER BY g.id DESC";
  469. $this->get_count($query);
  470. }
  471.  
  472. private function getGcmByPage(){
  473. if($this->get_request_method() != "GET") $this->response('',406);
  474. $limit = (int)$this->_request['limit'];
  475. $offset = ((int)$this->_request['page']) - 1;
  476. $query="SELECT DISTINCT * FROM gcm g ORDER BY g.id DESC LIMIT $limit OFFSET $offset";
  477. $this->get_list($query);
  478. }
  479.  
  480. private function insertGcm(){
  481. if($this->get_request_method() != "POST") $this->response('',406);
  482.  
  483. $gcm = json_decode(file_get_contents("php://input"),true);
  484. $device = $gcm['device'];
  485. $email = $gcm['email'];
  486. $regid = $gcm['regid'];
  487.  
  488. $column_names = array('device', 'email', 'version', 'regid', 'date_create');
  489. $table_name = 'gcm';
  490. $pk = 'id';
  491. $query="SELECT DISTINCT g.id FROM gcm g WHERE g.regid='$regid' OR ( g.device='$device' AND g.email='$email' )";
  492. $r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
  493. if($r->num_rows > 0){ // update
  494. $result = $r->fetch_assoc();
  495. $id = (int)$result['id'];
  496. $new_gcm['id'] = $id;
  497. $new_gcm['gcm'] = $gcm;
  498. $this-> post_update($id, $new_gcm, $pk, $column_names, $table_name);
  499. }else{ // insert
  500. $this->post_one($gcm, $pk, $column_names, $table_name);
  501. }
  502. }
  503.  
  504. private function sendNotif() {
  505. if($this->get_request_method() != "POST") $this->response('',406);
  506. $body = json_decode(file_get_contents("php://input"), true);
  507. $registatoin_ids = $body['registatoin_ids'];
  508. $notif_title = $body['data']['title'];
  509. $notif_content = $body['data']['content'];
  510. $notif_place = $body['data']['place'];
  511.  
  512. $gcmRegIds = array();
  513. $i = 0;
  514. // split gcm reg id per 1000 item
  515. foreach($registatoin_ids as $reg_id){
  516. $i++;
  517. $gcmRegIds[floor($i/1000)][] = $reg_id;
  518. }
  519. // send notif per 1000 items
  520. $pushStatus = array();
  521. foreach($gcmRegIds as $val){
  522. $pushStatus[] = $this->sendPushNotification($val, $notif_title, $notif_content, $notif_place);
  523. }
  524.  
  525. $success_count = 0;
  526. $failure_count = 0;
  527. foreach($pushStatus as $s){
  528. if(!empty($s['success'])) $success_count = $success_count + $s['success'];
  529. if(!empty($s['failure'])) $failure_count = $failure_count + ($s['failure']);
  530. }
  531.  
  532. $obj_data = array();
  533. if(!empty($pushStatus)){
  534. $obj_data['success'] = $success_count;
  535. $obj_data['failure'] = $failure_count;
  536. $resp['data'] = $obj_data;
  537. $this->response($this->json($resp), 200);
  538. }else{
  539. $this->response('',204); // "No Content" status
  540. }
  541.  
  542. }
  543.  
  544. private function sendPushNotification($registatoin_ids, $title, $content, $place){
  545. // Set POST variables
  546. $url = 'https://android.googleapis.com/gcm/send';
  547. $fields = array(
  548. 'registration_ids' => $registatoin_ids,
  549. 'data' => array( 'title' => $title, 'content' => $content, 'place' => $place, )
  550. );
  551. $api_key = self::GOOGLE_API_KEY;
  552. $headers = array( 'Authorization: key='.$api_key, 'Content-Type: application/json' );
  553. // Open connection
  554. $ch = curl_init();
  555.  
  556. // Set the url, number of POST vars, POST data
  557. curl_setopt($ch, CURLOPT_URL, $url);
  558. curl_setopt($ch, CURLOPT_POST, true);
  559. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  560. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  561.  
  562. // Disabling SSL Certificate support temporarly
  563. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  564. curl_setopt($ch, CURLOPT_POSTFIELDS, $this->json($fields));
  565. // Execute post
  566. $result = curl_exec($ch);
  567. if ($result === FALSE) { die('Curl failed: ' . curl_error($ch)); }
  568. // Close connection
  569. curl_close($ch);
  570. $result_data = json_decode($result);
  571. $result_arr = array();
  572. $result_arr['success'] = $result_data->success;
  573. $result_arr['failure'] = $result_data->failure;
  574. return $result_arr;
  575. }
  576.  
  577. /*
  578. * ========================================================================================================================
  579. * ===================================== API utilities # DO NOT EDIT ======================================================
  580. */
  581.  
  582. private function get_list($query){
  583. $r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
  584. if($r->num_rows > 0){
  585. $result = array();
  586. while($row = $r->fetch_assoc()){
  587. $result[] = $row;
  588. }
  589. $this->response($this->json($result), 200); // send user details
  590. }
  591. $this->response('',204); // If no records "No Content" status
  592. }
  593.  
  594. private function get_list_result($query){
  595. $result = array();
  596. $r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
  597. if($r->num_rows > 0){
  598. while($row = $r->fetch_assoc()){
  599. $result[] = $row;
  600. }
  601. }
  602. return $result;
  603. }
  604.  
  605. private function get_result($query){
  606. $result = array();
  607. $r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
  608. if($r->num_rows > 0) $result = $r->fetch_assoc();
  609. return $result;
  610. }
  611.  
  612. private function get_one($query){
  613. $r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
  614. if($r->num_rows > 0) {
  615. $result = $r->fetch_assoc();
  616. $this->response($this->json($result), 200); // send user details
  617. }
  618. $this->response('',204); // If no records "No Content" status
  619. }
  620.  
  621. private function get_count($query){
  622. $r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
  623. if($r->num_rows > 0) {
  624. $result = $r->fetch_row();
  625. $this->response($result[0], 200);
  626. }
  627. $this->response('',204); // If no records "No Content" status
  628. }
  629.  
  630. private function get_count_result($query){
  631. $r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
  632. if($r->num_rows > 0) {
  633. $result = $r->fetch_row();
  634. return $result[0];
  635. }
  636. return 0;
  637. }
  638.  
  639. private function post_one($obj, $pk, $column_names, $table_name){
  640. $keys = array_keys($obj);
  641. $columns = '';
  642. $values = '';
  643. foreach($column_names as $desired_key){
  644. if(!in_array($desired_key, $keys)) {
  645. $$desired_key = '';
  646. }else{
  647. $$desired_key = $obj[$desired_key];
  648. }
  649. $columns = $columns.$desired_key.',';
  650. $values = $values."'".$this->real_escape($$desired_key)."',";
  651. }
  652.  
  653. $query = "INSERT INTO ".$table_name."(".trim($columns,',').") VALUES(".trim($values,',').")";
  654. if(!empty($obj)){
  655. if ($this->mysqli->query($query)) {
  656. // retrive row after insert
  657. $last_id = $this->mysqli->insert_id;
  658. $get_query = "SELECT * FROM ".$table_name." WHERE ".$pk."=".$last_id;
  659. $r = $this->mysqli->query($get_query) or die($this->mysqli->error.__LINE__);
  660. if($r->num_rows > 0) {
  661. $obj = $r->fetch_assoc();
  662. }
  663. $status = "success";
  664. $msg = $table_name." created successfully";
  665. } else {
  666. $status = "failed";
  667. $msg = $this->mysqli->error.__LINE__;
  668. }
  669. $resp = array('status' => $status, "msg" => $msg, "data" => $obj);
  670. $this->response($this->json($resp),200);
  671. }else{
  672. $this->response('',204); //"No Content" status
  673. }
  674. }
  675.  
  676. private function post_array($obj_array, $column_names, $table_name){
  677. $query = "";
  678. for ($i = 0; $i < count($obj_array); $i++) {
  679. $obj = $obj_array[$i];
  680. $keys = array_keys($obj);
  681. $columns = '';
  682. $values = '';
  683. foreach($column_names as $desired_key){
  684. if(!in_array($desired_key, $keys)) {
  685. $$desired_key = '';
  686. }else{
  687. $$desired_key = $obj[$desired_key];
  688. }
  689. $columns = $columns.$desired_key.',';
  690. $values = $values."'".$this->real_escape($$desired_key)."',";
  691. }
  692. $query .= "INSERT INTO ".$table_name."(".trim($columns,',').") VALUES(".trim($values,',').");";
  693. }
  694. if(!empty($obj_array)){
  695. if ($this->mysqli->multi_query($query)) {
  696. $status = "success";
  697. $msg = $table_name." created successfully";
  698. } else {
  699. $status = "failed";
  700. $msg = $this->mysqli->error.__LINE__;
  701. }
  702. $resp = array('status' => $status, "msg" => $msg, "data" => $obj_array);
  703. $this->response($this->json($resp),200);
  704. }else{
  705. $this->response('',204); //"No Content" status
  706. }
  707. }
  708.  
  709. private function post_update($id, $obj, $pk, $column_names, $table_name){
  710. $keys = array_keys($obj[$table_name]);
  711. $columns = '';
  712. $values = '';
  713. foreach($column_names as $desired_key){ // Check the recipe received. If key does not exist, insert blank into the array.
  714. if(!in_array($desired_key, $keys)) {
  715. $$desired_key = '';
  716. }else{
  717. $$desired_key = $obj[$table_name][$desired_key];
  718. }
  719. $columns = $columns.$desired_key."='".$this->real_escape($$desired_key)."',";
  720. }
  721. $query = "UPDATE ".$table_name." SET ".trim($columns,',')." WHERE ".$pk."=$id";
  722. if(!empty($obj)){
  723. // $r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
  724. if ($this->mysqli->query($query)) {
  725. $status = "success";
  726. $msg = $table_name." update successfully";
  727. } else {
  728. $status = "failed";
  729. $msg = $this->mysqli->error.__LINE__;
  730. }
  731. $resp = array('status' => $status, "msg" => $msg, "data" => $obj);
  732. $this->response($this->json($resp),200);
  733. }else{
  734. $this->response('',204); // "No Content" status
  735. }
  736. }
  737.  
  738. private function delete_one($id, $pk, $table_name){
  739. $query="DELETE FROM ".$table_name." WHERE ".$pk." = $id";
  740. if ($this->mysqli->query($query)) {
  741. $status = "success";
  742. $msg = "One record " .$table_name." successfully deleted";
  743. } else {
  744. $status = "failed";
  745. $msg = $this->mysqli->error.__LINE__;
  746. }
  747. $resp = array('status' => $status, "msg" => $msg);
  748. $this->response($this->json($resp),200);
  749. }
  750.  
  751. private function delete_one_str($pkval, $pk, $table_name){
  752. $query="DELETE FROM ".$table_name." WHERE ".$pk." = '$pkval'";
  753. if ($this->mysqli->query($query)) {
  754. $status = "success";
  755. $msg = "One record " .$table_name." successfully deleted";
  756. } else {
  757. $status = "failed";
  758. $msg = $this->mysqli->error.__LINE__;
  759. }
  760. $resp = array('status' => $status, "msg" => $msg);
  761. $this->response($this->json($resp),200);
  762. }
  763.  
  764. private function responseInvalidParam(){
  765. $resp = array("status" => 'Failed', "msg" => 'Invalid Parameter' );
  766. $this->response($this->json($resp), 200);
  767. }
  768.  
  769. /* ==================================== End of API utilities ==========================================
  770. * ====================================================================================================
  771. */
  772.  
  773. /*Encode array into JSON */
  774. private function json($data){
  775. if(is_array($data)){
  776. return json_encode($data, JSON_NUMERIC_CHECK);
  777. }
  778. }
  779.  
  780. /* String mysqli_real_escape_string */
  781. private function real_escape($s){
  782. return mysqli_real_escape_string($this->mysqli, $s);
  783. }
  784.  
  785. }
  786.  
  787. // Initiiate Library
  788.  
  789. $api = new API;
  790. $api->processApi();
  791. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement