ssp.class.php 16 KB

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