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