forked from lazymofo/datagrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlazy_mofo.php
2774 lines (1978 loc) · 107 KB
/
lazy_mofo.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// CRUD datagrid for MySQL and PHP
// MIT License - https://github.com/lazymofo/datagrid
// send feedback or questions iansoko at gmail
// version 2020-12-21
class lazy_mofo{
public $dbh = false; // required, pass the PDO connection object into the constructor
public $table = ''; // required, table for use for sql_insert(), sql_update(), sql_update_grid() and sql_delete()
public $identity_name = ''; // required, column name of id primary key
public $rename = array(); // associative array of column names and friendly names. example: array('prod_id' => 'Product ID')
public $uri_path = ''; // experimental - to specify URI used for WordPress admin plugins, example: http://localhost:80/demo.php
public $absolute_redirect = false; // 2018-06 switched to relative redirects since it should be supported now, also port forwards don't work with absolute redirects
public $query_string_list = ''; // comma delimited list of variable names to carry around in the URL
public $exclude_field = array(); // don't allow users to update or insert into these fields, even if data is posted. place the field name in the key of the array. example: $lm->exclude_field['is_admin'] = '';
public $form_sql = ''; // render form from fields retuned in sql statement. if blank then 'select * from table where identity_name = identity_id' is used. when no record is found then a blank form to ADD a record is displayed
public $form_sql_param = array(); // associative array to bind named parameters to form_sql. use to pass in identity_id when specifiying form_sql.
public $form_input_control = array(); // for form(), define inputs like select boxes, checkboxes, etc. example: $lm->form_input_control['field_name'] = array('type' => 'select', 'sql' => "select id as val, title as opt from table");
public $form_default_value = array(); // for form(), define default values for columns when adding a record. if auto_populate_control = true then this array will be populated from the defaults in the database.
public $form_display_identity = true; // display identity value when editing a record
public $form_additional_html = ''; // add any addition html inside the <form> after the form buttons.
public $form_text_input_size = 35; // size of text inputs on form()
public $grid_sql = ''; // optional, render grid with query result. *important* to display [edit] and [delete] links, the identity must be the last column in the sql statement. include an 'order by' to prevent query parsing errors on complex queries.
public $grid_sql_param = array(); // associative array to bind variables to grid_sql. example: $lm->grid_sql_param(':market_id' => $market_id);
public $grid_default_order_by = ''; // free-form 'order by' clause. Not used if grid_sql is specified. Example: column1 desc, column2 asc
public $grid_input_control = array(); // for grid(), define inputs like select boxes, checkboxes, etc. example: $lm->grid_input_control['field_name'] = array('type' => 'select', 'sql' => "select id as val, title as opt from table");
public $grid_output_control = array(); // for grid(). define outputs like email or document to make a link. example: example: $lm->grid_output_control['field_name'] = array('type' => 'email');
public $grid_multi_delete = false; // display checkboxes on grid to allow for multiple record delete
public $grid_show_search_box = false; // display search field at the top - grid_sql must be altered to accomodate search
public $grid_limit = 200; // pagination limit number of records per page, verion >= 2018-07-10 set to 0 to disable pagination
public $grid_repeat_header_at = 0; // interval of records to repeat header column titles at
public $grid_show_images = false; // option to show images inside the grid, otherwise a link is displayed for --image type
public $grid_ellipse_at = 30; // limit number of characters displayed, set to 0 to disable truncation
public $grid_text_input_size = 10; // size of text input when input is displayed
public $text_input_max_length_default = 0; // global max_length attribute for input. 0 is disabled
public $text_input_max_length = array(); // array of column names to max length integers, optional
public $auto_populate_controls = true; // have get_columns() populate input and output controls according to meta data for types --date, --datetime, --number and --textarea. also, populate default values if user has read access to information_schema.columns
public $on_insert_validate = array(); // example : array('regexp' => '/.+/', 'error_msg' => 'Missing Market Name', 'placeholder' => 'this is required', 'optional' => false);
public $on_update_validate = array(); // regexp may be 'email' or a user defined function, all other parameters optional
public $validate_tip_in_placeholder = true; // allow input placeholder to display validation tip
public $on_insert_user_function = ''; // user function called before data is inserted, updated, or deleteed. return a string error message for server-side validation. Can be used to formating _POST data.
public $on_update_user_function = '';
public $on_delete_user_function = '';
public $on_update_grid_user_function = '';
public $after_insert_user_function = ''; // user function names to be called after data is inserted, updated, or deleted.
public $after_update_user_function = '';
public $after_delete_user_function = '';
public $after_update_grid_user_function = '';
public $cast_user_function = array(); // user function for casting data, example : $lm->cast_function['field_name'] = 'my_casting_function'
public $return_to_edit_after_insert = true; // redirect to edit screen after adding or updating a record. if false, user is sent back to grid view.
public $return_to_insert = true; // redirect to insert (if return_to_edit_after_insert is true)
public $return_to_edit_after_update = true;
public $redirect_using_js = false; // redirect to a page using java-script instead of header modification by means of PHP.
public $charset_mysql = 'utf8mb4'; // charset for mysql communications. was utf8 before version 2017-08-31
public $charset = 'UTF-8'; // charset for output
public $timezone = 'UTC'; // if no timezone is set in the application, then this timezone is set for strtotime. http://php.net/manual/en/timezones.others.php
// image settings
public $upload_width = 400; // 0 height or width means no resizing or cropping
public $upload_height = 400;
public $upload_crop = false; // crop versus resize: resize keeps the original aspect ratio but limits the size of the image
public $thumb_width = 100;
public $thumb_height = 100;
public $thumb_crop = true;
public $image_quality = 80; // image quality when resizing and cropping, 1-100
public $image_style = "style='height: 100px;'"; // apply style to all images displayed. limiting size is nice to keep things orderly.
public $restricted_numeric_input = '/[^0-9\.\-]/';// optional, regular expression of what numbers are allowed to be sent to the database. helpful to remove dollar signs and spaces. many non-US countries use comma instead of decimal points and spaces instead of commas.
public $upload_allow_list = '.mp3 .jpg .jpeg .png .gif .doc .docx .xls .xlsx .txt .pdf'; // space delimted file name extentions. include period
public $export_csv_file_name = '';
public $export_separator = ','; // separator for csv export
public $export_delim = '"'; // delimiter for csv export
public $export_delim_escape = '"'; // if delim is used in content add this string before for escaping
public $delim = '|'; // when using mutiple checkboxes or multipleselect, delimiter for values. to store data non delimited use on_insert_user_function and on_update_user_function to save data.
public $select_first_option_blank = true; // make first option blank on dropdown select and selectmultiple inputs
// start i18n defaults //
// javascript dialogs
public $delete_confirm = 'Are you sure you want to delete this record?';
public $update_grid_confirm = 'Are you sure you want to delete [count] record(s)?';
// validation general error - this is displayed at the top when a validation error occurs
public $validate_text_general = "Missing or Invalid Input";
// form buttons
public $form_add_button = "<input type='submit' value='Add' class='lm_button'>";
public $form_update_button = "<input type='submit' value='Update' class='lm_button'>";
public $form_back_button = "<input type='button' value='< Back' class='lm_button dull' onclick='_back();'>";
public $form_delete_button = "<input type='button' value='Delete' class='lm_button error' onclick='_delete();'>";
// titles in the <th> of top of the edit form
public $form_text_title_add = 'Add Record';
public $form_text_title_edit = 'Edit Record';
public $form_text_record_saved = 'Record Saved';
public $form_text_record_added = 'Record Added';
// links on grid
public $grid_add_link = "<a href='[script_name]action=edit&[qs]' class='lm_grid_add_link'>Add a Record</a>";
public $grid_edit_link = "<a href='[script_name]action=edit&[identity_name]=[identity_id]&[qs]'>[edit]</a>";
public $grid_delete_link = "<a href='#' onclick='return _delete(\"[identity_id]\");'>[delete]</a>";
public $grid_export_link = "<a href='[script_name]_export=1&[qs]' title='Download CSV'>Export</a>";
// search box
public $grid_search_box = "<form action='[script_name]' class='lm_search_box'><input type='text' name='_search' value='[_search]' size='20' class='lm_search_input'><a href='[script_name]' style='margin: 0 10px 0 -20px; display: inline-block;' title='Clear Search'>x</a><input type='submit' class='lm_button lm_search_button' value='Search'><input type='hidden' name='action' value='search'>[query_string_list]</form>";
// grid messages
public $grid_text_record_added = "Record Added";
public $grid_text_changes_saved = "Changes Saved";
public $grid_text_record_deleted = "Record Deleted";
public $grid_text_save_changes = "Save Changes";
public $grid_text_delete = "Delete";
public $grid_text_no_records_found = "No Records Found";
// pagination text
public $pagination_text_use_paging = 'use paging';
public $pagination_text_show_all = 'show all';
public $pagination_text_records = 'Record(s)';
public $pagination_text_go = 'Go';
public $pagination_text_page = 'Page';
public $pagination_text_of = 'of';
public $pagination_text_next = 'Next>';
public $pagination_text_back = '<Back';
// delete upload link text
public $text_delete_image = 'delete image';
public $text_delete_document = 'delete document';
// relative paths for image or documents uploads
// all paths are created at runtime as needed
public $upload_path = 'uploads'; // required when using input types
public $thumb_path = 'thumbs'; // optional, leave blank if you don't need thumbnails
// newly added absolute paths, 2019-09
// if absolute paths are defined then files are uploaded here, relative paths always used on the client side
public $upload_path_absolute = ''; // optional, defaults to $upload_path if not defined
public $thumb_path_absolute = ''; // optional, defaults to $thumb_path if not defined
// output date formats
public $date_out = 'm/d/Y'; // output date, change to d/m/Y for non-us
public $datetime_out = 'm/d/Y h:i A'; // output datetime, change to d/m/Y h:i A for non-us
// end i18n defaults //
public $date_in = 'Y-m-d'; // do not change - input format into database
public $datetime_in = 'Y-m-d H:i:s'; // do not change
private $set_names = false; // do not change - internal flag
function __construct($dbh, $i18n = 'en-us'){
if(!$dbh)
die('Pass in a PDO object connected to the mysql database.');
$this->dbh = $dbh;
$timezone = @date_default_timezone_get();
if($timezone == '' || $timezone == 'UTC')
date_default_timezone_set($this->timezone);
// avoid notices for this noonce token
if(!isset($_SESSION['_csrf']))
$_SESSION['_csrf'] = '';
// load requested internationalization file, en-us is defined above, in this class
if(strlen($i18n) > 0 && $i18n != 'en-us'){
$arr = pathinfo(__FILE__);
$path = $arr['dirname'] . "/i18n/{$i18n}.php";
if(!file_exists($path))
die("Error: Requested file $path does not exists.");
include($path);
}
}
function run(){
// purpose: controller
// change controls into newer format
foreach($this->form_input_control as $column_name => $control)
$this->form_input_control[$column_name] = $this->modernize_control($control, $column_name);
foreach($this->grid_input_control as $column_name => $control)
$this->grid_input_control[$column_name] = $this->modernize_control($control, $column_name);
foreach($this->grid_output_control as $column_name => $control)
$this->grid_output_control[$column_name] = $this->modernize_control($control, $column_name);
// change validation into newer format with keys
foreach($this->on_insert_validate as $column_name => $arr)
$this->on_insert_validate[$column_name] = $this->modernize_validate($arr, $column_name);
foreach($this->on_update_validate as $column_name => $arr)
$this->on_update_validate[$column_name] = $this->modernize_validate($arr, $column_name);
switch($this->get_action()){
case "edit": $this->edit(); break;
case "insert": $this->insert(); break;
case "update": $this->update(); break;
case "update_grid": $this->update_grid(); break;
case "delete": $this->delete(); break;
default: $this->index();
}
}
function edit($error = ''){
// purpose: called from contoller to display form() and add or edit a record
echo $this->form($error);
}
function insert(){
// purpose: called from contoller to display insert() data
$error = '';
// validation system
$is_valid = $this->validate($this->on_insert_validate);
if(!$is_valid)
$error = $this->validate_text_general; //optional general error at the top
// call user function to validate or whatever
if($is_valid && $this->on_insert_user_function != '')
$error = call_user_func($this->on_insert_user_function);
// go back on validation error
if($error != '' || !$is_valid){
$this->edit($error);
return;
}
// insert data
$id = $this->sql_insert();
// user function after insert
if($this->after_insert_user_function != '')
call_user_func($this->after_insert_user_function, $id);
// send user back to edit screen if desired
$action = '';
if($this->return_to_edit_after_insert)
$action = 'action=edit&';
// redirect user
if($this->return_to_insert)
$url = $this->get_uri_path() . "{$action}_success=1&" . $this->get_qs(''); // do carry items defined in query_string_list, '' removes the default
else
$url = $this->get_uri_path() . "{$action}_success=1&$this->identity_name=$id&" . $this->get_qs(''); // do carry items defined in query_string_list, '' removes the default
$this->redirect($url, $id);
}
function update(){
// purpose: called from contoller to display update() data
$error = '';
// validation system
$is_valid = $this->validate($this->on_update_validate);
if(!$is_valid)
$error = $this->validate_text_general; //optional general error at the top
// call user function to validate or whatever
if($is_valid && $this->on_update_user_function != '')
$error = call_user_func($this->on_update_user_function);
// go back on validation error
if($error != '' || !$is_valid){
$this->edit($error);
return;
}
// update data
$id = $this->sql_update();
// user function after update
if($this->after_update_user_function != '')
call_user_func($this->after_update_user_function);
// send user back to edit screen if desired
$action = '';
if($this->return_to_edit_after_update)
$action = 'action=edit&';
// redirect user
$url = $this->get_uri_path() . "{$action}_success=2&$this->identity_name=$id&" . $this->get_qs();
$this->redirect($url, $id);
}
function update_grid(){
// purpose: called from contoller to display update() data
// call user function to validate or whatever
$error = '';
if($this->on_update_grid_user_function != '')
$error = call_user_func($this->on_update_grid_user_function);
// go back on validation error
if($error != ''){
$this->index($error);
return;
}
// update data
$flag = $this->sql_update_grid();
// user function after updates
if($this->after_update_grid_user_function != '')
call_user_func($this->after_update_grid_user_function);
// redirect user
$url = $this->get_uri_path() . "_success=2&" . $this->get_qs();
$this->redirect($url, $flag);
}
function delete(){
// purpose: called from contoller to display update() data
// call user function to validate or whatever
$error = '';
if($this->on_delete_user_function != '')
$error = call_user_func($this->on_delete_user_function);
// go back on validation error
if($error != ''){
if($_POST['_called_from'] == 'form')
$this->edit($error);
else
$this->index($error);
return;
}
// delete data
$flag = $this->sql_delete();
// user function after delete
if($this->after_delete_user_function != '')
call_user_func($this->after_delete_user_function);
// redirect user
$url = $this->get_uri_path() . "_success=3&" . $this->get_qs();
$this->redirect($url, $flag);
}
function index($error = ''){
// purpose: called from contoller to display update() data
echo $this->grid($error);
}
function sql_delete(){
// purpose: delete the requested record
// returns: false on error, true on success
$identity_id = $this->cast_id($_POST[$this->identity_name]);
if($identity_id == 0){
$this->display_error("missing identity_value", 'delete()');
return false;
}
if(!$this->upload_delete($this->table, $this->identity_name, $identity_id, '*', $this->form_input_control))
return false;
$sql_param = array(':identity_id' => $identity_id);
$sql = "delete from `$this->table` where `$this->identity_name` = :identity_id limit 1";
if($this->query($sql, $sql_param, 'delete()') === false)
return false;
}
function sql_insert(){
// purpose: generate insert sql statement from the data posted and table's meta data
// returns: false on error, id returned on success
$columns = $this->get_columns();
$prev_key = null;
if(mb_strlen($this->table) == 0 || count($columns) == 0){
$this->display_error("missing tablename, or get_columns() failed", 'insert()');
return false;
}
// format list of fields from posted data
$sql_fields = '';
foreach($_POST as $key => $val){
// checkboxes require a special hidden field to identify unchecked values
if(mb_substr($key, -9) == '-checkbox')
if(mb_substr($key, 0, -9) != $prev_key)
$key = mb_substr($key, 0, -9);
// same as above but for -selectmultiple
if(mb_substr($key, -15) == '-selectmultiple')
if(mb_substr($key, 0, -15) != $prev_key)
$key = mb_substr($key, 0, -15);
$prev_key = $key;
if(!(array_search($key, $columns) === false))
$sql_fields .= "`$key`, ";
}
$sql_fields = rtrim($sql_fields, ', ');
// format list of values from posted data
$sql_param = array();
$sql_values = '';
foreach($_POST as $key => $val){
// don't allow updates on certain fields
if(array_key_exists($key, $this->exclude_field))
continue;
// checkboxes require a special hidden field to identify unchecked values
if(mb_substr($key, -9) == '-checkbox')
if(mb_substr($key, 0, -9) != $prev_key)
$key = mb_substr($key, 0, -9);
// same as above but for -selectmultiple
if(mb_substr($key, -15) == '-selectmultiple')
if(mb_substr($key, 0, -15) != $prev_key)
$key = mb_substr($key, 0, -15);
if(!(array_search($key, $columns) === false)){
$safe_np = $this->safe_np($key);
$sql_values .= ":$safe_np, ";
$sql_param[":$safe_np"] = $this->cast_value($val, $key);
}
$prev_key = $key;
}
$sql_values = rtrim($sql_values, ', ');
$sql = "insert into `$this->table` ($sql_fields) values ($sql_values);";
$identity_id = $this->query($sql, $sql_param, 'insert()');
if($identity_id === false)
return false;
if(!$this->get_upload($columns, $this->table, $this->identity_name, $identity_id))
return false;
return $identity_id;
}
function sql_update(){
// purpose: generate and run update sql statement from the data posted and table's meta data
// returns: false on error, true on success
$columns = $this->get_columns();
$identity_id = $this->cast_id($_POST[$this->identity_name]);
if(mb_strlen($this->table) == 0 || $identity_id == 0 || count($columns) == 0){
$this->display_error("missing tablename, or missing identity_value, or get_columns() failed", 'sql_update()');
return false;
}
// posted values are saved here for pdo execute
$sql_param = array();
$sql_param[':identity_id'] = $identity_id;
// make sql statement from key and values in $_POST data
$sql_set = '';
foreach($_POST as $key => $val){
// don't allow updates on certain fields
if(array_key_exists($key, $this->exclude_field))
continue;
// checkboxes require a special hidden field so unchecked values are detectable
if(mb_substr($key, -9) == '-checkbox')
if(!array_key_exists(mb_substr($key, 0, -9), $_POST)) // add key if none exists already
$key = mb_substr($key, 0, -9);
// same as above, but for selectmultiple
if(mb_substr($key, -15) == '-selectmultiple')
if(!array_key_exists(mb_substr($key, 0, -15), $_POST))
$key = mb_substr($key, 0, -15);
if(!(array_search($key, $columns) === false)){
$safe_np = $this->safe_np($key);
$sql_set .= "`$key` = :$safe_np, ";
$sql_param[":$safe_np"] = $this->cast_value($val, $key);
}
}
$sql_set = rtrim($sql_set, ', ');
// run sql update
if($sql_set != ''){
$sql_final = "update `$this->table` set $sql_set where `$this->identity_name` = :identity_id;";
if($this->query($sql_final, $sql_param, 'update()') === false)
return false;
}
if(!$this->get_upload($columns, $this->table, $this->identity_name, $identity_id))
return false;
return $identity_id;
}
function sql_update_grid(){
// purpose: generate multiple update sql statements from editable fields in grid()
// returns: false on error, true on success
$columns = $this->get_columns('grid');
$skip_update_on_column_name = '';
$table = $this->table;
$identity_name = $this->identity_name;
$input_control = $this->grid_input_control;
if(mb_strlen($table) == 0 || count($columns) == 0 || (count($input_control) == 0 && $this->grid_multi_delete == false)){
$this->display_error("missing table name, or get_columns(), or grid_input_control is empty", 'update_grid()');
return false;
}
// optimization
$run_upload = false;
foreach($input_control as $column_name => $ctrl)
if($this->is_upload($input_control, $column_name))
$run_upload = true;
// gather all identity ids from suffix of input_name-identity_id
$arr_identity_id = array();
$prev_identity_id = 0;
$post = array_merge($_POST, $_FILES);
foreach($post as $key => $val){
if(!mb_strstr($key, '-'))
continue;
$identity_id = $this->cast_id(mb_substr($key, mb_strrpos($key, '-') + 1));
if($identity_id == 0)
continue;
if($identity_id != $prev_identity_id)
array_push($arr_identity_id, $identity_id);
$prev_identity_id = $identity_id;
}
// run updates
$sql_final = '';
$sql_param = array();
$this->dbh->beginTransaction();
foreach($arr_identity_id as $identity_id){
$sql_set = '';
$sql_param[':identity_id'] = $identity_id;
// loop thur editable columns
foreach($input_control as $column_name => $control){
if(array_search($column_name, $columns) === false)
continue;
if($column_name == $skip_update_on_column_name)
continue;
if($this->is_upload($input_control, $column_name))
continue;
$safe_np = $this->safe_np($column_name);
$sql_set .= "`$column_name` = :$safe_np, ";
$sql_param[":$safe_np"] = $this->cast_value(@$_POST["$column_name-$identity_id"], $column_name, 'grid');
}
// append statements
if(mb_strlen($sql_set) > 0){
$sql_set = rtrim($sql_set, ', ');
$sql_final = "update `$table` set $sql_set where `$identity_name` = :identity_id;\n";
if($this->query($sql_final, $sql_param, 'sql_update_grid()') === false)
return false;
$sql_param = array();
}
}
$this->dbh->commit();
// upload files
if($run_upload)
foreach($arr_identity_id as $identity_id)
$this->get_upload($columns, $table, $identity_name, $identity_id, 'grid');
// get records to delete
$arr_delete = @$_POST['_delete'];
if(!is_array($arr_delete))
$arr_delete = array();
// delete records
$sql = '';
$sql_param = array();
foreach($arr_delete as $identity_id){
if($run_upload)
$this->upload_delete($table, $identity_name, $identity_id, '*', $input_control);
$sql = "delete from `$table` where `$identity_name` = :identity_id;";
$sql_param = array(':identity_id' => $identity_id);
if($this->query($sql, $sql_param, 'sql_update_grid() - delete') === false)
return false;
}
return true;
}
function form($error = ''){
// purpose: generate a form to edit or add a record
// if a record is found the form will be populated for editing, otherwise the form is empty and form is for adding/inserting data
// $error = error message to display before form, often from server-side validation
// returns: html
if(mb_strlen($this->identity_name) == 0)
return $this->display_error("property: identity_name must be set", 'form()');
if(mb_strlen($this->form_sql) == 0 && mb_strlen($this->table) == 0)
return $this->display_error("property: form_sql or table must be set", 'form()');
$identity_id = $this->cast_id(@$_GET[$this->identity_name]);
if($identity_id == 0)
$identity_id = $this->cast_id(@$_POST[$this->identity_name]);
$sql = $this->form_sql;
$sql_param = $this->form_sql_param;
// make sql statement from table name if no sql was provided
if(mb_strlen($sql) == 0){
$sql_param = array(':identity_id' => $identity_id);
$sql = "select * from `$this->table` where `$this->identity_name` = :identity_id";
}
// run query
$result = $this->query($sql, $sql_param, 'form()');
// quit on error
if($result === false)
return;
$columns = $this->get_columns('form');
$count = count($result);
$_posted = intval(@$_POST['_posted']);
// success messages
$success = intval(@$_GET['_success']);
if($success == 1)
$success = $this->form_text_record_added;
elseif($success == 2)
$success = $this->form_text_record_saved;
else
$success = '';
// are we adding (blank form) or editing (populated form) a record
if($count == 0){
$action = 'add';
$title = $this->form_text_title_add;
$validate = $this->on_insert_validate;
}
else{
$action = 'edit';
$title = $this->form_text_title_edit;
$validate = $this->on_update_validate;
}
// get 1 row of data if available
$row = false;
$identity_id = 0; // id fetched below
if(count($result) > 0){
$row = $result[0];
$identity_id = $this->cast_id($row[$this->identity_name]);
}
if($action == 'edit' && $identity_id == 0)
$error .= "Missing identity_id. If using a custom form_sql statement be sure to include the identity. ";
// query string is used here in form() to maintain pagination and sort data so user can return back to the same place in grid results
$qs = $this->get_qs();
if(mb_strlen($qs) > 0)
$qs = "$qs";
$uri_path = $this->get_uri_path();
$html = "<div id='lm'>\n";
$html .= "<form action='$uri_path$qs' method='post' enctype='multipart/form-data'>\n";
$html .= "<input type='hidden' name='_csrf' value='$_SESSION[_csrf]'>\n";
$html .= "<input type='hidden' name='_posted' value='1'>\n";
if(mb_strlen($error) > 0)
$html .= "<div class='lm_error'><b>$error</b></div>\n";
if(mb_strlen($success) > 0)
$html .= "<div class='lm_success'><b>$success</b></div>\n";
$html .= "<table id='lm_table' cellpadding='2' cellspacing='1' border='0' class='lm_form'>\n";
if(mb_strlen($title) > 0)
$html .= "<tr>\n <th colspan='2'>$title</th>\n</tr>\n";
// loop thru fields
foreach($columns as $column_name){
if($column_name == $this->identity_name && ($this->form_display_identity == false || $action == 'add'))
continue;
// get data from database or repost
if($_posted == 1 && @$this->form_input_control[$column_name]['type'] != 'readonly')
$value = @$_POST[$column_name];
elseif($count == 0)
$value = @$this->form_default_value[$column_name];
else
$value = $row[$column_name];
// field label
$title = $this->format_title($column_name, @$this->rename[$column_name]);
// render the html control according to the type of data
$control = "";
if($column_name == $this->identity_name)
$control = $this->clean_out($value);
elseif(array_key_exists($column_name, $this->form_input_control))
$control = $this->get_input_control($column_name, $value, $this->form_input_control[$column_name], 'form', $validate);
else
$control = $this->get_input_control($column_name, $value, null, 'form', $validate);
$html .= "<tr>\n";
$html .= " <td>$title:</td>\n";
$html .= " <td>$control</td>\n";
$html .= "</tr>\n";
}
$html .= "</table>\n";
if($action == 'edit')
$html .= "<input type='hidden' name='$this->identity_name' value='$identity_id'>\n";
// action
if($action == 'edit')
$html .= "<input type='hidden' name='action' value='update'>\n";
else
$html .= "<input type='hidden' name='action' value='insert'>\n";
// add buttons
if($action == 'edit')
$html .= "<div class='lm_form_button_bar'>$this->form_back_button $this->form_delete_button $this->form_update_button</div>";
else
$html .= "<div class='lm_form_button_bar'>$this->form_back_button $this->form_add_button</div>";
$html .= $this->form_additional_html;
$html .= "</form>\n";
$html .= "</div><!-- close #lm -->\n";
$html .= $this->delete_js($identity_id, 'form');
return $html;
}
function grid($error = ''){
// purpose: function to list a table of records. aka data grid
// returns: html
// populate_from_post tells inputs to populate from $_POST instead of the database. useful to preserve data when displaying validation errors.
// in grid_sql, select the identity_id as the last column to display the edit and delete links
// example: $lm->grid_sql = 'select title, create_date, foo_id from foo';
if(mb_strlen($this->identity_name) == 0 || (mb_strlen($this->grid_sql) && mb_strlen($this->table) == 0)){
$this->display_error("missing grid_sql and table (one is required), or missing identity_name", 'form()');
return;
}
// local copies
$sql = trim($this->grid_sql);
$sql_param = $this->grid_sql_param;
$grid_limit = intval($this->grid_limit);
$uri_path = $this->get_uri_path();
$default_order_by = $this->grid_default_order_by;
if($default_order_by == '')
$default_order_by = "`$this->identity_name`";
// remove line feeds which can cause problems with parsing
$sql = preg_replace('/[\n\r]/', ' ', $sql);
// default queries if only table and id names were provided
if(mb_strlen($sql) == 0)
$sql = "select *, `$this->identity_name` from `$this->table` order by $default_order_by";
// inject funciton for counting
$sql = preg_replace('/^select/i', 'select sql_calc_found_rows', $sql);
// get input
$_posted = intval(@$_REQUEST['_posted']);
$_search = $this->clean_out(@$_REQUEST['_search']);
$_pagination_off = intval(@$_REQUEST['_pagination_off']);
$_order_by = abs(intval(@$_REQUEST['_order_by'])); // order by is numeric index to column
$_desc = abs(intval(@$_REQUEST['_desc'])); // descending order flag
$_offset = abs(intval(@$_REQUEST['_offset'])); // pagination offset
$_export = intval(@$_REQUEST['_export']);
$qs = $this->get_qs();
// header links - invert current sort
$_desc_invert = 1;
if($_desc == 1)
$_desc_invert = 0;
// success messages
$success = intval(@$_GET['_success']);
if($success == 1)
$success = $this->grid_text_record_added;
elseif($success == 2)
$success = $this->grid_text_changes_saved;
elseif($success == 3)
$success = $this->grid_text_record_deleted;
else
$success = '';
// column array and column count
$columns = $this->get_columns('grid');
$column_count = count($columns);
if($column_count == 0)
return;
// alter order
$desc_str = '';
if($_order_by > 0){
if($_desc == 1)
$desc_str = 'desc';
$sql = rtrim($sql, '; '); // remove last semicolon
// try to remove last 'order by'. we need to allow functions in order by and order by in subqueries
$this->mb_preg_match_all('/order\s+by\s/im', $sql, $matches, PREG_OFFSET_CAPTURE);
if(count($matches) > 0){
$match = end($matches[0]);
$sql = mb_substr($sql, 0, $match[1]);
}
$sql .= " order by $_order_by $desc_str"; // add requested sort order
}
// remove existing limit
$sql = preg_replace('/\s+limit\s+[0-9,\s]+$/i', '', $sql);
// add limit and offset for pagination
if($_pagination_off == 0 && $_export == 0 && $grid_limit > 0)
$sql .= " limit $_offset, $grid_limit";
// run query
$result = $this->query($sql, $sql_param, 'grid() run query');
if(!is_array($result))
$result = array();
// get count
$count = 0;
$sql = 'select found_rows() as cnt';
$result_count = $this->query($sql);
foreach($result_count as $row)
$count = $row['cnt'];
// export data to CSV and quit
if($_export == 1 && $count > 0){
$this->export($result, $columns);
return;
}
// populate link placeholders
$grid_add_link = $this->grid_add_link;
$grid_edit_link = $this->grid_edit_link;
$grid_delete_link = $this->grid_delete_link;
$grid_export_link = $this->grid_export_link;
$grid_add_link = str_replace('[script_name]', $uri_path, $grid_add_link);
$grid_add_link = str_replace('[qs]', $qs, $grid_add_link);
$grid_edit_link = str_replace('[script_name]', $uri_path, $grid_edit_link);
$grid_edit_link = str_replace('[qs]', $qs, $grid_edit_link);
$grid_edit_link = str_replace('[identity_name]', $this->identity_name, $grid_edit_link);
$grid_delete_link = str_replace('[script_name]', $uri_path, $grid_delete_link);
$grid_delete_link = str_replace('[qs]', $qs, $grid_delete_link);
$grid_delete_link = str_replace('[identity_name]', $this->identity_name, $grid_delete_link);
$grid_export_link = str_replace('[script_name]', $uri_path, $grid_export_link);
$grid_export_link = str_replace('[qs]', $qs, $grid_export_link);
$links = $grid_edit_link . ' ' . $grid_delete_link;
// pagination and save changes link bar
$pagination = $this->get_pagination($count, $grid_limit, $_offset, $_pagination_off);
$button = '';
if(count($this->grid_input_control) > 0 || $this->grid_multi_delete == true)
$button = "<input type='submit' name='__update_grid' value='$this->grid_text_save_changes' class='lm_button lm_save_changes_button'>";
$pagination_button_bar = "<table cellpadding='2' cellspacing='1' border='0' width='100%' class='lm_pagination'><tr><td style='text-align: left'>$pagination</td><td style='text-align: right'>$button</td></tr></table>\n";
// search bar
$search_box = '';
if($this->grid_show_search_box){
// carry values defined in query_string_list
$query_string_list_inputs = '';
if(mb_strlen($this->query_string_list) > 0){
$arr = explode(',', trim($this->query_string_list, ', '));
foreach($arr as $val)
$query_string_list_inputs .= "<input type='hidden' name='$val' value='" . $this->clean_out(@$_REQUEST[$val]) . "'>";
}
$search_box = $this->grid_search_box;
$search_box = str_replace('[script_name]', $uri_path . $this->get_qs('') , $search_box); // for 'x' cancel do add get_qs('') to carry query_string_list
$search_box = str_replace('[_search]', $_search, $search_box);
$search_box = str_replace('[_csrf]', $_SESSION['_csrf'], $search_box);
$search_box = str_replace('[query_string_list]', $query_string_list_inputs, $search_box);
}
$add_record_search_bar = "<table cellpadding='2' cellspacing='1' border='0' width='100%' class='lm_add_search'><tr><td style='text-align: left'>$grid_add_link $grid_export_link</td><td style='text-align: right'>$search_box</td></tr></table>\n";
// generate table header
$head = "<tr>\n";
if($this->grid_multi_delete)
$head .= "<th><a href='#' onclick='return _toggle();' title='toggle checkboxes'>$this->grid_text_delete</a></th>\n";
$i = 0;
foreach($columns as $column_name){
$title = $this->format_title($column_name, @$this->rename[$column_name]);
if($column_name == $this->identity_name && $i == ($column_count - 1))
$head .= " <th></th>\n"; // if identity is last column then this is the column with the edit and delete links
else
$head .= " <th><a href='{$uri_path}_order_by=" . ($i + 1) . "&_desc=$_desc_invert&" . $this->get_qs('_search') . "'>$title</a></th>\n";
$i++;
}
$head .= "</tr>\n";
// start generating output //
$html = "<div id='lm'>\n";