-
Notifications
You must be signed in to change notification settings - Fork 0
/
incCommon.php
executable file
·1239 lines (1024 loc) · 54.6 KB
/
incCommon.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 ~~~~~~
getTableList() -- returns an associative array (tableName => tableData, tableData is array(tableCaption, tableDescription, tableIcon)) of tables accessible by current user
get_table_groups() -- returns an associative array (table_group => tables_array)
getLoggedMemberID() -- returns memberID of logged member. If no login, returns anonymous memberID
getLoggedGroupID() -- returns groupID of logged member, or anonymous groupID
logOutMember() -- destroys session and logs member out.
logInMember() -- checks POST login. If not valid, redirects to index.php, else returns TRUE
getTablePermissions($tn) -- returns an array of permissions allowed for logged member to given table (allowAccess, allowInsert, allowView, allowEdit, allowDelete) -- allowAccess is set to true if any access level is allowed
get_sql_fields($tn) -- returns the SELECT part of the table view query
get_sql_from($tn[, true]) -- returns the FROM part of the table view query, with full joins, optionally skipping permissions if true passed as 2nd param.
htmlUserBar() -- returns html code for displaying user login status to be used on top of pages.
showNotifications($msg, $class) -- returns html code for displaying a notification. If no parameters provided, processes the GET request for possible notifications.
parseMySQLDate(a, b) -- returns a if valid mysql date, or b if valid mysql date, or today if b is true, or empty if b is false.
parseCode(code) -- calculates and returns special values to be inserted in automatic fields.
addFilter(i, filterAnd, filterField, filterOperator, filterValue) -- enforce a filter over data
clearFilters() -- clear all filters
getMemberInfo() -- returns an array containing the currently signed-in member's info
loadView($view, $data) -- passes $data to templates/{$view}.php and returns the output
loadTable($table, $data) -- loads table template, passing $data to it
filterDropdownBy($filterable, $filterers, $parentFilterers, $parentPKField, $parentCaption, $parentTable, &$filterableCombo) -- applies cascading drop-downs for a lookup field, returns js code to be inserted into the page
br2nl($text) -- replaces all variations of HTML <br> tags with a new line character
htmlspecialchars_decode($text) -- inverse of htmlspecialchars()
entitiesToUTF8($text) -- convert unicode entities (e.g. Ӓ) to actual UTF8 characters, requires multibyte string PHP extension
func_get_args_byref() -- returns an array of arguments passed to a function, by reference
permissions_sql($table, $level) -- returns an array containing the FROM and WHERE additions for applying permissions to an SQL query
error_message($msg[, $back_url]) -- returns html code for a styled error message .. pass explicit false in second param to suppress back button
toMySQLDate($formattedDate, $sep = datalist_date_separator, $ord = datalist_date_format)
highlight($needle, $haystack) -- returns html of haystack where needle is wrapped in highlight span
reIndex(&$arr) -- returns a copy of the given array, with keys replaced by 1-based numeric indices, and values replaced by original keys
get_embed($provider, $url[, $width, $height, $retrieve]) -- returns embed code for a given url (supported providers: youtube, googlemap)
check_record_permission($table, $id, $perm = 'view') -- returns true if current user has the specified permission $perm ('view', 'edit' or 'delete') for the given recors, false otherwise
sql($query, $o) -- executes given $query and returns its result set. $o is an options array (see the function definition for details)
NavMenus($options) -- returns the HTML code for the top navigation menus. $options is not implemented currently.
StyleSheet() -- returns the HTML code for included style sheet files to be placed in the <head> section.
getUploadDir($dir) -- if dir is empty, returns upload dir configured in defaultLang.php, else returns $dir.
PrepareUploadedFile($FieldName, $MaxSize, $FileTypes='jpg|jpeg|gif|png', $NoRename=false, $dir="") -- validates and moves uploaded file for given $FieldName into the given $dir (or the default one if empty)
get_home_links($homeLinks, $default_classes, $tgroup) -- process $homeLinks array and return custom links for homepage. Applies $default_classes to links if links have classes defined, and filters links by $tgroup (using '*' matches all table_group values)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#########################################################
function getTableList($skip_authentication = false){
$arrAccessTables = array();
$arrTables = array(
'acquisition' => array('Acquisition', 'The acquisition sections helps buyers keep track of their current deals. The buyer may also upload photos when they are on site. This section is full of useful cold calling features. ', 'resources/table_icons/client_account_template.png', 'Operations'),
'inventory' => array('Inventory', 'Keep track of items simply. ', 'resources/table_icons/attributes_display.png', 'Operations'),
'repairs' => array('Repairs', 'Register instruments for repair. Batch numbers can be used to filter cost of repairs, or show repairs that match your criteria.', 'resources/table_icons/repair.png', 'Operations'),
'shipping' => array('Shipping', 'Here you can access shippers info, and also see orders handled by each shipper.', 'resources/table_icons/box_closed.png', 'Sales'),
'register' => array('Register', 'Register sales through this section. Simply add the item you wish to sell to a client and the price it sold for.', 'resources/table_icons/cash_register.png', 'Sales'),
'expenses' => array('Expenses', 'Expenses is a simplified way to store your business expenses and receipts for tax purposes, with easy export to TurboTax or Quicken via \'Filter\' and \'Save CSV\'. Simply input the information into the desired fields, take a photo of the receipt, and it is saved in the database. <br>', 'resources/table_icons/credit.png', 'Accounting'),
'employees' => array('Employees', 'This table lists the employees sorted by last name.<br>When you click an employee name to view his/her details, you can also view the orders processed by them. ', 'resources/table_icons/ceo.png', 'Accounting'),
'register_items' => array('Order Items', '', 'resources/table_icons/application_form_magnify.png', 'Sales')
);
if($skip_authentication || getLoggedAdmin()) return $arrTables;
if(is_array($arrTables)){
foreach($arrTables as $tn => $tc){
$arrPerm = getTablePermissions($tn);
if($arrPerm[0]){
$arrAccessTables[$tn] = $tc;
}
}
}
return $arrAccessTables;
}
#########################################################
function get_table_groups($skip_authentication = false){
$tables = getTableList($skip_authentication);
$all_groups = array('Operations', 'Accounting', 'Sales');
$groups = array();
foreach($all_groups as $grp){
foreach($tables as $tn => $td){
if($td[3] && $td[3] == $grp) $groups[$grp][] = $tn;
if(!$td[3]) $groups[0][] = $tn;
}
}
return $groups;
}
#########################################################
function getTablePermissions($tn){
static $table_permissions = array();
if(isset($table_permissions[$tn])) return $table_permissions[$tn];
$groupID = getLoggedGroupID();
$memberID = makeSafe(getLoggedMemberID());
$res_group = sql("select tableName, allowInsert, allowView, allowEdit, allowDelete from membership_grouppermissions where groupID='{$groupID}'", $eo);
$res_user = sql("select tableName, allowInsert, allowView, allowEdit, allowDelete from membership_userpermissions where lcase(memberID)='{$memberID}'", $eo);
while($row = db_fetch_assoc($res_group)){
$table_permissions[$row['tableName']] = array(
1 => intval($row['allowInsert']),
2 => intval($row['allowView']),
3 => intval($row['allowEdit']),
4 => intval($row['allowDelete']),
'insert' => intval($row['allowInsert']),
'view' => intval($row['allowView']),
'edit' => intval($row['allowEdit']),
'delete' => intval($row['allowDelete'])
);
}
// user-specific permissions, if specified, overwrite his group permissions
while($row = db_fetch_assoc($res_user)){
$table_permissions[$row['tableName']] = array(
1 => intval($row['allowInsert']),
2 => intval($row['allowView']),
3 => intval($row['allowEdit']),
4 => intval($row['allowDelete']),
'insert' => intval($row['allowInsert']),
'view' => intval($row['allowView']),
'edit' => intval($row['allowEdit']),
'delete' => intval($row['allowDelete'])
);
}
// if user has any type of access, set 'access' flag
foreach($table_permissions as $t => $p){
$table_permissions[$t]['access'] = $table_permissions[$t][0] = false;
if($p['insert'] || $p['view'] || $p['edit'] || $p['delete']){
$table_permissions[$t]['access'] = $table_permissions[$t][0] = true;
}
}
return $table_permissions[$tn];
}
#########################################################
function get_sql_fields($table_name){
$sql_fields = array(
'acquisition' => "`acquisition`.`id` as 'id', `acquisition`.`call_back` as 'call_back', `acquisition`.`seller_name` as 'seller_name', CONCAT_WS('-', LEFT(`acquisition`.`phone`,3), MID(`acquisition`.`phone`,4,3), RIGHT(`acquisition`.`phone`,4)) as 'phone', `acquisition`.`purchase_notes` as 'purchase_notes', `acquisition`.`priority` as 'priority', `acquisition`.`location_city` as 'location_city', `acquisition`.`location_state` as 'location_state', if(`acquisition`.`pickup_date`,date_format(`acquisition`.`pickup_date`,'%m/%d/%Y'),'') as 'pickup_date', TIME_FORMAT(`acquisition`.`pickup_time`, '%r') as 'pickup_time', `acquisition`.`street_address` as 'street_address', `acquisition`.`category` as 'category', `acquisition`.`ref_listing` as 'ref_listing', `acquisition`.`photo_1` as 'photo_1', `acquisition`.`photo_2` as 'photo_2', `acquisition`.`photo_3` as 'photo_3', `acquisition`.`photo_4` as 'photo_4', `acquisition`.`photo_5` as 'photo_5', `acquisition`.`photo_6` as 'photo_6'",
'inventory' => "`inventory`.`id` as 'id', `inventory`.`item` as 'item', `inventory`.`status` as 'status', `inventory`.`description` as 'description', `inventory`.`item_cost` as 'item_cost', CONCAT('$', FORMAT(`inventory`.`price_high`, 2)) as 'price_high', CONCAT('$', FORMAT(`inventory`.`price_low`, 2)) as 'price_low', `inventory`.`item_number` as 'item_number', `inventory`.`ref_listing` as 'ref_listing', `inventory`.`inventory_photo` as 'inventory_photo', `inventory`.`last_update` as 'last_update', `inventory`.`location` as 'location'",
'repairs' => "`repairs`.`id` as 'id', `repairs`.`repair_status` as 'repair_status', IF( CHAR_LENGTH(`inventory1`.`id`) || CHAR_LENGTH(`inventory1`.`item`), CONCAT_WS('', `inventory1`.`id`, ' - ', `inventory1`.`item`), '') as 'item', `repairs`.`perform` as 'perform', `repairs`.`repair_notes` as 'repair_notes', CONCAT('$', FORMAT(`repairs`.`cost`, 2)) as 'cost', `repairs`.`batch_number` as 'batch_number', `repairs`.`photo_1` as 'photo_1', `repairs`.`photo_2` as 'photo_2', `repairs`.`last_update` as 'last_update'",
'shipping' => "`shipping`.`id` as 'id', IF( CHAR_LENGTH(`register1`.`id`) || CHAR_LENGTH(`register1`.`client_name`), CONCAT_WS('', `register1`.`id`, ' - ', `register1`.`client_name`), '') as 'register_id', IF( CHAR_LENGTH(`register1`.`client_name`), CONCAT_WS('', `register1`.`client_name`), '') as 'client_name', IF( CHAR_LENGTH(`register1`.`phone`), CONCAT_WS('', `register1`.`phone`), '') as 'phone', IF( CHAR_LENGTH(`register1`.`email`), CONCAT_WS('', `register1`.`email`), '') as 'email', `shipping`.`company` as 'company', `shipping`.`shipping_gateway` as 'shipping_gateway', `shipping`.`street_address` as 'street_address', `shipping`.`city` as 'city', `shipping`.`state` as 'state', `shipping`.`zip` as 'zip', `shipping`.`country` as 'country', `shipping`.`ship_width` as 'ship_width', `shipping`.`ship_length` as 'ship_length', `shipping`.`ship_height` as 'ship_height', `shipping`.`distance_unit` as 'distance_unit', `shipping`.`ship_weight` as 'ship_weight', `shipping`.`ship_mass_unit` as 'ship_mass_unit', `shipping`.`tracking_number` as 'tracking_number'",
'register' => "`register`.`id` as 'id', `register`.`client_name` as 'client_name', IF( CHAR_LENGTH(`employees1`.`first`) || CHAR_LENGTH(`employees1`.`last`), CONCAT_WS('', `employees1`.`first`, ' ', `employees1`.`last`), '') as 'seller', `register`.`date` as 'date', `register`.`phone` as 'phone', `register`.`email` as 'email'",
'expenses' => "`expenses`.`id` as 'id', `expenses`.`category` as 'category', `expenses`.`account` as 'account', CONCAT('$', FORMAT(`expenses`.`price`, 2)) as 'price', `expenses`.`decription` as 'decription', if(`expenses`.`date`,date_format(`expenses`.`date`,'%m/%d/%Y'),'') as 'date', `expenses`.`from_account` as 'from_account', `expenses`.`account_detail` as 'account_detail', `expenses`.`check_number` as 'check_number', `expenses`.`photo` as 'photo'",
'employees' => "`employees`.`id` as 'id', `employees`.`first` as 'first', `employees`.`last` as 'last', `employees`.`street_addr` as 'street_addr', `employees`.`city` as 'city', `employees`.`state` as 'state', if(`employees`.`hire_date`,date_format(`employees`.`hire_date`,'%m/%d/%Y'),'') as 'hire_date', `employees`.`notes` as 'notes', `employees`.`last_update` as 'last_update'",
'register_items' => "`register_items`.`id` as 'id', IF( CHAR_LENGTH(`register1`.`id`), CONCAT_WS('', `register1`.`id`), '') as 'previous_order', IF( CHAR_LENGTH(`inventory1`.`item`), CONCAT_WS('', `inventory1`.`item`), '') as 'item_name', IF( CHAR_LENGTH(`inventory1`.`price_high`), CONCAT_WS('', `inventory1`.`price_high`), '') as 'cost', IF( CHAR_LENGTH(`inventory1`.`inventory_photo`), CONCAT_WS('', `inventory1`.`inventory_photo`), '') as 'ref_img'"
);
if(isset($sql_fields[$table_name])){
return $sql_fields[$table_name];
}
return false;
}
#########################################################
function get_sql_from($table_name, $skip_permissions = false){
$sql_from = array(
'acquisition' => "`acquisition` ",
'inventory' => "`inventory` ",
'repairs' => "`repairs` LEFT JOIN `inventory` as inventory1 ON `inventory1`.`id`=`repairs`.`item` ",
'shipping' => "`shipping` LEFT JOIN `register` as register1 ON `register1`.`id`=`shipping`.`register_id` ",
'register' => "`register` LEFT JOIN `employees` as employees1 ON `employees1`.`id`=`register`.`seller` ",
'expenses' => "`expenses` ",
'employees' => "`employees` ",
'register_items' => "`register_items` LEFT JOIN `register` as register1 ON `register1`.`id`=`register_items`.`previous_order` LEFT JOIN `inventory` as inventory1 ON `inventory1`.`id`=`register_items`.`item_name` "
);
$pkey = array(
'acquisition' => 'id',
'inventory' => 'id',
'repairs' => 'id',
'shipping' => 'id',
'register' => 'id',
'expenses' => 'id',
'employees' => 'id',
'register_items' => 'id'
);
if(isset($sql_from[$table_name])){
if($skip_permissions) return $sql_from[$table_name];
// mm: build the query based on current member's permissions
$perm = getTablePermissions($table_name);
if($perm[2] == 1){ // view owner only
$sql_from[$table_name] .= ", membership_userrecords WHERE `{$table_name}`.`{$pkey[$table_name]}`=membership_userrecords.pkValue and membership_userrecords.tableName='{$table_name}' and lcase(membership_userrecords.memberID)='" . getLoggedMemberID() . "'";
}elseif($perm[2] == 2){ // view group only
$sql_from[$table_name] .= ", membership_userrecords WHERE `{$table_name}`.`{$pkey[$table_name]}`=membership_userrecords.pkValue and membership_userrecords.tableName='{$table_name}' and membership_userrecords.groupID='" . getLoggedGroupID() . "'";
}elseif($perm[2] == 3){ // view all
$sql_from[$table_name] .= ' WHERE 1=1';
}else{ // view none
return false;
}
return $sql_from[$table_name];
}
return false;
}
#########################################################
function getLoggedGroupID(){
if($_SESSION['memberGroupID']!=''){
return $_SESSION['memberGroupID'];
}else{
setAnonymousAccess();
return getLoggedGroupID();
}
}
#########################################################
function getLoggedMemberID(){
if($_SESSION['memberID']!=''){
return strtolower($_SESSION['memberID']);
}else{
setAnonymousAccess();
return getLoggedMemberID();
}
}
#########################################################
function setAnonymousAccess(){
$adminConfig = config('adminConfig');
$anonGroupID=sqlValue("select groupID from membership_groups where name='".$adminConfig['anonymousGroup']."'");
$_SESSION['memberGroupID']=($anonGroupID ? $anonGroupID : 0);
$anonMemberID=sqlValue("select lcase(memberID) from membership_users where lcase(memberID)='".strtolower($adminConfig['anonymousMember'])."' and groupID='$anonGroupID'");
$_SESSION['memberID']=($anonMemberID ? $anonMemberID : 0);
}
#########################################################
function logInMember(){
$redir = 'index.php';
if($_POST['signIn'] != ''){
if($_POST['username'] != '' && $_POST['password'] != ''){
$username = makeSafe(strtolower($_POST['username']));
$password = md5($_POST['password']);
if(sqlValue("select count(1) from membership_users where lcase(memberID)='$username' and passMD5='$password' and isApproved=1 and isBanned=0")==1){
$_SESSION['memberID']=$username;
$_SESSION['memberGroupID']=sqlValue("select groupID from membership_users where lcase(memberID)='$username'");
if($_POST['rememberMe']==1){
@setcookie('Luthier_Technologies_rememberMe', md5($username.$password), time()+86400*30);
}else{
@setcookie('Luthier_Technologies_rememberMe', '', time()-86400*30);
}
// hook: login_ok
if(function_exists('login_ok')){
$args=array();
if(!$redir=login_ok(getMemberInfo(), $args)){
$redir='index.php';
}
}
redirect($redir);
exit;
}
}
// hook: login_failed
if(function_exists('login_failed')){
$args=array();
login_failed(array(
'username' => $_POST['username'],
'password' => $_POST['password'],
'IP' => $_SERVER['REMOTE_ADDR']
), $args);
}
if(!headers_sent()) header('HTTP/1.0 403 Forbidden');
redirect("index.php?loginFailed=1");
exit;
}elseif((!$_SESSION['memberID'] || $_SESSION['memberID']==$adminConfig['anonymousMember']) && $_COOKIE['Luthier_Technologies_rememberMe']!=''){
$chk=makeSafe($_COOKIE['Luthier_Technologies_rememberMe']);
if($username=sqlValue("select memberID from membership_users where convert(md5(concat(memberID, passMD5)), char)='$chk' and isBanned=0")){
$_SESSION['memberID']=$username;
$_SESSION['memberGroupID']=sqlValue("select groupID from membership_users where lcase(memberID)='$username'");
}
}
}
#########################################################
function logOutMember(){
logOutUser();
redirect("index.php?signIn=1");
}
#########################################################
function htmlUserBar(){
global $adminConfig, $Translation;
if(!defined('PREPEND_PATH')) define('PREPEND_PATH', '');
ob_start();
$home_page = (basename($_SERVER['PHP_SELF'])=='index.php' ? true : false);
?>
<nav class="navbar navbar-default navbar-fixed-top hidden-print" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- application title is obtained from the name besides the yellow database icon in AppGini, use underscores for spaces -->
<a class="navbar-brand" href="<?php echo PREPEND_PATH; ?>index.php"><i class="glyphicon glyphicon-home"></i> Luthier Technologies</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<?php if(!$home_page){ ?>
<?php echo NavMenus(); ?>
<?php } ?>
</ul>
<?php if(getLoggedAdmin()){ ?>
<ul class="nav navbar-nav">
<a href="<?php echo PREPEND_PATH; ?>admin/pageHome.php" class="btn btn-danger navbar-btn hidden-xs"><i class="glyphicon glyphicon-cog"></i> <?php echo $Translation['admin area']; ?></a>
<a href="<?php echo PREPEND_PATH; ?>admin/pageHome.php" class="btn btn-danger navbar-btn visible-xs btn-lg"><i class="glyphicon glyphicon-cog"></i> <?php echo $Translation['admin area']; ?></a>
</ul>
<?php } ?>
<?php if(!$_GET['signIn'] && !$_GET['loginFailed']){ ?>
<?php if(getLoggedMemberID() == $adminConfig['anonymousMember']){ ?>
<p class="navbar-text navbar-right"> </p>
<a href="<?php echo PREPEND_PATH; ?>index.php?signIn=1" class="btn btn-success navbar-btn navbar-right"><?php echo $Translation['sign in']; ?></a>
<p class="navbar-text navbar-right">
<?php echo $Translation['not signed in']; ?>
</p>
<?php }else{ ?>
<ul class="nav navbar-nav navbar-right hidden-xs" style="min-width: 330px;">
<a class="btn navbar-btn btn-default" href="<?php echo PREPEND_PATH; ?>index.php?signOut=1"><i class="glyphicon glyphicon-log-out"></i> <?php echo $Translation['sign out']; ?></a>
<p class="navbar-text">
<?php echo $Translation['signed as']; ?> <strong><a href="<?php echo PREPEND_PATH; ?>membership_profile.php" class="navbar-link"><?php echo getLoggedMemberID(); ?></a></strong>
</p>
</ul>
<ul class="nav navbar-nav visible-xs">
<a class="btn navbar-btn btn-default btn-lg visible-xs" href="<?php echo PREPEND_PATH; ?>index.php?signOut=1"><i class="glyphicon glyphicon-log-out"></i> <?php echo $Translation['sign out']; ?></a>
<p class="navbar-text text-center">
<?php echo $Translation['signed as']; ?> <strong><a href="<?php echo PREPEND_PATH; ?>membership_profile.php" class="navbar-link"><?php echo getLoggedMemberID(); ?></a></strong>
</p>
</ul>
<?php } ?>
<?php } ?>
</div>
</nav>
<?php
$html = ob_get_contents();
ob_end_clean();
return $html;
}
#########################################################
function showNotifications($msg = '', $class = '', $fadeout = true){
global $Translation;
$notify_template_no_fadeout = '<div id="%%ID%%" class="alert alert-dismissable %%CLASS%%" style="display: none; padding-top: 6px; padding-bottom: 6px;">' .
'<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' .
'%%MSG%%</div>' .
'<script> jQuery(function(){ jQuery("#%%ID%%").show("slow"); }); </script>'."\n";
$notify_template = '<div id="%%ID%%" class="alert %%CLASS%%" style="display: none; padding-top: 6px; padding-bottom: 6px;">%%MSG%%</div>' .
'<script>' .
'jQuery(function(){' .
'jQuery("#%%ID%%").show("slow", function(){' .
'setTimeout(function(){ jQuery("#%%ID%%").hide("slow"); }, 4000);' .
'});' .
'});' .
'</script>'."\n";
if(!$msg){ // if no msg, use url to detect message to display
if($_REQUEST['record-added-ok'] != ''){
$msg = $Translation['new record saved'];
$class = 'alert-success';
}elseif($_REQUEST['record-added-error'] != ''){
$msg = $Translation['Couldn\'t save the new record'];
$class = 'alert-danger';
$fadeout = false;
}elseif($_REQUEST['record-updated-ok'] != ''){
$msg = $Translation['record updated'];
$class = 'alert-success';
}elseif($_REQUEST['record-updated-error'] != ''){
$msg = $Translation['Couldn\'t save changes to the record'];
$class = 'alert-danger';
$fadeout = false;
}elseif($_REQUEST['record-deleted-ok'] != ''){
$msg = $Translation['The record has been deleted successfully'];
$class = 'alert-success';
$fadeout = false;
}elseif($_REQUEST['record-deleted-error'] != ''){
$msg = $Translation['Couldn\'t delete this record'];
$class = 'alert-danger';
$fadeout = false;
}else{
return '';
}
}
$id = 'notification-' . rand();
$out = ($fadeout ? $notify_template : $notify_template_no_fadeout);
$out = str_replace('%%ID%%', $id, $out);
$out = str_replace('%%MSG%%', $msg, $out);
$out = str_replace('%%CLASS%%', $class, $out);
return $out;
}
#########################################################
function parseMySQLDate($date, $altDate){
// is $date valid?
if(preg_match("/^\d{4}-\d{1,2}-\d{1,2}$/", trim($date))){
return trim($date);
}
if($date != '--' && preg_match("/^\d{4}-\d{1,2}-\d{1,2}$/", trim($altDate))){
return trim($altDate);
}
if($date != '--' && $altDate && intval($altDate)==$altDate){
return @date('Y-m-d', @time() + ($altDate >= 1 ? $altDate - 1 : $altDate) * 86400);
}
return '';
}
#########################################################
function parseCode($code, $isInsert=true, $rawData=false){
if($isInsert){
$arrCodes=array(
'<%%creatorusername%%>' => $_SESSION['memberID'],
'<%%creatorgroupid%%>' => $_SESSION['memberGroupID'],
'<%%creatorip%%>' => $_SERVER['REMOTE_ADDR'],
'<%%creatorgroup%%>' => sqlValue("select name from membership_groups where groupID='{$_SESSION['memberGroupID']}'"),
'<%%creationdate%%>' => ($rawData ? @date('Y-m-d') : @date('n/j/Y')),
'<%%creationtime%%>' => ($rawData ? @date('H:i:s') : @date('h:i:s a')),
'<%%creationdatetime%%>' => ($rawData ? @date('Y-m-d H:i:s') : @date('n/j/Y h:i:s a')),
'<%%creationtimestamp%%>' => ($rawData ? @date('Y-m-d H:i:s') : @time())
);
}else{
$arrCodes=array(
'<%%editorusername%%>' => $_SESSION['memberID'],
'<%%editorgroupid%%>' => $_SESSION['memberGroupID'],
'<%%editorip%%>' => $_SERVER['REMOTE_ADDR'],
'<%%editorgroup%%>' => sqlValue("select name from membership_groups where groupID='{$_SESSION['memberGroupID']}'"),
'<%%editingdate%%>' => ($rawData ? @date('Y-m-d') : @date('n/j/Y')),
'<%%editingtime%%>' => ($rawData ? @date('H:i:s') : @date('h:i:s a')),
'<%%editingdatetime%%>' => ($rawData ? @date('Y-m-d H:i:s') : @date('n/j/Y h:i:s a')),
'<%%editingtimestamp%%>' => ($rawData ? @date('Y-m-d H:i:s') : @time())
);
}
$pc=str_ireplace(array_keys($arrCodes), array_values($arrCodes), $code);
return $pc;
}
#########################################################
function addFilter($index, $filterAnd, $filterField, $filterOperator, $filterValue){
// validate input
if($index < 1 || $index > 80 || !is_int($index)) return false;
if($filterAnd != 'or') $filterAnd = 'and';
$filterField = intval($filterField);
/* backward compatibility */
if(in_array($filterOperator, $GLOBALS['filter_operators'])){
$filterOperator = array_search($filterOperator, $GLOBALS['filter_operators']);
}
if(!in_array($filterOperator, array_keys($GLOBALS['filter_operators']))){
$filterOperator = 'like';
}
if(!$filterField){
$filterOperator = '';
$filterValue = '';
}
$_REQUEST['FilterAnd'][$index] = $filterAnd;
$_REQUEST['FilterField'][$index] = $filterField;
$_REQUEST['FilterOperator'][$index] = $filterOperator;
$_REQUEST['FilterValue'][$index] = $filterValue;
return true;
}
#########################################################
function clearFilters(){
for($i=1; $i<=80; $i++){
addFilter($i, '', 0, '', '');
}
}
#########################################################
function getMemberInfo($memberID = ''){
static $member_info = array();
if(!$memberID){
$memberID = getLoggedMemberID();
}
// return cached results, if present
if(isset($member_info[$memberID])) return $member_info[$memberID];
$adminConfig = config('adminConfig');
$mi = array();
if($memberID){
$res = sql("select * from membership_users where memberID='" . makeSafe($memberID) . "'", $eo);
if($row = db_fetch_assoc($res)){
$mi = array(
'username' => $memberID,
'groupID' => $row['groupID'],
'group' => sqlValue("select name from membership_groups where groupID='{$row['groupID']}'"),
'admin' => ($adminConfig['adminUsername'] == $memberID ? true : false),
'email' => $row['email'],
'custom' => array(
$row['custom1'],
$row['custom2'],
$row['custom3'],
$row['custom4']
),
'banned' => ($row['isBanned'] ? true : false),
'approved' => ($row['isApproved'] ? true : false),
'signupDate' => @date('n/j/Y', @strtotime($row['signupDate'])),
'comments' => $row['comments'],
'IP' => $_SERVER['REMOTE_ADDR']
);
// cache results
$member_info[$memberID] = $mi;
}
}
return $mi;
}
#########################################################
if(!function_exists('str_ireplace')){
function str_ireplace($search, $replace, $subject){
$ret=$subject;
if(is_array($search)){
for($i=0; $i<count($search); $i++){
$ret=str_ireplace($search[$i], $replace[$i], $ret);
}
}else{
$ret=preg_replace('/'.preg_quote($search, '/').'/i', $replace, $ret);
}
return $ret;
}
}
#########################################################
/**
* Loads a given view from the templates folder, passing the given data to it
* @param $view the name of a php file (without extension) to be loaded from the 'templates' folder
* @param $the_data_to_pass_to_the_view (optional) associative array containing the data to pass to the view
* @return the output of the parsed view as a string
*/
function loadView($view, $the_data_to_pass_to_the_view=false){
global $Translation;
$view = dirname(__FILE__)."/templates/$view.php";
if(!is_file($view)) return false;
if(is_array($the_data_to_pass_to_the_view)){
foreach($the_data_to_pass_to_the_view as $k => $v)
$$k = $v;
}
unset($the_data_to_pass_to_the_view, $k, $v);
ob_start();
@include($view);
$out=ob_get_contents();
ob_end_clean();
return $out;
}
#########################################################
/**
* Loads a table template from the templates folder, passing the given data to it
* @param $table_name the name of the table whose template is to be loaded from the 'templates' folder
* @param $the_data_to_pass_to_the_table associative array containing the data to pass to the table template
* @return the output of the parsed table template as a string
*/
function loadTable($table_name, $the_data_to_pass_to_the_table = array()){
$dont_load_header = $the_data_to_pass_to_the_table['dont_load_header'];
$dont_load_footer = $the_data_to_pass_to_the_table['dont_load_footer'];
$header = $table = $footer = '';
if(!$dont_load_header){
// try to load tablename-header
if(!($header = loadView("{$table_name}-header", $the_data_to_pass_to_the_table))){
$header = loadView('table-common-header', $the_data_to_pass_to_the_table);
}
}
$table = loadView($table_name, $the_data_to_pass_to_the_table);
if(!$dont_load_footer){
// try to load tablename-footer
if(!($footer = loadView("{$table_name}-footer", $the_data_to_pass_to_the_table))){
$footer = loadView('table-common-footer', $the_data_to_pass_to_the_table);
}
}
return "{$header}{$table}{$footer}";
}
#########################################################
function filterDropdownBy($filterable, $filterers, $parentFilterers, $parentPKField, $parentCaption, $parentTable, &$filterableCombo){
$filterersArray = explode(',', $filterers);
$parentFilterersArray = explode(',', $parentFilterers);
$parentFiltererList = '`' . implode('`, `', $parentFilterersArray) . '`';
$res=sql("SELECT `$parentPKField`, $parentCaption, $parentFiltererList FROM `$parentTable` ORDER BY 2", $eo);
$filterableData = array();
while($row=db_fetch_row($res)){
$filterableData[$row[0]] = $row[1];
$filtererIndex = 0;
foreach($filterersArray as $filterer){
$filterableDataByFilterer[$filterer][$row[$filtererIndex + 2]][$row[0]] = $row[1];
$filtererIndex++;
}
$row[0] = addslashes($row[0]);
$row[1] = addslashes($row[1]);
$jsonFilterableData .= "\"{$row[0]}\":\"{$row[1]}\",";
}
$jsonFilterableData .= '}';
$jsonFilterableData = '{'.str_replace(',}', '}', $jsonFilterableData);
$filterJS = "\nvar {$filterable}_data = $jsonFilterableData;";
foreach($filterersArray as $filterer){
if(is_array($filterableDataByFilterer[$filterer])) foreach($filterableDataByFilterer[$filterer] as $filtererItem => $filterableItem){
$jsonFilterableDataByFilterer[$filterer] .= '"'.addslashes($filtererItem).'":{';
foreach($filterableItem as $filterableItemID => $filterableItemData){
$jsonFilterableDataByFilterer[$filterer] .= '"'.addslashes($filterableItemID).'":"'.addslashes($filterableItemData).'",';
}
$jsonFilterableDataByFilterer[$filterer] .= '},';
}
$jsonFilterableDataByFilterer[$filterer] .= '}';
$jsonFilterableDataByFilterer[$filterer] = '{'.str_replace(',}', '}', $jsonFilterableDataByFilterer[$filterer]);
$filterJS.="\n\n// code for filtering {$filterable} by {$filterer}\n";
$filterJS.="\nvar {$filterable}_data_by_{$filterer} = {$jsonFilterableDataByFilterer[$filterer]}; ";
$filterJS.="\nvar selected_{$filterable} = \$F('{$filterable}');";
$filterJS.="\nvar {$filterable}_change_by_{$filterer} = function(){";
$filterJS.="\n\t$('{$filterable}').options.length=0;";
$filterJS.="\n\t$('{$filterable}').options[0] = new Option();";
$filterJS.="\n\tif(\$F('{$filterer}')){";
$filterJS.="\n\t\tfor({$filterable}_item in {$filterable}_data_by_{$filterer}[\$F('{$filterer}')]){";
$filterJS.="\n\t\t\t$('{$filterable}').options[$('{$filterable}').options.length] = new Option(";
$filterJS.="\n\t\t\t\t{$filterable}_data_by_{$filterer}[\$F('{$filterer}')][{$filterable}_item],";
$filterJS.="\n\t\t\t\t{$filterable}_item,";
$filterJS.="\n\t\t\t\t({$filterable}_item == selected_{$filterable} ? true : false),";
$filterJS.="\n\t\t\t\t({$filterable}_item == selected_{$filterable} ? true : false)";
$filterJS.="\n\t\t\t);";
$filterJS.="\n\t\t}";
$filterJS.="\n\t}else{";
$filterJS.="\n\t\tfor({$filterable}_item in {$filterable}_data){";
$filterJS.="\n\t\t\t$('{$filterable}').options[$('{$filterable}').options.length] = new Option(";
$filterJS.="\n\t\t\t\t{$filterable}_data[{$filterable}_item],";
$filterJS.="\n\t\t\t\t{$filterable}_item,";
$filterJS.="\n\t\t\t\t({$filterable}_item == selected_{$filterable} ? true : false),";
$filterJS.="\n\t\t\t\t({$filterable}_item == selected_{$filterable} ? true : false)";
$filterJS.="\n\t\t\t);";
$filterJS.="\n\t\t}";
$filterJS.="\n\t\tif(selected_{$filterable} && selected_{$filterable} == \$F('{$filterable}')){";
$filterJS.="\n\t\t\tfor({$filterer}_item in {$filterable}_data_by_{$filterer}){";
$filterJS.="\n\t\t\t\tfor({$filterable}_item in {$filterable}_data_by_{$filterer}[{$filterer}_item]){";
$filterJS.="\n\t\t\t\t\tif({$filterable}_item == selected_{$filterable}){";
$filterJS.="\n\t\t\t\t\t\t$('{$filterer}').value = {$filterer}_item;";
$filterJS.="\n\t\t\t\t\t\tbreak;";
$filterJS.="\n\t\t\t\t\t}";
$filterJS.="\n\t\t\t\t}";
$filterJS.="\n\t\t\t\tif({$filterable}_item == selected_{$filterable}) break;";
$filterJS.="\n\t\t\t}";
$filterJS.="\n\t\t}";
$filterJS.="\n\t}";
$filterJS.="\n\t$('{$filterable}').highlight();";
$filterJS.="\n};";
$filterJS.="\n$('{$filterer}').observe('change', function(){ window.setTimeout({$filterable}_change_by_{$filterer}, 25); });";
$filterJS.="\n";
}
$filterableCombo = new Combo;
$filterableCombo->ListType = 0;
$filterableCombo->ListItem = array_slice(array_values($filterableData), 0, 10);
$filterableCombo->ListData = array_slice(array_keys($filterableData), 0, 10);
$filterableCombo->SelectName = $filterable;
$filterableCombo->AllowNull = true;
return $filterJS;
}
#########################################################
function br2nl($text){
return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $text);
}
#########################################################
if(!function_exists('htmlspecialchars_decode')){
function htmlspecialchars_decode($string, $quote_style = ENT_COMPAT){
return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
}
}
#########################################################
function entitiesToUTF8($input){
return preg_replace_callback('/(&#[0-9]+;)/', '_toUTF8', $input);
}
function _toUTF8($m){
if(function_exists('mb_convert_encoding')){
return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES");
}else{
return $m[1];
}
}
#########################################################
function func_get_args_byref() {
if(!function_exists('debug_backtrace')) return false;
$trace = debug_backtrace();
return $trace[1]['args'];
}
#########################################################
function permissions_sql($table, $level = 'all'){
if(!in_array($level, array('user', 'group'))){ $level = 'all'; }
$perm = getTablePermissions($table);
$from = '';
$where = '';
$pk = getPKFieldName($table);
if($perm[2] == 1 || ($perm[2] > 1 && $level == 'user')){ // view owner only
$from = 'membership_userrecords';
$where = "(`$table`.`$pk`=membership_userrecords.pkValue and membership_userrecords.tableName='$table' and lcase(membership_userrecords.memberID)='".getLoggedMemberID()."')";
}elseif($perm[2] == 2 || ($perm[2] > 2 && $level == 'group')){ // view group only
$from = 'membership_userrecords';
$where = "(`$table`.`$pk`=membership_userrecords.pkValue and membership_userrecords.tableName='$table' and membership_userrecords.groupID='".getLoggedGroupID()."')";
}elseif($perm[2] == 3){ // view all
// no further action
}elseif($perm[2] == 0){ // view none
return false;
}
return array('where' => $where, 'from' => $from, 0 => $where, 1 => $from);
}
#########################################################
function error_message($msg, $back_url = ''){
$curr_dir = dirname(__FILE__);
global $Translation;
ob_start();
include_once($curr_dir . '/header.php');
echo '<div class="panel panel-danger">';
echo '<div class="panel-heading"><h3 class="panel-title">' . $Translation['error:'] . '</h3></div>';
echo '<div class="panel-body"><p class="text-danger">' . $msg . '</p>';
if($back_url !== false){ // explicitly passing false suppresses the back link completely
echo '<div class="text-center">';
if($back_url){
echo '<a href="' . $back_url . '" class="btn btn-danger btn-lg vspacer-lg"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['< back'] . '</a>';
}else{
echo '<a href="#" class="btn btn-danger btn-lg vspacer-lg" onclick="history.go(-1); return false;"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['< back'] . '</a>';
}
echo '</div>';
}
echo '</div>';
echo '</div>';
include_once($curr_dir . '/footer.php');
$out = ob_get_contents();
ob_end_clean();
return $out;
}
#########################################################
function toMySQLDate($formattedDate, $sep = datalist_date_separator, $ord = datalist_date_format){
// extract date elements
$de=explode($sep, $formattedDate);
$mySQLDate=intval($de[strpos($ord, 'Y')]).'-'.intval($de[strpos($ord, 'm')]).'-'.intval($de[strpos($ord, 'd')]);
return $mySQLDate;
}
#########################################################
function highlight($needle, $haystack){
$needle = preg_quote($needle, "/");
return preg_replace("/(?!<.*?)({$needle})(?![^<>]*?>)/i", '<span class="search_highlight">\1</span>', $haystack);
}
#########################################################
function reIndex(&$arr){
$i=1;
foreach($arr as $n=>$v){
$arr2[$i]=$n;
$i++;
}
return $arr2;
}
#########################################################
function get_embed($provider, $url, $max_width = '', $max_height = '', $retrieve = 'html'){
global $Translation;
if(!$url) return '';
$providers = array(
'youtube' => array('oembed' => 'http://www.youtube.com/oembed?'),
'googlemap' => array('oembed' => '', 'regex' => '/^http.*\.google\..*maps/i')
);
if(!isset($providers[$provider])){
return '<div class="text-danger">' . $Translation['invalid provider'] . '</div>';
}
if(isset($providers[$provider]['regex']) && !preg_match($providers[$provider]['regex'], $url)){
return '<div class="text-danger">' . $Translation['invalid url'] . '</div>';
}
if($providers[$provider]['oembed']){
$oembed = $providers[$provider]['oembed'] . 'url=' . urlencode($url) . "&maxwidth={$max_width}&maxheight={$max_height}&format=json";
$data_json = request_cache($oembed);
$data = json_decode($data_json, true);
if($data === null){
/* an error was returned rather than a json string */
if($retrieve == 'html') return "<div class=\"text-danger\">{$data_json}\n<!-- {$oembed} --></div>";
return '';
}
return (isset($data[$retrieve]) ? $data[$retrieve] : $data['html']);
}
/* special cases (where there is no oEmbed provider) */
if($provider == 'googlemap') return get_embed_googlemap($url, $max_width, $max_height, $retrieve);
return '<div class="text-danger">Invalid provider!</div>';
}
#########################################################
function get_embed_googlemap($url, $max_width = '', $max_height = '', $retrieve = 'html'){
global $Translation;
$url_parts = parse_url($url);
$coords_regex = '/-?\d+(\.\d+)?[,+]-?\d+(\.\d+)?(,\d{1,2}z)?/'; /* http://stackoverflow.com/questions/2660201 */
if(preg_match($coords_regex, $url_parts['path'] . '?' . $url_parts['query'], $m)){
list($lat, $long, $zoom) = explode(',', $m[0]);
$zoom = intval($zoom);
if(!$zoom) $zoom = 10; /* default zoom */
if(!$max_height) $max_height = 360;
if(!$max_width) $max_width = 480;
$api_key = '';
$embed_url = "https://www.google.com/maps/embed/v1/view?key={$api_key}¢er={$lat},{$long}&zoom={$zoom}&maptype=roadmap";
$thumbnail_url = "https://maps.googleapis.com/maps/api/staticmap?center={$lat},{$long}&zoom={$zoom}&maptype=roadmap&size={$max_width}x{$max_height}";
if($retrieve == 'html'){
return "<iframe width=\"{$max_width}\" height=\"{$max_height}\" frameborder=\"0\" style=\"border:0\" src=\"{$embed_url}\"></iframe>";
}else{
return $thumbnail_url;
}
}else{
return '<div class="text-danger">' . $Translation['cant retrieve coordinates from url'] . '</div>';
}
}
#########################################################
function request_cache($request, $force_fetch = false){
$max_cache_lifetime = 7 * 86400; /* max cache lifetime in seconds before refreshing from source */
/* membership_cache table exists? if not, create it */
static $cache_table_exists = false;
if(!$cache_table_exists && !$force_fetch){
$te = sqlValue("show tables like 'membership_cache'");
if(!$te){
if(!sql("CREATE TABLE `membership_cache` (`request` VARCHAR(100) NOT NULL, `request_ts` INT, `response` TEXT NOT NULL, PRIMARY KEY (`request`))", $eo)){
/* table can't be created, so force fetching request */
return request_cache($request, true);
}
}
$cache_table_exists = true;
}
/* retrieve response from cache if exists */
if(!$force_fetch){
$res = sql("select response, request_ts from membership_cache where request='" . md5($request) . "'", $eo);
if(!$row = db_fetch_array($res)) return request_cache($request, true);
$response = $row[0];
$response_ts = $row[1];
if($response_ts < time() - $max_cache_lifetime) return request_cache($request, true);
}
/* if no response in cache, issue a request */
if(!$response || $force_fetch){
$response = @file_get_contents($request);
if($response === false){
$error = error_get_last();
$error_message = preg_replace('/.*: (.*)/', '$1', $error['message']);
return $error_message;
}elseif($cache_table_exists){
/* store response in cache */
$ts = time();
sql("replace into membership_cache set request='" . md5($request) . "', request_ts='{$ts}', response='" . makeSafe($response, false) . "'", $eo);
}
}
return $response;
}
#########################################################
function check_record_permission($table, $id, $perm = 'view'){
if($perm != 'edit' && $perm != 'delete') $perm = 'view';
$perms = getTablePermissions($table);
if(!$perms[$perm]) return false;
$safe_id = makeSafe($id);
$safe_table = makeSafe($table);
if($perms[$perm] == 1){ // own records only
$username = getLoggedMemberID();
$owner = sqlValue("select memberID from membership_userrecords where tableName='{$safe_table}' and pkValue='{$safe_id}'");
if($owner == $username) return true;
}elseif($perms[$perm] == 2){ // group records
$group_id = getLoggedGroupID();
$owner_group_id = sqlValue("select groupID from membership_userrecords where tableName='{$safe_table}' and pkValue='{$safe_id}'");
if($owner_group_id == $group_id) return true;
}elseif($perms[$perm] == 3){ // all records
return true;
}
return false;
}
#########################################################
function sql($statment, &$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.
*/
global $Translation;
static $connected = false, $db_link;
$dbServer = config('dbServer');
$dbUsername = config('dbUsername');
$dbPassword = config('dbPassword');
$dbDatabase = config('dbDatabase');
ob_start();
if(!$connected){
/****** Connect to MySQL ******/
if(!extension_loaded('mysql') && !extension_loaded('mysqli')){
echo error_message('PHP is not configured to connect to MySQL on this machine. Please see <a href="http://www.php.net/manual/en/ref.mysql.php">this page</a> for help on how to configure MySQL.');