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. GROUP BY `{$tablesAS}`.`{$primaryKey}`
  250. $order
  251. $limit"
  252. );
  253. // Data set length after filtering
  254. $resFilterLength = self::sql_exec( $db, $bindings,
  255. "SELECT COUNT(DISTINCT `{$tablesAS}`.`{$primaryKey}`)
  256. FROM `$table` AS `$tablesAS`
  257. $join
  258. $where"
  259. );
  260. $recordsFiltered = $resFilterLength[0][0];
  261. // Total data set length
  262. $resTotalLength = self::sql_exec( $db,
  263. "SELECT COUNT(`{$tablesAS}`.`{$primaryKey}`)
  264. FROM `$table` AS `$tablesAS`"
  265. );
  266. $recordsTotal = $resTotalLength[0][0];
  267. /*
  268. * Output
  269. */
  270. return array(
  271. "draw" => isset ( $request['draw'] ) ?
  272. intval( $request['draw'] ) :
  273. 0,
  274. "recordsTotal" => intval( $recordsTotal ),
  275. "recordsFiltered" => intval( $recordsFiltered ),
  276. "data" => self::data_output( $columns, $data )
  277. );
  278. }
  279. /**
  280. * The difference between this method and the `simple` one, is that you can
  281. * apply additional `where` conditions to the SQL queries. These can be in
  282. * one of two forms:
  283. *
  284. * * 'Result condition' - This is applied to the result set, but not the
  285. * overall paging information query - i.e. it will not effect the number
  286. * of records that a user sees they can have access to. This should be
  287. * used when you want apply a filtering condition that the user has sent.
  288. * * 'All condition' - This is applied to all queries that are made and
  289. * reduces the number of records that the user can access. This should be
  290. * used in conditions where you don't want the user to ever have access to
  291. * particular records (for example, restricting by a login id).
  292. *
  293. * In both cases the extra condition can be added as a simple string, or if
  294. * you are using external values, as an assoc. array with `condition` and
  295. * `bindings` parameters. The `condition` is a string with the SQL WHERE
  296. * condition and `bindings` is an assoc. array of the binding names and
  297. * values.
  298. *
  299. * @param array $request Data sent to server by DataTables
  300. * @param array|PDO $conn PDO connection resource or connection parameters array
  301. * @param string|array $table SQL table to query, if array second key is AS
  302. * @param string $primaryKey Primary key of the table
  303. * @param array $columns Column information array
  304. * @param string $join JOIN sql string
  305. * @param string|array $whereResult WHERE condition to apply to the result set
  306. * @return array Server-side processing response array
  307. */
  308. static function complex (
  309. $request,
  310. $conn,
  311. $table,
  312. $primaryKey,
  313. $columns,
  314. $join=null,
  315. $whereResult=null
  316. ) {
  317. $bindings = array();
  318. $db = self::db( $conn );
  319. // table AS
  320. $tablesAS = null;
  321. if(is_array($table)) {
  322. $tablesAS = $table[1];
  323. $table = $table[0];
  324. }
  325. // Build the SQL query string from the request
  326. list($select, $order) = self::order( $tablesAS, $request, $columns );
  327. $limit = self::limit( $request, $columns );
  328. list($join_filter, $where) = self::filter( $tablesAS, $request, $columns, $bindings );
  329. // whereResult can be a simple string, or an assoc. array with a
  330. // condition and bindings
  331. if ( $whereResult ) {
  332. $str = $whereResult;
  333. if ( is_array($whereResult) ) {
  334. $str = $whereResult['condition'];
  335. if ( isset($whereResult['bindings']) ) {
  336. self::add_bindings($bindings, $whereResult);
  337. }
  338. }
  339. $where = $where ?
  340. $where .' AND '.$str :
  341. 'WHERE '.$str;
  342. }
  343. // Main query to actually get the data
  344. $data = self::sql_exec( $db, $bindings,
  345. "SELECT `$tablesAS`.`".implode("`, `$tablesAS`.`", self::pluck($columns, 'db'))."`
  346. $select
  347. FROM `$table` AS `$tablesAS`
  348. $join
  349. $join_filter
  350. $where
  351. GROUP BY `{$tablesAS}`.`{$primaryKey}`
  352. $order
  353. $limit"
  354. );
  355. // Data set length after filtering
  356. $resFilterLength = self::sql_exec( $db, $bindings,
  357. "SELECT COUNT(DISTINCT `{$tablesAS}`.`{$primaryKey}`)
  358. FROM `$table` AS `$tablesAS`
  359. $join
  360. $join_filter
  361. $where"
  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. );
  372. $recordsTotal = (isset($resTotalLength[0])) ? $resTotalLength[0][0] : 0;
  373. /*
  374. * Output
  375. */
  376. return array(
  377. "draw" => isset ( $request['draw'] ) ?
  378. intval( $request['draw'] ) :
  379. 0,
  380. "recordsTotal" => intval( $recordsTotal ),
  381. "recordsFiltered" => intval( $recordsFiltered ),
  382. "data" => self::data_output( $columns, $data )
  383. );
  384. }
  385. /**
  386. * Connect to the database
  387. *
  388. * @param array $sql_details SQL server connection details array, with the
  389. * properties:
  390. * * host - host name
  391. * * db - database name
  392. * * user - user name
  393. * * pass - user password
  394. * @return resource Database connection handle
  395. */
  396. static function sql_connect ( $sql_details )
  397. {
  398. try {
  399. $db = @new PDO(
  400. "mysql:host={$sql_details['host']};dbname={$sql_details['db']}",
  401. $sql_details['user'],
  402. $sql_details['pass'],
  403. array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION )
  404. );
  405. }
  406. catch (PDOException $e) {
  407. self::fatal(
  408. "An error occurred while connecting to the database. ".
  409. "The error reported by the server was: ".$e->getMessage()
  410. );
  411. }
  412. return $db;
  413. }
  414. /**
  415. * Execute an SQL query on the database
  416. *
  417. * @param resource $db Database handler
  418. * @param array $bindings Array of PDO binding values from bind() to be
  419. * used for safely escaping strings. Note that this can be given as the
  420. * SQL query string if no bindings are required.
  421. * @param string $sql SQL query to execute.
  422. * @return array Result from the query (all rows)
  423. */
  424. static function sql_exec ( $db, $bindings, $sql=null )
  425. {
  426. // Argument shifting
  427. if ( $sql === null ) {
  428. $sql = $bindings;
  429. }
  430. $stmt = $db->prepare( $sql );
  431. // Bind parameters
  432. if ( is_array( $bindings ) ) {
  433. for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) {
  434. $binding = $bindings[$i];
  435. $stmt->bindValue( $binding['key'], $binding['val'], $binding['type'] );
  436. }
  437. }
  438. // Execute
  439. try {
  440. $stmt->execute();
  441. }
  442. catch (PDOException $e) {
  443. self::fatal( "An SQL error occurred: ".$e->getMessage() );
  444. }
  445. // Return all
  446. return $stmt->fetchAll( PDO::FETCH_BOTH );
  447. }
  448. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  449. * Internal methods
  450. */
  451. /**
  452. * Throw a fatal error.
  453. *
  454. * This writes out an error message in a JSON string which DataTables will
  455. * see and show to the user in the browser.
  456. *
  457. * @param string $msg Message to send to the client
  458. */
  459. static function fatal ( $msg )
  460. {
  461. echo json_encode( array(
  462. "error" => $msg
  463. ) );
  464. exit(0);
  465. }
  466. /**
  467. * Create a PDO binding key which can be used for escaping variables safely
  468. * when executing a query with sql_exec()
  469. *
  470. * @param array &$a Array of bindings
  471. * @param * $val Value to bind
  472. * @param int $type PDO field type
  473. * @return string Bound key to be used in the SQL where this parameter
  474. * would be used.
  475. */
  476. static function bind ( &$a, $val, $type )
  477. {
  478. $key = ':binding_'.count( $a );
  479. $a[] = array(
  480. 'key' => $key,
  481. 'val' => $val,
  482. 'type' => $type
  483. );
  484. return $key;
  485. }
  486. static function add_bindings(&$bindings, $vals)
  487. {
  488. foreach($vals['bindings'] as $key => $value) {
  489. $bindings[] = array(
  490. 'key' => $key,
  491. 'val' => $value,
  492. 'type' => PDO::PARAM_STR
  493. );
  494. }
  495. }
  496. /**
  497. * Pull a particular property from each assoc. array in a numeric array,
  498. * returning and array of the property values from each item.
  499. *
  500. * @param array $a Array to get data from
  501. * @param string $prop Property to read
  502. * @return array Array of property values
  503. */
  504. static function pluck ( $a, $prop )
  505. {
  506. $out = array();
  507. for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
  508. if ( empty($a[$i][$prop]) && $a[$i][$prop] !== 0 ) {
  509. continue;
  510. }
  511. if ( $prop == 'db' && isset($a[$i]['dummy']) && $a[$i]['dummy'] === true ) {
  512. continue;
  513. }
  514. //removing the $out array index confuses the filter method in doing proper binding,
  515. //adding it ensures that the array data are mapped correctly
  516. $out[$i] = $a[$i][$prop];
  517. }
  518. return $out;
  519. }
  520. /**
  521. * Return a string from an array or a string
  522. *
  523. * @param array|string $a Array to join
  524. * @param string $join Glue for the concatenation
  525. * @return string Joined string
  526. */
  527. static function _flatten ( $a, $join = ' AND ' )
  528. {
  529. if ( ! $a ) {
  530. return '';
  531. }
  532. else if ( $a && is_array($a) ) {
  533. return implode( $join, $a );
  534. }
  535. return $a;
  536. }
  537. }