ssp.class.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. <?php
  2. /*
  3. * Helper functions for building a DataTables server-side processing SQL query
  4. *
  5. * The static functions in this class are just helper functions to help build
  6. * the SQL used in the DataTables demo server-side processing scripts. These
  7. * functions obviously do not represent all that can be done with server-side
  8. * processing, they are intentionally simple to show how it works. More complex
  9. * server-side processing operations will likely require a custom script.
  10. *
  11. * See https://datatables.net/usage/server-side for full details on the server-
  12. * side processing requirements of DataTables.
  13. *
  14. * @license MIT - https://datatables.net/license_mit
  15. */
  16. class SSP {
  17. /**
  18. * Create the data output array for the DataTables rows
  19. *
  20. * @param array $columns Column information array
  21. * @param array $data Data from the SQL get
  22. * @return array Formatted data in a row based format
  23. */
  24. static function data_output ( $columns, $data )
  25. {
  26. $out = array();
  27. for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) {
  28. $row = array();
  29. for ( $j=0, $jen=count($columns) ; $j<$jen ; $j++ ) {
  30. $column = $columns[$j];
  31. // Is there a formatter?
  32. if ( isset( $column['formatter'] ) ) {
  33. if(empty($column['db'])){
  34. $row[ $column['dt'] ] = $column['formatter']( $data[$i] );
  35. }
  36. else{
  37. $row[ $column['dt'] ] = $column['formatter']( $data[$i][ $column['db'] ], $data[$i] );
  38. }
  39. }
  40. else {
  41. if(!empty($column['db'])){
  42. $row[ $column['dt'] ] = $data[$i][ $columns[$j]['db'] ];
  43. }
  44. else{
  45. $row[ $column['dt'] ] = "";
  46. }
  47. }
  48. }
  49. $out[] = $row;
  50. }
  51. return $out;
  52. }
  53. /**
  54. * Database connection
  55. *
  56. * Obtain an PHP PDO connection from a connection details array
  57. *
  58. * @param array $conn SQL connection details. The array should have
  59. * the following properties
  60. * * host - host name
  61. * * db - database name
  62. * * user - user name
  63. * * pass - user password
  64. * * Optional: `'charset' => 'utf8'` - you might need this depending on your PHP / MySQL config
  65. * @return resource PDO connection
  66. */
  67. static function db ( $conn )
  68. {
  69. if ( is_array( $conn ) ) {
  70. return self::sql_connect( $conn );
  71. }
  72. return $conn;
  73. }
  74. /**
  75. * Paging
  76. *
  77. * Construct the LIMIT clause for server-side processing SQL query
  78. *
  79. * @param array $request Data sent to server by DataTables
  80. * @param array $columns Column information array
  81. * @return string SQL limit clause
  82. */
  83. static function limit ( $request, $columns )
  84. {
  85. $limit = '';
  86. if ( isset($request['start']) && $request['length'] != -1 ) {
  87. $limit = "LIMIT ".intval($request['start']).", ".intval($request['length']);
  88. }
  89. return $limit;
  90. }
  91. /**
  92. * Ordering
  93. *
  94. * Construct the ORDER BY clause for server-side processing SQL query
  95. *
  96. * @param array $request Data sent to server by DataTables
  97. * @param array $columns Column information array
  98. * @return string SQL order by clause
  99. */
  100. static function order ( $tableAS, $request, $columns )
  101. {
  102. $order = '';
  103. if ( isset($request['order']) && count($request['order']) ) {
  104. $orderBy = array();
  105. $dtColumns = self::pluck( $columns, 'dt' );
  106. for ( $i=0, $ien=count($request['order']) ; $i<$ien ; $i++ ) {
  107. // Convert the column index into the column data property
  108. $columnIdx = intval($request['order'][$i]['column']);
  109. $requestColumn = $request['columns'][$columnIdx];
  110. $columnIdx = array_search( $columnIdx, $dtColumns );
  111. $column = $columns[ $columnIdx ];
  112. if ( $requestColumn['orderable'] == 'true' ) {
  113. $dir = $request['order'][$i]['dir'] === 'asc' ?
  114. 'ASC' :
  115. 'DESC';
  116. $orderBy[] = '`'.$tableAS.'`.`'.$column['db'].'` '.$dir;
  117. }
  118. }
  119. if ( count( $orderBy ) ) {
  120. $order = 'ORDER BY '.implode(', ', $orderBy);
  121. }
  122. }
  123. return $order;
  124. }
  125. /**
  126. * Searching / Filtering
  127. *
  128. * Construct the WHERE clause for server-side processing SQL query.
  129. *
  130. * NOTE this does not match the built-in DataTables filtering which does it
  131. * word by word on any field. It's possible to do here performance on large
  132. * databases would be very poor
  133. *
  134. * @param array $request Data sent to server by DataTables
  135. * @param array $columns Column information array
  136. * @param array $bindings Array of values for PDO bindings, used in the
  137. * sql_exec() function
  138. * @return string SQL where clause
  139. */
  140. static function filter ( $tablesAS, $request, $columns, &$bindings )
  141. {
  142. $globalSearch = array();
  143. $columnSearch = array();
  144. $dtColumns = self::pluck( $columns, 'dt' );
  145. if ( isset($request['search']) && $request['search']['value'] != '' ) {
  146. $str = $request['search']['value'];
  147. for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
  148. $requestColumn = $request['columns'][$i];
  149. $columnIdx = array_search( $requestColumn['data'], $dtColumns );
  150. $column = $columns[ $columnIdx ];
  151. if ( $requestColumn['searchable'] == 'true' ) {
  152. if(!empty($column['db'])){
  153. $binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
  154. $globalSearch[] = "`".$tablesAS."`.`".$column['db']."` LIKE ".$binding;
  155. }
  156. }
  157. }
  158. }
  159. // Individual column filtering
  160. if ( isset( $request['columns'] ) ) {
  161. for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
  162. $requestColumn = $request['columns'][$i];
  163. $columnIdx = array_search( $requestColumn['data'], $dtColumns );
  164. $column = $columns[ $columnIdx ];
  165. $str = $requestColumn['search']['value'];
  166. if ( $requestColumn['searchable'] == 'true' &&
  167. $str != '' ) {
  168. if(!empty($column['db'])){
  169. $binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
  170. $columnSearch[] = "`".$tablesAS."`.`".$column['db']."` LIKE ".$binding;
  171. }
  172. }
  173. }
  174. }
  175. // Combine the filters into a single string
  176. $where = '';
  177. if ( count( $globalSearch ) ) {
  178. $where = '('.implode(' OR ', $globalSearch).')';
  179. }
  180. if ( count( $columnSearch ) ) {
  181. $where = $where === '' ?
  182. implode(' AND ', $columnSearch) :
  183. $where .' AND '. implode(' AND ', $columnSearch);
  184. }
  185. if ( $where !== '' ) {
  186. $where = 'WHERE '.$where;
  187. }
  188. return $where;
  189. }
  190. /**
  191. * Perform the SQL queries needed for an server-side processing requested,
  192. * utilising the helper functions of this class, limit(), order() and
  193. * filter() among others. The returned array is ready to be encoded as JSON
  194. * in response to an SSP request, or can be modified if needed before
  195. * sending back to the client.
  196. *
  197. * @param array $request Data sent to server by DataTables
  198. * @param array|PDO $conn PDO connection resource or connection parameters array
  199. * @param string $table SQL table to query
  200. * @param string $primaryKey Primary key of the table
  201. * @param array $columns Column information array
  202. * @return array Server-side processing response array
  203. */
  204. static function simple ( $request, $conn, $table, $primaryKey, $columns )
  205. {
  206. $bindings = array();
  207. $db = self::db( $conn );
  208. // Allow for a JSON string to be passed in
  209. if (isset($request['json'])) {
  210. $request = json_decode($request['json'], true);
  211. }
  212. // table AS
  213. $tablesAS = null;
  214. if(is_array($table)) {
  215. $tablesAS = $table[1];
  216. $table = $table[0];
  217. }
  218. // Build the SQL query string from the request
  219. $limit = self::limit( $request, $columns );
  220. $order = self::order( $tablesAS, $request, $columns );
  221. $where = self::filter( $tablesAS, $request, $columns, $bindings );
  222. // Main query to actually get the data
  223. $data = self::sql_exec( $db, $bindings,
  224. "SELECT `$tablesAS`.`".implode("`, `$tablesAS`.`", self::pluck($columns, 'db'))."`
  225. FROM `$table` AS `$tablesAS`
  226. $where
  227. $order
  228. $limit"
  229. );
  230. // Data set length after filtering
  231. $resFilterLength = self::sql_exec( $db, $bindings,
  232. "SELECT COUNT(`{$primaryKey}`)
  233. FROM `$table` AS `$tablesAS`
  234. $where"
  235. );
  236. $recordsFiltered = $resFilterLength[0][0];
  237. // Total data set length
  238. $resTotalLength = self::sql_exec( $db,
  239. "SELECT COUNT(`{$primaryKey}`)
  240. FROM `$table` AS `$tablesAS`"
  241. );
  242. $recordsTotal = $resTotalLength[0][0];
  243. /*
  244. * Output
  245. */
  246. return array(
  247. "draw" => isset ( $request['draw'] ) ?
  248. intval( $request['draw'] ) :
  249. 0,
  250. "recordsTotal" => intval( $recordsTotal ),
  251. "recordsFiltered" => intval( $recordsFiltered ),
  252. "data" => self::data_output( $columns, $data )
  253. );
  254. }
  255. /**
  256. * The difference between this method and the `simple` one, is that you can
  257. * apply additional `where` conditions to the SQL queries. These can be in
  258. * one of two forms:
  259. *
  260. * * 'Result condition' - This is applied to the result set, but not the
  261. * overall paging information query - i.e. it will not effect the number
  262. * of records that a user sees they can have access to. This should be
  263. * used when you want apply a filtering condition that the user has sent.
  264. * * 'All condition' - This is applied to all queries that are made and
  265. * reduces the number of records that the user can access. This should be
  266. * used in conditions where you don't want the user to ever have access to
  267. * particular records (for example, restricting by a login id).
  268. *
  269. * In both cases the extra condition can be added as a simple string, or if
  270. * you are using external values, as an assoc. array with `condition` and
  271. * `bindings` parameters. The `condition` is a string with the SQL WHERE
  272. * condition and `bindings` is an assoc. array of the binding names and
  273. * values.
  274. *
  275. * @param array $request Data sent to server by DataTables
  276. * @param array|PDO $conn PDO connection resource or connection parameters array
  277. * @param string|array $table SQL table to query, if array second key is AS
  278. * @param string $primaryKey Primary key of the table
  279. * @param array $columns Column information array
  280. * @param string $join JOIN sql string
  281. * @param string|array $whereResult WHERE condition to apply to the result set
  282. * @return array Server-side processing response array
  283. */
  284. static function complex (
  285. $request,
  286. $conn,
  287. $table,
  288. $primaryKey,
  289. $columns,
  290. $join=null,
  291. $whereResult=null
  292. ) {
  293. $bindings = array();
  294. $db = self::db( $conn );
  295. // table AS
  296. $tablesAS = null;
  297. if(is_array($table)) {
  298. $tablesAS = $table[1];
  299. $table = $table[0];
  300. }
  301. // Build the SQL query string from the request
  302. $limit = self::limit( $request, $columns );
  303. $order = self::order( $tablesAS, $request, $columns );
  304. $where = self::filter( $tablesAS, $request, $columns, $bindings );
  305. // whereResult can be a simple string, or an assoc. array with a
  306. // condition and bindings
  307. if ( $whereResult ) {
  308. $str = $whereResult;
  309. if ( is_array($whereResult) ) {
  310. $str = $whereResult['condition'];
  311. if ( isset($whereResult['bindings']) ) {
  312. self::add_bindings($bindings, $whereResult);
  313. }
  314. }
  315. $where = $where ?
  316. $where .' AND '.$str :
  317. 'WHERE '.$str;
  318. }
  319. // Main query to actually get the data
  320. $data = self::sql_exec( $db, $bindings,
  321. "SELECT `$tablesAS`.`".implode("`, `$tablesAS`.`", self::pluck($columns, 'db'))."`
  322. FROM `$table` AS `$tablesAS`
  323. $join
  324. $where
  325. $order
  326. $limit"
  327. );
  328. // Data set length after filtering
  329. $resFilterLength = self::sql_exec( $db, $bindings,
  330. "SELECT COUNT(`{$tablesAS}`.`{$primaryKey}`)
  331. FROM `$table` AS `$tablesAS`
  332. $join
  333. $where"
  334. );
  335. $recordsFiltered = $resFilterLength[0][0];
  336. // Total data set length
  337. $resTotalLength = self::sql_exec( $db, $bindings,
  338. "SELECT COUNT(`{$tablesAS}`.`{$primaryKey}`)
  339. FROM `$table` AS `$tablesAS`
  340. $join
  341. $where"
  342. );
  343. $recordsTotal = $resTotalLength[0][0];
  344. /*
  345. * Output
  346. */
  347. return array(
  348. "draw" => isset ( $request['draw'] ) ?
  349. intval( $request['draw'] ) :
  350. 0,
  351. "recordsTotal" => intval( $recordsTotal ),
  352. "recordsFiltered" => intval( $recordsFiltered ),
  353. "data" => self::data_output( $columns, $data )
  354. );
  355. }
  356. /**
  357. * Connect to the database
  358. *
  359. * @param array $sql_details SQL server connection details array, with the
  360. * properties:
  361. * * host - host name
  362. * * db - database name
  363. * * user - user name
  364. * * pass - user password
  365. * @return resource Database connection handle
  366. */
  367. static function sql_connect ( $sql_details )
  368. {
  369. try {
  370. $db = @new PDO(
  371. "mysql:host={$sql_details['host']};dbname={$sql_details['db']}",
  372. $sql_details['user'],
  373. $sql_details['pass'],
  374. array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION )
  375. );
  376. }
  377. catch (PDOException $e) {
  378. self::fatal(
  379. "An error occurred while connecting to the database. ".
  380. "The error reported by the server was: ".$e->getMessage()
  381. );
  382. }
  383. return $db;
  384. }
  385. /**
  386. * Execute an SQL query on the database
  387. *
  388. * @param resource $db Database handler
  389. * @param array $bindings Array of PDO binding values from bind() to be
  390. * used for safely escaping strings. Note that this can be given as the
  391. * SQL query string if no bindings are required.
  392. * @param string $sql SQL query to execute.
  393. * @return array Result from the query (all rows)
  394. */
  395. static function sql_exec ( $db, $bindings, $sql=null )
  396. {
  397. // Argument shifting
  398. if ( $sql === null ) {
  399. $sql = $bindings;
  400. }
  401. $stmt = $db->prepare( $sql );
  402. // Bind parameters
  403. if ( is_array( $bindings ) ) {
  404. for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) {
  405. $binding = $bindings[$i];
  406. $stmt->bindValue( $binding['key'], $binding['val'], $binding['type'] );
  407. }
  408. }
  409. // Execute
  410. try {
  411. $stmt->execute();
  412. }
  413. catch (PDOException $e) {
  414. self::fatal( "An SQL error occurred: ".$e->getMessage() );
  415. }
  416. // Return all
  417. return $stmt->fetchAll( PDO::FETCH_BOTH );
  418. }
  419. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  420. * Internal methods
  421. */
  422. /**
  423. * Throw a fatal error.
  424. *
  425. * This writes out an error message in a JSON string which DataTables will
  426. * see and show to the user in the browser.
  427. *
  428. * @param string $msg Message to send to the client
  429. */
  430. static function fatal ( $msg )
  431. {
  432. echo json_encode( array(
  433. "error" => $msg
  434. ) );
  435. exit(0);
  436. }
  437. /**
  438. * Create a PDO binding key which can be used for escaping variables safely
  439. * when executing a query with sql_exec()
  440. *
  441. * @param array &$a Array of bindings
  442. * @param * $val Value to bind
  443. * @param int $type PDO field type
  444. * @return string Bound key to be used in the SQL where this parameter
  445. * would be used.
  446. */
  447. static function bind ( &$a, $val, $type )
  448. {
  449. $key = ':binding_'.count( $a );
  450. $a[] = array(
  451. 'key' => $key,
  452. 'val' => $val,
  453. 'type' => $type
  454. );
  455. return $key;
  456. }
  457. static function add_bindings(&$bindings, $vals)
  458. {
  459. foreach($vals['bindings'] as $key => $value) {
  460. $bindings[] = array(
  461. 'key' => $key,
  462. 'val' => $value,
  463. 'type' => PDO::PARAM_STR
  464. );
  465. }
  466. }
  467. /**
  468. * Pull a particular property from each assoc. array in a numeric array,
  469. * returning and array of the property values from each item.
  470. *
  471. * @param array $a Array to get data from
  472. * @param string $prop Property to read
  473. * @return array Array of property values
  474. */
  475. static function pluck ( $a, $prop )
  476. {
  477. $out = array();
  478. for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
  479. if ( empty($a[$i][$prop]) && $a[$i][$prop] !== 0 ) {
  480. continue;
  481. }
  482. //removing the $out array index confuses the filter method in doing proper binding,
  483. //adding it ensures that the array data are mapped correctly
  484. $out[$i] = $a[$i][$prop];
  485. }
  486. return $out;
  487. }
  488. /**
  489. * Return a string from an array or a string
  490. *
  491. * @param array|string $a Array to join
  492. * @param string $join Glue for the concatenation
  493. * @return string Joined string
  494. */
  495. static function _flatten ( $a, $join = ' AND ' )
  496. {
  497. if ( ! $a ) {
  498. return '';
  499. }
  500. else if ( $a && is_array($a) ) {
  501. return implode( $join, $a );
  502. }
  503. return $a;
  504. }
  505. }