Debian Codegraph @

R/utils.R

raw ◀ ▶
1 Debian patch touch this file
1 #' @include globals.R
2 #' @include map.R
3 NULL
4
5 # @staticimports pkg:staticimports
6 # is_installed get_package_version system_file
7 # s3_register
8 # any_named any_unnamed
9
10 #' Make a random number generator repeatable
11 #'
12 #' Given a function that generates random data, returns a wrapped version of
13 #' that function that always uses the same seed when called. The seed to use can
14 #' be passed in explicitly if desired; otherwise, a random number is used.
15 #'
16 #' @param rngfunc The function that is affected by the R session's seed.
17 #' @param seed The seed to set every time the resulting function is called.
18 #' @return A repeatable version of the function that was passed in.
19 #'
20 #' @note When called, the returned function attempts to preserve the R session's
21 #' current seed by snapshotting and restoring
22 #' [base::.Random.seed()].
23 #'
24 #' @examples
25 #' rnormA <- repeatable(rnorm)
26 #' rnormB <- repeatable(rnorm)
27 #' rnormA(3) # [1] 1.8285879 -0.7468041 -0.4639111
28 #' rnormA(3) # [1] 1.8285879 -0.7468041 -0.4639111
29 #' rnormA(5) # [1] 1.8285879 -0.7468041 -0.4639111 -1.6510126 -1.4686924
30 #' rnormB(5) # [1] -0.7946034 0.2568374 -0.6567597 1.2451387 -0.8375699
31 #' @export
32 repeatable <- function(rngfunc, seed = stats::runif(1, 0, .Machine$integer.max)) {
33 force(seed)
34
35 function(...) {
36 # When we exit, restore the seed to its original state
37 if (exists('.Random.seed', where=globalenv())) {
38 currentSeed <- get('.Random.seed', pos=globalenv())
39 on.exit(assign('.Random.seed', currentSeed, pos=globalenv()))
40 }
41 else {
42 on.exit(rm('.Random.seed', pos=globalenv()))
43 }
44
45 set.seed(seed)
46
47 rngfunc(...)
48 }
49 }
50
51 .globals$ownSeed <- NULL
52 # Evaluate an expression using Shiny's own private stream of
53 # randomness (not affected by set.seed).
54 withPrivateSeed <- function(expr) {
55 # Save the old seed if present.
56 if (exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) {
57 hasOrigSeed <- TRUE
58 origSeed <- .GlobalEnv$.Random.seed
59 } else {
60 hasOrigSeed <- FALSE
61 }
62
63 # Swap in the private seed.
64 if (is.null(.globals$ownSeed)) {
65 if (hasOrigSeed) {
66 # Move old seed out of the way if present.
67 rm(.Random.seed, envir = .GlobalEnv, inherits = FALSE)
68 }
69 } else {
70 .GlobalEnv$.Random.seed <- .globals$ownSeed
71 }
72
73 # On exit, save the modified private seed, and put the old seed back.
74 on.exit({
75 .globals$ownSeed <- .GlobalEnv$.Random.seed
76
77 if (hasOrigSeed) {
78 .GlobalEnv$.Random.seed <- origSeed
79 } else {
80 rm(.Random.seed, envir = .GlobalEnv, inherits = FALSE)
81 }
82 # Need to call this to make sure that the value of .Random.seed gets put
83 # into R's internal RNG state. (Issue #1763)
84 httpuv::getRNGState()
85 })
86
87 expr
88 }
89
90 # Version of runif that runs with private seed
91 p_runif <- function(...) {
92 withPrivateSeed(stats::runif(...))
93 }
94
95 # Version of sample that runs with private seed
96 p_sample <- function(...) {
97 withPrivateSeed(sample(...))
98 }
99
100 # Return a random integral value in the range [min, max).
101 # If only one argument is passed, then min=0 and max=argument.
102 randomInt <- function(min, max) {
103 if (missing(max)) {
104 max <- min
105 min <- 0
106 }
107 if (min < 0 || max <= min)
108 stop("Invalid min/max values")
109
110 min + sample(max-min, 1)-1
111 }
112
113 p_randomInt <- function(...) {
114 withPrivateSeed(randomInt(...))
115 }
116
117 isWholeNum <- function(x, tol = .Machine$double.eps^0.5) {
118 abs(x - round(x)) < tol
119 }
120
121 # Given a vector or list, drop all the NULL items in it
122 dropNulls <- function(x) {
123 x[!vapply(x, is.null, FUN.VALUE=logical(1))]
124 }
125
126 nullOrEmpty <- function(x) {
127 is.null(x) || length(x) == 0
128 }
129 # Given a vector or list, drop all the NULL items in it
130 dropNullsOrEmpty <- function(x) {
131 x[!vapply(x, nullOrEmpty, FUN.VALUE=logical(1))]
132 }
133
134
135 # Given a vector/list, returns a named vector/list (the labels will be blank).
136 asNamed <- function(x) {
137 if (is.null(names(x))) {
138 names(x) <- character(length(x))
139 }
140
141 x
142 }
143
144 empty_named_list <- function() {
145 list(a = 1)[0]
146 }
147
148 # Given two named vectors, join them together, and keep only the last element
149 # with a given name in the resulting vector. If b has any elements with the same
150 # name as elements in a, the element in a is dropped. Also, if there are any
151 # duplicated names in a or b, only the last one with that name is kept.
152 mergeVectors <- function(a, b) {
153 if (any_unnamed(a) || any_unnamed(b)) {
154 stop("Vectors must be either NULL or have names for all elements")
155 }
156
157 x <- c(a, b)
158 drop_idx <- duplicated(names(x), fromLast = TRUE)
159 x[!drop_idx]
160 }
161
162 # Sort a vector by the names of items. If there are multiple items with the
163 # same name, preserve the original order of those items. For empty
164 # vectors/lists/NULL, return the original value.
165 sortByName <- function(x, method = "auto") {
166 if (any_unnamed(x))
167 stop("All items must be named")
168
169 # Special case for empty vectors/lists, and NULL
170 if (length(x) == 0)
171 return(x)
172
173 # Must provide consistent sort order
174 # https://github.com/rstudio/shinytest/issues/409
175 # Using a flag in the snapshot url to determine the method
176 # `method="radix"` uses `C` locale, which is consistent across platforms
177 # Even if two platforms share `en_us.UTF-8`, they may not sort consistently
178 # https://blog.zhimingwang.org/macos-lc_collate-hunt
179 # (macOS) $ LC_ALL=en_US.UTF-8 sort <<<$'python-dev\npython3-dev'
180 # python-dev
181 # python3-dev
182 # (Linux) $ LC_ALL=en_US.UTF-8 sort <<<$'python-dev\npython3-dev'
183 # python3-dev
184 # python-dev
185 x[order(names(x), method = method)]
186 }
187
188 # Sort a vector. If a character vector, sort using C locale, which is consistent
189 # across platforms. Note that radix sort uses C locale according to ?sort.
190 sort_c <- function(x, ...) {
191 # Use UTF-8 encoding, because if encoding is "unknown" for non-ASCII
192 # characters, the sort() will throw an error.
193 if (is.character(x))
194 x <- enc2utf8(x)
195 sort(x, method = "radix", ...)
196 }
197
198
199 # Wrapper around list2env with a NULL check. In R <3.2.0, if an empty unnamed
200 # list is passed to list2env(), it errors. But an empty named list is OK. For
201 # R >=3.2.0, this wrapper is not necessary.
202 list2env2 <- function(x, ...) {
203 # Ensure that zero-length lists have a name attribute
204 if (length(x) == 0)
205 attr(x, "names") <- character(0)
206
207 list2env(x, ...)
208 }
209
210 # Combine dir and (file)name into a file path. If a file already exists with a
211 # name differing only by case, then use it instead.
212 file.path.ci <- function(...) {
213 result <- find.file.ci(...)
214 if (!is.null(result))
215 return(result)
216
217 # If not found, return the file path that was given to us.
218 return(file.path(...))
219 }
220
221 # Does a particular file exist? Case-insensitive for filename, case-sensitive
222 # for path (on platforms with case-sensitive file system).
223 file.exists.ci <- function(...) {
224 !is.null(find.file.ci(...))
225 }
226
227 # Look for a file, case-insensitive for filename, case-sensitive for path (on
228 # platforms with case-sensitive filesystem). If found, return the path to the
229 # file, with the correct case. If not found, return NULL.
230 find.file.ci <- function(...) {
231 default <- file.path(...)
232 if (length(default) > 1)
233 stop("find.file.ci can only check for one file at a time.")
234 if (file.exists(default))
235 return(default)
236
237 dir <- dirname(default)
238 name <- basename(default)
239
240 # If we got here, then we'll check for a directory with the exact case, and a
241 # name with any case.
242 all_files <- list.files(dir, all.files=TRUE, full.names=TRUE,
243 include.dirs=TRUE)
244 match_idx <- tolower(name) == tolower(basename(all_files))
245 matches <- all_files[match_idx]
246 if (length(matches) == 0)
247 return(NULL)
248
249 return(matches[1])
250 }
251
252 # The function base::dir.exists was added in R 3.2.0, but for backward
253 # compatibility we need to add this function
254 dirExists <- function(paths) {
255 file.exists(paths) & file.info(paths)$isdir
256 }
257
258 # Removes empty directory (vectorized). This is needed because file.remove()
259 # on Unix will remove empty directories, but on Windows, it will not. On
260 # Windows, you would need to use unlink(recursive=TRUE), which is not very
261 # safe. This function does it safely on Unix and Windows.
262 dirRemove <- function(path) {
263 for (p in path) {
264 if (!dirExists(p)) {
265 stop("Cannot remove non-existent directory ", p, ".")
266 }
267 if (length(dir(p, all.files = TRUE, no.. = TRUE)) != 0) {
268 stop("Cannot remove non-empty directory ", p, ".")
269 }
270 result <- unlink(p, recursive = TRUE)
271 if (result == 1) {
272 stop("Error removing directory ", p, ".")
273 }
274 }
275 }
276
277 # Attempt to join a path and relative path, and turn the result into a
278 # (normalized) absolute path. The result will only be returned if it is an
279 # existing file/directory and is a descendant of dir.
280 #
281 # Example:
282 # resolve("/Users/jcheng", "shiny") # "/Users/jcheng/shiny"
283 # resolve("/Users/jcheng", "./shiny") # "/Users/jcheng/shiny"
284 # resolve("/Users/jcheng", "shiny/../shiny/") # "/Users/jcheng/shiny"
285 # resolve("/Users/jcheng", ".") # NULL
286 # resolve("/Users/jcheng", "..") # NULL
287 # resolve("/Users/jcheng", "shiny/..") # NULL
288 resolve <- function(dir, relpath) {
289 abs.path <- file.path(dir, relpath)
290 if (!file.exists(abs.path))
291 return(NULL)
292 abs.path <- normalizePath(abs.path, winslash='/', mustWork=TRUE)
293 dir <- normalizePath(dir, winslash='/', mustWork=TRUE)
294 # trim the possible trailing slash under Windows (#306)
295 if (isWindows()) dir <- sub('/$', '', dir)
•296 ## Debian specific hack for /usr/share/javascript symlinks
297 if (substr(abs.path,1,nchar('/usr/share/javascript/'))=='/usr/share/javascript/')
298 return(abs.path)
299 ## Debian specific hack for /usr/share/twitter-bootstrap symlinks
300 if (substr(abs.path,1,nchar('/usr/share/twitter-bootstrap/'))=='/usr/share/twitter-bootstrap/')
301 return(abs.path)
302 if (nchar(abs.path) <= nchar(dir) + 1)
303 return(NULL)
304 if (substr(abs.path, 1, nchar(dir)) != dir ||
305 substr(abs.path, nchar(dir)+1, nchar(dir)+1) != '/') {
306 return(NULL)
307 }
308 return(abs.path)
309 }
310
311 # Given a string, make sure it has a trailing slash.
312 ensure_trailing_slash <- function(path) {
313 if (!grepl("/$", path)) {
314 path <- paste0(path, "/")
315 }
316 path
317 }
318
319
320 isWindows <- function() .Platform$OS.type == 'windows'
321
322 # This is a wrapper for download.file and has the same interface.
323 # The only difference is that, if the protocol is https, it changes the
324 # download settings, depending on platform.
325 download <- function(url, ...) {
326 # First, check protocol. If http or https, check platform:
327 if (grepl('^https?://', url)) {
328
329 # Check whether we are running R 3.2
330 isR32 <- getRversion() >= "3.2"
331
332 # Windows
333 if (.Platform$OS.type == "windows") {
334
335 if (isR32) {
336 method <- "wininet"
337 } else {
338
339 # If we directly use setInternet2, R CMD CHECK gives a Note on Mac/Linux
340 seti2 <- `::`(utils, 'setInternet2')
341
342 # Check whether we are already using internet2 for internal
343 internet2_start <- seti2(NA)
344
345 # If not then temporarily set it
346 if (!internet2_start) {
347 # Store initial settings, and restore on exit
348 on.exit(suppressWarnings(seti2(internet2_start)))
349
350 # Needed for https. Will get warning if setInternet2(FALSE) already run
351 # and internet routines are used. But the warnings don't seem to matter.
352 suppressWarnings(seti2(TRUE))
353 }
354
355 method <- "internal"
356 }
357
358 # download.file will complain about file size with something like:
359 # Warning message:
360 # In download.file(url, ...) : downloaded length 19457 != reported length 200
361 # because apparently it compares the length with the status code returned (?)
362 # so we supress that
363 suppressWarnings(utils::download.file(url, method = method, ...))
364
365 } else {
366 # If non-Windows, check for libcurl/curl/wget/lynx, then call download.file with
367 # appropriate method.
368
369 if (isR32 && capabilities("libcurl")) {
370 method <- "libcurl"
371 } else if (nzchar(Sys.which("wget")[1])) {
372 method <- "wget"
373 } else if (nzchar(Sys.which("curl")[1])) {
374 method <- "curl"
375
376 # curl needs to add a -L option to follow redirects.
377 # Save the original options and restore when we exit.
378 orig_extra_options <- getOption("download.file.extra")
379 on.exit(options(download.file.extra = orig_extra_options))
380
381 options(download.file.extra = paste("-L", orig_extra_options))
382
383 } else if (nzchar(Sys.which("lynx")[1])) {
384 method <- "lynx"
385 } else {
386 stop("no download method found")
387 }
388
389 utils::download.file(url, method = method, ...)
390 }
391
392 } else {
393 utils::download.file(url, ...)
394 }
395 }
396
397 getContentType <- function(file, defaultType = 'application/octet-stream') {
398 subtype <- ifelse(grepl('[.]html?$', file), 'charset=UTF-8', '')
399 mime::guess_type(file, unknown = defaultType, subtype = subtype)
400 }
401
402 #' Parse a GET query string from a URL
403 #'
404 #' Returns a named list of key-value pairs.
405 #'
406 #' @noMd
407 #' @param str The query string. It can have a leading \code{"?"} or not.
408 #' @param nested Whether to parse the query string of as a nested list when it
409 #' contains pairs of square brackets \code{[]}. For example, the query
410 #' \samp{a[i1][j1]=x&b[i1][j1]=y&b[i2][j1]=z} will be parsed as \code{list(a =
411 #' list(i1 = list(j1 = 'x')), b = list(i1 = list(j1 = 'y'), i2 = list(j1 =
412 #' 'z')))} when \code{nested = TRUE}, and \code{list(`a[i1][j1]` = 'x',
413 #' `b[i1][j1]` = 'y', `b[i2][j1]` = 'z')} when \code{nested = FALSE}.
414 #' @export
415 #' @examples
416 #' parseQueryString("?foo=1&bar=b%20a%20r")
417 #'
418 #' \dontrun{
419 #' # Example of usage within a Shiny app
420 #' function(input, output, session) {
421 #'
422 #' output$queryText <- renderText({
423 #' query <- parseQueryString(session$clientData$url_search)
424 #'
425 #' # Ways of accessing the values
426 #' if (as.numeric(query$foo) == 1) {
427 #' # Do something
428 #' }
429 #' if (query[["bar"]] == "targetstring") {
430 #' # Do something else
431 #' }
432 #'
433 #' # Return a string with key-value pairs
434 #' paste(names(query), query, sep = "=", collapse=", ")
435 #' })
436 #' }
437 #' }
438 #'
439 parseQueryString <- function(str, nested = FALSE) {
440 if (is.null(str) || nchar(str) == 0)
441 return(list())
442
443 # Remove leading ?
444 if (substr(str, 1, 1) == '?')
445 str <- substr(str, 2, nchar(str))
446
447 pairs <- strsplit(str, '&', fixed = TRUE)[[1]]
448 # Drop any empty items (if there's leading/trailing/consecutive '&' chars)
449 pairs <- pairs[pairs != ""]
450 pairs <- strsplit(pairs, '=', fixed = TRUE)
451
452 keys <- vapply(pairs, function(x) x[1], FUN.VALUE = character(1))
453 values <- vapply(pairs, function(x) x[2], FUN.VALUE = character(1))
454 # Replace NA with '', so they don't get converted to 'NA' by URLdecode
455 values[is.na(values)] <- ''
456
457 # Convert "+" to " ", since URLdecode doesn't do it
458 keys <- gsub('+', ' ', keys, fixed = TRUE)
459 values <- gsub('+', ' ', values, fixed = TRUE)
460
461 keys <- URLdecode(keys)
462 values <- URLdecode(values)
463
464 res <- stats::setNames(as.list(values), keys)
465 if (!nested) return(res)
466
467 # Make a nested list from a query of the form ?a[1][1]=x11&a[1][2]=x12&...
468 for (i in grep('\\[.+\\]', keys)) {
469 k <- strsplit(keys[i], '[][]')[[1L]] # split by [ or ]
470 res <- assignNestedList(res, k[k != ''], values[i])
471 res[[keys[i]]] <- NULL # remove res[['a[1][1]']]
472 }
473 res
474 }
475
476 # Assign value to the bottom element of the list x using recursive indices idx
477 assignNestedList <- function(x = list(), idx, value) {
478 for (i in seq_along(idx)) {
479 sub <- idx[seq_len(i)]
480 if (is.null(x[[sub]])) x[[sub]] <- list()
481 }
482 x[[idx]] <- value
483 x
484 }
485
486 # decide what to do in case of errors; it is customizable using the shiny.error
487 # option (e.g. we can set options(shiny.error = recover))
488 #' @include conditions.R
489 shinyCallingHandlers <- function(expr) {
490 withCallingHandlers(captureStackTraces(expr),
491 error = function(e) {
492 # Don't intercept shiny.silent.error (i.e. validation errors)
493 if (cnd_inherits(e, "shiny.silent.error"))
494 return()
495
496 handle <- getOption('shiny.error')
497 if (is.function(handle)) handle()
498 }
499 )
500 }
501
502 #' Register a function with the debugger (if one is active).
503 #'
504 #' Call this function after exprToFunction to give any active debugger a hook
505 #' to set and clear breakpoints in the function. A debugger may implement
506 #' registerShinyDebugHook to receive callbacks when Shiny functions are
507 #' instantiated at runtime.
508 #'
509 #' @param name Name of the field or object containing the function.
510 #' @param where The reference object or environment containing the function.
511 #' @param label A label to display on the function in the debugger.
512 #' @noRd
513 registerDebugHook <- function(name, where, label) {
514 if (exists("registerShinyDebugHook", mode = "function")) {
515 registerShinyDebugHook <- get("registerShinyDebugHook", mode = "function")
516 params <- new.env(parent = emptyenv())
517 params$name <- name
518 params$where <- where
519 params$label <- label
520 registerShinyDebugHook(params)
521 }
522 }
523
524 Callbacks <- R6Class(
525 'Callbacks',
526 portable = FALSE,
527 class = FALSE,
528 public = list(
529 .nextId = integer(0),
530 .callbacks = 'Map',
531
532 initialize = function() {
533 # NOTE: we avoid using '.Machine$integer.max' directly
534 # as R 3.3.0's 'radixsort' could segfault when sorting
535 # an integer vector containing this value
536 .nextId <<- as.integer(.Machine$integer.max - 1L)
537 .callbacks <<- Map$new()
538 },
539 register = function(callback) {
540 if (!is.function(callback)) {
541 stop("callback must be a function")
542 }
543 id <- as.character(.nextId)
544 .nextId <<- .nextId - 1L
545 .callbacks$set(id, callback)
546 return(function() {
547 .callbacks$remove(id)
548 })
549 },
550 invoke = function(..., onError=NULL, ..stacktraceon = FALSE) {
551 # Ensure that calls are invoked in the order that they were registered
552 keys <- as.character(sort(as.integer(.callbacks$keys()), decreasing = TRUE))
553 callbacks <- .callbacks$mget(keys)
554
555 for (callback in callbacks) {
556 if (is.null(onError)) {
557 if (..stacktraceon) {
558 ..stacktraceon..(callback(...))
559 } else {
560 callback(...)
561 }
562 } else {
563 tryCatch(
564 captureStackTraces(
565 if (..stacktraceon)
566 ..stacktraceon..(callback(...))
567 else
568 callback(...)
569 ),
570 error = onError
571 )
572 }
573 }
574 },
575 count = function() {
576 .callbacks$size()
577 }
578 )
579 )
580
581 # convert a data frame to JSON as required by DataTables request
582 dataTablesJSON <- function(data, req) {
583 n <- nrow(data)
584 # DataTables requests were sent via POST
585 params <- URLdecode(rawToChar(req$rook.input$read()))
586 q <- parseQueryString(params, nested = TRUE)
587 ci <- q$search[['caseInsensitive']] == 'true'
588
589 # data may have been replaced/updated in the new table while the Ajax request
590 # from the previous table is still on its way, so it is possible that the old
591 # request asks for more columns than the current data, in which case we should
592 # discard this request and return empty data; the next Ajax request from the
593 # new table will retrieve the correct number of columns of data
594 if (length(q$columns) != ncol(data)) {
595 res <- toJSON(list(
596 draw = as.integer(q$draw),
597 recordsTotal = n,
598 recordsFiltered = 0,
599 data = NULL
600 ))
601 return(httpResponse(200, 'application/json', enc2utf8(res)))
602 }
603
604 # global searching
605 i <- seq_len(n)
606 if (length(q$search[['value']]) && q$search[['value']] != '') {
607 i0 <- apply(data, 2, function(x) {
608 grep2(q$search[['value']], as.character(x),
609 fixed = q$search[['regex']] == 'false', ignore.case = ci)
610 })
611 i <- intersect(i, unique(unlist(i0)))
612 }
613
614 # search by columns
615 if (length(i)) for (j in names(q$columns)) {
616 col <- q$columns[[j]]
617 # if the j-th column is not searchable or the search string is "", skip it
618 if (col[['searchable']] != 'true') next
619 if ((k <- col[['search']][['value']]) == '') next
620 j <- as.integer(j)
621 dj <- data[, j + 1]
622 r <- commaToRange(k)
623 ij <- if (length(r) == 2 && is.numeric(dj)) {
624 which(dj >= r[1] & dj <= r[2])
625 } else {
626 grep2(k, as.character(dj), fixed = col[['search']][['regex']] == 'false',
627 ignore.case = ci)
628 }
629 i <- intersect(ij, i)
630 if (length(i) == 0) break
631 }
632 if (length(i) != n) data <- data[i, , drop = FALSE]
633
634 # sorting
635 oList <- list()
636 for (ord in q$order) {
637 k <- ord[['column']] # which column to sort
638 d <- ord[['dir']] # direction asc/desc
639 if (q$columns[[k]][['orderable']] != 'true') next
640 col <- data[, as.integer(k) + 1]
641 oList[[length(oList) + 1]] <- (if (d == 'asc') identity else `-`)(
642 if (is.numeric(col)) col else xtfrm(col)
643 )
644 }
645 if (length(oList)) {
646 i <- do.call(order, oList)
647 data <- data[i, , drop = FALSE]
648 }
649 # paging
650 if (q$length != '-1') {
651 i <- seq(as.integer(q$start) + 1L, length.out = as.integer(q$length))
652 i <- i[i <= nrow(data)]
653 fdata <- data[i, , drop = FALSE] # filtered data
654 } else fdata <- data
655
656 fdata <- unname(as.matrix(fdata))
657 if (is.character(fdata) && q$escape != 'false') {
658 if (q$escape == 'true') {
659 # fdata must be a matrix at this point, and we need to preserve
660 # dimensions. Note that it could be a 1xn matrix.
661 dims <- dim(fdata)
662 fdata <- htmlEscape(fdata)
663 dim(fdata) <- dims
664
665 } else {
666 k <- as.integer(strsplit(q$escape, ',')[[1]])
667 # use seq_len() in case escape = negative indices, e.g. c(-1, -5)
668 for (j in seq_len(ncol(fdata))[k]) fdata[, j] <- htmlEscape(fdata[, j])
669 }
670 }
671
672 res <- toJSON(list(
673 draw = as.integer(q$draw),
674 recordsTotal = n,
675 recordsFiltered = nrow(data),
676 data = fdata
677 ))
678 httpResponse(200, 'application/json', enc2utf8(res))
679 }
680
681 # when both ignore.case and fixed are TRUE, we use grep(ignore.case = FALSE,
682 # fixed = TRUE) to do lower-case matching of pattern on x
683 grep2 <- function(pattern, x, ignore.case = FALSE, fixed = FALSE, ...) {
684 if (fixed && ignore.case) {
685 pattern <- tolower(pattern)
686 x <- tolower(x)
687 ignore.case <- FALSE
688 }
689 # when the user types in the search box, the regular expression may not be
690 # complete before it is sent to the server, in which case we do not search
691 if (!fixed && inherits(try(grep(pattern, ''), silent = TRUE), 'try-error'))
692 return(seq_along(x))
693 grep(pattern, x, ignore.case = ignore.case, fixed = fixed, ...)
694 }
695
696 getExists <- function(x, mode, envir = parent.frame()) {
697 if (exists(x, envir = envir, mode = mode, inherits = FALSE))
698 get(x, envir = envir, mode = mode, inherits = FALSE)
699 }
700
701 # convert a string of the form "lower,upper" to c(lower, upper)
702 commaToRange <- function(string) {
703 if (!grepl(',', string)) return()
704 r <- strsplit(string, ',')[[1]]
705 if (length(r) > 2) return()
706 if (length(r) == 1) r <- c(r, '') # lower,
707 r <- as.numeric(r)
708 if (is.na(r[1])) r[1] <- -Inf
709 if (is.na(r[2])) r[2] <- Inf
710 r
711 }
712
713 # for options passed to DataTables/Selectize/..., the options of the class AsIs
714 # will be evaluated as literal JavaScript code
715 checkAsIs <- function(options) {
716 evalOptions <- if (length(options)) {
717 nms <- names(options)
718 if (length(nms) == 0L || any(nms == '')) stop("'options' must be a named list")
719 i <- unlist(lapply(options, function(x) {
720 is.character(x) && inherits(x, 'AsIs')
721 }))
722 if (any(i)) {
723 # must convert to character, otherwise toJSON() turns it to an array []
724 options[i] <- lapply(options[i], paste, collapse = '\n')
725 nms[i] # options of these names will be evaluated in JS
726 }
727 }
728 list(options = options, eval = evalOptions)
729 }
730
731 srcrefFromShinyCall <- function(expr) {
732 srcrefs <- attr(expr, "srcref")
733 num_exprs <- length(srcrefs)
734 if (num_exprs < 1)
735 return(NULL)
736 c(srcrefs[[1]][1], srcrefs[[1]][2],
737 srcrefs[[num_exprs]][3], srcrefs[[num_exprs]][4],
738 srcrefs[[1]][5], srcrefs[[num_exprs]][6])
739 }
740
741 # Indicates whether the given querystring should cause the associated request
742 # to be handled in showcase mode. Returns the showcase mode if set, or NULL
743 # if no showcase mode is set.
744 showcaseModeOfQuerystring <- function(querystring) {
745 if (nchar(querystring) > 0) {
746 qs <- parseQueryString(querystring)
747 if (exists("showcase", where = qs)) {
748 return(as.numeric(qs$showcase))
749 }
750 }
751 return(NULL)
752 }
753
754 showcaseModeOfReq <- function(req) {
755 showcaseModeOfQuerystring(req$QUERY_STRING)
756 }
757
758 # Returns (just) the filename containing the given source reference, or an
759 # empty string if the source reference doesn't include file information.
760 srcFileOfRef <- function(srcref) {
761 fileEnv <- attr(srcref, "srcfile")
762 # The 'srcfile' attribute should be a non-null environment containing the
763 # variable 'filename', which gives the full path to the source file.
764 if (!is.null(fileEnv) &&
765 is.environment(fileEnv) &&
766 exists("filename", where = fileEnv))
767 basename(fileEnv[["filename"]])
768 else
769 ""
770 }
771
772 # Format a number without sci notation, and keep as many digits as possible (do
773 # we really need to go beyond 15 digits?)
774 formatNoSci <- function(x) {
775 if (is.null(x)) return(NULL)
776 format(x, scientific = FALSE, digits = 15)
777 }
778
779 # A simple getter/setting to track the last time the auto-reload process
780 # updated. This value is used by `cachedFuncWithFile()` when auto-reload is
781 # enabled to reload app/ui/server files when watched supporting files change.
782 cachedAutoReloadLastChanged <- local({
783 last_update <- 0
784
785 list(
786 set = function() {
787 last_update <<- as.integer(Sys.time())
788 invisible(last_update)
789 },
790 get = function() {
791 last_update
792 }
793 )
794 })
795
796 # Returns a function that calls the given func and caches the result for
797 # subsequent calls, unless the given file's mtime changes.
798 cachedFuncWithFile <- function(dir, file, func, case.sensitive = FALSE) {
799 dir <- normalizePath(dir, mustWork = TRUE)
800
801 value <- NULL
802 last_mtime_file <- NA
803 last_autoreload <- 0
804
805 function(...) {
806 fname <- if (case.sensitive) {
807 file.path(dir, file)
808 } else {
809 file.path.ci(dir, file)
810 }
811
812 now <- file.info(fname)$mtime
813 autoreload <- last_autoreload < cachedAutoReloadLastChanged$get()
814 if (autoreload || !identical(last_mtime_file, now)) {
815 value <<- func(fname, ...)
816 last_mtime_file <<- now
817 last_autoreload <<- cachedAutoReloadLastChanged$get()
818 }
819 value
820 }
821 }
822
823 # turn column-based data to row-based data (mainly for JSON), e.g. data.frame(x
824 # = 1:10, y = 10:1) ==> list(list(x = 1, y = 10), list(x = 2, y = 9), ...)
825 columnToRowData <- function(data) {
826 do.call(
827 mapply, c(
828 list(FUN = function(...) list(...), SIMPLIFY = FALSE, USE.NAMES = FALSE),
829 as.list(data)
830 )
831 )
832 }
833
834 #' Declare an error safe for the user to see
835 #'
836 #' This should be used when you want to let the user see an error
837 #' message even if the default is to sanitize all errors. If you have an
838 #' error `e` and call `stop(safeError(e))`, then Shiny will
839 #' ignore the value of `getOption("shiny.sanitize.errors")` and always
840 #' display the error in the app itself.
841 #'
842 #' @param error Either an "error" object or a "character" object (string).
843 #' In the latter case, the string will become the message of the error
844 #' returned by `safeError`.
845 #'
846 #' @return An "error" object
847 #'
848 #' @details An error generated by `safeError` has priority over all
849 #' other Shiny errors. This can be dangerous. For example, if you have set
850 #' `options(shiny.sanitize.errors = TRUE)`, then by default all error
851 #' messages are omitted in the app, and replaced by a generic error message.
852 #' However, this does not apply to `safeError`: whatever you pass
853 #' through `error` will be displayed to the user. So, this should only
854 #' be used when you are sure that your error message does not contain any
855 #' sensitive information. In those situations, `safeError` can make
856 #' your users' lives much easier by giving them a hint as to where the
857 #' error occurred.
858 #'
859 #' @seealso [shiny-options()]
860 #'
861 #' @examples
862 #' ## Only run examples in interactive R sessions
863 #' if (interactive()) {
864 #'
865 #' # uncomment the desired line to experiment with shiny.sanitize.errors
866 #' # options(shiny.sanitize.errors = TRUE)
867 #' # options(shiny.sanitize.errors = FALSE)
868 #'
869 #' # Define UI
870 #' ui <- fluidPage(
871 #' textInput('number', 'Enter your favorite number from 1 to 10', '5'),
872 #' textOutput('normalError'),
873 #' textOutput('safeError')
874 #' )
875 #'
876 #' # Server logic
877 #' server <- function(input, output) {
878 #' output$normalError <- renderText({
879 #' number <- input$number
880 #' if (number %in% 1:10) {
881 #' return(paste('You chose', number, '!'))
882 #' } else {
883 #' stop(
884 #' paste(number, 'is not a number between 1 and 10')
885 #' )
886 #' }
887 #' })
888 #' output$safeError <- renderText({
889 #' number <- input$number
890 #' if (number %in% 1:10) {
891 #' return(paste('You chose', number, '!'))
892 #' } else {
893 #' stop(safeError(
894 #' paste(number, 'is not a number between 1 and 10')
895 #' ))
896 #' }
897 #' })
898 #' }
899 #'
900 #' # Complete app with UI and server components
901 #' shinyApp(ui, server)
902 #' }
903 #' @export
904 safeError <- function(error) {
905 if (inherits(error, "character")) {
906 error <- simpleError(error)
907 }
908 if (!inherits(error, "error")) {
909 stop("The class of the `error` parameter must be either 'error' or 'character'")
910 }
911 class(error) <- c("shiny.custom.error", class(error))
912 error
913 }
914
915 #***********************************************************************#
916 #**** Keep this function internal for now, may chnage in the future ****#
917 #***********************************************************************#
918 # #' Propagate an error through Shiny, but catch it before it throws
919 # #'
920 # #' Throws a type of exception that is caught by observers. When such an
921 # #' exception is triggered, all reactive links are broken. So, essentially,
922 # #' \code{reactiveStop()} behaves just like \code{stop()}, except that
923 # #' instead of ending the session, it is silently swalowed by Shiny.
924 # #'
925 # #' This function should be used when you want to disrupt the reactive
926 # #' links in a reactive chain, but do not want to end the session. For
927 # #' example, this enables you to disallow certain inputs, but get back
928 # #' to business as usual when valid inputs are re-entered.
929 # #' \code{reactiveStop} is also called internally by Shiny to create
930 # #' special errors, such as the ones generated by \code{\link{validate}()},
931 # #' \code{\link{req}()} and \code{\link{cancelOutput}()}.
932 # #'
933 # #' @param message An optional error message.
934 # #' @param class An optional class to add to the error.
935 # #' @export
936 # #' @examples
937 # #' ## Note: the breaking of the reactive chain that happens in the app
938 # #' ## below (when input$txt = 'bad' and input$allowBad = 'FALSE') is
939 # #' ## easily visualized with `reactlogShow()`
940 # #'
941 # #' ## Only run examples in interactive R sessions
942 # #' if (interactive()) {
943 # #'
944 # #' ui <- fluidPage(
945 # #' textInput('txt', 'Enter some text...'),
946 # #' selectInput('allowBad', 'Allow the string \'bad\'?',
947 # #' c('TRUE', 'FALSE'), selected = 'FALSE')
948 # #' )
949 # #'
950 # #' server <- function(input, output) {
951 # #' val <- reactive({
952 # #' if (!(as.logical(input$allowBad))) {
953 # #' if (identical(input$txt, "bad")) {
954 # #' reactiveStop()
955 # #' }
956 # #' }
957 ## ' })
958 # #'
959 # #' observe({
960 # #' val()
961 # #' })
962 # #' }
963 # #'
964 # #' shinyApp(ui, server)
965 # #' }
966 # #' @export
967 reactiveStop <- function(message = "", class = NULL) {
968 stopWithCondition(c("shiny.silent.error", class), message)
969 }
970
971 #' Validate input values and other conditions
972 #'
973 #' @description
974 #' `validate()` provides convenient mechanism for validating that an output
975 #' has all the inputs necessary for successful rendering. It takes any number
976 #' of (unnamed) arguments, each representing a condition to test. If any
977 #' of condition fails (i.e. is not ["truthy"][isTruthy]), a special type of
978 #' error is signaled to stop execution. If this error is not handled by
979 #' application-specific code, it is displayed to the user by Shiny.
980 #'
981 #' If you use `validate()` in a [reactive()] validation failures will
982 #' automatically propagate to outputs that use the reactive.
983 #'
984 #' @section `need()`:
985 #' An easy way to provide arguments to `validate()` is to use `need()`, which
986 #' takes an expression and a string. If the expression is not
987 #' ["truthy"][isTruthy] then the string will be used as the error message.
988 #'
989 #' If "truthiness" is flexible for your use case, you'll need to explicitly
990 #' generate a logical values. For example, if you want allow `NA` but not
991 #' `NULL`, you can `!is.null(input$foo)`.
992 #'
993 #' If you need validation logic that differs significantly from `need()`, you
994 #' can create your own validation test functions. A passing test should return
995 #' `NULL`. A failing test should return either a string providing the error
996 #' to display to the user, or if the failure should happen silently, `FALSE`.
997 #'
998 #' Alternatively you can use `validate()` within an `if` statement, which is
999 #' particularly useful for more complex conditions:
1000 #'
1001 #' ```
1002 #' if (input$x < 0 && input$choice == "positive") {
1003 #' validate("If choice is positive then x must be greater than 0")
1004 #' }
1005 #' ```
1006 #'
1007 #' @param ... A list of tests. Each test should equal `NULL` for success,
1008 #' `FALSE` for silent failure, or a string for failure with an error
1009 #' message.
1010 #' @param errorClass A CSS class to apply. The actual CSS string will have
1011 #' `shiny-output-error-` prepended to this value.
1012 #' @export
1013 #' @examples
1014 #' ## Only run examples in interactive R sessions
1015 #' if (interactive()) {
1016 #' options(device.ask.default = FALSE)
1017 #'
1018 #' ui <- fluidPage(
1019 #' checkboxGroupInput('in1', 'Check some letters', choices = head(LETTERS)),
1020 #' selectizeInput('in2', 'Select a state', choices = c("", state.name)),
1021 #' plotOutput('plot')
1022 #' )
1023 #'
1024 #' server <- function(input, output) {
1025 #' output$plot <- renderPlot({
1026 #' validate(
1027 #' need(input$in1, 'Check at least one letter!'),
1028 #' need(input$in2 != '', 'Please choose a state.')
1029 #' )
1030 #' plot(1:10, main = paste(c(input$in1, input$in2), collapse = ', '))
1031 #' })
1032 #' }
1033 #'
1034 #' shinyApp(ui, server)
1035 #'
1036 #' }
1037 validate <- function(..., errorClass = character(0)) {
1038 results <- sapply(list2(...), function(x) {
1039 # Detect NULL or NA
1040 if (is.null(x))
1041 return(NA_character_)
1042 else if (identical(x, FALSE))
1043 return("")
1044 else if (is.character(x))
1045 return(paste(as.character(x), collapse = "\n"))
1046 else
1047 stop("Unexpected validation result: ", as.character(x))
1048 })
1049
1050 results <- stats::na.omit(results)
1051 if (length(results) == 0)
1052 return(invisible())
1053
1054 # There may be empty strings remaining; these are message-less failures that
1055 # started as FALSE
1056 results <- results[nzchar(results)]
1057 reactiveStop(paste(results, collapse="\n"), c(errorClass, "validation"))
1058 }
1059
1060 #' @param expr An expression to test. The condition will pass if the expression
1061 #' meets the conditions spelled out in Details.
1062 #' @param message A message to convey to the user if the validation condition is
1063 #' not met. If no message is provided, one will be created using `label`.
1064 #' To fail with no message, use `FALSE` for the message.
1065 #' @param label A human-readable name for the field that may be missing. This
1066 #' parameter is not needed if `message` is provided, but must be provided
1067 #' otherwise.
1068 #' @export
1069 #' @rdname validate
1070 need <- function(expr, message = paste(label, "must be provided"), label) {
1071
1072 force(message) # Fail fast on message/label both being missing
1073
1074 if (!isTruthy(expr))
1075 return(message)
1076 else
1077 return(invisible(NULL))
1078 }
1079
1080 #' Check for required values
1081 #'
1082 #' Ensure that values are available (["truthy"][isTruthy]) before proceeding
1083 #' with a calculation or action. If any of the given values is not truthy, the
1084 #' operation is stopped by raising a "silent" exception (not logged by Shiny,
1085 #' nor displayed in the Shiny app's UI).
1086 #'
1087 #' The `req` function was designed to be used in one of two ways. The first
1088 #' is to call it like a statement (ignoring its return value) before attempting
1089 #' operations using the required values:
1090 #'
1091 #' ```
1092 #' rv <- reactiveValues(state = FALSE)
1093 #' r <- reactive({
1094 #' req(input$a, input$b, rv$state)
1095 #' # Code that uses input$a, input$b, and/or rv$state...
1096 #' })
1097 #' ```
1098 #'
1099 #' In this example, if `r()` is called and any of `input$a`,
1100 #' `input$b`, and `rv$state` are `NULL`, `FALSE`, `""`,
1101 #' etc., then the `req` call will trigger an error that propagates all the
1102 #' way up to whatever render block or observer is executing.
1103 #'
1104 #' The second is to use it to wrap an expression that must be truthy:
1105 #'
1106 #' ```
1107 #' output$plot <- renderPlot({
1108 #' if (req(input$plotType) == "histogram") {
1109 #' hist(dataset())
1110 #' } else if (input$plotType == "scatter") {
1111 #' qplot(dataset(), aes(x = x, y = y))
1112 #' }
1113 #' })
1114 #' ```
1115 #'
1116 #' In this example, `req(input$plotType)` first checks that
1117 #' `input$plotType` is truthy, and if so, returns it. This is a convenient
1118 #' way to check for a value "inline" with its first use.
1119 #'
1120 #' @section Using `req(FALSE)`:
1121 #'
1122 #' You can use `req(FALSE)` (i.e. no condition) if you've already performed
1123 #' all the checks you needed to by that point and just want to stop the reactive
1124 #' chain now. There is no advantage to this, except perhaps ease of readability
1125 #' if you have a complicated condition to check for (or perhaps if you'd like to
1126 #' divide your condition into nested `if` statements).
1127 #'
1128 #' @section Using `cancelOutput = TRUE`:
1129 #'
1130 #' When `req(..., cancelOutput = TRUE)` is used, the "silent" exception is
1131 #' also raised, but it is treated slightly differently if one or more outputs are
1132 #' currently being evaluated. In those cases, the reactive chain does not proceed
1133 #' or update, but the output(s) are left is whatever state they happen to be in
1134 #' (whatever was their last valid state).
1135 #'
1136 #' Note that this is always going to be the case if
1137 #' this is used inside an output context (e.g. `output$txt <- ...`). It may
1138 #' or may not be the case if it is used inside a non-output context (e.g.
1139 #' [reactive()], [observe()] or [observeEvent()])
1140 #' --- depending on whether or not there is an `output$...` that is triggered
1141 #' as a result of those calls. See the examples below for concrete scenarios.
1142 #'
1143 #' @param ... Values to check for truthiness.
1144 #' @param cancelOutput If `TRUE` and an output is being evaluated, stop
1145 #' processing as usual but instead of clearing the output, leave it in
1146 #' whatever state it happens to be in. If `"progress"`, do the same as `TRUE`,
1147 #' but also keep the output in recalculating state; this is intended for cases
1148 #' when an in-progress calculation will not be completed in this reactive
1149 #' flush cycle, but is still expected to provide a result in the future.
1150 #' @return The first value that was passed in.
1151 #' @export
1152 #' @examples
1153 #' ## Only run examples in interactive R sessions
1154 #' if (interactive()) {
1155 #' ui <- fluidPage(
1156 #' textInput('data', 'Enter a dataset from the "datasets" package', 'cars'),
1157 #' p('(E.g. "cars", "mtcars", "pressure", "faithful")'), hr(),
1158 #' tableOutput('tbl')
1159 #' )
1160 #'
1161 #' server <- function(input, output) {
1162 #' output$tbl <- renderTable({
1163 #'
1164 #' ## to require that the user types something, use: `req(input$data)`
1165 #' ## but better: require that input$data is valid and leave the last
1166 #' ## valid table up
1167 #' req(exists(input$data, "package:datasets", inherits = FALSE),
1168 #' cancelOutput = TRUE)
1169 #'
1170 #' head(get(input$data, "package:datasets", inherits = FALSE))
1171 #' })
1172 #' }
1173 #'
1174 #' shinyApp(ui, server)
1175 #' }
1176 req <- function(..., cancelOutput = FALSE) {
1177 dotloop(function(item) {
1178 if (!isTruthy(item)) {
1179 if (isTRUE(cancelOutput)) {
1180 cancelOutput()
1181 } else if (identical(cancelOutput, "progress")) {
1182 reactiveStop(class = "shiny.output.progress")
1183 } else {
1184 reactiveStop(class = "validation")
1185 }
1186 }
1187 }, ...)
1188
1189 if (!missing(..1))
1190 ..1
1191 else
1192 invisible()
1193 }
1194
1195 #***********************************************************************#
1196 #**** Keep this function internal for now, may chnage in the future ****#
1197 #***********************************************************************#
1198 # #' Cancel processing of the current output
1199 # #'
1200 # #' Signals an error that Shiny treats specially if an output is currently being
1201 # #' evaluated. Execution will stop, but rather than clearing the output (as
1202 # #' \code{\link{req}} does) or showing an error message (as \code{\link{stop}}
1203 # #' does), the output simply remains unchanged.
1204 # #'
1205 # #' If \code{cancelOutput} is called in any non-output context (like in an
1206 # #' \code{\link{observe}} or \code{\link{observeEvent}}), the effect is the same
1207 # #' as \code{\link{req}(FALSE)}.
1208 # #' @export
1209 # #' @examples
1210 # #' ## Only run examples in interactive R sessions
1211 # #' if (interactive()) {
1212 # #'
1213 # #' # uncomment the desired line to experiment with cancelOutput() vs. req()
1214 # #'
1215 # #' ui <- fluidPage(
1216 # #' textInput('txt', 'Enter text'),
1217 # #' textOutput('check')
1218 # #' )
1219 # #'
1220 # #' server <- function(input, output) {
1221 # #' output$check <- renderText({
1222 # #' # req(input$txt)
1223 # #' if (input$txt == 'hi') return('hi')
1224 # #' else if (input$txt == 'bye') return('bye')
1225 # #' # else cancelOutput()
1226 # #' })
1227 # #' }
1228 # #'
1229 # #' shinyApp(ui, server)
1230 # #' }
1231 cancelOutput <- function() {
1232 reactiveStop(class = "shiny.output.cancel")
1233 }
1234
1235 # Execute a function against each element of ..., but only evaluate each element
1236 # after the previous element has been passed to fun_. The return value of fun_
1237 # is discarded, and only invisible() is returned from dotloop.
1238 #
1239 # Can be used to facilitate short-circuit eval on dots.
1240 dotloop <- function(fun_, ...) {
1241 for (i in seq_len(nargs() - 1)) {
1242 fun_(eval(as.symbol(paste0("..", i))))
1243 }
1244 invisible()
1245 }
1246
1247 #' Truthy and falsy values
1248 #'
1249 #' The terms "truthy" and "falsy" generally indicate whether a value, when
1250 #' coerced to a [base::logical()], is `TRUE` or `FALSE`. We use
1251 #' the term a little loosely here; our usage tries to match the intuitive
1252 #' notions of "Is this value missing or available?", or "Has the user provided
1253 #' an answer?", or in the case of action buttons, "Has the button been
1254 #' clicked?".
1255 #'
1256 #' For example, a `textInput` that has not been filled out by the user has
1257 #' a value of `""`, so that is considered a falsy value.
1258 #'
1259 #' To be precise, a value is truthy *unless* it is one of:
1260 #'
1261 #' * `FALSE`
1262 #' * `NULL`
1263 #' * `""`
1264 #' * An empty atomic vector
1265 #' * An atomic vector that contains only missing values
1266 #' * A logical vector that contains all `FALSE` or missing values
1267 #' * An object of class `"try-error"`
1268 #' * A value that represents an unclicked [actionButton()]
1269 #'
1270 #' Note in particular that the value `0` is considered truthy, even though
1271 #' `as.logical(0)` is `FALSE`.
1272 #'
1273 #' @param x An expression whose truthiness value we want to determine
1274 #' @export
1275 isTruthy <- function(x) {
1276 if (is.null(x))
1277 return(FALSE)
1278 if (inherits(x, 'try-error'))
1279 return(FALSE)
1280 if (!is.atomic(x))
1281 return(TRUE)
1282 if (length(x) == 0)
1283 return(FALSE)
1284 if (all(is.na(x)))
1285 return(FALSE)
1286 if (is.character(x) && !any(nzchar(stats::na.omit(x))))
1287 return(FALSE)
1288 if (inherits(x, 'shinyActionButtonValue') && x == 0)
1289 return(FALSE)
1290 if (is.logical(x) && !any(stats::na.omit(x)))
1291 return(FALSE)
1292
1293 return(TRUE)
1294 }
1295
1296 # add class(es) to the error condition, which will be used as names of CSS
1297 # classes, e.g. shiny-output-error shiny-output-error-validation
1298 stopWithCondition <- function(class, message) {
1299 cond <- structure(
1300 list(message = message),
1301 class = c(class, 'error', 'condition')
1302 )
1303 stop(cond)
1304 }
1305
1306 #' Collect information about the Shiny Server environment
1307 #'
1308 #' This function returns the information about the current Shiny Server, such as
1309 #' its version, and whether it is the open source edition or professional
1310 #' edition. If the app is not served through the Shiny Server, this function
1311 #' just returns `list(shinyServer = FALSE)`.
1312 #'
1313 #' This function will only return meaningful data when using Shiny Server
1314 #' version 1.2.2 or later.
1315 #' @export
1316 #' @return A list of the Shiny Server information.
1317 serverInfo <- function() {
1318 .globals$serverInfo
1319 }
1320 .globals$serverInfo <- list(shinyServer = FALSE)
1321
1322 setServerInfo <- function(...) {
1323 infoOld <- serverInfo()
1324 infoNew <- list(...)
1325 infoOld[names(infoNew)] <- infoNew
1326 .globals$serverInfo <- infoOld
1327 }
1328
1329 # assume file is encoded in UTF-8, but warn against BOM
1330 checkEncoding <- function(file) {
1331 # skip *nix because its locale is normally UTF-8 based (e.g. en_US.UTF-8), and
1332 # *nix users have to make a conscious effort to save a file with an encoding
1333 # that is not UTF-8; if they choose to do so, we cannot do much about it
1334 # except sitting back and seeing them punished after they choose to escape a
1335 # world of consistency (falling back to getOption('encoding') will not help
1336 # because native.enc is also normally UTF-8 based on *nix)
1337 if (!isWindows()) return('UTF-8')
1338 size <- file.info(file)[, 'size']
1339 if (is.na(size)) stop('Cannot access the file ', file)
1340 # BOM is 3 bytes, so if the file contains BOM, it must be at least 3 bytes
1341 if (size < 3L) return('UTF-8')
1342
1343 # check if there is a BOM character: this is also skipped on *nix, because R
1344 # on *nix simply ignores this meaningless character if present, but it hurts
1345 # on Windows
1346 if (identical(charToRaw(readChar(file, 3L, TRUE)), charToRaw('\UFEFF'))) {
1347 warning('You should not include the Byte Order Mark (BOM) in ', file, '. ',
1348 'Please re-save it in UTF-8 without BOM. See ',
1349 'https://shiny.rstudio.com/articles/unicode.html for more info.')
1350 return('UTF-8-BOM')
1351 }
1352 x <- readChar(file, size, useBytes = TRUE)
1353 if (is.na(iconv(x, 'UTF-8', 'UTF-8'))) {
1354 warning('The input file ', file, ' does not seem to be encoded in UTF8')
1355 }
1356 'UTF-8'
1357 }
1358
1359 # read a file using UTF-8 and (on Windows) convert to native encoding if possible
1360 readUTF8 <- function(file) {
1361 enc <- checkEncoding(file)
1362 file <- base::file(file, encoding = enc)
1363 on.exit(close(file), add = TRUE)
1364 x <- enc2utf8(readLines(file, warn = FALSE))
1365 tryNativeEncoding(x)
1366 }
1367
1368 # if the UTF-8 string can be represented in the native encoding, use native encoding
1369 tryNativeEncoding <- function(string) {
1370 if (!isWindows()) return(string)
1371 string2 <- enc2native(string)
1372 if (identical(enc2utf8(string2), string)) string2 else string
1373 }
1374
1375 maybeAnnotateSourceForArk <- function(file, lines) {
1376 ark_annotate_source <- get0(".ark_annotate_source", baseenv())
1377
1378 if (is.null(ark_annotate_source)) {
1379 return(lines)
1380 }
1381
1382 file <- normalizePath(file, mustWork = TRUE, winslash = "/") # Just to be safe
1383 uri <- paste0("file:///", sub("^/", "", file)) # Ark expects URIs
1384 lines_str <- paste(lines, collapse = "\n")
1385 tryCatch(
1386 {
1387 annotated <- ark_annotate_source(lines_str, uri)
1388 if (!is.null(annotated)) {
1389 lines <- strsplit(annotated, "\n", fixed = TRUE)[[1]]
1390 }
1391 },
1392 error = function(cnd) {
1393 rlang::warn("Can't inject breakpoints for Ark", parent = cnd)
1394 }
1395 )
1396
1397
1398 lines
1399 }
1400
1401 # similarly, try to source() a file with UTF-8
1402 sourceUTF8 <- function(file, envir = globalenv()) {
1403 file_norm <- normalizePath(file, mustWork = TRUE, winslash = "/")
1404 lines <- readUTF8(file)
1405 enc <- if (any(Encoding(lines) == 'UTF-8')) 'UTF-8' else 'unknown'
1406
1407 # Inject Ark annotations for breakpoints if available
1408 lines <- maybeAnnotateSourceForArk(file, lines)
1409
1410 # Wrap in `..stacktraceon..({...})` using string manipulation before parsing,
1411 # with a `#line` directive to map source references back to the original file
1412 lines <- c(
1413 "..stacktraceon..({",
1414 sprintf('#line 1 "%s"', file_norm),
1415 lines,
1416 "})"
1417 )
1418
1419 # Create a source file copy, i.e. an in-memory srcfile that contains all the
1420 # code but refers to an original file
1421 src <- srcfilecopy(file, lines, isFile = TRUE)
1422
1423 # Parse from our annotated lines
1424 exprs <- tryCatch(
1425 parse(text = lines, keep.source = FALSE, srcfile = src, encoding = enc),
1426 error = function(cnd) {
1427 diagnoseCode(file)
1428 stop("Error sourcing ", file)
1429 }
1430 )
1431
1432 eval(exprs, envir)
1433 }
1434
1435 # @param func Name of function, in unquoted form
1436 # @param args An evaluated list of unevaluated argument expressions
1437 makeCall <- function(func, args) {
1438 as.call(c(list(substitute(func)), args))
1439 }
1440
1441 # a workaround for https://bugs.r-project.org/bugzilla3/show_bug.cgi?id=16264
1442 srcfilecopy <- function(filename, lines, ...) {
1443 if (getRversion() > '3.2.2') return(base::srcfilecopy(filename, lines, ...))
1444 src <- base::srcfilecopy(filename, lines = '', ...)
1445 src$lines <- lines
1446 src
1447 }
1448
1449 # write text as UTF-8
1450 writeUTF8 <- function(text, ...) {
1451 text <- enc2utf8(text)
1452 writeLines(text, ..., useBytes = TRUE)
1453 }
1454
1455 URLdecode <- function(value) {
1456 decodeURIComponent(value)
1457 }
1458
1459 URLencode <- function(value, reserved = FALSE) {
1460 value <- enc2utf8(value)
1461 if (reserved) encodeURIComponent(value) else encodeURI(value)
1462 }
1463
1464 # Make sure user-supplied dates are either NULL or can be coerced to a
1465 # yyyy-mm-dd formatted string. If a date is specified, this function returns a
1466 # string for consistency across locales. Also, `as.Date()` is used to coerce
1467 # strings to date objects so that strings like "2016-08-9" are expanded to
1468 # "2016-08-09". If any of the values result in error or NA, then the input
1469 # `date` is returned unchanged.
1470 dateYMD <- function(date = NULL, argName = "value") {
1471 if (!length(date)) return(NULL)
1472 tryCatch({
1473 if (inherits(date, "POSIXt")) {
1474 res <- format(date, "%Y-%m-%d")
1475 } else {
1476 res <- format(as.Date(date), "%Y-%m-%d")
1477 }
1478 if (any(is.na(res))) stop()
1479 date <- res
1480 },
1481 error = function(e) {
1482 warning(
1483 "Couldn't coerce the `", argName,
1484 "` argument to a date string with format yyyy-mm-dd",
1485 call. = FALSE
1486 )
1487 }
1488 )
1489 date
1490 }
1491
1492 # This function takes a name and function, and it wraps that function in a new
1493 # function which calls the original function using the specified name. This can
1494 # be helpful for profiling, because the specified name will show up on the stack
1495 # trace.
1496 wrapFunctionLabel <- function(func, name, ..stacktraceon = FALSE, dots = TRUE) {
1497 if (name == "name" || name == "func" || name == "relabelWrapper") {
1498 stop("Invalid name for wrapFunctionLabel: ", name)
1499 }
1500 if (nchar(name, "bytes") > 10000) {
1501 # Max variable length in R is 10000 bytes. Truncate to a shorter number of
1502 # chars because some characters could be multi-byte.
1503 name <- substr(name, 1, 5000)
1504 }
1505
1506 assign(name, func, environment())
1507 registerDebugHook(name, environment(), name)
1508
1509 if (isTRUE(dots)) {
1510 if (..stacktraceon) {
1511 # We need to wrap the `...` in `!!quote(...)` so that R CMD check won't
1512 # complain about "... may be used in an incorrect context"
1513 body <- expr({ ..stacktraceon..((!!name)(!!quote(...))) })
1514 } else {
1515 body <- expr({ (!!name)(!!quote(...)) })
1516 }
1517 relabelWrapper <- new_function(pairlist2(... =), body, environment())
1518 } else {
1519 # Same logic as when `dots = TRUE`, but without the `...`
1520 if (..stacktraceon) {
1521 body <- expr({ ..stacktraceon..((!!name)()) })
1522 } else {
1523 body <- expr({ (!!name)() })
1524 }
1525 relabelWrapper <- new_function(list(), body, environment())
1526 }
1527
1528 # Preserve the original function that was passed in; is used for caching.
1529 attr(relabelWrapper, "wrappedFunc") <- func
1530 relabelWrapper
1531 }
1532
1533
1534 # This is a very simple mutable object which only stores one value
1535 # (which we can set and get). Using this class is sometimes useful
1536 # when communicating persistent changes across functions.
1537 Mutable <- R6Class("Mutable",
1538 private = list(
1539 value = NULL
1540 ),
1541 public = list(
1542 set = function(value) { private$value <- value },
1543 get = function() { private$value }
1544 )
1545 )
1546
1547 # More convenient way of chaining together promises than then/catch/finally,
1548 # without the performance impact of %...>%.
1549 promise_chain <- function(promise, ..., catch = NULL, finally = NULL,
1550 domain = NULL, replace = FALSE) {
1551
1552 do <- function() {
1553 p <- Reduce(function(memo, func) {
1554 promises::then(memo, func)
1555 }, list(...), promise)
1556
1557 if (!is.null(catch)) {
1558 p <- promises::catch(p, catch)
1559 }
1560
1561 if (!is.null(finally)) {
1562 p <- promises::finally(p, finally)
1563 }
1564
1565 p
1566 }
1567
1568 if (!is.null(domain)) {
1569 with_promise_domain(domain, do(), replace = replace)
1570 } else {
1571 do()
1572 }
1573 }
1574
1575 # Like promise_chain, but if `expr` returns a non-promise, then `...`, `catch`,
1576 # and `finally` are all executed synchronously
1577 hybrid_chain <- function(expr, ..., catch = NULL, finally = NULL,
1578 domain = NULL, replace = FALSE) {
1579
1580 do <- function() {
1581 runFinally <- TRUE
1582 tryCatch(
1583 {
1584 captureStackTraces({
1585 result <- withVisible(force(expr))
1586 if (is.promising(result$value)) {
1587 # Purposefully NOT including domain (nor replace), as we're already in
1588 # the domain at this point
1589 p <- promise_chain(valueWithVisible(result), ..., catch = catch, finally = finally)
1590 runFinally <- FALSE
1591 p
1592 } else {
1593 result <- Reduce(
1594 function(v, func) {
1595 if (v$visible) {
1596 withVisible(func(v$value))
1597 } else {
1598 withVisible(func(invisible(v$value)))
1599 }
1600 },
1601 list(...),
1602 result
1603 )
1604
1605 valueWithVisible(result)
1606 }
1607 })
1608 },
1609 error = function(e) {
1610 if (!is.null(catch))
1611 catch(e)
1612 else
1613 stop(e)
1614 },
1615 finally = if (runFinally && !is.null(finally)) finally()
1616 )
1617 }
1618
1619 if (!is.null(domain)) {
1620 with_promise_domain(domain, do(), replace = replace)
1621 } else {
1622 do()
1623 }
1624 }
1625
1626 # Given a list with items named `value` and `visible`, return `x$value` either
1627 # visibly, or invisibly, depending on the value of `x$visible`.
1628 valueWithVisible <- function(x) {
1629 if (x$visible) x$value else invisible(x$value)
1630 }
1631
1632
1633 createVarPromiseDomain <- function(env, name, value) {
1634 force(env)
1635 force(name)
1636 force(value)
1637
1638 new_promise_domain(
1639 wrapOnFulfilled = function(onFulfilled) {
1640 function(...) {
1641 orig <- env[[name]]
1642 env[[name]] <- value
1643 on.exit(env[[name]] <- orig)
1644
1645 onFulfilled(...)
1646 }
1647 },
1648 wrapOnRejected = function(onRejected) {
1649 function(...) {
1650 orig <- env[[name]]
1651 env[[name]] <- value
1652 on.exit(env[[name]] <- orig)
1653
1654 onRejected(...)
1655 }
1656 },
1657 wrapSync = function(expr) {
1658 orig <- env[[name]]
1659 env[[name]] <- value
1660 on.exit(env[[name]] <- orig)
1661
1662 force(expr)
1663 }
1664 )
1665 }
1666
1667 getSliderType <- function(min, max, value) {
1668 vals <- dropNulls(list(value, min, max))
1669 if (length(vals) == 0) return("")
1670 type <- unique(lapply(vals, function(x) {
1671 if (inherits(x, "Date")) "date"
1672 else if (inherits(x, "POSIXt")) "datetime"
1673 else "number"
1674 }))
1675 if (length(type) > 1) {
1676 rlang::abort(c(
1677 "Type mismatch for `min`, `max`, and `value`.",
1678 "All values must either be numeric, Date, or POSIXt."
1679 ))
1680 }
1681 type[[1]]
1682 }
1683
1684 # Reads the `shiny.sharedSecret` global option, and returns a function that can
1685 # be used to test header values for a match.
1686 loadSharedSecret <- function() {
1687 normalizeToRaw <- function(value, label = "value") {
1688 if (is.null(value)) {
1689 raw()
1690 } else if (is.character(value)) {
1691 charToRaw(paste(value, collapse = "\n"))
1692 } else if (is.raw(value)) {
1693 value
1694 } else {
1695 stop("Wrong type for ", label, "; character or raw expected")
1696 }
1697 }
1698
1699 sharedSecret <- normalizeToRaw(getOption("shiny.sharedSecret"))
1700 if (is.null(sharedSecret)) {
1701 function(x) TRUE
1702 } else {
1703 # We compare the digest of the two values so that their lengths are equalized
1704 function(x) {
1705 x <- normalizeToRaw(x)
1706 # Constant time comparison to avoid timing attacks
1707 constantTimeEquals(sharedSecret, x)
1708 }
1709 }
1710 }
1711
1712 # Compares two raw vectors of equal length for equality, in constant time
1713 constantTimeEquals <- function(raw1, raw2) {
1714 stopifnot(is.raw(raw1))
1715 stopifnot(is.raw(raw2))
1716 if (length(raw1) != length(raw2)) {
1717 return(FALSE)
1718 }
1719
1720 sum(as.integer(xor(raw1, raw2))) == 0
1721 }
1722
1723 cat_line <- function(...) {
1724 cat(paste(..., "\n", collapse = ""))
1725 }
1726
1727 select_menu <- function(choices, title = NULL, msg = "Enter one or more numbers (with spaces), or an empty line to exit: \n")
1728 {
1729 if (!is.null(title)) {
1730 cat(title, "\n", sep = "")
1731 }
1732 nc <- length(choices)
1733 op <- paste0(format(seq_len(nc)), ": ", choices)
1734 fop <- format(op)
1735 cat("", fop, "", sep = "\n")
1736 repeat {
1737 answer <- readline(msg)
1738 answer <- strsplit(answer, "[ ,]+")[[1]]
1739 if (all(answer %in% seq_along(choices))) {
1740 return(choices[as.integer(answer)])
1741 }
1742 }
1743 }
1744
1745 #' @noRd
1746 isAppDir <- function(path) {
1747
1748 if (file.exists(file.path.ci(path, "app.R")))
1749 return(TRUE)
1750
1751 if (file.exists(file.path.ci(path, "server.R"))
1752 && file.exists(file.path.ci(path, "ui.R")))
1753 return(TRUE)
1754
1755 FALSE
1756 }
1757
1758 # Borrowed from rprojroot which borrowed from devtools
1759 #' @noRd
1760 is_root <- function(path) {
1761 identical(
1762 normalizePath(path, winslash = "/"),
1763 normalizePath(dirname(path), winslash = "/")
1764 )
1765 }
1766
1767 #' @noRd
1768 findEnclosingApp <- function(path = ".") {
1769 orig_path <- path
1770 path <- normalizePath(path, winslash = "/", mustWork = TRUE)
1771 repeat {
1772 if (isAppDir(path))
1773 return(path)
1774 if (is_root(path))
1775 stop("Shiny app not found at ", orig_path, " or in any parent directory.")
1776 path <- dirname(path)
1777 }
1778 }
1779
1780 # Until `rlang::cnd_inherits()` is on CRAN
1781 cnd_inherits <- function(cnd, class) {
1782 cnd_some(cnd, ~ inherits(.x, class))
1783 }
1784 cnd_some <- function(.cnd, .p, ...) {
1785 .p <- rlang::as_function(.p)
1786
1787 while (rlang::is_condition(.cnd)) {
1788 if (.p(.cnd, ...)) {
1789 return(TRUE)
1790 }
1791
1792 .cnd <- .cnd$parent
1793 }
1794
1795 FALSE
1796 }