general_functions.php
Table of Contents
Functions
- getval() : mixed
- Retrieve a user-submitted parameter from the browser via post/get/cookies, in that order.
- escape_check() : string
- Escape a value prior to using it in SQL.
- unescape() : string
- For comparing escape_checked strings against mysql content because just doing $text=str_replace("\\","",$text); does not undo escape_check
- nicedate() : string
- Formats a MySQL ISO date
- date_to_age() : string
- Generates a text representation of the age from a given date
- preview_from_text() : string
- Generates preview text of a certain line length and count
- redirect() : never
- Redirect to the provided URL using a HTTP header Location directive. Exits after redirect
- trim_spaces() : string
- replace multiple spaces with a single space
- trim_array() : array<string|int, mixed>
- Removes whitespace from the beginning/end of all elements in an array
- tidylist() : string
- Takes a value as returned from a check-list field type and reformats to be more display-friendly.
- tidy_trim() : string
- Trims $text to $length if necessary. Tries to trim at a space if possible. Adds three full stops if trimmed.
- average_length() : float
- Returns the average length of the strings in an array
- get_stats_activity_types() : array<string|int, mixed>
- Returns a list of activity types for which we have stats data (Search, User Session etc.)
- newlines() : string
- Replace escaped newlines with real newlines.
- get_all_site_text() : array<string|int, mixed>
- Returns a list of all available editable site text (content). If $find is specified a search is performed across page, name and text fields.
- get_site_text() : string
- Returns a specific site text entry.
- check_site_text_custom() : bool
- Check if site text section is custom, i.e. deletable.
- save_site_text() : void
- Saves the submitted site text changes to the database.
- formatfilesize() : string
- Return a human-readable string representing $bytes in either KB or MB.
- filesize2bytes() : int
- Converts human readable file size (e.g. 10 MB, 200.20 GB) into bytes.
- get_mime_type() : array<string|int, mixed>
- Get the mime type for a file on disk
- get_mime_types_by_extension() : array<int, string>
- Find matching MIME type(s) for a file extension.
- get_unsafe_mime_types() : array<string|int, mixed>
- Get the global MIME types associated with the configured banned extensions.
- allowed_type_mime() : string
- Convert the permitted resource type extension to MIME type. Used by upload_batch.php
- send_mail() : mixed
- Send a mail - but correctly encode the message/subject in quoted-printable UTF-8.
- send_mail_phpmailer() : void
- if ($use_phpmailer==true) this function is used instead.
- log_mail() : void
- Log email
- rs_quoted_printable_encode() : string
- Quoted printable encoding is rather simple.
- rs_quoted_printable_encode_subject() : string
- As rs_quoted_printable_encode() but for e-mail subject
- pager() : void
- A generic pager function used by many display lists in ResourceSpace.
- remove_extension() : string
- Remove the extension part of a filename
- get_allowed_extensions_by_type() : string
- Retrieve a list of permitted extensions for the given resource type.
- getAbsolutePath() : string
- Detect if a path is relative or absolute.
- getFolderContents() : array<string|int, mixed>
- Find the files present in a folder, and sub-folder.
- mb_basename() : string
- Returns filename component of path This version is UTF-8 proof.
- strip_extension() : string
- Remove the extension part of a filename.
- is_process_lock() : bool
- Checks to see if a process lock exists for the given process name.
- set_process_lock() : bool
- Set a process lock
- clear_process_lock() : bool
- Clear a process lock
- filesize_unlimited() : int|bool
- Custom function for retrieving a file size. A resolution for PHP's issue with large files and filesize().
- strip_leading_comma() : string
- Strip the leading comma from a string
- get_temp_dir() : string
- Determines where the tmp directory is. There are three options here: 1. tempdir - If set in config.php, use this value.
- convert_path_to_url() : Url
- Converts a path to a url relative to the installation.
- escape_command_args() : string
- Escaping an unsafe command string
- run_command() : string
- Utility function which works like system(), but returns the complete output string rather than just the last line of it.
- run_external() : array<string|int, mixed>
- Similar to run_command but returns an array with the resulting output (stdout & stderr) fetched concurrently for improved performance.
- error_alert() : void
- Display a styledalert() modal error and optionally return the browser to the previous page after 2 seconds
- format_display_field() : string
- When displaying metadata, applies trim/wordwrap.
- format_string_more_link() : string
- Formats a string with a collapsible more / less section
- draw_performance_footer() : void
- Render a performance footer with metrics.
- format_query() : string
- Format SQL queries for display purposes Note: these queries are no longer known to be safe from sql injection
- sql_affected_rows() : mixed
- Abstracted mysqli_affected_rows()
- get_imagemagick_path() : string
- Returns the path to the ImageMagick utilities such as 'convert'.
- get_utility_path() : string|bool
- Returns the full path to a utility, if installed or FALSE otherwise.
- get_executable_path() : string|bool
- Get full path to utility
- truncate_cache_arrays() : void
- Clean up the resource data cache to keep within $cache_array_limit
- is_html() : bool
- Work out of a string is likely to be in HTML format.
- rs_setcookie() : void
- Set a cookie.
- get_editable_states() : array<string|int, mixed>
- Get an array of all the states that a user has edit access to
- validate_html() : bool|string
- Returns true if $html is valid HTML, otherwise an error string describing the problem.
- generateURL() : string
- Utility function to generate URLs with query strings easier, with the ability to override existing query string parameters when needed.
- move_array_element() : void
- Utility function used to move the element of one array from a position to another one in the same array Note: the manipulation is done on the same array
- emptyiszero() : bool
- Check if a value that may equate to false in PHP is actually a zero
- get_slideshow_files_data() : array<string|int, mixed>
- Get data for each image that should be used on the slideshow.
- is_login_slideshow_enabled() : bool
- Determines if at least one slideshow image is configured for the login page
- form_value_display() : string
- Returns a sanitised row from the table in a safe form for use in a form value, suitable overwritten by POSTed data if it has been supplied.
- user_set_usergroup() : void
- Change the user's user group
- generateSecureKey() : string
- Generates a random string of requested length.
- IsModal() : bool
- Check if current page is a modal and set global $modal variable if not already set
- generateCSRFToken() : string
- Generates a CSRF token (Encrypted Token Pattern)
- isValidCSRFToken() : bool
- Checks if CSRF Token is valid
- generateFormToken() : void
- Render the CSRF Token input tag
- generateAjaxToken() : string
- Render the CSRF Token for AJAX use
- generate_csrf_js_object() : string
- Create a CSRF token as a JS object
- generate_csrf_data_for_api_native_authmode() : string
- Create an HTML data attribute holding a CSRF token (JS) object
- enforcePostRequest() : bool|void
- Enforce using POST requests
- is_resourcespace_upgrade_available() : bool
- Check if ResourceSpace is up to date or an upgrade is available
- get_recent_users() : int
- Fetch a count of recently active users
- get_total_approved_users() : int
- Return the total number of approved
- get_total_resources() : int
- Return the number of resources in the system with optional filter by archive state
- check_script_last_ran() : bool
- Check if script last ran more than the failure notification days Note: Never/ period longer than allowed failure should return false
- count_errors() : int
- Counting errors found in a collection of items. An error is found when an item has an "error" key.
- search_array_by_keyvalue() : array<string|int, mixed>
- Function can be used to order a multi-dimensional array using a key and corresponding value
- bypass_permissions() : mixed
- Temporary bypass access controls for a particular function
- set_sysvar() : bool
- Set a system variable (which is stored in the sysvars table) - set to null to remove
- get_sysvar() : string
- Get a system variable (which is received from the sysvars table)
- hook() : mixed
- Plugin architecture. Look for hooks with this name (and corresponding page, if applicable) and run them sequentially.
- html_find_and_replace_node() : void
- Performs a string replace once a text-only node is encountered, otherwise loops and calls itself to iterate over child nodes Not intended to be called directly - use html_find_and_replace
- html_find_and_replace() : string
- Loads HTML fragment into a DOMDocument instance to parse and perform a recursive find/replace on text-only nodes.
- strip_tags_and_attributes() : mixed
- Utility function to remove unwanted HTML tags and attributes.
- strip_paragraph_tags() : string
- Remove paragraph tags from start and end of text.
- get_inner_html_from_tag() : string
- Helper function to quickly return the inner HTML of a specific tag element from a DOM document.
- show_pagetime() : string
- Returns the page load time until this point.
- get_debug_log_dir() : string
- Determines where the debug log will live. Typically, same as tmp dir (See general.php: get_temp_dir().
- debug() : bool
- Output debug information to the debug log, if debugging is enabled.
- rcRmdir() : bool
- Recursively removes a directory.
- daily_stat() : void
- Update the daily statistics after a loggable event.
- pagename() : string
- Returns the current page name minus the extension, e.g. "home" for pages/home.php
- pluginname() : string
- text() : string
- Returns the site content from the language strings. These will already be overridden with site_text content if present.
- get_section_list() : array<string|int, mixed>
- Gets a list of site text sections, used for a multi-page help area.
- resolve_user_agent() : string
- Returns a more friendly user agent string based on the passed user agent. Used in the user area to establish browsers used.
- get_ip() : string
- Returns the current user's IP address, using HTTP proxy headers if present.
- ResolveKB() : string
- For a value such as 10M return the kilobyte equivalent such as 10240. Used by check.php
- trim_filename() : string
- Trim a filename that is longer than 255 characters while keeping its extension (if present)
- array_flip_by_value_key() : array<string|int, mixed>
- Flip array keys to use one of the keys of the values it contains. All elements (ie values) of the array must contain the key (ie. they are arrays). Helper function to greatly increase search performance on huge PHP arrays.
- reshape_array_by_value_keys() : array<string|int, mixed>
- Reshape array using the keys of its values. All values must contain the selected keys.
- permission_j() : bool
- Permission check for "j[ref]"
- permission_negative_j() : bool
- Permission check for "-j[ref]"
- cleanup_files() : void
- Delete temporary files
- is_int_loose() : bool
- Validate if value is integer or string integer
- is_positive_int_loose() : bool
- Helper function to check if value is a positive integer looking type.
- is_positive_or_zero_int_loose() : bool
- Helper function to check if value is a positive or zero integer looking type.
- is_array_of_pos_or_zero_ints() : bool
- Helper function to check if value is an array containing only positive or zero integer looking types
- is_string_loose() : bool
- Helper function to check if a value is able to be cast to a string
- is_input_list_loose() : bool
- Input (type) validation helper function for a list of integers (mostly used for IDs). This covers cases when the submitted data is either sent as an actual list (i.e. myInput[]) or when retrieved from the cookie/query string as a CSV.
- is_float_loose() : bool
- Helper function to check if a value is able to be cast to a float
- ip_matches() : bool|int
- Does the provided $ip match the string $ip_restrict? Used for restricting user access by IP address.
- set_unique_filename() : string
- Ensures filename is unique in $filenames array and adds resulting filename to the array
- build_permission() : Closure
- Build a specific permission closure which can be applied to a list of items.
- validate_remote_code() : bool
- Attempt to validate remote code.
- get_system_status() : array<string|int, mixed>
- Get system status information
- try_unlink() : bool|string
- Try and delete a file without triggering a fatal error
- try_getimagesize() : mixed
- check_filestore_browseability() : array<string|int, mixed>
- Check filestore folder browseability.
- check_imagemagick_cli_version_found() : array<string|int, mixed>
- Check CLI version found for ImageMagick is as expected.
- check_exiftool_cli_version_found() : array<string|int, mixed>
- Check CLI version found for Exiftool is as expected.
- check_numeric_cli_version_found() : array<string|int, mixed>
- Check CLI numeric version found for a utility is as expected.
- check_utility_cli_version_found_by_name() : array<string|int, mixed>
- Check CLI version found for a utility is as expected by looking up for its name.
- command_line_only() : void
- Check we're running on the command line, exit otherwise. Security feature for the scripts in /pages/tools/
- prefix_value() : Closure
- Helper function to quickly build a list of values, all prefixed the same way.
- validateDatetime() : bool
- Utility function to check string is a valid date/time with a specific format.
- string_ends_with() : mixed
- set_order_by_to_zero() : array<string|int, mixed>
- Helper function to set the order_by key of an array to zero.
- cast_echo_to_string() : string
- Helper function to cast functions that only echo things out (e.g render functions) to string type.
- parse_csv_to_list_of_type() : array<string|int, mixed>
- Helper function to parse input to a list of a particular type.
- execution_lockout_remove_resource_type_field_props() : array<string|int, mixed>
- Remove metadata field properties during execution lockout
- set_watermark_image() : void
- Update global variable watermark to point to the correct file. Watermark set on System Configuration page will override a watermark set in config.php. config.default.php will apply otherwise (blank) so no watermark will be applied.
- compute_dpi() : mixed
- DPI calculations
- compute_megapixel() : float
- MP calculation
- get_size_info() : string
- Get size info as a paragraphs HTML tag
- is_jpeg_extension() : bool
- Simple function to check if a given extension is associated with a JPG file
- url_starts_with() : bool
- Input validation helper function to check a URL is ours (e.g. if it's our base URL). Mostly used for redirect URLs.
- is_safe_url() : bool
- Input validation helper function to check if a URL is safe (from XSS) in an HTML context.
- sanitise_url() : string
- Sanitise URL for HTML rendering purposes.
- validate_sort_value() : bool
- Input validation helper function for sorting (ASC/DESC).
- validate_digit_csv() : bool
- Input validation helper function for a CSV of integers (mostly used for IDs).
- get_sub_array_with() : callable
- Helper function to get an array of values with a subset of their original keys.
- enforceSharePassword() : void
- Server side check to backup front end javascript validation.
- js_call_CentralSpaceLoad() : never
- Helper function to call the JS CentralSpaceLoad().
- getCertificateExpiry() : string|bool
- Get expiration date of a given PEM certificate
- isValidCssColor() : bool
- Is the provided colour a valid CSS colour and therefore safe to display?
- hslToRgb() : array<string|int, mixed>
- Convert HSL to RGB.
- check_tinymce_plugins() : string
- Check TinyMCE plugin list against an array of valid options The passed list is checked against TINYMCE_VALID_PLUGINS.
- check_tinymce_toolbar() : string
- Check TinyMCE toolbar configuration to ensure it contains only alphanumeric characters, spaces and the pipe (|) symbol.
- get_non_ingested_resources() : int
- Return the number of resources in the system that are not ingested into the filestore i.e. with 'file_path' set
- get_favicon_url() : string
- Return URL of the application favicon
- is_original_preview() : bool
- Determine what is a manually uploaded preview based off of data in the resource log
- get_page_title() : string
- Return the page title to use for the given page and optionally plugin.
- log_bandwidth() : void
- Log the bandwidth used by download.php
- strip_unicode_points() : string
- Strip Unicode points from a text value.
- allow_unicode_characters() : string
- Strip any characters not present in the allow list. Mostly useful for search/indexing purposes where we care more about the words themselves and less about linking or any other type of characters.
- set_per_page_cookie() : void
- Add or update the value used for paging for the current page to the list of stored pager cookies
- get_per_page_cookie() : int
- Retrieve the pager cookie for the current page.
- parse_int_ranges() : array<string|int, mixed>
- Parse a comma-separated list of integers and integer ranges into a sorted array.
- build_range_where_condition() : array<string|int, mixed>
- Build a SQL WHERE fragment and bound parameters from a list of integers and ranges.
Functions
getval()
Retrieve a user-submitted parameter from the browser via post/get/cookies, in that order.
getval(string $param, string $default[, bool $force_numeric = false ][, callable $type_check = null ]) : mixed
Parameters
- $param : string
-
The parameter name
- $default : string
-
A default value to return if no matching parameter was found
- $force_numeric : bool = false
-
Ensure a number is returned. (DEPRECATED)
- $type_check : callable = null
-
Validate param type. Default is to check param values are strings.
escape_check()
Escape a value prior to using it in SQL.
escape_check(string $text) : string
IMPORTANT! NO LONGER NEEDED with prepared statements. This is only used when exporting SQL scripts.
Parameters
- $text : string
Return values
stringunescape()
For comparing escape_checked strings against mysql content because just doing $text=str_replace("\\","",$text); does not undo escape_check
unescape(mixed $text) : string
Parameters
- $text : mixed
Return values
stringnicedate()
Formats a MySQL ISO date
nicedate(mixed $date[, mixed $time = false ][, mixed $wordy = true ][, mixed $offset_tz = false ]) : string
Always use the 'wordy' style from now on as this works better internationally.
Parameters
- $date : mixed
- $time : mixed = false
- $wordy : mixed = true
- $offset_tz : mixed = false
Tags
Return values
string —Returns an empty string if date not set/invalid
date_to_age()
Generates a text representation of the age from a given date
date_to_age(string $datetime) : string
This can be used to give a more user friendly indication of how old something is.
Parameters
- $datetime : string
-
ISO format date which can be a BCE date (ie. with negative year -yyyy)
Return values
string —Returns a string representing the age calculated from $datetime, otherwise an empty string if date is invalid
preview_from_text()
Generates preview text of a certain line length and count
preview_from_text(string $text, int $line_length, int $line_count[, bool $add_ellipsis = true ]) : string
Can be used for generating previews of text output, such as messages.
Parameters
- $text : string
-
The text to generate the preview of, can contain HTML
- $line_length : int
-
The number of characters that the preview can have on each line
- $line_count : int
-
The number of lines to be generated in the preview
- $add_ellipsis : bool = true
-
Should ellipsis (...) be added if the original $text exceeds $line_count
Return values
string —Returns a string of the preview text, or an empty string if the preview is unable to be generated
redirect()
Redirect to the provided URL using a HTTP header Location directive. Exits after redirect
redirect(string $url) : never
Parameters
- $url : string
-
URL to redirect to
Return values
nevertrim_spaces()
replace multiple spaces with a single space
trim_spaces(mixed $text) : string
Parameters
- $text : mixed
Return values
stringtrim_array()
Removes whitespace from the beginning/end of all elements in an array
trim_array(array<string|int, mixed> $array[, string $trimchars = '' ]) : array<string|int, mixed>
Parameters
- $array : array<string|int, mixed>
- $trimchars : string = ''
Return values
array<string|int, mixed>tidylist()
Takes a value as returned from a check-list field type and reformats to be more display-friendly.
tidylist(string $list) : string
Check-list fields have a leading comma.
Parameters
- $list : string
Return values
stringtidy_trim()
Trims $text to $length if necessary. Tries to trim at a space if possible. Adds three full stops if trimmed.
tidy_trim(string $text, int $length) : string
..
Parameters
- $text : string
- $length : int
Return values
stringaverage_length()
Returns the average length of the strings in an array
average_length(array<string|int, mixed> $array) : float
Parameters
- $array : array<string|int, mixed>
Return values
floatget_stats_activity_types()
Returns a list of activity types for which we have stats data (Search, User Session etc.)
get_stats_activity_types() : array<string|int, mixed>
Return values
array<string|int, mixed>newlines()
Replace escaped newlines with real newlines.
newlines(string $text) : string
Parameters
- $text : string
Return values
stringget_all_site_text()
Returns a list of all available editable site text (content). If $find is specified a search is performed across page, name and text fields.
get_all_site_text([string $findpage = "" ][, string $findname = "" ][, string $findtext = "" ]) : array<string|int, mixed>
Parameters
- $findpage : string = ""
- $findname : string = ""
- $findtext : string = ""
Return values
array<string|int, mixed>get_site_text()
Returns a specific site text entry.
get_site_text(string $page, string $name, string $getlanguage, string $group) : string
Parameters
- $page : string
- $name : string
- $getlanguage : string
- $group : string
Return values
stringcheck_site_text_custom()
Check if site text section is custom, i.e. deletable.
check_site_text_custom(mixed $page, mixed $name) : bool
Parameters
- $page : mixed
- $name : mixed
Return values
boolsave_site_text()
Saves the submitted site text changes to the database.
save_site_text(string $page, string $name, string $language, int $group) : void
Parameters
- $page : string
- $name : string
- $language : string
- $group : int
formatfilesize()
Return a human-readable string representing $bytes in either KB or MB.
formatfilesize(int $bytes[, bool $html = true ]) : string
Parameters
- $bytes : int
-
file size to format in bytes
- $html : bool = true
-
if set to true output will include  instead of a space
Return values
stringfilesize2bytes()
Converts human readable file size (e.g. 10 MB, 200.20 GB) into bytes.
filesize2bytes(string $str) : int
Parameters
- $str : string
Return values
int —the result is in bytes
get_mime_type()
Get the mime type for a file on disk
get_mime_type(string $path[, string $ext = null ][, bool|null $file_based_detection = null ]) : array<string|int, mixed>
Parameters
- $path : string
- $ext : string = null
- $file_based_detection : bool|null = null
-
Determine the MIME type:
- null: Check by extension or using exiftool
- true: Only file based (uses exiftool)
- false: Only based on extension
Return values
array<string|int, mixed>get_mime_types_by_extension()
Find matching MIME type(s) for a file extension.
get_mime_types_by_extension(string $extension) : array<int, string>
Parameters
- $extension : string
Return values
array<int, string>get_unsafe_mime_types()
Get the global MIME types associated with the configured banned extensions.
get_unsafe_mime_types() : array<string|int, mixed>
Return values
array<string|int, mixed>allowed_type_mime()
Convert the permitted resource type extension to MIME type. Used by upload_batch.php
allowed_type_mime(mixed $allowedtype) : string
Parameters
- $allowedtype : mixed
Return values
string —MIME type e.g. image/jpeg
send_mail()
Send a mail - but correctly encode the message/subject in quoted-printable UTF-8.
send_mail(string $email, string $subject, string $message[, string $from = "" ][, string $reply_to = "" ][, string $html_template = "" ][, array<string|int, mixed> $templatevars = array() ][, string $from_name = "" ][, string $cc = "" ][, string $bcc = "" ][, array<string|int, mixed> $files = array() ]) : mixed
NOTE: $from is the name of the user sending the email, while $from_name is the name that should be put in the header, which can be the system name It is necessary to specify two since in all cases the email should be able to contain the user's name.
Old mail function remains the same to avoid possible issues with phpmailer send_mail_phpmailer allows for the use of text and html (multipart) emails, and the use of email templates in Manage Content.
Parameters
- $email : string
-
Email address to send to
- $subject : string
-
Email subject
- $message : string
-
Message text
- $from : string = ""
-
From address - defaults to $email_from
- $reply_to : string = ""
-
Reply to address - defaults to $email_from
- $html_template : string = ""
-
Optional template (this is a $lang entry with placeholders)
- $templatevars : array<string|int, mixed> = array()
-
Used to populate email template placeholders
- $from_name : string = ""
-
Email from name
- $cc : string = ""
-
Optional CC addresses
- $bcc : string = ""
-
Optional BCC addresses
- $files : array<string|int, mixed> = array()
-
Optional array of file paths to attach in the format [filename.txt => /path/to/file.txt]
send_mail_phpmailer()
if ($use_phpmailer==true) this function is used instead.
send_mail_phpmailer(string $email, string $subject[, string $message = "" ][, string $from = "" ][, string $reply_to = "" ][, string $html_template = "" ][, array<string|int, mixed> $templatevars = array() ][, string $from_name = "" ][, string $cc = "" ][, string $bcc = "" ][, array<string|int, mixed> $files = array() ]) : void
Mail templates can include lang, server, site_text, and POST variables by default ex ( [lang_mycollections], [server_REMOTE_ADDR], [text_footer] , [message]
additional values must be made available through $templatevars For example, a complex url or image path that may be sent in an email should be added to the templatevars array and passed into send_mail. available templatevars need to be well-documented, and sample templates need to be available.
Parameters
- $email : string
-
Email address to send to
- $subject : string
-
Email subject
- $message : string = ""
-
Message text
- $from : string = ""
-
From address - defaults to $email_from
- $reply_to : string = ""
-
Reply to address - defaults to $email_from
- $html_template : string = ""
-
Optional template (this is a $lang entry with placeholders)
- $templatevars : array<string|int, mixed> = array()
-
Used to populate email template placeholders
- $from_name : string = ""
-
Email from name
- $cc : string = ""
-
Optional CC addresses
- $bcc : string = ""
-
Optional BCC addresses
- $files : array<string|int, mixed> = array()
-
Optional array of file paths to attach in the format [filename.txt => /path/to/file.txt]
log_mail()
Log email
log_mail(string $email, string $subject, string $sender) : void
Data logged is: Time To address From, User ID or 0 for system emails (cron etc.) Subject
Parameters
- $email : string
- $subject : string
- $sender : string
-
The email address of the sender
rs_quoted_printable_encode()
Quoted printable encoding is rather simple.
rs_quoted_printable_encode(string $string[, int $linelen = 0 ][, string $linebreak = "=\r\n" ][, int $breaklen = 0 ][, bool $encodecrlf = false ]) : string
Each character in the string $string should be encoded if: Character code is <0x20 (space) Character is = (as it has a special meaning: 0x3d) Character is over ASCII range (>=0x80)
Parameters
- $string : string
- $linelen : int = 0
- $linebreak : string = "=\r\n"
- $breaklen : int = 0
- $encodecrlf : bool = false
Return values
stringrs_quoted_printable_encode_subject()
As rs_quoted_printable_encode() but for e-mail subject
rs_quoted_printable_encode_subject(string $string[, string $encoding = 'UTF-8' ]) : string
Parameters
- $string : string
- $encoding : string = 'UTF-8'
Return values
stringpager()
A generic pager function used by many display lists in ResourceSpace.
pager([bool $break = false ][, bool $scrolltotop = true ][, array<string|int, mixed> $options = array() ]) : void
Requires the following globals to be set or passed inb the $options array $url - Current page url $curpage - Current page $totalpages - Total number of pages
Parameters
- $break : bool = false
- $scrolltotop : bool = true
- $options : array<string|int, mixed> = array()
-
- array of options to use instead of globals
remove_extension()
Remove the extension part of a filename
remove_extension(mixed $strName) : string
Parameters
- $strName : mixed
-
The filename
Return values
string —The filename minus the extension
get_allowed_extensions_by_type()
Retrieve a list of permitted extensions for the given resource type.
get_allowed_extensions_by_type(int $resource_type) : string
Parameters
- $resource_type : int
Return values
stringgetAbsolutePath()
Detect if a path is relative or absolute.
getAbsolutePath(string $path[, bool $create_if_not_exists = false ]) : string
If it is relative, we compute its absolute location by assuming it is relative to the application root (parent folder).
Parameters
- $path : string
-
A relative or absolute path
- $create_if_not_exists : bool = false
-
Try to create the path if it does not exists. Default to False.
Tags
Return values
string —A absolute path
getFolderContents()
Find the files present in a folder, and sub-folder.
getFolderContents(string $path[, bool $recurse = true ][, bool $include_hidden = false ]) : array<string|int, mixed>
Parameters
- $path : string
-
The path to look into.
- $recurse : bool = true
-
Trigger the recursion, default to True.
- $include_hidden : bool = false
-
Trigger the listing of hidden files / hidden directories, default to False.
Tags
Return values
array<string|int, mixed> —A list of files present in the inspected folder (paths are relative to the inspected folder path).
mb_basename()
Returns filename component of path This version is UTF-8 proof.
mb_basename(string $file) : string
Parameters
- $file : string
-
A path.
Tags
Return values
string —Returns the base name of the given path.
strip_extension()
Remove the extension part of a filename.
strip_extension(string $name[, mixed $use_ext_list = false ]) : string
Parameters
- $name : string
-
A file name.
- $use_ext_list : mixed = false
Tags
Return values
string —Return the file name without the extension part.
is_process_lock()
Checks to see if a process lock exists for the given process name.
is_process_lock(string $name) : bool
Parameters
- $name : string
-
Name of lock to check
Return values
bool —TRUE if a current process lock is in place, false if not
set_process_lock()
Set a process lock
set_process_lock(string $name) : bool
Parameters
- $name : string
Return values
boolclear_process_lock()
Clear a process lock
clear_process_lock(string $name) : bool
Parameters
- $name : string
Return values
boolfilesize_unlimited()
Custom function for retrieving a file size. A resolution for PHP's issue with large files and filesize().
filesize_unlimited(string $path) : int|bool
Parameters
- $path : string
Return values
int|bool —The file size in bytes
strip_leading_comma()
Strip the leading comma from a string
strip_leading_comma(string $val) : string
Parameters
- $val : string
Return values
stringget_temp_dir()
Determines where the tmp directory is. There are three options here: 1. tempdir - If set in config.php, use this value.
get_temp_dir([bool $asUrl = false ][, mixed $uniqid = "" ]) : string
- storagedir ."/tmp" - If storagedir is set in config.php, use it and create a subfolder tmp.
- generate default path - use filestore/tmp if all other attempts fail.
- if a uniqid is provided, create a folder within tmp and return the full path
Parameters
- $asUrl : bool = false
-
- If we want the return to be like http://my.resourcespace.install/path set this as true.
- $uniqid : mixed = ""
Tags
Return values
string —Path to the tmp directory.
convert_path_to_url()
Converts a path to a url relative to the installation.
convert_path_to_url(string $abs_path) : Url
Parameters
- $abs_path : string
-
: The absolute path.
Return values
Url —that is the relative path.
escape_command_args()
Escaping an unsafe command string
escape_command_args(string $cmd, array<string|int, mixed> $args) : string
Parameters
- $cmd : string
-
Unsafe command to run
- $args : array<string|int, mixed>
-
List of placeholders and their values which will have to be escapedshellarg()d.
Tags
Return values
string —Escaped command string
run_command()
Utility function which works like system(), but returns the complete output string rather than just the last line of it.
run_command(string $command[, bool $geterrors = false ][, array<string|int, mixed> $params = array() ][, int $timeout = 0 ]) : string
Parameters
- $command : string
-
Command to run
- $geterrors : bool = false
-
Set to TRUE to include errors in the output
- $params : array<string|int, mixed> = array()
-
List of placeholders and their values which will have to be escapedshellarg()d.
- $timeout : int = 0
-
Maximum time in seconds before a command is forcibly stopped
Tags
Return values
string —Command output
run_external()
Similar to run_command but returns an array with the resulting output (stdout & stderr) fetched concurrently for improved performance.
run_external(mixed $command) : array<string|int, mixed>
Parameters
- $command : mixed
-
Command to run
Return values
array<string|int, mixed> —Command output
error_alert()
Display a styledalert() modal error and optionally return the browser to the previous page after 2 seconds
error_alert(string $error[, bool $back = true ][, int $code = 403 ]) : void
Parameters
- $error : string
-
Error text to display
- $back : bool = true
-
Return to previous page?
- $code : int = 403
-
(Optional) HTTP code to return
format_display_field()
When displaying metadata, applies trim/wordwrap.
format_display_field(string $value) : string
Parameters
- $value : string
Return values
stringformat_string_more_link()
Formats a string with a collapsible more / less section
format_string_more_link(string $string[, int $max_words_before_more = 30 ]) : string
Parameters
- $string : string
- $max_words_before_more : int = 30
Return values
stringdraw_performance_footer()
Render a performance footer with metrics.
draw_performance_footer() : void
format_query()
Format SQL queries for display purposes Note: these queries are no longer known to be safe from sql injection
format_query(string $query, array<string|int, mixed> $params) : string
Parameters
- $query : string
- $params : array<string|int, mixed>
Return values
stringsql_affected_rows()
Abstracted mysqli_affected_rows()
sql_affected_rows() : mixed
get_imagemagick_path()
Returns the path to the ImageMagick utilities such as 'convert'.
get_imagemagick_path(string $utilityname, string $exeNames, string &$checked_path) : string
Parameters
- $utilityname : string
- $exeNames : string
- $checked_path : string
Tags
Return values
stringget_utility_path()
Returns the full path to a utility, if installed or FALSE otherwise.
get_utility_path(string $utilityname[, string &$checked_path = null ]) : string|bool
Note: this function doesn't check that the utility is working.
Parameters
- $utilityname : string
- $checked_path : string = null
Tags
Return values
string|bool —Returns full path to utility tool or FALSE
get_executable_path()
Get full path to utility
get_executable_path(string $path, array<string|int, mixed> $executable, string &$checked_path[, bool $check_exe = false ]) : string|bool
Parameters
- $path : string
- $executable : array<string|int, mixed>
- $checked_path : string
- $check_exe : bool = false
Tags
Return values
string|booltruncate_cache_arrays()
Clean up the resource data cache to keep within $cache_array_limit
truncate_cache_arrays() : void
is_html()
Work out of a string is likely to be in HTML format.
is_html(mixed $string) : bool
Parameters
- $string : mixed
Return values
boolrs_setcookie()
Set a cookie.
rs_setcookie(string $name, string $value[, int $daysexpire = 0 ][, string $path = "" ][, string $domain = "" ][, bool $secure = false ][, bool $httponly = true ][, string $samesite = "Strict" ]) : void
Note: The argument $daysexpire is not the same as the argument $expire in the PHP internal function setcookie.
Parameters
- $name : string
- $value : string
- $daysexpire : int = 0
- $path : string = ""
- $domain : string = ""
- $secure : bool = false
- $httponly : bool = true
- $samesite : string = "Strict"
get_editable_states()
Get an array of all the states that a user has edit access to
get_editable_states(int $userref) : array<string|int, mixed>
Parameters
- $userref : int
Return values
array<string|int, mixed>validate_html()
Returns true if $html is valid HTML, otherwise an error string describing the problem.
validate_html(mixed $html) : bool|string
Parameters
- $html : mixed
Return values
bool|stringgenerateURL()
Utility function to generate URLs with query strings easier, with the ability to override existing query string parameters when needed.
generateURL(string $url[, array<string|int, mixed> $parameters = array() ][, array<string|int, mixed> $set_params = array() ]) : string
Parameters
- $url : string
- $parameters : array<string|int, mixed> = array()
-
Default query string params (e.g "k", which appears on most of ResourceSpace URLs)
- $set_params : array<string|int, mixed> = array()
-
Override existing query string params
Tags
Return values
stringmove_array_element()
Utility function used to move the element of one array from a position to another one in the same array Note: the manipulation is done on the same array
move_array_element(array<string|int, mixed> &$array, int $from_index, int $to_index) : void
Parameters
- $array : array<string|int, mixed>
- $from_index : int
-
Array index we are moving from
- $to_index : int
-
Array index we are moving to
emptyiszero()
Check if a value that may equate to false in PHP is actually a zero
emptyiszero(mixed $value) : bool
Parameters
- $value : mixed
Return values
boolget_slideshow_files_data()
Get data for each image that should be used on the slideshow.
get_slideshow_files_data() : array<string|int, mixed>
The format of the returned array should be: Array ( [0] => Array ( [ref] => 1 [resource_ref] => [homepage_show] => 1 [login_show] => 1 [file_path] => /var/www/filestore/system/slideshow_1bf4796ac6f051a/1.jpg [checksum] => 1539875502 )
[1] => Array
(
[ref] => 4
[resource_ref] => 19
[homepage_show] => 1
[login_show] => 0
[file_path] => /var/www/filestore/system/slideshow_1bf4796ac6f051a/4.jpg
[checksum] => 1542818794
[link] => http://localhost/?r=19
)
)
Return values
array<string|int, mixed>is_login_slideshow_enabled()
Determines if at least one slideshow image is configured for the login page
is_login_slideshow_enabled() : bool
Return values
boolform_value_display()
Returns a sanitised row from the table in a safe form for use in a form value, suitable overwritten by POSTed data if it has been supplied.
form_value_display(array<string|int, mixed> $row, string $name[, string $default = "" ]) : string
Parameters
- $row : array<string|int, mixed>
- $name : string
- $default : string = ""
Return values
stringuser_set_usergroup()
Change the user's user group
user_set_usergroup(int $user, int $usergroup) : void
Parameters
- $user : int
- $usergroup : int
generateSecureKey()
Generates a random string of requested length.
generateSecureKey([int $length = 64 ]) : string
Used to generate initial spider and scramble keys.
Parameters
- $length : int = 64
-
Length of desired string of bytes
Tags
Return values
string —Random character string
IsModal()
Check if current page is a modal and set global $modal variable if not already set
IsModal() : bool
Return values
bool —true if modal, false otherwise
generateCSRFToken()
Generates a CSRF token (Encrypted Token Pattern)
generateCSRFToken(string $session_id, string $form_id) : string
Parameters
- $session_id : string
-
The current user session ID
- $form_id : string
-
A unique form ID
Tags
Return values
string —Token
isValidCSRFToken()
Checks if CSRF Token is valid
isValidCSRFToken(mixed $token_data, mixed $session_id) : bool
Parameters
- $token_data : mixed
- $session_id : mixed
Tags
Return values
bool —Returns TRUE if token is valid or CSRF is not enabled, FALSE otherwise
generateFormToken()
Render the CSRF Token input tag
generateFormToken(string $form_id) : void
Parameters
- $form_id : string
-
The id/ name attribute of the form
Tags
generateAjaxToken()
Render the CSRF Token for AJAX use
generateAjaxToken(string $form_id) : string
Parameters
- $form_id : string
-
The id/ name attribute of the form or just the calling function for this type of request
Tags
Return values
stringgenerate_csrf_js_object()
Create a CSRF token as a JS object
generate_csrf_js_object(string $name) : string
Parameters
- $name : string
-
The name of the token identifier (e.g API function called)
Tags
Return values
string —JS object with CSRF data (identifier & token) if CSRF is enabled, empty object otherwise
generate_csrf_data_for_api_native_authmode()
Create an HTML data attribute holding a CSRF token (JS) object
generate_csrf_data_for_api_native_authmode(string $fct_name) : string
Parameters
- $fct_name : string
-
The name of the API function called (e.g create_resource)
Return values
stringenforcePostRequest()
Enforce using POST requests
enforcePostRequest(bool $ajax) : bool|void
Parameters
- $ajax : bool
-
Set to TRUE if request is done via AJAX
Return values
bool|void —Returns true if request method is POST or sends 405 header otherwise
is_resourcespace_upgrade_available()
Check if ResourceSpace is up to date or an upgrade is available
is_resourcespace_upgrade_available() : bool
Tags
Return values
boolget_recent_users()
Fetch a count of recently active users
get_recent_users(int $days) : int
Parameters
- $days : int
-
How many days to look back
Return values
intget_total_approved_users()
Return the total number of approved
get_total_approved_users() : int
Return values
int —The number of approved users
get_total_resources()
Return the number of resources in the system with optional filter by archive state
get_total_resources([int|bool $status = false ]) : int
Parameters
- $status : int|bool = false
-
Archive state to filter by if required
Return values
int —Number of resources in the system, filtered by status if provided
check_script_last_ran()
Check if script last ran more than the failure notification days Note: Never/ period longer than allowed failure should return false
check_script_last_ran(string $name, int $fail_notify_allowance, string &$last_ran_datetime) : bool
Parameters
- $name : string
-
Name of the sysvar to check the record for
- $fail_notify_allowance : int
-
How long to allow (in days) before user can consider script has failed
- $last_ran_datetime : string
-
Datetime (string format) when script was last run
Return values
boolcount_errors()
Counting errors found in a collection of items. An error is found when an item has an "error" key.
count_errors(array<string|int, mixed> $a) : int
Parameters
- $a : array<string|int, mixed>
-
Collection of items that may contain errors.
Return values
intsearch_array_by_keyvalue()
Function can be used to order a multi-dimensional array using a key and corresponding value
search_array_by_keyvalue(array<string|int, mixed> $array2search, string $search_key, string $search_value, array<string|int, mixed> $return_array) : array<string|int, mixed>
Parameters
- $array2search : array<string|int, mixed>
-
multi-dimensional array in which the key/value pair may be present
- $search_key : string
-
key of the key/value pair used for search
- $search_value : string
-
value of the key/value pair to search
- $return_array : array<string|int, mixed>
-
array to which the matching elements in the search array are pushed - also returned by function
Return values
array<string|int, mixed> —$return_array
bypass_permissions()
Temporary bypass access controls for a particular function
bypass_permissions(array<string|int, mixed> $perms, callable $f[, array<string|int, mixed> $p = array() ]) : mixed
When functions check for permissions internally, in order to keep backwards compatibility it may be better if we temporarily bypass the permissions instead of adding a parameter to the function for this. It will allow developers to keep the code clean.
IMPORTANT: never make this function public to the API.
Example code: $log = bypass_permissions(array("v"), "get_resource_log", array($ref));
Parameters
- $perms : array<string|int, mixed>
-
Permission list to be bypassed
- $f : callable
-
Callable that we need to bypas permissions for
- $p : array<string|int, mixed> = array()
-
Parameters to be passed to the callable if required
set_sysvar()
Set a system variable (which is stored in the sysvars table) - set to null to remove
set_sysvar(mixed $name[, mixed $value = null ][, bool $clear_cache = true ]) : bool
Parameters
- $name : mixed
-
Variable name
- $value : mixed = null
-
String to set a new value; null to remove any existing value.
- $clear_cache : bool = true
-
Set to false to skip the clearing of any cached values (default true).
Tags
Return values
boolget_sysvar()
Get a system variable (which is received from the sysvars table)
get_sysvar(string $name[, string $default = false ]) : string
Parameters
- $name : string
- $default : string = false
-
Returned if no matching variable was found
Tags
Return values
stringhook()
Plugin architecture. Look for hooks with this name (and corresponding page, if applicable) and run them sequentially.
hook(string $name[, string $pagename = "" ][, array<string|int, mixed> $params = array() ][, bool $last_hook_value_wins = false ]) : mixed
Utilises a cache for significantly better performance. Enable $draw_performance_footer in config.php to see stats.
Parameters
- $name : string
- $pagename : string = ""
- $params : array<string|int, mixed> = array()
- $last_hook_value_wins : bool = false
Tags
html_find_and_replace_node()
Performs a string replace once a text-only node is encountered, otherwise loops and calls itself to iterate over child nodes Not intended to be called directly - use html_find_and_replace
html_find_and_replace_node(string $findstring, string $replacestring, DOMNode $node) : void
Parameters
- $findstring : string
- $replacestring : string
-
can be blank if using for removal
- $node : DOMNode
html_find_and_replace()
Loads HTML fragment into a DOMDocument instance to parse and perform a recursive find/replace on text-only nodes.
html_find_and_replace(string $findstring, string $replacestring, string $html) : string
Returns modified HTML if possible, otherwise the original HTML.
Parameters
- $findstring : string
- $replacestring : string
-
can be blank if using for removal
- $html : string
Return values
stringstrip_tags_and_attributes()
Utility function to remove unwanted HTML tags and attributes.
strip_tags_and_attributes(string $html[, array<string|int, mixed> $tags = array() ][, array<string|int, mixed> $attributes = array() ]) : mixed
Note: if $html is a full page, developers should allow html and body tags.
Parameters
- $html : string
-
HTML string
- $tags : array<string|int, mixed> = array()
-
Extra tags to be allowed
- $attributes : array<string|int, mixed> = array()
-
Extra attributes to be allowed
Return values
mixed —Normally a string however if anything but a string is supplied, return type will be as supplied.
strip_paragraph_tags()
Remove paragraph tags from start and end of text.
strip_paragraph_tags(string $text) : string
Inner paragraph tags are untouched
Parameters
- $text : string
-
HTML string
Return values
string —Returns the text without surrounding
and
tags.get_inner_html_from_tag()
Helper function to quickly return the inner HTML of a specific tag element from a DOM document.
get_inner_html_from_tag(string $txt, string $tag) : string
Example usage: get_inner_html_from_tag(strip_tags_and_attributes($unsafe_html), "p");
Parameters
- $txt : string
-
HTML string
- $tag : string
-
DOM document tag element (e.g a, div, p)
Return values
string —Returns the inner HTML of the first tag requested and found. Returns empty string if caller code requested the wrong tag.
show_pagetime()
Returns the page load time until this point.
show_pagetime() : string
Return values
stringget_debug_log_dir()
Determines where the debug log will live. Typically, same as tmp dir (See general.php: get_temp_dir().
get_debug_log_dir() : string
Since general.php may not be included, we cannot use that method so I have created this one too.
Return values
string —- The path to the debug_log directory.
debug()
Output debug information to the debug log, if debugging is enabled.
debug(string $text[, mixed $resource_log_resource_ref = null ][, string $resource_log_code = LOG_CODE_TRANSFORMED ]) : bool
Parameters
- $text : string
- $resource_log_resource_ref : mixed = null
-
Update the resource log if resource reference passed.
- $resource_log_code : string = LOG_CODE_TRANSFORMED
-
If updating the resource log, the code to use
Tags
Return values
boolrcRmdir()
Recursively removes a directory.
rcRmdir(string $path[, array<string|int, mixed> $ignore = array() ]) : bool
Parameters
- $path : string
-
Directory path to remove.
- $ignore : array<string|int, mixed> = array()
-
List of directories to ignore.
Return values
booldaily_stat()
Update the daily statistics after a loggable event.
daily_stat(string $activity_type, int $object_ref[, int $to_add = 1 ]) : void
The daily_stat table contains a counter for each 'activity type' (i.e. download) for each object (i.e. resource) per day.
Parameters
- $activity_type : string
- $object_ref : int
- $to_add : int = 1
-
Optional, how many counts to add, defaults to 1.
pagename()
Returns the current page name minus the extension, e.g. "home" for pages/home.php
pagename() : string
Return values
stringpluginname()
pluginname() : string
Return values
stringtext()
Returns the site content from the language strings. These will already be overridden with site_text content if present.
text(string $name) : string
Parameters
- $name : string
Return values
stringget_section_list()
Gets a list of site text sections, used for a multi-page help area.
get_section_list(mixed $page) : array<string|int, mixed>
Parameters
- $page : mixed
Return values
array<string|int, mixed>resolve_user_agent()
Returns a more friendly user agent string based on the passed user agent. Used in the user area to establish browsers used.
resolve_user_agent(mixed $agent) : string
Parameters
- $agent : mixed
-
The user agent string
Return values
stringget_ip()
Returns the current user's IP address, using HTTP proxy headers if present.
get_ip() : string
Return values
stringResolveKB()
For a value such as 10M return the kilobyte equivalent such as 10240. Used by check.php
ResolveKB(mixed $value) : string
Parameters
- $value : mixed
Return values
stringtrim_filename()
Trim a filename that is longer than 255 characters while keeping its extension (if present)
trim_filename(string $s) : string
Parameters
- $s : string
Return values
stringarray_flip_by_value_key()
Flip array keys to use one of the keys of the values it contains. All elements (ie values) of the array must contain the key (ie. they are arrays). Helper function to greatly increase search performance on huge PHP arrays.
array_flip_by_value_key(array<string|int, mixed> $a, string $k) : array<string|int, mixed>
Normal use is: array_flip_by_value_key($huge_array, 'ref');
IMPORTANT: make sure that for the key you intend to use all elements will have a unique value set.
Example: Result after calling array_flip_by_value_key($nodes, 'ref'); [20382] => Array ( [ref] => 20382 [name] => Example node [parent] => 20381 )
Parameters
- $a : array<string|int, mixed>
- $k : string
-
A values' key to use as an index/key in the main array, ideally an integer
Return values
array<string|int, mixed>reshape_array_by_value_keys()
Reshape array using the keys of its values. All values must contain the selected keys.
reshape_array_by_value_keys(array<string|int, mixed> $a, string $k, string $v) : array<string|int, mixed>
Parameters
- $a : array<string|int, mixed>
-
Array to reshape
- $k : string
-
The current elements' key to be used as the KEY in the new array. MUST be unique otherwise elements will be lost
- $v : string
-
The current elements' key to be used as the VALUE in the new array
Return values
array<string|int, mixed>permission_j()
Permission check for "j[ref]"
permission_j(int $ref) : bool
Parameters
- $ref : int
-
Featured collection category ref
Return values
boolpermission_negative_j()
Permission check for "-j[ref]"
permission_negative_j(int $ref) : bool
Parameters
- $ref : int
-
Featured collection sub-category ref
Return values
boolcleanup_files()
Delete temporary files
cleanup_files(array<string|int, mixed> $files) : void
Parameters
- $files : array<string|int, mixed>
-
array of file paths
is_int_loose()
Validate if value is integer or string integer
is_int_loose(mixed $var) : bool
Parameters
- $var : mixed
-
- variable to check
Return values
bool —true if variable resolves to integer value
is_positive_int_loose()
Helper function to check if value is a positive integer looking type.
is_positive_int_loose(int|float|string $V) : bool
Parameters
- $V : int|float|string
-
Value to be tested
Return values
boolis_positive_or_zero_int_loose()
Helper function to check if value is a positive or zero integer looking type.
is_positive_or_zero_int_loose(int|float|string $V) : bool
Parameters
- $V : int|float|string
-
Value to be tested
Return values
boolis_array_of_pos_or_zero_ints()
Helper function to check if value is an array containing only positive or zero integer looking types
is_array_of_pos_or_zero_ints(mixed $var) : bool
Parameters
- $var : mixed
-
value to be tested
Return values
boolis_string_loose()
Helper function to check if a value is able to be cast to a string
is_string_loose(mixed $var) : bool
Parameters
- $var : mixed
-
value to be tested
Return values
boolis_input_list_loose()
Input (type) validation helper function for a list of integers (mostly used for IDs). This covers cases when the submitted data is either sent as an actual list (i.e. myInput[]) or when retrieved from the cookie/query string as a CSV.
is_input_list_loose(mixed $val) : bool
Parameters
- $val : mixed
-
User input value to be validated
Return values
boolis_float_loose()
Helper function to check if a value is able to be cast to a float
is_float_loose(mixed $var) : bool
Parameters
- $var : mixed
-
value to be tested
Return values
boolip_matches()
Does the provided $ip match the string $ip_restrict? Used for restricting user access by IP address.
ip_matches(string $ip, string $ip_restrict) : bool|int
Parameters
- $ip : string
- $ip_restrict : string
Return values
bool|intset_unique_filename()
Ensures filename is unique in $filenames array and adds resulting filename to the array
set_unique_filename(string &$filename, array<string|int, mixed> &$filenames) : string
Parameters
- $filename : string
-
Requested filename to be added. Passed by reference
- $filenames : array<string|int, mixed>
-
Array of filenames already in use. Passed by reference
Return values
string —New filename
build_permission()
Build a specific permission closure which can be applied to a list of items.
build_permission(string $perm) : Closure
Parameters
- $perm : string
-
Permission string to build (e.g f-, F, T, X, XU)
Return values
Closurevalidate_remote_code()
Attempt to validate remote code.
validate_remote_code(string $code) : bool
IMPORTANT: Never use this function or eval() on any code received externally from a source that can't be trusted!
Parameters
- $code : string
-
Remote code to validate
Return values
boolget_system_status()
Get system status information
get_system_status([bool $basic = false ]) : array<string|int, mixed>
Parameters
- $basic : bool = false
-
Optional, set to true to perform a quick "system up" check only.
Return values
array<string|int, mixed>try_unlink()
Try and delete a file without triggering a fatal error
try_unlink(string $deletefile) : bool|string
Parameters
- $deletefile : string
-
Full path to file
Return values
bool|string —Returns TRUE on success or a string containing error
try_getimagesize()
try_getimagesize(string $filename[, mixed &$image_info = null ]) : mixed
Parameters
- $filename : string
- $image_info : mixed = null
check_filestore_browseability()
Check filestore folder browseability.
check_filestore_browseability() : array<string|int, mixed>
For security reasons (e.g data breach) the filestore location shouldn't be indexed by the web server (in Apache2 - disable autoindex module)
Return values
array<string|int, mixed> —Returns data structure with following keys:-
- status: An end user status of OK/FAIL
- info: Any extra relevant information (aimed at end users)
- filestore_url: ResourceSpace URL to the filestore location
- index_disabled: PHP bool (used by code). FALSE if web server allows indexing/browsing the filestore, TRUE otherwise
check_imagemagick_cli_version_found()
Check CLI version found for ImageMagick is as expected.
check_imagemagick_cli_version_found(string $version_output, array<string|int, mixed> $utility) : array<string|int, mixed>
Parameters
- $version_output : string
-
The version output for ImageMagick
- $utility : array<string|int, mixed>
-
Utility structure. RS_SYSTEM_UTILITIES
Return values
array<string|int, mixed> —Returns array as expected by the check.php page
- utility - New utility value for its display name
- found - PHP bool representing whether we've found what we were expecting in the version output.
check_exiftool_cli_version_found()
Check CLI version found for Exiftool is as expected.
check_exiftool_cli_version_found(string $version_output, array<string|int, mixed> $utility) : array<string|int, mixed>
Parameters
- $version_output : string
-
The version output for ImageMagick
- $utility : array<string|int, mixed>
-
Utility structure. RS_SYSTEM_UTILITIES
Return values
array<string|int, mixed> —Returns array as expected by the check.php page
- utility - New utility value for its display name
- found - PHP bool representing whether we've found what we were expecting in the version output.
- error_message - optional error message if an issue is detected
check_numeric_cli_version_found()
Check CLI numeric version found for a utility is as expected.
check_numeric_cli_version_found(string $version_output, array<string|int, mixed> $utility) : array<string|int, mixed>
Parameters
- $version_output : string
-
The version output
- $utility : array<string|int, mixed>
-
Utility structure. RS_SYSTEM_UTILITIES
Return values
array<string|int, mixed> —Returns array as expected by the check.php page
- utility - not used
- found - PHP bool representing whether we've found what we were expecting in the version output.
check_utility_cli_version_found_by_name()
Check CLI version found for a utility is as expected by looking up for its name.
check_utility_cli_version_found_by_name(string $version_output, array<string|int, mixed> $utility, array<string|int, mixed> $lookup_names) : array<string|int, mixed>
Parameters
- $version_output : string
-
The version output for the utility
- $utility : array<string|int, mixed>
-
Utility structure. RS_SYSTEM_UTILITIES
- $lookup_names : array<string|int, mixed>
Return values
array<string|int, mixed> —Returns array as expected by the check.php page
- utility - not used
- found - PHP bool representing whether we've found what we were expecting in the version output.
command_line_only()
Check we're running on the command line, exit otherwise. Security feature for the scripts in /pages/tools/
command_line_only() : void
prefix_value()
Helper function to quickly build a list of values, all prefixed the same way.
prefix_value(string $prefix) : Closure
$fieldXs = array_map(prefix_value('field'), [3, 88]);
Parameters
- $prefix : string
-
Prefix value to prepend.
Return values
ClosurevalidateDatetime()
Utility function to check string is a valid date/time with a specific format.
validateDatetime(string $datetime[, string $format = 'Y-m-d H:i:s' ]) : bool
Parameters
- $datetime : string
-
Date/time value
- $format : string = 'Y-m-d H:i:s'
-
The format that date/time value should be in. https://www.php.net/manual/en/datetimeimmutable.createfromformat.php
Return values
boolstring_ends_with()
string_ends_with(string $haystack, mixed $needle) : mixed
Parameters
- $haystack : string
-
Value to be checked @param string $needle Substing to seach for in the haystack
@return bool True if the haystack ends with the needle otherwise false
- $needle : mixed
set_order_by_to_zero()
Helper function to set the order_by key of an array to zero.
set_order_by_to_zero(array<string|int, mixed> $item) : array<string|int, mixed>
Parameters
- $item : array<string|int, mixed>
Return values
array<string|int, mixed> —Same item with the order_by key zero.
cast_echo_to_string()
Helper function to cast functions that only echo things out (e.g render functions) to string type.
cast_echo_to_string(callable $fn[, array<string|int, mixed> $args = [] ]) : string
Parameters
- $fn : callable
-
Function to cast
- $args : array<string|int, mixed> = []
-
Provide function's arguments (if applicable)
Return values
stringparse_csv_to_list_of_type()
Helper function to parse input to a list of a particular type.
parse_csv_to_list_of_type(string $csv, callable $type) : array<string|int, mixed>
Parameters
- $csv : string
-
CSV of raw data
- $type : callable
-
Function checking each CSV item, as required by your context, to determine if it should be allowed in the result set
Tags
Return values
array<string|int, mixed>execution_lockout_remove_resource_type_field_props()
Remove metadata field properties during execution lockout
execution_lockout_remove_resource_type_field_props(array<string|int, mixed> $rtf) : array<string|int, mixed>
Parameters
- $rtf : array<string|int, mixed>
-
Resource type field data structure
Return values
array<string|int, mixed> —Returns without the relevant properties if execution lockout is enabled
set_watermark_image()
Update global variable watermark to point to the correct file. Watermark set on System Configuration page will override a watermark set in config.php. config.default.php will apply otherwise (blank) so no watermark will be applied.
set_watermark_image() : void
compute_dpi()
DPI calculations
compute_dpi(mixed $width, mixed $height, mixed &$dpi, mixed &$dpi_unit, mixed &$dpi_w, mixed &$dpi_h) : mixed
Parameters
- $width : mixed
- $height : mixed
- $dpi : mixed
- $dpi_unit : mixed
- $dpi_w : mixed
- $dpi_h : mixed
compute_megapixel()
MP calculation
compute_megapixel(int $width, int $height) : float
Parameters
- $width : int
- $height : int
Return values
floatget_size_info()
Get size info as a paragraphs HTML tag
get_size_info(array<string|int, mixed> $size[, array<string|int, mixed>|null $originalSize = null ]) : string
Parameters
- $size : array<string|int, mixed>
-
Preview size information
- $originalSize : array<string|int, mixed>|null = null
-
Original preview size information
Return values
stringis_jpeg_extension()
Simple function to check if a given extension is associated with a JPG file
is_jpeg_extension(string $extension) : bool
Parameters
- $extension : string
-
File extension
Return values
boolurl_starts_with()
Input validation helper function to check a URL is ours (e.g. if it's our base URL). Mostly used for redirect URLs.
url_starts_with(string $base, mixed $val) : bool
Parameters
- $base : string
-
The value the URL is expected to start with. Due to the structure of a URL, you can also check for (partial) paths.
- $val : mixed
-
URL to check
Return values
boolis_safe_url()
Input validation helper function to check if a URL is safe (from XSS) in an HTML context.
is_safe_url(mixed $url) : bool
Parameters
- $url : mixed
Tags
Return values
boolsanitise_url()
Sanitise URL for HTML rendering purposes.
sanitise_url(string $val) : string
ResourceSpace only works with absolute (via $baseurl) and relative root (via $baseurl_short) URLs.
Parameters
- $val : string
-
Untrusted URL
Tags
Return values
string —Returns the provided value (URL) if considered safe, "#" otherwise.
validate_sort_value()
Input validation helper function for sorting (ASC/DESC).
validate_sort_value(mixed $val) : bool
Parameters
- $val : mixed
-
User input value to be validated
Return values
boolvalidate_digit_csv()
Input validation helper function for a CSV of integers (mostly used for IDs).
validate_digit_csv(mixed $val) : bool
Parameters
- $val : mixed
-
User input value to be validated
Return values
boolget_sub_array_with()
Helper function to get an array of values with a subset of their original keys.
get_sub_array_with(array<string|int, mixed> $keys) : callable
Parameters
- $keys : array<string|int, mixed>
Return values
callableenforceSharePassword()
Server side check to backup front end javascript validation.
enforceSharePassword(string $password) : void
Parameters
- $password : string
-
Password supplied when creating or editing external share.
js_call_CentralSpaceLoad()
Helper function to call the JS CentralSpaceLoad().
js_call_CentralSpaceLoad(string $url) : never
Parameters
- $url : string
Return values
nevergetCertificateExpiry()
Get expiration date of a given PEM certificate
getCertificateExpiry(string $cert) : string|bool
Parameters
- $cert : string
-
Certificate text
Return values
string|bool —Expiry date. False if unable to parse certificate
isValidCssColor()
Is the provided colour a valid CSS colour and therefore safe to display?
isValidCssColor(string $colour) : bool
Parameters
- $colour : string
Return values
bool —True if a valid colour, false if not
hslToRgb()
Convert HSL to RGB.
hslToRgb(float $h, float $s, float $l) : array<string|int, mixed>
Parameters
- $h : float
-
Hue (0-360).
- $s : float
-
Saturation (0-1).
- $l : float
-
Lightness (0-1).
Return values
array<string|int, mixed> —Array with RGB values (0-255).
check_tinymce_plugins()
Check TinyMCE plugin list against an array of valid options The passed list is checked against TINYMCE_VALID_PLUGINS.
check_tinymce_plugins([string $plugins = "" ]) : string
The autoresize plugin is also included by default.
Parameters
- $plugins : string = ""
-
A comma-separated list of plugins for TinyMCE
Return values
string —The list of plugins with any invalid options removed
check_tinymce_toolbar()
Check TinyMCE toolbar configuration to ensure it contains only alphanumeric characters, spaces and the pipe (|) symbol.
check_tinymce_toolbar([string $toolbar = "" ]) : string
Parameters
- $toolbar : string = ""
-
The requested configuration for the toolbar
Return values
string —The configured toolbar with any invalid characters removed
get_non_ingested_resources()
Return the number of resources in the system that are not ingested into the filestore i.e. with 'file_path' set
get_non_ingested_resources() : int
Return values
int —Number of non-ingested resources in the system
get_favicon_url()
Return URL of the application favicon
get_favicon_url() : string
Return values
string —Favicon URL
is_original_preview()
Determine what is a manually uploaded preview based off of data in the resource log
is_original_preview(int $ref) : bool
@param int $ref resource ID
Parameters
- $ref : int
Return values
bool —returns true if a resource is using its original preview otherwise false.
get_page_title()
Return the page title to use for the given page and optionally plugin.
get_page_title(string $page[, string $plugin = "" ]) : string
Parameters
- $page : string
-
Page name without any leading filepath or trailing file extension.
- $plugin : string = ""
-
Optional. Used to denote which plugin the page is part of.
Return values
string —If a language string is found, returns "%%APPLICATION_NAME%% - %%PAGENAME%%"; otherwise, returns "%%APPLICATION_NAME%%".
log_bandwidth()
Log the bandwidth used by download.php
log_bandwidth(int $bandwidth_usage) : void
Parameters
- $bandwidth_usage : int
strip_unicode_points()
Strip Unicode points from a text value.
strip_unicode_points(string $value[, array<int, string> $blocklist = [] ]) : string
Parameters
- $value : string
-
Text value subject
- $blocklist : array<int, string> = []
-
List of unicode points (e.g. \x{FEFF}), ranges allowed too (e.g. \x{200B}-\x{200D})
Return values
stringallow_unicode_characters()
Strip any characters not present in the allow list. Mostly useful for search/indexing purposes where we care more about the words themselves and less about linking or any other type of characters.
allow_unicode_characters(string $text[, array<int, string> $allowlist = [] ]) : string
Parameters
- $text : string
-
Initial text value
- $allowlist : array<int, string> = []
-
List of allowed characters. IMPORTANT: it's used to create a regex pattern.
Return values
stringset_per_page_cookie()
Add or update the value used for paging for the current page to the list of stored pager cookies
set_per_page_cookie(int $per_page) : void
Parameters
- $per_page : int
-
value to be stored
get_per_page_cookie()
Retrieve the pager cookie for the current page.
get_per_page_cookie() : int
This function also clears the per_page and per_page_list cookies
Return values
intparse_int_ranges()
Parse a comma-separated list of integers and integer ranges into a sorted array.
parse_int_ranges(string $input[, int $max_val = 0 ][, bool $optional = false ][, bool $allow_wildcard = false ]) : array<string|int, mixed>
Accepts input such as:
- "*"
- "1,2,5"
- "1-3,7,10-12"
- "1-3,10-*"
Parameters
- $input : string
-
Comma-separated list of integers and/or ranges (e.g. "1,3-5,10")
- $max_val : int = 0
-
Optional upper bound for allowed values. Use 0 for no limit
- $optional : bool = false
-
If true, an empty input string is allowed. If false, empty input is an error
- $allow_wildcard : bool = false
-
If true, an asterisk can be used as a wildcard (e.g * for all, 10-* for 10 and above)
Return values
array<string|int, mixed> —ok: bool True when parsing succeeds, false when any validation error occurs numbers: int[] Sorted list of unique integers when ok is true and allow_wildcard is false, otherwise empty errors: string[] List of error messages when ok is false, otherwise empty
build_range_where_condition()
Build a SQL WHERE fragment and bound parameters from a list of integers and ranges.
build_range_where_condition(string $input, string $field[, int $max_val = 0 ][, bool $allow_wildcard = false ]) : array<string|int, mixed>
Parses a comma-separated input string containing single integers and/or ranges and can take optional wildcards (e.g. "1,3-5,10,12-*") Converts each item into a parameterized SQL condition:
- Single value: "
= ?" - Range: "
BETWEEN ? AND ?" - Sole wildcard: No filter, so 1=1 is used
- Range wildcard: "
>= ?"
All generated conditions are joined using OR and wrapped in parentheses. Parameters are returned in the order they appear in the WHERE fragment.
Parameters
- $input : string
-
Comma-separated list of integers and/or ranges (e.g. "1,3-5,10")
- $field : string
-
Database column name to use in the generated SQL expressions
- $max_val : int = 0
-
Optional upper bound for allowed values. Use 0 for no limit
- $allow_wildcard : bool = false
-
If true, an asterisk can be used as a wildcard (e.g * for all, 10-* for 10 and above)
Return values
array<string|int, mixed> —ok: bool True when the WHERE clause is successfully built, false on validation errors where: string|null Parenthesized SQL fragment joined with OR when ok is true, otherwise null params: array Ordered list of bind types and values errors: string[] List of error messages when ok is false, otherwise empty