ssp.class.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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']) && (!isset($column['dummy']) || $column['dummy'] !== true)){
  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. $select = '';
  103. $order = '';
  104. if ( isset($request['order']) && count($request['order']) ) {
  105. $selects = [];
  106. $orderBy = [];
  107. $dtColumns = self::pluck( $columns, 'dt' );
  108. for ( $i=0, $ien=count($request['order']) ; $i<$ien ; $i++ ) {
  109. // Convert the column index into the column data property
  110. $columnIdx = intval($request['order'][$i]['column']);
  111. $requestColumn = $request['columns'][$columnIdx];
  112. $columnIdx = array_search( $columnIdx, $dtColumns );
  113. $column = $columns[ $columnIdx ];
  114. if ( $requestColumn['orderable'] == 'true' ) {
  115. $dir = $request['order'][$i]['dir'] === 'asc' ?
  116. 'ASC' :
  117. 'DESC';
  118. if(isset($column['order_subquery'])) {
  119. $selects[] = '('.$column['order_subquery'].') AS `'.$column['db'].'_count`';
  120. $orderBy[] = '`'.$column['db'].'_count` '.$dir;
  121. } else {
  122. $orderBy[] = '`'.$tableAS.'`.`'.$column['db'].'` '.$dir;
  123. }
  124. }
  125. }
  126. if ( count( $selects ) ) {
  127. $select = ', '.implode(', ', $selects);
  128. }
  129. if ( count( $orderBy ) ) {
  130. $order = 'ORDER BY '.implode(', ', $orderBy);
  131. }
  132. }
  133. return [$select, $order];
  134. }
  135. /**
  136. * Searching / Filtering
  137. *
  138. * Construct the WHERE clause for server-side processing SQL query.
  139. *
  140. * NOTE this does not match the built-in DataTables filtering which does it
  141. * word by word on any field. It's possible to do here performance on large
  142. * databases would be very poor
  143. *
  144. * @param array $request Data sent to server by DataTables
  145. * @param array $columns Column information array
  146. * @param array $bindings Array of values for PDO bindings, used in the
  147. * sql_exec() function
  148. * @return string SQL where clause
  149. */
  150. static function filter ( $tablesAS, $request, $columns, &$bindings )
  151. {
  152. $globalSearch = array();
  153. $columnSearch = array();
  154. $joins = array();
  155. $dtColumns = self::pluck( $columns, 'dt' );
  156. if ( isset($request['search']) && $request['search']['value'] != '' ) {
  157. $str = $request['search']['value'];
  158. for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
  159. $requestColumn = $request['columns'][$i];
  160. $columnIdx = array_search( $i, $dtColumns );
  161. $column = $columns[ $columnIdx ];
  162. if ( $requestColumn['searchable'] == 'true' ) {
  163. if(!empty($column['db'])){
  164. $binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
  165. if(isset($column['search']['join'])) {
  166. $joins[] = $column['search']['join'];
  167. $globalSearch[] = $column['search']['where_column'].' LIKE '.$binding;
  168. } else {
  169. $globalSearch[] = "`".$tablesAS."`.`".$column['db']."` LIKE ".$binding;
  170. }
  171. }
  172. }
  173. }
  174. }
  175. // Individual column filtering
  176. if ( isset( $request['columns'] ) ) {
  177. for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
  178. $requestColumn = $request['columns'][$i];
  179. $columnIdx = array_search( $requestColumn['data'], $dtColumns );
  180. $column = $columns[ $columnIdx ];
  181. $str = $requestColumn['search']['value'];
  182. if ( $requestColumn['searchable'] == 'true' &&
  183. $str != '' ) {
  184. if(!empty($column['db'])){
  185. $binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
  186. $columnSearch[] = "`".$tablesAS."`.`".$column['db']."` LIKE ".$binding;
  187. }
  188. }
  189. }
  190. }
  191. // Combine the filters into a single string
  192. $where = '';
  193. if ( count( $globalSearch ) ) {
  194. $where = '('.implode(' OR ', $globalSearch).')';
  195. }
  196. if ( count( $columnSearch ) ) {
  197. $where = $where === '' ?
  198. implode(' AND ', $columnSearch) :
  199. $where .' AND '. implode(' AND ', $columnSearch);
  200. }
  201. $join = '';
  202. if( count($joins) ) {
  203. $join = implode(' ', $joins);
  204. }
  205. if ( $where !== '' ) {
  206. $where = 'WHERE '.$where;
  207. }
  208. return [$join, $where];
  209. }
  210. /**
  211. * Perform the SQL queries needed for an server-side processing requested,
  212. * utilising the helper functions of this class, limit(), order() and
  213. * filter() among others. The returned array is ready to be encoded as JSON
  214. * in response to an SSP request, or can be modified if needed before
  215. * sending back to the client.
  216. *
  217. * @param array $request Data sent to server by DataTables
  218. * @param array|PDO $conn PDO connection resource or connection parameters array
  219. * @param string $table SQL table to query
  220. * @param string $primaryKey Primary key of the table
  221. * @param array $columns Column information array
  222. * @return array Server-side processing response array
  223. */
  224. static function simple ( $request, $conn, $table, $primaryKey, $columns )
  225. {
  226. $bindings = array();
  227. $db = self::db( $conn );
  228. // Allow for a JSON string to be passed in
  229. if (isset($request['json'])) {
  230. $request = json_decode($request['json'], true);
  231. }
  232. // table AS
  233. $tablesAS = null;
  234. if(is_array($table)) {
  235. $tablesAS = $table[1];
  236. $table = $table[0];
  237. }
  238. // Build the SQL query string from the request
  239. list($select, $order) = self::order( $tablesAS, $request, $columns );
  240. $limit = self::limit( $request, $columns );
  241. list($join, $where) = self::filter( $tablesAS, $request, $columns, $bindings );
  242. // Main query to actually get the data
  243. $data = self::sql_exec( $db, $bindings,
  244. "SELECT `$tablesAS`.`".implode("`, `$tablesAS`.`", self::pluck($columns, 'db'))."`
  245. $select
  246. FROM `$table` AS `$tablesAS`
  247. $join
  248. $where
  249. $order
  250. $limit"
  251. );
  252. // Data set length after filtering
  253. $resFilterLength = self::sql_exec( $db, $bindings,
  254. "SELECT COUNT(`{$tablesAS}`.`{$primaryKey}`)
  255. FROM `$table` AS `$tablesAS`
  256. $join
  257. $where"
  258. );
  259. $recordsFiltered = $resFilterLength[0][0];
  260. // Total data set length
  261. $resTotalLength = self::sql_exec( $db,
  262. "SELECT COUNT(`{$tablesAS}`.`{$primaryKey}`)
  263. FROM `$table` AS `$tablesAS`"
  264. );
  265. $recordsTotal = $resTotalLength[0][0];
  266. /*
  267. * Output
  268. */
  269. return array(
  270. "draw" => isset ( $request['draw'] ) ?
  271. intval( $request['draw'] ) :
  272. 0,
  273. "recordsTotal" => intval( $recordsTotal ),
  274. "recordsFiltered" => intval( $recordsFiltered ),
  275. "data" => self::data_output( $columns, $data )
  276. );
  277. }
  278. /**
  279. * The difference between this method and the `simple` one, is that you can
  280. * apply additional `where` conditions to the SQL queries. These can be in
  281. * one of two forms:
  282. *
  283. * * 'Result condition' - This is applied to the result set, but not the
  284. * overall paging information query - i.e. it will not effect the number
  285. * of records that a user sees they can have access to. This should be
  286. * used when you want apply a filtering condition that the user has sent.
  287. * * 'All condition' - This is applied to all queries that are made and
  288. * reduces the number of records that the user can access. This should be
  289. * used in conditions where you don't want the user to ever have access to
  290. * particular records (for example, restricting by a login id).
  291. *
  292. * In both cases the extra condition can be added as a simple string, or if
  293. * you are using external values, as an assoc. array with `condition` and
  294. * `bindings` parameters. The `condition` is a string with the SQL WHERE
  295. * condition and `bindings` is an assoc. array of the binding names and
  296. * values.
  297. *
  298. * @param array $request Data sent to server by DataTables
  299. * @param array|PDO $conn PDO connection resource or connection parameters array
  300. * @param string|array $table SQL table to query, if array second key is AS
  301. * @param string $primaryKey Primary key of the table
  302. * @param array $columns Column information array
  303. * @param string $join JOIN sql string
  304. * @param string|array $whereResult WHERE condition to apply to the result set
  305. * @return array Server-side processing response array
  306. */
  307. static function complex (
  308. $request,
  309. $conn,
  310. $table,
  311. $primaryKey,
  312. $columns,
  313. $join=null,
  314. $whereResult=null
  315. ) {
  316. $bindings = array();
  317. $db = self::db( $conn );
  318. // table AS
  319. $tablesAS = null;
  320. if(is_array($table)) {
  321. $tablesAS = $table[1];
  322. $table = $table[0];
  323. }
  324. // Build the SQL query string from the request
  325. list($select, $order) = self::order( $tablesAS, $request, $columns );
  326. $limit = self::limit( $request, $columns );
  327. list($join_filter, $where) = self::filter( $tablesAS, $request, $columns, $bindings );
  328. // whereResult can be a simple string, or an assoc. array with a
  329. // condition and bindings
  330. if ( $whereResult ) {
  331. $str = $whereResult;
  332. if ( is_array($whereResult) ) {
  333. $str = $whereResult['condition'];
  334. if ( isset($whereResult['bindings']) ) {
  335. self::add_bindings($bindings, $whereResult);
  336. }
  337. }
  338. $where = $where ?
  339. $where .' AND '.$str :
  340. 'WHERE '.$str;
  341. }
  342. // Main query to actually get the data
  343. $data = self::sql_exec( $db, $bindings,
  344. "SELECT `$tablesAS`.`".implode("`, `$tablesAS`.`", self::pluck($columns, 'db'))."`
  345. $select
  346. FROM `$table` AS `$tablesAS`
  347. $join
  348. $join_filter
  349. $where
  350. GROUP BY `{$tablesAS}`.`{$primaryKey}`
  351. $order
  352. $limit"
  353. );
  354. // Data set length after filtering
  355. $resFilterLength = self::sql_exec( $db, $bindings,
  356. "SELECT COUNT(`{$tablesAS}`.`{$primaryKey}`)
  357. FROM `$table` AS `$tablesAS`
  358. $join
  359. $join_filter
  360. $where
  361. GROUP BY `{$tablesAS}`.`{$primaryKey}`"
  362. );
  363. $recordsFiltered = (isset($resFilterLength[0])) ? $resFilterLength[0][0] : 0;
  364. // Total data set length
  365. $resTotalLength = self::sql_exec( $db, $bindings,
  366. "SELECT COUNT(`{$tablesAS}`.`{$primaryKey}`)
  367. FROM `$table` AS `$tablesAS`
  368. $join
  369. $join_filter
  370. $where
  371. GROUP BY `{$tablesAS}`.`{$primaryKey}`"
  372. );
  373. $recordsTotal = (isset($resTotalLength[0])) ? $resTotalLength[0][0] : 0;
  374. /*
  375. * Output
  376. */
  377. return array(
  378. "draw" => isset ( $request['draw'] ) ?
  379. intval( $request['draw'] ) :
  380. 0,
  381. "recordsTotal" => intval( $recordsTotal ),
  382. "recordsFiltered" => intval( $recordsFiltered ),
  383. "data" => self::data_output( $columns, $data )
  384. );
  385. }
  386. /**
  387. * Connect to the database
  388. *
  389. * @param array $sql_details SQL server connection details array, with the
  390. * properties:
  391. * * host - host name
  392. * * db - database name
  393. * * user - user name
  394. * * pass - user password
  395. * @return resource Database connection handle
  396. */
  397. static function sql_connect ( $sql_details )
  398. {
  399. try {
  400. $db = @new PDO(
  401. "mysql:host={$sql_details['host']};dbname={$sql_details['db']}",
  402. $sql_details['user'],
  403. $sql_details['pass'],
  404. array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION )
  405. );
  406. }
  407. catch (PDOException $e) {
  408. self::fatal(
  409. "An error occurred while connecting to the database. ".
  410. "The error reported by the server was: ".$e->getMessage()
  411. );
  412. }
  413. return $db;
  414. }
  415. /**
  416. * Execute an SQL query on the database
  417. *
  418. * @param resource $db Database handler
  419. * @param array $bindings Array of PDO binding values from bind() to be
  420. * used for safely escaping strings. Note that this can be given as the
  421. * SQL query string if no bindings are required.
  422. * @param string $sql SQL query to execute.
  423. * @return array Result from the query (all rows)
  424. */
  425. static function sql_exec ( $db, $bindings, $sql=null )
  426. {
  427. // Argument shifting
  428. if ( $sql === null ) {
  429. $sql = $bindings;
  430. }
  431. $stmt = $db->prepare( $sql );
  432. // Bind parameters
  433. if ( is_array( $bindings ) ) {
  434. for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) {
  435. $binding = $bindings[$i];
  436. $stmt->bindValue( $binding['key'], $binding['val'], $binding['type'] );
  437. }
  438. }
  439. // Execute
  440. try {
  441. $stmt->execute();
  442. }
  443. catch (PDOException $e) {
  444. self::fatal( "An SQL error occurred: ".$e->getMessage() );
  445. }
  446. // Return all
  447. return $stmt->fetchAll( PDO::FETCH_BOTH );
  448. }
  449. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  450. * Internal methods
  451. */
  452. /**
  453. * Throw a fatal error.
  454. *
  455. * This writes out an error message in a JSON string which DataTables will
  456. * see and show to the user in the browser.
  457. *
  458. * @param string $msg Message to send to the client
  459. */
  460. static function fatal ( $msg )
  461. {
  462. echo json_encode( array(
  463. "error" => $msg
  464. ) );
  465. exit(0);
  466. }
  467. /**
  468. * Create a PDO binding key which can be used for escaping variables safely
  469. * when executing a query with sql_exec()
  470. *
  471. * @param array &$a Array of bindings
  472. * @param * $val Value to bind
  473. * @param int $type PDO field type
  474. * @return string Bound key to be used in the SQL where this parameter
  475. * would be used.
  476. */
  477. static function bind ( &$a, $val, $type )
  478. {
  479. $key = ':binding_'.count( $a );
  480. $a[] = array(
  481. 'key' => $key,
  482. 'val' => $val,
  483. 'type' => $type
  484. );
  485. return $key;
  486. }
  487. static function add_bindings(&$bindings, $vals)
  488. {
  489. foreach($vals['bindings'] as $key => $value) {
  490. $bindings[] = array(
  491. 'key' => $key,
  492. 'val' => $value,
  493. 'type' => PDO::PARAM_STR
  494. );
  495. }
  496. }
  497. /**
  498. * Pull a particular property from each assoc. array in a numeric array,
  499. * returning and array of the property values from each item.
  500. *
  501. * @param array $a Array to get data from
  502. * @param string $prop Property to read
  503. * @return array Array of property values
  504. */
  505. static function pluck ( $a, $prop )
  506. {
  507. $out = array();
  508. for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
  509. if ( empty($a[$i][$prop]) && $a[$i][$prop] !== 0 ) {
  510. continue;
  511. }
  512. if ( $prop == 'db' && isset($a[$i]['dummy']) && $a[$i]['dummy'] === true ) {
  513. continue;
  514. }
  515. //removing the $out array index confuses the filter method in doing proper binding,
  516. //adding it ensures that the array data are mapped correctly
  517. $out[$i] = $a[$i][$prop];
  518. }
  519. return $out;
  520. }
  521. /**
  522. * Return a string from an array or a string
  523. *
  524. * @param array|string $a Array to join
  525. * @param string $join Glue for the concatenation
  526. * @return string Joined string
  527. */
  528. static function _flatten ( $a, $join = ' AND ' )
  529. {
  530. if ( ! $a ) {
  531. return '';
  532. }
  533. else if ( $a && is_array($a) ) {
  534. return implode( $join, $a );
  535. }
  536. return $a;
  537. }
  538. }