/
incFunctions.php
2481 lines (2178 loc) · 91.9 KB
/
incFunctions.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
########################################################################
/*
~~~~~~ LIST OF FUNCTIONS ~~~~~~
set_headers() -- sets HTTP headers (encoding, same-origin frame policy, .. etc)
getTableList() -- returns an associative array of all tables in this application in the format tableName=>tableCaption
getThumbnailSpecs($tableName, $fieldName, $view) -- returns an associative array specifying the width, height and identifier of the thumbnail file.
createThumbnail($img, $specs) -- $specs is an array as returned by getThumbnailSpecs(). Returns true on success, false on failure.
makeSafe($string)
checkPermissionVal($pvn)
sql($statement, $o)
sqlValue($statement)
getLoggedAdmin()
checkUser($username, $password)
logOutUser()
getPKFieldName($tn)
getCSVData($tn, $pkValue, $stripTag=true)
errorMsg($msg)
redirect($URL, $absolute=FALSE)
htmlRadioGroup($name, $arrValue, $arrCaption, $selectedValue, $selClass="", $class="", $separator="<br>")
htmlSelect($name, $arrValue, $arrCaption, $selectedValue, $class="", $selectedClass="")
htmlSQLSelect($name, $sql, $selectedValue, $class="", $selectedClass="")
isEmail($email) -- returns $email if valid or false otherwise.
notifyMemberApproval($memberID) -- send an email to member acknowledging his approval by admin, returns false if no mail is sent
setupMembership() -- check if membership tables exist or not. If not, create them.
thisOr($this_val, $or) -- return $this_val if it has a value, or $or if not.
getUploadedFile($FieldName, $MaxSize=0, $FileTypes='csv|txt', $NoRename=false, $dir='')
toBytes($val)
convertLegacyOptions($CSVList)
getValueGivenCaption($query, $caption)
time24($t) -- return time in 24h format
time12($t) -- return time in 12h format
application_url($page) -- return absolute URL of provided page
is_ajax() -- return true if this is an ajax request, false otherwise
array_trim($arr) -- recursively trim provided value/array
is_allowed_username($username, $exception = false) -- returns username if valid and unique, or false otherwise (if exception is provided and same as username, no uniqueness check is performed)
csrf_token($validate) -- csrf-proof a form
get_plugins() -- scans for installed plugins and returns them in an array ('name', 'title', 'icon' or 'glyphicon', 'admin_path')
maintenance_mode($new_status = '') -- retrieves (and optionally sets) maintenance mode status
html_attr($str) -- prepare $str to be placed inside an HTML attribute
html_attr_tags_ok($str) -- same as html_attr, but allowing HTML tags
Notification() -- class for providing a standardized html notifications functionality
sendmail($mail) -- sends an email using PHPMailer as specified in the assoc array $mail( ['to', 'name', 'subject', 'message', 'debug'] ) and returns true on success or an error message on failure
safe_html($str, $noBr = false) -- sanitize HTML strings, and apply nl2br() to non-HTML ones (unless optional 2nd param is passed as true)
get_tables_info($skip_authentication = false) -- retrieves table properties as a 2D assoc array ['table_name' => ['prop1' => 'val', ..], ..]
getLoggedMemberID() -- returns memberID of logged member. If no login, returns anonymous memberID
getLoggedGroupID() -- returns groupID of logged member, or anonymous groupID
getMemberInfo() -- returns an array containing the currently signed-in member's info
get_group_id($user = '') -- returns groupID of given user, or current one if empty
prepare_sql_set($set_array, $glue = ', ') -- Prepares data for a SET or WHERE clause, to be used in an INSERT/UPDATE query
insert($tn, $set_array) -- Inserts a record specified by $set_array to the given table $tn
update($tn, $set_array, $where_array) -- Updates a record identified by $where_array to date specified by $set_array in the given table $tn
set_record_owner($tn, $pk, $user) -- Set/update the owner of given record
app_datetime_format($destination = 'php', $datetime = 'd') -- get date/time format string for use with one of these: 'php' (see date function), 'mysql', 'moment'. $datetime: 'd' = date, 't' = time, 'dt' = both
mysql_datetime($app_datetime) -- converts $app_datetime to mysql-formatted datetime, 'yyyy-mm-dd H:i:s', or empty string on error
app_datetime($mysql_datetime, $datetime = 'd') -- converts $mysql_datetime to app-formatted datetime (if 2nd param is 'dt'), or empty string on error
to_utf8($str) -- converts string from app-configured encoding to utf8
from_utf8($str) -- converts string from utf8 to app-configured encoding
membership_table_functions() -- returns a list of update_membership_* functions
configure_anonymous_group() -- sets up anonymous group and guest user if necessary
configure_admin_group() -- sets up admins group and super admin user if necessary
get_table_keys($tn) -- returns keys (indexes) of given table
get_table_fields($tn) -- returns fields spec for given table
update_membership_{tn}() -- sets up membership table tn and its indexes if necessary
test($subject, $test) -- perform a test and return results
invoke_method($object, $methodName, $param_array) -- invoke a private/protected method of a given object
invoke_static_method($class, $methodName, $param_array) -- invoke a private/protected method of a given class statically
get_parent_tables($tn) -- returns parents of given table: ['parent table' => [main lookup fields in child], ..]
backtick_keys_once($data) -- wraps keys of given array with backticks ` if not already wrapped. Useful for use with fieldnames passed to update() and insert()
calculated_fields() -- returns calculated fields config array: [table => [field => query, ..], ..]
update_calc_fields($table, $id, $formulas, $mi = false) -- updates record of given $id in given $table according to given $formulas on behalf of user specified in given info array (or current user if false)
latest_jquery() -- detects and returns the name of the latest jQuery file found in resources/jquery/js
existing_value($tn, $fn, $id, $cache = true) -- returns (cached) value of field $fn of record having $id in table $tn. Set $cache to false to bypass caching.
checkAppRequirements() -- if PHP doesn't meet app requirements, outputs error and exits
getRecord($table, $id) -- return the record having a PK of $id from $table as an associative array, falsy value on error/not found
guessMySQLDateTime($dt) -- if $dt is not already a mysql date/datetime, use mysql_datetime() to convert then return mysql date/datetime. Returns false if $dt invalid or couldn't be detected.
pkGivenLookupText($val, $tn, $lookupField, $falseIfNotFound) -- returns corresponding PK value for given $val which is the textual lookup value for given $lookupField in given $tn table. If $val has no corresponding PK value, $val is returned as-is, unless $falseIfNotFound is set to true, in which case false is returned.
userCanImport() -- returns true if user (or his group) can import CSV files (through the permission set in the group page in the admin area).
bgStyleToClass($html) -- replaces bg color 'style' attr with a class to prevent style loss on xss cleanup.
assocArrFilter($arr, $func) -- filters provided array using provided callback function. The callback receives 2 params ($key, $value) and should return a boolean.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
########################################################################
function set_headers() {
@header('Content-Type: text/html; charset=' . datalist_db_encoding);
@header('X-Frame-Options: SAMEORIGIN'); // prevent iframing by other sites to prevent clickjacking
}
########################################################################
function get_tables_info($skip_authentication = false) {
static $all_tables = [], $accessible_tables = [];
/* return cached results, if found */
if(($skip_authentication || getLoggedAdmin()) && count($all_tables)) return $all_tables;
if(!$skip_authentication && count($accessible_tables)) return $accessible_tables;
/* table groups */
$tg = array(
'None'
);
$all_tables = array(
/* ['table_name' => [table props assoc array] */
'invoices' => array(
'Caption' => 'Invoices',
'Description' => '',
'tableIcon' => 'resources/table_icons/attributes_display.png',
'group' => $tg[0],
'homepageShowCount' => 1
),
'clients' => array(
'Caption' => 'Clients',
'Description' => '',
'tableIcon' => 'resources/table_icons/administrator.png',
'group' => $tg[0],
'homepageShowCount' => 1
),
'item_prices' => array(
'Caption' => 'Prices History',
'Description' => '',
'tableIcon' => 'resources/table_icons/card_money.png',
'group' => $tg[0],
'homepageShowCount' => 0
),
'invoice_items' => array(
'Caption' => 'Invoice items',
'Description' => '',
'tableIcon' => 'resources/table_icons/barcode.png',
'group' => $tg[0],
'homepageShowCount' => 0
),
'items' => array(
'Caption' => 'Items',
'Description' => '',
'tableIcon' => 'resources/table_icons/installer_box.png',
'group' => $tg[0],
'homepageShowCount' => 1
),
);
if($skip_authentication || getLoggedAdmin()) return $all_tables;
foreach($all_tables as $tn => $ti) {
$arrPerm = getTablePermissions($tn);
if($arrPerm['access']) $accessible_tables[$tn] = $ti;
}
return $accessible_tables;
}
#########################################################
if(!function_exists('getTableList')) {
function getTableList($skip_authentication = false) {
$arrTables = array(
'invoices' => 'Invoices',
'clients' => 'Clients',
'item_prices' => 'Prices History',
'invoice_items' => 'Invoice items',
'items' => 'Items',
);
return $arrTables;
}
}
########################################################################
function getThumbnailSpecs($tableName, $fieldName, $view) {
return FALSE;
}
########################################################################
function createThumbnail($img, $specs) {
$w = $specs['width'];
$h = $specs['height'];
$id = $specs['identifier'];
$path = dirname($img);
// image doesn't exist or inaccessible?
if(!$size = @getimagesize($img)) return false;
// calculate thumbnail size to maintain aspect ratio
$ow = $size[0]; // original image width
$oh = $size[1]; // original image height
$twbh = $h / $oh * $ow; // calculated thumbnail width based on given height
$thbw = $w / $ow * $oh; // calculated thumbnail height based on given width
if($w && $h) {
if($twbh > $w) $h = $thbw;
if($thbw > $h) $w = $twbh;
} elseif($w) {
$h = $thbw;
} elseif($h) {
$w = $twbh;
} else {
return false;
}
// dir not writeable?
if(!is_writable($path)) return false;
// GD lib not loaded?
if(!function_exists('gd_info')) return false;
$gd = gd_info();
// GD lib older than 2.0?
preg_match('/\d/', $gd['GD Version'], $gdm);
if($gdm[0] < 2) return false;
// get file extension
preg_match('/\.[a-zA-Z]{3,4}$/U', $img, $matches);
$ext = strtolower($matches[0]);
// check if supplied image is supported and specify actions based on file type
if($ext == '.gif') {
if(!$gd['GIF Create Support']) return false;
$thumbFunc = 'imagegif';
} elseif($ext == '.png') {
if(!$gd['PNG Support']) return false;
$thumbFunc = 'imagepng';
} elseif($ext == '.jpg' || $ext == '.jpe' || $ext == '.jpeg') {
if(!$gd['JPG Support'] && !$gd['JPEG Support']) return false;
$thumbFunc = 'imagejpeg';
} else {
return false;
}
// determine thumbnail file name
$ext = $matches[0];
$thumb = substr($img, 0, -5) . str_replace($ext, $id . $ext, substr($img, -5));
// if the original image smaller than thumb, then just copy it to thumb
if($h > $oh && $w > $ow) {
return (@copy($img, $thumb) ? true : false);
}
// get image data
if(!$imgData = imagecreatefromstring(implode('', file($img)))) return false;
// finally, create thumbnail
$thumbData = imagecreatetruecolor($w, $h);
//preserve transparency of png and gif images
if($thumbFunc == 'imagepng') {
if(($clr = @imagecolorallocate($thumbData, 0, 0, 0)) != -1) {
@imagecolortransparent($thumbData, $clr);
@imagealphablending($thumbData, false);
@imagesavealpha($thumbData, true);
}
} elseif($thumbFunc == 'imagegif') {
@imagealphablending($thumbData, false);
$transIndex = imagecolortransparent($imgData);
if($transIndex >= 0) {
$transClr = imagecolorsforindex($imgData, $transIndex);
$transIndex = imagecolorallocatealpha($thumbData, $transClr['red'], $transClr['green'], $transClr['blue'], 127);
imagefill($thumbData, 0, 0, $transIndex);
}
}
// resize original image into thumbnail
if(!imagecopyresampled($thumbData, $imgData, 0, 0 , 0, 0, $w, $h, $ow, $oh)) return false;
unset($imgData);
// gif transparency
if($thumbFunc == 'imagegif' && $transIndex >= 0) {
imagecolortransparent($thumbData, $transIndex);
for($y = 0; $y < $h; ++$y)
for($x = 0; $x < $w; ++$x)
if(((imagecolorat($thumbData, $x, $y) >> 24) & 0x7F) >= 100) imagesetpixel($thumbData, $x, $y, $transIndex);
imagetruecolortopalette($thumbData, true, 255);
imagesavealpha($thumbData, false);
}
if(!$thumbFunc($thumbData, $thumb)) return false;
unset($thumbData);
return true;
}
########################################################################
function makeSafe($string, $is_gpc = true) {
static $cached = []; /* str => escaped_str */
if(!strlen($string)) return '';
if(!db_link()) sql("SELECT 1+1", $eo);
// if this is a previously escaped string, return from cached
// checking both keys and values
if(isset($cached[$string])) return $cached[$string];
$key = array_search($string, $cached);
if($key !== false) return $string; // already an escaped string
$cached[$string] = db_escape($string);
return $cached[$string];
}
########################################################################
function checkPermissionVal($pvn) {
// fn to make sure the value in the given POST variable is 0, 1, 2 or 3
// if the value is invalid, it default to 0
$pvn=intval($_POST[$pvn]);
if($pvn!=1 && $pvn!=2 && $pvn!=3) {
return 0;
} else {
return $pvn;
}
}
########################################################################
function dieErrorPage($error) {
global $Translation;
$header = (defined('ADMIN_AREA') ? __DIR__ . '/incHeader.php' : __DIR__ . '/../header.php');
$footer = (defined('ADMIN_AREA') ? __DIR__ . '/incFooter.php' : __DIR__ . '/../footer.php');
ob_start();
@include_once($header);
echo Notification::placeholder();
echo Notification::show([
'message' => $error,
'class' => 'danger',
'dismiss_seconds' => 7200
]);
@include_once($footer);
echo ob_get_clean();
exit;
}
########################################################################
function openDBConnection(&$o) {
static $connected = false, $db_link;
$dbServer = config('dbServer');
$dbUsername = config('dbUsername');
$dbPassword = config('dbPassword');
$dbDatabase = config('dbDatabase');
if($connected) return $db_link;
/****** Check that MySQL module is enabled ******/
if(!extension_loaded('mysql') && !extension_loaded('mysqli')) {
$o['error'] = 'PHP is not configured to connect to MySQL on this machine. Please see <a href="https://www.php.net/manual/en/ref.mysql.php">this page</a> for help on how to configure MySQL.';
if($o['silentErrors']) return false;
dieErrorPage($o['error']);
}
/****** Connect to MySQL ******/
if(!($db_link = @db_connect($dbServer, $dbUsername, $dbPassword))) {
$o['error'] = db_error($db_link, true);
if($o['silentErrors']) return false;
dieErrorPage($o['error']);
}
/****** Select DB ********/
if(!db_select_db($dbDatabase, $db_link)) {
$o['error'] = db_error($db_link);
if($o['silentErrors']) return false;
dieErrorPage($o['error']);
}
$connected = true;
return $db_link;
}
########################################################################
function sql($statement, &$o) {
/*
Supported options that can be passed in $o options array (as array keys):
'silentErrors': If true, errors will be returned in $o['error'] rather than displaying them on screen and exiting.
'noSlowQueryLog': don't log slow query if true
'noErrorQueryLog': don't log error query if true
*/
global $Translation;
$db_link = openDBConnection($o);
/*
if openDBConnection() fails, it would abort execution unless 'silentErrors' is true,
in which case, we should return false from sql() without further action since
$o['error'] would be already set by openDBConnection()
*/
if(!$db_link) return false;
$t0 = microtime(true);
if(!$result = @db_query($statement, $db_link)) {
if(!stristr($statement, "show columns")) {
// retrieve error codes
$errorNum = db_errno($db_link);
$o['error'] = htmlspecialchars(db_error($db_link));
if(empty($o['noErrorQueryLog']))
logErrorQuery($statement, $o['error']);
if(getLoggedAdmin())
$o['error'] .= "<pre class=\"ltr\">{$Translation['query:']}\n" . htmlspecialchars($statement) . "</pre><p><i class=\"text-right\">{$Translation['admin-only info']}</i></p><p>{$Translation['try rebuild fields']}</p>";
if($o['silentErrors']) return false;
dieErrorPage($o['error']);
}
}
/* log slow queries that take more than 1 sec */
$t1 = microtime(true);
if($t1 - $t0 > 1.0 && empty($o['noSlowQueryLog']))
logSlowQuery($statement, $t1 - $t0);
return $result;
}
########################################################################
function logSlowQuery($statement, $duration) {
if(!createQueryLogTable()) return;
$o = [
'silentErrors' => true,
'noSlowQueryLog' => true,
'noErrorQueryLog' => true
];
$statement = makeSafe($statement);
$duration = floatval($duration);
$memberID = makeSafe(getLoggedMemberID());
$uri = makeSafe($_SERVER['REQUEST_URI']);
sql("INSERT INTO `appgini_query_log` SET
`statement`='$statement',
`duration`=$duration,
`memberID`='$memberID',
`uri`='$uri'
", $o);
}
########################################################################
function logErrorQuery($statement, $error) {
if(!createQueryLogTable()) return;
$o = [
'silentErrors' => true,
'noSlowQueryLog' => true,
'noErrorQueryLog' => true
];
$statement = makeSafe($statement);
$error = makeSafe($error);
$memberID = makeSafe(getLoggedMemberID());
$uri = makeSafe($_SERVER['REQUEST_URI']);
sql("INSERT INTO `appgini_query_log` SET
`statement`='$statement',
`error`='$error',
`memberID`='$memberID',
`uri`='$uri'
", $o);
}
########################################################################
function createQueryLogTable() {
static $created = false;
if($created) return true;
$o = [
'silentErrors' => true,
'noSlowQueryLog' => true,
'noErrorQueryLog' => true
];
sql("CREATE TABLE IF NOT EXISTS `appgini_query_log` (
`datetime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`statement` LONGTEXT,
`duration` DECIMAL(10,2) UNSIGNED DEFAULT 0.0,
`error` TEXT,
`memberID` VARCHAR(200),
`uri` VARCHAR(200)
) CHARSET " . mysql_charset, $o);
// check if table created
//$o2 = $o;
//$o2['error'] = '';
//sql("SELECT COUNT(1) FROM 'appgini_query_log'", $o2);
//$created = empty($o2['error']);
$created = true;
return $created;
}
########################################################################
function sqlValue($statement, &$error = NULL) {
// executes a statement that retreives a single data value and returns the value retrieved
$eo = ['silentErrors' => true];
if(!$res = sql($statement, $eo)) { $error = $eo['error']; return false; }
if(!$row = db_fetch_row($res)) return false;
return $row[0];
}
########################################################################
function getLoggedAdmin() {
// checks session variables to see whether the admin is logged or not
// if not, it returns false
// if logged, it returns the user id
$adminConfig = config('adminConfig');
if(empty($_SESSION['memberID'])) return false;
if($_SESSION['memberID'] == $adminConfig['adminUsername']) {
$_SESSION['adminUsername'] = $_SESSION['memberID'];
return $_SESSION['adminUsername'];
}
unset($_SESSION['adminUsername']);
return false;
}
########################################################################
function checkUser($username, $password) {
// checks given username and password for validity
// if valid, registers the username in a session and returns true
// else, returns false and destroys session
$adminConfig = config('adminConfig');
if($username != $adminConfig['adminUsername'] || !password_match($password, $adminConfig['adminPassword'])) {
return false;
}
$_SESSION['adminUsername'] = $username;
$_SESSION['memberGroupID'] = sqlValue("select groupID from membership_users where memberID='" . makeSafe($username) ."'");
$_SESSION['memberID'] = $username;
return true;
}
########################################################################
function initSession() {
$sh = @ini_get('session.save_handler');
$options = [
'name' => 'online_inovicing_system',
'save_handler' => stripos($sh, 'memcache') === false ? 'files' : $sh,
'serialize_handler' => 'php',
'cookie_lifetime' => '0',
'cookie_path' => '/' . trim(config('appURI'), '/'),
'cookie_httponly' => '1',
'use_strict_mode' => '1',
'use_cookies' => '1',
'use_only_cookies' => '1',
'cache_limiter' => $_SERVER['REQUEST_METHOD'] == 'POST' ? 'private' : 'nocache',
'cache_expire' => '2',
];
// hook: session_options(), if defined, $options is passed to it by reference
// to override default session behavior.
// should be defined in hooks/bootstrap.php
if(function_exists('session_options')) session_options($options);
// check sessions config
$noPathCheck = true; // set to false for debugging session issues
$arrPath = explode(';', ini_get('session.save_path'));
$save_path = $arrPath[count($arrPath) - 1];
if(!$noPathCheck && !is_dir($save_path)) die('Invalid session.save_path in php.ini');
if(session_id()) { session_write_close(); }
foreach($options as $key => $value)
@ini_set("session.{$key}", $value);
session_start();
}
########################################################################
function jwt_key() {
$config_file = dirname(__FILE__) . '/../config.php';
if(!is_file($config_file)) return false;
return md5_file($config_file);
}
########################################################################
function jwt_token($user = false) {
if($user === false) $user = $_SESSION['memberID'];
$key = jwt_key();
if($key === false) return false;
return JWT::encode(array('user' => $user), $key);
}
########################################################################
function jwt_header() {
/* adapted from https://stackoverflow.com/a/40582472/1945185 */
$auth_header = null;
if(isset($_SERVER['Authorization'])) {
$auth_header = trim($_SERVER['Authorization']);
} elseif(isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
$auth_header = trim($_SERVER['HTTP_AUTHORIZATION']);
} elseif(isset($_SERVER['HTTP_X_AUTHORIZATION'])) { //hack if all else fails
$auth_header = trim($_SERVER['HTTP_X_AUTHORIZATION']);
} elseif(function_exists('apache_request_headers')) {
$rh = apache_request_headers();
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
$rh = array_combine(array_map('ucwords', array_keys($rh)), array_values($rh));
if(isset($rh['Authorization'])) {
$auth_header = trim($rh['Authorization']);
} elseif(isset($rh['X-Authorization'])) {
$auth_header = trim($rh['X-Authorization']);
}
}
if(!empty($auth_header)) {
if(preg_match('/Bearer\s(\S+)/', $auth_header, $matches)) return $matches[1];
}
return null;
}
########################################################################
function jwt_check_login() {
// do we have an Authorization Bearer header?
$token = jwt_header();
if(!$token) return false;
$key = jwt_key();
if($key === false) return false;
$error = '';
$payload = JWT::decode($token, $key, $error);
if(empty($payload['user'])) return false;
$_SESSION['memberID'] = $payload['user'];
$safe_user = makeSafe($payload['user']);
$_SESSION['memberGroupID'] = sqlValue(
"SELECT `groupID` FROM `membership_users` WHERE `memberID`='{$safe_user}'"
);
// for API calls that just trigger an action and then close connection,
// we need to continue running
@ignore_user_abort(true);
@set_time_limit(120);
return true;
}
########################################################################
function curl_insert_handler($table, $data) {
if(!function_exists('curl_init')) return false;
$ch = curl_init();
$payload = $data;
$payload['insert_x'] = 1;
$url = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . config('host') . '/' . application_uri("{$table}_view.php");
$token = jwt_token();
$options = array(
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($payload),
CURLOPT_HTTPHEADER => array(
"User-Agent: {$_SERVER['HTTP_USER_AGENT']}",
"Accept: {$_SERVER['HTTP_ACCEPT']}",
"Authorization: Bearer " . $token,
"X-Authorization: Bearer " . $token,
),
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
/* this is a localhost request so need to verify SSL */
CURLOPT_SSL_VERIFYPEER => false,
// the following option allows sending request and then
// closing the connection without waiting for response
// see https://stackoverflow.com/a/10895361/1945185
CURLOPT_TIMEOUT => 8,
);
if(defined('CURLOPT_TCP_FASTOPEN')) $options[CURLOPT_TCP_FASTOPEN] = true;
if(defined('CURLOPT_SAFE_UPLOAD'))
$options[CURLOPT_SAFE_UPLOAD] = function_exists('curl_file_create');
// this is safe to use as we're sending a local request
if(defined('CURLOPT_UNRESTRICTED_AUTH')) $options[CURLOPT_UNRESTRICTED_AUTH] = 1;
curl_setopt_array($ch, $options);
return $ch;
}
########################################################################
function curl_batch($handlers) {
if(!function_exists('curl_init')) return false;
if(!is_array($handlers)) return false;
if(!count($handlers)) return false;
$mh = curl_multi_init();
if(function_exists('curl_multi_setopt')) {
curl_multi_setopt($mh, CURLMOPT_PIPELINING, 1);
curl_multi_setopt($mh, CURLMOPT_MAXCONNECTS, min(20, count($handlers)));
}
foreach($handlers as $ch) {
@curl_multi_add_handle($mh, $ch);
}
$active = false;
do {
@curl_multi_exec($mh, $active);
usleep(2000);
} while($active > 0);
}
########################################################################
function logOutUser() {
RememberMe::logout();
}
########################################################################
function getPKFieldName($tn) {
// get pk field name of given table
static $pk = [];
if(isset($pk[$tn])) return $pk[$tn];
$stn = makeSafe($tn, false);
$eo = ['silentErrors' => true];
if(!$res = sql("SHOW FIELDS FROM `$stn`", $eo)) return $pk[$tn] = false;
while($row = db_fetch_assoc($res))
if($row['Key'] == 'PRI') return $pk[$tn] = $row['Field'];
return $pk[$tn] = false;
}
########################################################################
function getCSVData($tn, $pkValue, $stripTags=true) {
// get pk field name for given table
if(!$pkField=getPKFieldName($tn)) {
return "";
}
// get a concat string to produce a csv list of field values for given table record
if(!$res=sql("show fields from `$tn`", $eo)) {
return "";
}
while($row=db_fetch_assoc($res)) {
$csvFieldList.="`{$row['Field']}`,";
}
$csvFieldList=substr($csvFieldList, 0, -1);
$csvData=sqlValue("select CONCAT_WS(', ', $csvFieldList) from `$tn` where `$pkField`='" . makeSafe($pkValue, false) . "'");
return ($stripTags ? strip_tags($csvData) : $csvData);
}
########################################################################
function errorMsg($msg) {
echo "<div class=\"alert alert-danger\">{$msg}</div>";
}
########################################################################
function redirect($url, $absolute = false) {
$fullURL = ($absolute ? $url : application_url($url));
if(!headers_sent()) header("Location: {$fullURL}");
echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;url={$fullURL}\">";
echo "<br><br><a href=\"{$fullURL}\">Click here</a> if you aren't automatically redirected.";
exit;
}
########################################################################
function htmlRadioGroup($name, $arrValue, $arrCaption, $selectedValue, $selClass = 'text-primary', $class = '', $separator = '<br>') {
if(!is_array($arrValue)) return '';
ob_start();
?>
<div class="radio %%CLASS%%"><label>
<input type="radio" name="%%NAME%%" id="%%ID%%" value="%%VALUE%%" %%CHECKED%%> %%LABEL%%
</label></div>
<?php
$template = ob_get_contents();
ob_end_clean();
$out = '';
for($i = 0; $i < count($arrValue); $i++) {
$replacements = array(
'%%CLASS%%' => html_attr($arrValue[$i] == $selectedValue ? $selClass :$class),
'%%NAME%%' => html_attr($name),
'%%ID%%' => html_attr($name . $i),
'%%VALUE%%' => html_attr($arrValue[$i]),
'%%LABEL%%' => $arrCaption[$i],
'%%CHECKED%%' => ($arrValue[$i]==$selectedValue ? " checked" : "")
);
$out .= str_replace(array_keys($replacements), array_values($replacements), $template);
}
return $out;
}
########################################################################
function htmlSelect($name, $arrValue, $arrCaption, $selectedValue, $class = '', $selectedClass = '') {
if($selectedClass == '') {
$selectedClass=$class;
}
if(is_array($arrValue)) {
$out="<select name=\"$name\" id=\"$name\">";
for($i = 0; $i < count($arrValue); $i++) {
$out .= '<option value="' . $arrValue[$i] . '"' . ($arrValue[$i] == $selectedValue ? " selected class=\"$class\"" : " class=\"$selectedClass\"") . '>' . $arrCaption[$i] . '</option>';
}
$out .= '</select>';
}
return $out;
}
########################################################################
function htmlSQLSelect($name, $sql, $selectedValue, $class = '', $selectedClass = '') {
$arrVal[] = '';
$arrCap[] = '';
if($res = sql($sql, $eo)) {
while($row = db_fetch_row($res)) {
$arrVal[] = $row[0];
$arrCap[] = $row[1];
}
return htmlSelect($name, $arrVal, $arrCap, $selectedValue, $class, $selectedClass);
} else {
return "";
}
}
########################################################################
function bootstrapSelect($name, $arrValue, $arrCaption, $selectedValue, $class = '', $selectedClass = '') {
if($selectedClass == '') $selectedClass = $class;
$out = "<select class=\"form-control\" name=\"{$name}\" id=\"{$name}\">";
if(is_array($arrValue)) {
for($i = 0; $i < count($arrValue); $i++) {
$selected = "class=\"{$class}\"";
if($arrValue[$i] == $selectedValue) $selected = "selected class=\"{$selectedClass}\"";
$out .= "<option value=\"{$arrValue[$i]}\" {$selected}>{$arrCaption[$i]}</option>";
}
}
$out .= '</select>';
return $out;
}
########################################################################
function bootstrapSQLSelect($name, $sql, $selectedValue, $class = '', $selectedClass = '') {
$arrVal[] = '';
$arrCap[] = '';
if($res = sql($sql, $eo)) {
while($row = db_fetch_row($res)) {
$arrVal[] = $row[0];
$arrCap[] = $row[1];
}
return bootstrapSelect($name, $arrVal, $arrCap, $selectedValue, $class, $selectedClass);
}
return '';
}
########################################################################
function isEmail($email) {
return filter_var(trim($email), FILTER_VALIDATE_EMAIL);
}
########################################################################
function notifyMemberApproval($memberID) {
$adminConfig = config('adminConfig');
$memberID = strtolower($memberID);
$email = sqlValue("select email from membership_users where lcase(memberID)='{$memberID}'");
return sendmail(array(
'to' => $email,
'name' => $memberID,
'subject' => $adminConfig['approvalSubject'],
'message' => nl2br($adminConfig['approvalMessage'])
));
}
########################################################################
function setupMembership() {
// run once per session, but force proceeding if not all mem tables created
$res = sql("show tables like 'membership_%'", $eo);
$num_mem_tables = db_num_rows($res);
$mem_update_fn = membership_table_functions();
if(isset($_SESSION['setupMembership']) && $num_mem_tables >= count($mem_update_fn)) return;
/* abort if current page is one of the following exceptions */
if(in_array(basename($_SERVER['PHP_SELF']), array(
'pageEditMember.php',
'membership_passwordReset.php',
'membership_profile.php',
'membership_signup.php',
'pageChangeMemberStatus.php',
'pageDeleteGroup.php',
'pageDeleteMember.php',
'pageEditGroup.php',
'pageEditMemberPermissions.php',
'pageRebuildFields.php',
'pageSettings.php',
'ajax_check_login.php'
))) return;
// call each update_membership function
foreach($mem_update_fn as $mem_fn) {
$mem_fn();
}
configure_anonymous_group();
configure_admin_group();
$_SESSION['setupMembership'] = time();
}
########################################################################
function membership_table_functions() {
// returns a list of update_membership_* functions
$arr = get_defined_functions();
return array_filter($arr['user'], function($f) {
return (strpos($f, 'update_membership_') !== false);
});
}
########################################################################
function configure_anonymous_group() {
$eo = ['silentErrors' => true];
$adminConfig = config('adminConfig');
$today = @date('Y-m-d');
$anon_group_safe = makeSafe($adminConfig['anonymousGroup']);
$anon_user = strtolower($adminConfig['anonymousMember']);
$anon_user_safe = makeSafe($anon_user);
/* create anonymous group if not there and get its ID */
$same_fields = "`allowSignup`=0, `needsApproval`=0";
sql("INSERT INTO `membership_groups` SET
`name`='{$anon_group_safe}', {$same_fields},
`description`='Anonymous group created automatically on {$today}'
ON DUPLICATE KEY UPDATE {$same_fields}",
$eo);
$anon_group_id = sqlValue("SELECT `groupID` FROM `membership_groups` WHERE `name`='{$anon_group_safe}'");
if(!$anon_group_id) return;
/* create guest user if not there or if guest name in config differs from that in db */
$anon_user_db = sqlValue("SELECT LCASE(`memberID`) FROM `membership_users`
WHERE `groupID`='{$anon_group_id}'");
if(!$anon_user_db || $anon_user_db != $anon_user) {
sql("DELETE FROM `membership_users` WHERE `groupID`='{$anon_group_id}'", $eo);
sql("INSERT INTO `membership_users` SET
`memberID`='{$anon_user_safe}',
`signUpDate`='{$today}',
`groupID`='{$anon_group_id}',
`isBanned`=0,
`isApproved`=1,
`comments`='Anonymous member created automatically on {$today}'",
$eo);
}
}
########################################################################
function configure_admin_group() {
$eo = ['silentErrors' => true];
$adminConfig = config('adminConfig');
$today = @date('Y-m-d');
$admin_group_safe = 'Admins';
$admin_user_safe = makeSafe(strtolower($adminConfig['adminUsername']));
$admin_hash_safe = makeSafe($adminConfig['adminPassword']);
$admin_email_safe = makeSafe($adminConfig['senderEmail']);
/* create admin group if not there and get its ID */
$same_fields = "`allowSignup`=0, `needsApproval`=1";
sql("INSERT INTO `membership_groups` SET
`name`='{$admin_group_safe}', {$same_fields},
`description`='Admin group created automatically on {$today}'
ON DUPLICATE KEY UPDATE {$same_fields}",
$eo);
$admin_group_id = sqlValue("SELECT `groupID` FROM `membership_groups` WHERE `name`='{$admin_group_safe}'");
if(!$admin_group_id) return;
/* create super-admin user if not there (if exists, query would abort with suppressed error) */
sql("INSERT INTO `membership_users` SET
`memberID`='{$admin_user_safe}',
`passMD5`='{$admin_hash_safe}',
`email`='{$admin_email_safe}',
`signUpDate`='{$today}',
`groupID`='{$admin_group_id}',
`isBanned`=0,
`isApproved`=1,
`comments`='Admin member created automatically on {$today}'",
$eo);
/* insert/update admin group permissions to allow full access to all tables */
$tables = getTableList(true);
foreach($tables as $tn => $ignore) {
$same_fields = '`allowInsert`=1,`allowView`=3,`allowEdit`=3,`allowDelete`=3';
sql("INSERT INTO `membership_grouppermissions` SET
`groupID`='{$admin_group_id}',
`tableName`='{$tn}',
{$same_fields}
ON DUPLICATE KEY UPDATE {$same_fields}",
$eo);
}
}
########################################################################
function get_table_keys($tn) {
$keys = [];
$res = sql("SHOW KEYS FROM `{$tn}`", $eo);
while($row = db_fetch_assoc($res))
$keys[$row['Key_name']][$row['Seq_in_index']] = $row;
return $keys;
}
########################################################################
function get_table_fields($tn = null) {
static $schema = null;
if($schema === null) {
/* application schema as created in AppGini */
$schema = [
'invoices' => [
'id' => ['appgini' => "INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT"],
'code' => ['appgini' => "VARCHAR(20) NULL UNIQUE"],
'status' => ['appgini' => "VARCHAR(20) NOT NULL DEFAULT 'Unpaid'"],
'date_due' => ['appgini' => "DATE NULL"],
'client' => ['appgini' => "INT UNSIGNED NULL"],
'client_contact' => ['appgini' => "INT UNSIGNED NULL"],
'client_address' => ['appgini' => "INT UNSIGNED NULL"],
'client_phone' => ['appgini' => "INT UNSIGNED NULL"],
'client_email' => ['appgini' => "INT UNSIGNED NULL"],
'client_website' => ['appgini' => "INT UNSIGNED NULL"],
'client_comments' => ['appgini' => "INT UNSIGNED NULL"],
'subtotal' => ['appgini' => "DECIMAL(9,2) NULL"],
'discount' => ['appgini' => "DECIMAL(4,2) NULL DEFAULT '0'"],
'tax' => ['appgini' => "DECIMAL(9,2) NULL DEFAULT '0'"],
'total' => ['appgini' => "DECIMAL(9,2) NULL"],
'comments' => ['appgini' => "TEXT NULL"],