-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathGlobal.cfc
More file actions
4537 lines (4220 loc) · 168 KB
/
Copy pathGlobal.cfc
File metadata and controls
4537 lines (4220 loc) · 168 KB
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
component output="false" {
public any function $doubleCheckedLock(
required string name,
required string condition,
required string execute,
struct conditionArgs = "#StructNew()#",
struct executeArgs = "#StructNew()#",
numeric timeout = 30
) {
local.rv = $invoke(method = arguments.condition, invokeArgs = arguments.conditionArgs);
if (IsBoolean(local.rv) AND NOT local.rv) {
lock timeout="#arguments.timeout#" name="#arguments.name#" {
local.rv = $invoke(method = arguments.condition, invokeArgs = arguments.conditionArgs);
if (IsBoolean(local.rv) AND NOT local.rv) {
local.rv = $invoke(method = arguments.execute, invokeArgs = arguments.executeArgs)
}
}
}
return local.rv;
}
public any function $simpleLock(
required string name,
required string type,
required string execute,
struct executeArgs = "#StructNew()#",
numeric timeout = 30
) {
if (StructKeyExists(arguments, "object")) {
lock name="#arguments.name#" type="#arguments.type#" timeout="#arguments.timeout#" {
local.rv = $invoke(
component = "#arguments.object#",
method = "#arguments.execute#",
argumentCollection = "#arguments.executeArgs#"
);
}
} else {
arguments.executeArgs.$locked = true;
lock name="#arguments.name#" type="#arguments.type#" timeout="#arguments.timeout#" {
local.rv = $invoke(method = "#arguments.execute#", argumentCollection = "#arguments.executeArgs#");
}
}
if (StructKeyExists(local, "rv")) {
return local.rv;
}
}
public struct function $image() {
local.rv = {};
if (arguments.action == "info") {
local.rv = $engineAdapter().imageInfo(arguments.source);
} else if ($engineAdapter().isBoxLang()) {
Throw(
type = "Wheels.Image.UnsupportedAction",
message = "The `$image()` function in BoxLang currently supports only the 'info' action."
);
} else {
// Adobe or Lucee: use cfimage
arguments.structName = "rv";
local.args = {};
for (local.key in arguments) {
local.args[local.key] = arguments[local.key];
}
cfimage(attributeCollection = local.args);
local.rv = local.rv;
}
return local.rv;
}
public void function $mail() {
if (StructKeyExists(arguments, "mailparts")) {
local.mailparts = arguments.mailparts;
StructDelete(arguments, "mailparts");
}
if (StructKeyExists(arguments, "mailparams")) {
local.mailparams = arguments.mailparams;
StructDelete(arguments, "mailparams");
}
if (StructKeyExists(arguments, "tagContent")) {
local.tagContent = arguments.tagContent;
StructDelete(arguments, "tagContent");
}
local.args = {};
for (local.key in arguments) {
local.args[local.key] = arguments[local.key];
}
cfmail(attributeCollection = "#local.args#") {
if (StructKeyExists(local, "mailparams")) {
for (local.i in local.mailparams) {
cfmailparam(attributeCollection = "#local.i#");
}
}
if (StructKeyExists(local, "mailparts")) {
for (local.i in local.mailparts) {
local.innerTagContent = local.i.tagContent;
StructDelete(local.i, "tagContent");
cfmailpart(attributeCollection = "#local.i#") {
WriteOutput(local.innerTagContent)
}
}
}
if (StructKeyExists(local, "tagContent")) {
WriteOutput(local.tagContent)
}
}
}
public any function $cache() {
// If cache is found only the function is aborted, not page. --->
variables.$instance.reCache = false;
// Engines without the `cfcache` built-in (e.g. RustCFML) can't back
// the template/static cache. Degrade to a no-op: leaving reCache=true
// means the request still renders normally, just without this layer.
if ($hasEngineAdapter() && !$engineAdapter().supportsCfcache()) {
variables.$instance.reCache = true;
return;
}
local.args = {};
for (local.key in arguments) {
local.args[local.key] = arguments[local.key];
}
cfcache(attributeCollection = "#local.args#");
variables.$instance.reCache = true;
}
public void function $content() {
local.args = {};
for (local.key in arguments) {
local.args[local.key] = arguments[local.key];
}
// Best-effort: cfcontent throws on a committed response (Adobe CF).
if ($responseCommitted()) {
return;
}
try {
cfcontent(attributeCollection = "#local.args#");
} catch (any e) {
// Re-probe to handle the isCommitted/throw race; rethrow only when
// the response is still uncommitted (a genuine caller error).
if (!$responseCommitted()) {
rethrow;
}
}
}
public void function $header() {
// Plain-struct copy: Adobe CF 2023+ rejects `arguments` as
// attributeCollection (#10 cross-engine invariant). `statusText` is
// stripped because Adobe CF 2025 removed it.
local.args = {};
for (local.key in arguments) {
if (local.key != "statusText") {
local.args[local.key] = arguments[local.key];
}
}
// Best-effort: cfheader throws on a committed response (Adobe CF). The
// short-circuit is critical inside onError, where letting the exception
// escape would replace the original error with the cfheader-failure stack.
if ($responseCommitted()) {
return;
}
try {
cfheader(attributeCollection = "#local.args#");
} catch (any e) {
// Re-probe to handle the isCommitted/throw race; rethrow only when
// the response is still uncommitted (a genuine caller error).
if (!$responseCommitted()) {
rethrow;
}
}
}
/**
* Returns true when the servlet response has been committed and headers
* can no longer be modified. Returns false on engines or contexts where
* the underlying servlet probe is unavailable.
*/
public boolean function $responseCommitted() {
try {
return GetPageContext().getResponse().isCommitted();
} catch (any e) {
return false;
}
}
public void function $include(required string template) {
include "#LCase(arguments.template)#";
}
public void function $includeAndOutput(required string template) {
include "#LCase(arguments.template)#";
}
public string function $includeAndReturnOutput(required string $template) {
// Make it so the developer can reference passed in arguments in the loc scope if they prefer.
if (StructKeyExists(arguments, "$type") AND arguments.$type IS "partial") {
local = arguments;
}
// Include the template and return the result.
// Variable is set to $wheels to limit chances of it being overwritten in the included template.
// cfformat-ignore-start
savecontent variable="local.$wheels" {
include "#LCase(arguments.$template)#"
};
// cfformat-ignore-end
return local.$wheels;
}
/**
* Includes a config file like /config/settings.cfm or /config/services.cfm
* during application start, capturing any output it produces.
*
* If the file fails to compile or run, the failure is logged and rethrown
* as a named `Wheels.ConfigIncludeFailed` error that carries the failing
* template path and the original engine message (original type/detail are
* preserved in `detail`). This is deliberate fail-closed behavior in EVERY
* environment: an app whose config did not load must not boot on framework
* defaults and serve traffic. The named error propagates out of
* onApplicationStart by design, and renders on the development error page
* now that onError no longer masks application-start errors.
*
* If the include succeeds but the captured output is non-empty — almost
* always a sign that the file is missing a cfscript wrapper, so Lucee/Adobe
* parse the body as markup and any cfscript-style code becomes literal
* output text that never executes — log a clear warning pointing the
* developer at the most likely cause, and discard the output so it doesn't
* leak into the response of whichever request happened to trigger
* onApplicationStart.
*
* Note for maintainers: deliberately avoids putting any literal cf-tags
* in this docblock — Lucee 7's tag scanner reads CFC comments before
* compilation and treats unclosed tags as an error.
*
* @template Mapping-relative path like "/config/services.cfm".
*/
public void function $includeConfig(required string template) {
try {
// cfformat-ignore-start
savecontent variable="local.$wheelsConfigOutput" {
include "#LCase(arguments.template)#"
};
// cfformat-ignore-end
} catch (any e) {
// Fail closed: a compile-time or runtime failure in a config template is a
// boot-blocking configuration error in EVERY environment. Booting anyway
// would silently run the app on framework defaults (no DI registrations,
// default settings, …) and serve traffic fail-open — strictly worse than
// a hard stop. Log the offending template, then rethrow a NAMED, located
// error that says what broke, where, and why — instead of the old masked,
// app-wide HTTP 500 whose secondary onError failure hid the real cause
// (the canonical trigger is Adobe CF rejecting a top-level
// `var di = injector();` in config/services.cfm — a compile error on
// Adobe, accepted on Lucee — issue #3063). The throw is unconditional:
// no environment branching, no swallowed path.
try {
writeLog(
file = "wheels",
type = "error",
text = "Wheels: " & arguments.template & " failed to compile or run during"
& " onApplicationStart — application start was aborted (fail-closed)."
& " Error: " & e.message
);
} catch (any logErr) {
// Logging is best-effort during application start.
}
Throw(
type = "Wheels.ConfigIncludeFailed",
message = "Failed to include config template '" & arguments.template & "': " & e.message,
detail = "Original exception type: " & e.type & "."
& (StructKeyExists(e, "detail") && Len(e.detail) ? " " & e.detail : "")
& " Application start was aborted because this config file could not be"
& " loaded — fix the file and restart (booting without it would run the"
& " application on framework defaults)."
);
}
if (Len(Trim(local.$wheelsConfigOutput))) {
local.preview = Left(Trim(local.$wheelsConfigOutput), 200);
local.scriptOpen = Chr(60) & "cfscript" & Chr(62);
local.scriptClose = Chr(60) & "/cfscript" & Chr(62);
try {
writeLog(
file = "wheels",
type = "warning",
text = "Wheels: " & arguments.template & " produced output during onApplicationStart"
& " — this almost always means the file body is missing a "
& local.scriptOpen & "..." & local.scriptClose & " wrapper, so the engine is"
& " parsing CFScript-style code as literal markup (registrations like"
& " var di = injector(); never execute, and the bare lines would leak onto"
& " every response if not captured here)."
& " First 200 chars of captured output: " & local.preview
);
} catch (any e) {
// Logging is best-effort during application start.
}
}
}
public any function $directory() {
local.rv = "";
arguments.name = "rv";
local.args = {};
for (local.key in arguments) {
local.args[local.key] = arguments[local.key];
}
cfdirectory(attributeCollection = "#local.args#");
return local.rv;
}
public any function $file() {
local.args = {};
for (local.key in arguments) {
local.args[local.key] = arguments[local.key];
}
cffile(attributeCollection = "#local.args#");
}
public any function $cfinvoke(required string component, required string method, struct invokeArguments) {
cfinvoke
component = "#arguments.component#"
method = "#arguments.method#"
returnVariable = "#arguments.returnVariable#"
argumentCollection = "#arguments.invokeArguments#";
return local.rv;
}
public any function $invoke() {
arguments.returnVariable = "local.rv";
if (StructKeyExists(arguments, "componentReference")) {
arguments.component = arguments.componentReference;
StructDelete(arguments, "componentReference");
} else if (NOT StructKeyExists(variables, arguments.method)) {
// this is done so that we can call dynamic methods via "onMissingMethod" on the object (we need to pass in the object for this so it can call methods on the "this" scope instead)
arguments.component = this;
}
if (StructKeyExists(arguments, "invokeArgs")) {
arguments.argumentCollection = arguments.invokeArgs;
if (StructCount(arguments.argumentCollection) IS NOT ListLen(StructKeyList(arguments.argumentCollection))) {
// work-around for fasthashremoved cf8 bug
arguments.argumentCollection = StructNew();
for (local.i in StructKeyList(arguments.invokeArgs)) {
arguments.argumentCollection[local.i] = arguments.invokeArgs[local.i];
}
}
if (StructKeyExists(arguments.invokeArgs, "componentReference")) {
arguments.component = arguments.invokeArgs.componentReference;
}
StructDelete(arguments, "invokeArgs");
}
local.args = {};
for (local.key in arguments) {
local.args[local.key] = arguments[local.key];
}
cfinvoke(attributeCollection = "#local.args#");
if (StructKeyExists(local, "rv")) {
return local.rv;
}
}
public void function $location(boolean delay = false) {
StructDelete(arguments, "$args", false);
if (NOT arguments.delay) {
StructDelete(arguments, "delay", false);
local.args = {};
for (local.key in arguments) {
local.args[local.key] = arguments[local.key];
}
cflocation(attributeCollection = "#local.args#");
}
}
public void function $htmlhead() {
local.args = {};
for (local.key in arguments) {
local.args[local.key] = arguments[local.key];
}
// Best-effort: cfhtmlhead throws "Unable to add text to HTML HEAD tag"
// on a committed response (Adobe CF). Same defensive shape as $header().
if ($responseCommitted()) {
return;
}
try {
cfhtmlhead(attributeCollection = "#local.args#");
} catch (any e) {
// Re-probe to handle the isCommitted/throw race; rethrow only when
// the response is still uncommitted (a genuine caller error).
if (!$responseCommitted()) {
rethrow;
}
}
}
public any function $dbinfo() {
arguments.name = "local.rv";
if (StructKeyExists(arguments, "username") && !Len(arguments.username)) {
StructDelete(arguments, "username");
}
if (StructKeyExists(arguments, "password") && !Len(arguments.password)) {
StructDelete(arguments, "password");
}
// BoxLang specific fix for index queries (MSSQL/Oracle)
if (
$engineAdapter().isBoxLang() &&
StructKeyExists(arguments, "type") && arguments.type == "index" &&
StructKeyExists(arguments, "table")
) {
local.adapter = $get("adapterName");
if (local.adapter == "MicrosoftSQLServerModel") {
local.sql = "
SELECT
DB_NAME() AS TABLE_CAT,
SCHEMA_NAME(t.schema_id) AS TABLE_SCHEM,
t.name AS TABLE_NAME,
CAST(CASE WHEN i.is_unique = 0 THEN 1 ELSE 0 END AS INT) AS NON_UNIQUE,
t.name AS INDEX_QUALIFIER,
i.name AS INDEX_NAME,
CASE
WHEN i.type = 1 THEN 'Clustered Index'
WHEN i.type = 2 THEN 'Other Index'
ELSE 'Other Index'
END AS TYPE,
CAST(ic.key_ordinal AS INT) AS ORDINAL_POSITION,
c.name AS COLUMN_NAME,
CASE WHEN ic.is_descending_key = 0 THEN 'A' ELSE 'D' END AS ASC_OR_DESC,
CAST(0 AS INT) AS CARDINALITY,
CAST(0 AS INT) AS PAGES,
'' AS FILTER_CONDITION
FROM sys.indexes i
INNER JOIN sys.objects t ON i.object_id = t.object_id
INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
WHERE t.name = '#arguments.table#'
AND t.type = 'U'
AND i.type_desc IN ('CLUSTERED', 'NONCLUSTERED')
ORDER BY i.name, ic.key_ordinal
";
local.rv = $query(sql = local.sql, datasource = arguments.datasource);
return local.rv;
}
if (local.adapter == "OracleModel") {
local.sql = "
SELECT
NULL AS TABLE_CAT,
ai.OWNER AS TABLE_SCHEM,
ai.TABLE_NAME,
CASE WHEN ai.UNIQUENESS = 'NONUNIQUE' THEN 1 ELSE 0 END AS NON_UNIQUE,
ai.OWNER AS INDEX_QUALIFIER,
ai.INDEX_NAME,
'Other Index' AS TYPE,
ac.COLUMN_POSITION AS ORDINAL_POSITION,
ac.COLUMN_NAME,
CASE WHEN ac.DESCEND = 'DESC' THEN 'D' ELSE 'A' END AS ASC_OR_DESC,
0 AS CARDINALITY,
0 AS PAGES,
'' AS FILTER_CONDITION
FROM ALL_INDEXES ai
JOIN ALL_IND_COLUMNS ac ON ai.INDEX_NAME = ac.INDEX_NAME AND ai.OWNER = ac.INDEX_OWNER
WHERE ai.TABLE_NAME = UPPER('#arguments.table#')
AND ai.INDEX_TYPE != 'LOB'
ORDER BY ai.INDEX_NAME, ac.COLUMN_POSITION
";
local.rv = $query(sql = local.sql, datasource = arguments.datasource);
return local.rv;
}
}
if (
StructKeyExists(arguments, "type") &&
arguments.type eq "index" &&
$get("adapterName") eq "SQLiteModel"
) {
local.sql = "
SELECT
NULL AS TABLE_CAT,
NULL AS TABLE_SCHEM,
'#arguments.table#' AS TABLE_NAME,
CASE WHEN il.""unique"" = 0 THEN 1 ELSE 0 END AS NON_UNIQUE,
NULL AS INDEX_QUALIFIER,
il.name AS INDEX_NAME,
'Other Index' AS TYPE,
ii.seqno + 1 AS ORDINAL_POSITION,
ii.name AS COLUMN_NAME,
'A' AS ASC_OR_DESC,
0 AS CARDINALITY,
0 AS PAGES,
'' AS FILTER_CONDITION
FROM pragma_index_list('#arguments.table#') il
JOIN pragma_index_info(il.name) ii
UNION ALL
SELECT
NULL AS TABLE_CAT,
NULL AS TABLE_SCHEM,
'#arguments.table#' AS TABLE_NAME,
0 AS NON_UNIQUE,
NULL AS INDEX_QUALIFIER,
'PRIMARY' AS INDEX_NAME,
'Primary Key' AS TYPE,
pk AS ORDINAL_POSITION,
name AS COLUMN_NAME,
'A' AS ASC_OR_DESC,
0 AS CARDINALITY,
0 AS PAGES,
'' AS FILTER_CONDITION
FROM pragma_table_info('#arguments.table#')
WHERE pk > 0
ORDER BY INDEX_NAME, ORDINAL_POSITION;
";
local.rv = $query(sql = local.sql, datasource = arguments.datasource);
return local.rv;
}
// If the cfdbinfo call fails we try it again, this time setting "dbname" explicitly.
// Sometimes the call fails when using a custom database connection string.
// In that case the database name is not known by the CF server and it will just use any of the databases that the data source has access to.
// That can incorrectly be "information_schema" for example.
try {
local.args = {};
for (local.key in arguments) {
local.args[local.key] = arguments[local.key];
}
cfdbinfo(attributeCollection = local.args);
} catch (any e) {
local.args = {};
for (local.key in arguments) {
local.args[local.key] = arguments[local.key];
}
cfdbinfo(attributeCollection = local.args);
local.type = arguments.type;
arguments.type = "dbnames";
local.args = {};
for (local.key in arguments) {
local.args[local.key] = arguments[local.key];
}
cfdbinfo(attributeCollection = local.args);
if (local.rv.recordCount GT 1) {
for (local.i in local.rv) {
if (local.i.database_name IS NOT "information_schema") {
arguments.dbname = local.i.database_name;
}
}
}
arguments.type = local.type;
local.args = {};
for (local.key in arguments) {
local.args[local.key] = arguments[local.key];
}
cfdbinfo(attributeCollection = local.args);
}
// Override name for test mode
if (
arguments.type IS "version" AND
StructKeyExists(url, "controller") AND
StructKeyExists(url, "action") AND
StructKeyExists(url, "view") AND
StructKeyExists(url, "type") AND
StructKeyExists(url, "adapter")
) {
if (url.controller IS "wheels" AND url.action IS "wheels" AND url.view IS "tests" AND url.type IS "core") {
QuerySetCell(local.rv, "driver_name", url.adapter);
}
}
return local.rv;
}
public any function $wddx(required any input, string action = "cfml2wddx", boolean useTimeZoneInfo = true) {
arguments.output = "local.output";
local.args = {};
for (local.key in arguments) {
local.args[local.key] = arguments[local.key];
}
cfwddx(attributeCollection = "#local.args#");
if (StructKeyExists(local, "output")) {
return local.output;
}
}
public any function $zip() {
$engineAdapter().prepareZipArgs(arguments);
local.args = {};
for (local.key in arguments) {
local.args[local.key] = arguments[local.key];
}
cfzip(attributeCollection = "#local.args#");
}
public any function $query(required string sql) {
StructDelete(arguments, "name");
// allow the use of query of queries, caveat: Query must be called query. Eg: SELECT * from query
if (StructKeyExists(arguments, "query") && IsQuery(arguments.query)) {
var query = Duplicate(arguments.query);
}
local.rv = QueryExecute(PreserveSingleQuotes(arguments.sql), [], arguments);
// some sql statements may not return a value
if (StructKeyExists(local, "rv")) {
return local.rv;
}
}
/**
* Returns the current setting for the supplied Wheels setting or the current default for the supplied Wheels function argument.
*
* [section: Configuration]
* [category: Miscellaneous Functions]
*
* @name Variable name to get setting for.
* @functionName Function name to get setting for.
*/
public any function get(required string name, string functionName = "") {
return $get(argumentCollection = arguments);
}
/**
* Returns the value of an environment variable. Checks application.env (loaded from .env files) first, then falls back to system environment variables (server.system.environment). Returns the default if the variable is not found in either location.
*
* [section: Configuration]
* [category: Miscellaneous Functions]
*
* @name The environment variable name to look up.
* @defaultValue Value to return if the variable is not found. The legacy
* named argument `default` is also accepted for backwards compatibility
* with pre-rename callers.
*/
public any function env(required string name, any defaultValue = "") {
if (StructKeyExists(application, "env") && StructKeyExists(application.env, arguments.name)) {
return application.env[arguments.name];
}
if (
StructKeyExists(server, "system")
&& StructKeyExists(server.system, "environment")
&& StructKeyExists(server.system.environment, arguments.name)
) {
return server.system.environment[arguments.name];
}
// Back-compat for the legacy `default = "Y"` named-arg form. The
// parameter was renamed from `default` (a CFML reserved word Adobe CF
// refuses to bind) to `defaultValue`; named arguments still land in
// `arguments` under their literal key on every engine.
if (StructKeyExists(arguments, "default")) {
return arguments.default;
}
return arguments.defaultValue;
}
/**
* Use to configure a global setting or set a default for a function.
*
* [section: Configuration]
* [category: Miscellaneous Functions]
*/
public void function set() {
$set(argumentCollection = arguments);
}
/**
* Internal function.
* Called from get().
*/
public any function $get(required string name, string functionName = "") {
// Multi-tenant config override: per-tenant settings take precedence
// over application-level settings (non-function settings only).
// Security-sensitive settings cannot be overridden per-tenant.
// Use a StructKeyExists chain for safe nested scope traversal during app
// startup (IsDefined string-parses its dotted-path argument on every call
// and $get runs on every settings read so it's too expensive here).
if (
!Len(arguments.functionName)
&& StructKeyExists(request, "wheels")
&& StructKeyExists(request.wheels, "tenant")
&& StructKeyExists(request.wheels.tenant, "config")
&& StructKeyExists(request.wheels.tenant.config, arguments.name)
&& !ListFindNoCase(
"encryptionAlgorithm,encryptionSecretKey,encryptionEncoding,CSRFProtection,csrfStore,reloadPassword,obfuscateUrls",
arguments.name
)
) {
return request.wheels.tenant.config[arguments.name];
}
local.appKey = $appKey();
if (Len(arguments.functionName)) {
local.rv = application[local.appKey].functions[arguments.functionName][arguments.name];
} else {
local.rv = application[local.appKey][arguments.name];
}
return local.rv;
}
/**
* Internal function.
* Called from set().
*/
public void function $set() {
local.appKey = $appKey();
if (ArrayLen(arguments) > 1) {
for (local.key in arguments) {
if (local.key != "functionName") {
local.functionNameArray = ListToArray(arguments.functionName);
local.iEnd = ArrayLen(local.functionNameArray);
for (local.i = 1; local.i <= local.iEnd; local.i++) {
local.functionName = Trim(local.functionNameArray[local.i]);
application[local.appKey].functions[local.functionName][local.key] = arguments[local.key];
}
}
}
} else {
application[local.appKey][StructKeyList(arguments)] = arguments[1];
}
}
// ======================================================================
// MULTI-TENANCY FUNCTIONS
// ======================================================================
/**
* Returns the current tenant struct, or an empty struct if no tenant is active.
* The tenant struct contains: `id`, `dataSource`, `config`, and `$locked`.
*
* [section: Configuration]
* [category: Multi-Tenancy]
*/
public struct function tenant() {
if (IsDefined("request.wheels.tenant")) {
return request.wheels.tenant;
}
return {};
}
/**
* Returns the current tenant's datasource name, or the application default if no tenant is active.
*
* [section: Configuration]
* [category: Multi-Tenancy]
*/
public string function $tenantDataSource() {
if (
IsDefined("request.wheels.tenant.dataSource")
&& Len(request.wheels.tenant.dataSource)
) {
return request.wheels.tenant.dataSource;
}
return $get("dataSourceName");
}
/**
* Switches the active tenant mid-request. Throws if the current tenant is locked
* (set by TenantResolver middleware) unless `force` is true.
*
* [section: Configuration]
* [category: Multi-Tenancy]
*
* @tenant Struct with at minimum a `dataSource` key. Optional: `id`, `config`.
* @force If true, overrides the lock set by TenantResolver middleware.
*/
public void function switchTenant(required struct tenant, boolean force = false) {
if (!StructKeyExists(arguments.tenant, "dataSource") || !Len(arguments.tenant.dataSource)) {
Throw(type = "Wheels.InvalidTenant", message = "The tenant struct must contain a non-empty `dataSource` key.");
}
if (!StructKeyExists(request, "wheels")) {
request.wheels = {};
}
// Check if current tenant is locked
if (
!arguments.force
&& IsDefined("request.wheels.tenant")
&& StructKeyExists(request.wheels.tenant, "$locked")
&& request.wheels.tenant["$locked"]
) {
Throw(
type = "Wheels.TenantLocked",
message = "Cannot switch tenants mid-request. The current tenant was set by middleware and is locked.",
extendedInfo = "Use `switchTenant(tenant={...}, force=true)` to override, or remove the lock in your middleware configuration."
);
}
// Set defaults
if (!StructKeyExists(arguments.tenant, "id")) {
arguments.tenant.id = "";
}
if (!StructKeyExists(arguments.tenant, "config")) {
arguments.tenant.config = {};
}
request.wheels.tenant = arguments.tenant;
}
// ======================================================================
// CACHE FUNCTIONS
// ======================================================================
/**
* Creates a unique string based on any arguments passed in (used as a key for caching mostly).
*/
public string function $hashedKey() {
local.rv = "";
// make all cache keys domain specific (do not use request scope below since it may not always be initialized)
StructInsert(arguments, ListLen(StructKeyList(arguments)) + 1, cgi.http_host, true);
// we need to make sure we are looping through the passed in arguments in the same order everytime
local.values = [];
local.keyList = ListSort(StructKeyList(arguments), "textnocase", "asc");
local.keyArray = ListToArray(local.keyList);
local.iEnd = ArrayLen(local.keyArray);
for (local.i = 1; local.i <= local.iEnd; local.i++) {
ArrayAppend(local.values, arguments[local.keyArray[local.i]]);
}
if (!ArrayIsEmpty(local.values)) {
// this might fail if a query contains binary data so in those rare cases we fall back on using cfwddx (which is a little bit slower which is why we don't use it all the time)
try {
local.rv = SerializeJSON(local.values);
local.rv = $engineAdapter().normalizeForHash(local.rv);
} catch (any e) {
local.rv = $wddx(input = local.values);
}
}
return Hash(local.rv);
}
/**
* Internal function.
* Case-sensitive, constant-time string comparison. Both values are hashed with
* SHA-256 before being compared via MessageDigest.isEqual so the comparison
* neither leaks length information nor exits early on the first differing byte.
* Used by the reload/restart password gate and the environment-switch gate.
*/
public boolean function $secureCompare(required string candidate, required string comparedValue) {
return CreateObject("java", "java.security.MessageDigest").isEqual(
Hash(arguments.candidate, "SHA-256").getBytes("UTF-8"),
Hash(arguments.comparedValue, "SHA-256").getBytes("UTF-8")
);
}
/**
* Internal function.
*/
public any function $timeSpanForCache(
required any cache,
numeric defaultCacheTime = application.wheels.defaultCacheTime,
string cacheDatePart = application.wheels.cacheDatePart
) {
local.cache = arguments.defaultCacheTime;
if (IsNumeric(arguments.cache)) {
local.cache = arguments.cache;
}
local.listArray = [0, 0, 0, 0];
local.dateParts = "d,h,n,s";
local.datePartsArray = ListToArray(local.dateParts);
local.iEnd = ArrayLen(local.datePartsArray);
for (local.i = 1; local.i <= local.iEnd; local.i++) {
if (arguments.cacheDatePart == local.datePartsArray[local.i]) {
local.listArray[local.i] = local.cache;
}
}
local.rv = CreateTimespan(local.listArray[1], local.listArray[2], local.listArray[3], local.listArray[4]);
return local.rv;
}
/**
* Internal function.
*/
public void function $addToCache(
required string key,
required any value,
numeric time = application.wheels.defaultCacheTime,
string category = "main"
) {
local.currentCount = $cacheCount();
if (
application.wheels.cacheCullPercentage > 0
&& application.wheels.cacheLastCulledAt < DateAdd("n", -application.wheels.cacheCullInterval, Now())
&& local.currentCount >= application.wheels.maximumItemsToCache
) {
// the cache is full so flush out expired items to make more room if possible
// (the maximum applies to the cache as a whole so we cull across all categories,
// otherwise a write to a small category would free nothing and get dropped)
local.deletedItems = 0;
if (application.wheels.cacheCullPercentage < 100) {
local.maxItemsToDelete = Ceiling(local.currentCount * application.wheels.cacheCullPercentage / 100);
} else {
local.maxItemsToDelete = local.currentCount;
}
local.now = Now();
local.categories = StructKeyArray(application.wheels.cache);
local.iEnd = ArrayLen(local.categories);
for (local.i = 1; local.i <= local.iEnd && local.deletedItems < local.maxItemsToDelete; local.i++) {
local.cacheCategory = local.categories[local.i];
// snapshot the keys so we never delete from the struct we are iterating over
local.cacheKeys = StructKeyArray(application.wheels.cache[local.cacheCategory]);
local.jEnd = ArrayLen(local.cacheKeys);
for (local.j = 1; local.j <= local.jEnd && local.deletedItems < local.maxItemsToDelete; local.j++) {
local.cacheKey = local.cacheKeys[local.j];
if (
StructKeyExists(application.wheels.cache[local.cacheCategory], local.cacheKey)
&& local.now > application.wheels.cache[local.cacheCategory][local.cacheKey].expiresAt
) {
$removeFromCache(key = local.cacheKey, category = local.cacheCategory);
local.deletedItems++;
}
}
}
local.currentCount -= local.deletedItems;
application.wheels.cacheLastCulledAt = Now();
}
if (local.currentCount < application.wheels.maximumItemsToCache) {
local.cacheItem = {};
local.cacheItem.expiresAt = DateAdd(application.wheels.cacheDatePart, arguments.time, Now());
if (IsSimpleValue(arguments.value)) {
local.cacheItem.value = arguments.value;
} else {
local.cacheItem.value = Duplicate(arguments.value);
}
application.wheels.cache[arguments.category][arguments.key] = local.cacheItem;
}
}
/**
* Internal function.
*/
public any function $getFromCache(required string key, string category = "main") {
local.rv = false;
try {
if (StructKeyExists(application.wheels.cache[arguments.category], arguments.key)) {
if (Now() > application.wheels.cache[arguments.category][arguments.key].expiresAt) {
$removeFromCache(key = arguments.key, category = arguments.category);
} else {
if (IsSimpleValue(application.wheels.cache[arguments.category][arguments.key].value)) {
local.rv = application.wheels.cache[arguments.category][arguments.key].value;
} else {
local.rv = Duplicate(application.wheels.cache[arguments.category][arguments.key].value);
}
}
}
} catch (any e) {
}
return local.rv;
}
/**
* Internal function.
*/
public void function $removeFromCache(required string key, string category = "main") {
StructDelete(application.wheels.cache[arguments.category], arguments.key);
}
/**
* Internal function.
*/
public numeric function $cacheCount(string category = "") {
if (Len(arguments.category)) {
local.rv = StructCount(application.wheels.cache[arguments.category]);
} else {
local.rv = 0;
for (local.key in application.wheels.cache) {
local.rv += StructCount(application.wheels.cache[local.key]);
}
}
return local.rv;
}
/**
* Internal function.
*/
public void function $clearCache(string category = "") {
if (Len(arguments.category)) {
StructClear(application.wheels.cache[arguments.category]);
} else {
StructClear(application.wheels.cache);
}
}
// ======================================================================
// FACTORY FUNCTIONS
// ======================================================================
/**
* Internal function.
*/
public any function $cachedModelClassExists(required string name) {
local.rv = false;
if (StructKeyExists(application.wheels.models, arguments.name)) {
local.rv = application.wheels.models[arguments.name];
}
return local.rv;
}
/**
* Internal function.
*
* Lock-free warm fast-path lookup used by `model()` to bypass
* `$doubleCheckedLock` and its `$invoke` reflective dispatch on cache