sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function escRefsDeep($value, $times = 1, $___recursion = false) { if (is_array($value) || is_object($value)) { foreach ($value as &$_value) { $_value = $this->escRefsDeep($_value, $times, true); } // unset($_value); // Housekeeping. return $value; } $value = (string) $value; $times = abs((int) $times); return str_replace(['\\', '$'], [str_repeat('\\', $times).'\\', str_repeat('\\', $times).'$'], $value); }
Escapes regex backreference chars deeply (i.e. `\\$` and `\\\\`). @since 140417 Initial release. @note This is a recursive scan running deeply into multiple dimensions of arrays/objects. @note This routine will usually NOT include private, protected or static properties of an object class. However, private/protected properties *will* be included, if the current scope allows access to these private/protected properties. Static properties are NEVER considered by this routine, because static properties are NOT iterated by `foreach()`. @param mixed $value Any value can be converted into an escaped string. Actually, objects can't, but this recurses into objects. @param int $times Number of escapes. Defaults to `1`. @param bool $___recursion Internal use only. @return string|array|object Escaped string, array, object.
entailment
protected function cacheDir($type, $checksum = '', $base_only = false) { if ($type !== $this::DIR_PUBLIC_TYPE) { if ($type !== $this::DIR_PRIVATE_TYPE) { throw new \Exception('Invalid type.'); } } $checksum = (string) $checksum; if (isset($checksum[4])) { $checksum = substr($checksum, 0, 5); } else { $checksum = ''; // Invalid or empty. } $cache_key = $type.$checksum.(int) $base_only; if (isset($this->cache[__FUNCTION__.'_'.$cache_key])) { return $this->cache[__FUNCTION__.'_'.$cache_key]; } if (!empty($this->options['cache_dir_'.$type])) { $basedir = $this->nDirSeps($this->options['cache_dir_'.$type]); } elseif (defined('WP_CONTENT_DIR')) { $basedir = $this->nDirSeps(WP_CONTENT_DIR.'/htmlc/cache/'.$type); } elseif (!empty($_SERVER['DOCUMENT_ROOT'])) { $basedir = $this->nDirSeps($_SERVER['DOCUMENT_ROOT'].'/htmlc/cache/'.$type); } else { throw new \Exception(sprintf('Unable to find a good location for the cache directory. Please set option: `%1$s`.', __FUNCTION__.'_'.$type)); } if ($base_only) { $dir = $basedir; // Caller wants only the base directory. } else { $dir = $basedir; // Start with the base directory. $dir .= '/'.trim(preg_replace('/[^a-z0-9]/ui', '-', $this->currentUrlHost()), '-'); $dir .= $checksum ? '/'.implode('/', str_split($checksum)) : ''; } if (!is_dir($dir) && mkdir($dir, 0755, true)) { if ($type === $this::DIR_PUBLIC_TYPE && !is_file($basedir.'/.htaccess')) { if (!file_put_contents($basedir.'/.htaccess', $this->dir_htaccess_allow)) { throw new \Exception(sprintf('Unable to create `.htaccess` file in public cache directory: `%1$s`.', $basedir)); } } if ($type === $this::DIR_PRIVATE_TYPE && !is_file($basedir.'/.htaccess')) { if (!file_put_contents($basedir.'/.htaccess', $this->dir_htaccess_deny)) { throw new \Exception(sprintf('Unable to create `.htaccess` file in private cache directory: `%1$s`.', $basedir)); } } } if (!is_readable($dir) || !is_writable($dir)) { throw new \Exception(sprintf('Cache directory not readable/writable: `%1$s`. Failed on `%2$s`.', $basedir, $dir)); } return $this->cache[__FUNCTION__.'_'.$cache_key] = $dir; }
Get (and possibly create) the cache dir. @since 140417 Initial release. @param string $type One of `$this::dir_public_type` or `$this::dir_private_type`. @param string $checksum Optional. If supplied, we'll build a nested sub-directory based on the checksum. @param bool $base_only Defaults to a FALSE value. If TRUE, return only the base directory. i.e. Do NOT suffix the directory in any way. No host and no checksum. @throws \Exception If unable to create the cache dir. @throws \Exception If cache directory is not readable/writable. @return string Server path to cache dir.
entailment
protected function cacheDirUrl($type, $checksum = '', $base_only = false) { if ($type !== $this::DIR_PUBLIC_TYPE) { if ($type !== $this::DIR_PRIVATE_TYPE) { throw new \Exception('Invalid type.'); } } $checksum = (string) $checksum; if (isset($checksum[4])) { $checksum = substr($checksum, 0, 5); } else { $checksum = ''; // Invalid or empty. } $cache_key = $type.$checksum.(int) $base_only; if (isset($this->cache[__FUNCTION__.'_'.$cache_key])) { return $this->cache[__FUNCTION__.'_'.$cache_key]; } $basedir = $this->cacheDir($type, '', true); if (!empty($this->options['cache_dir_url_'.$type])) { $baseurl = $this->setUrlScheme(rtrim($this->options['cache_dir_url_'.$type], '/')); } elseif (defined('WP_CONTENT_DIR') && defined('WP_CONTENT_URL') && $basedir === $this->nDirSeps(WP_CONTENT_DIR.'/htmlc/cache/'.$type)) { $baseurl = $this->setUrlScheme(rtrim(WP_CONTENT_URL, '/').'/htmlc/cache/'.$type); } elseif (!empty($_SERVER['DOCUMENT_ROOT']) && mb_strpos($basedir, $_SERVER['DOCUMENT_ROOT']) === 0) { $baseurl = $this->currentUrlScheme().'://'.$this->currentUrlHost(); $baseurl .= str_replace(rtrim($_SERVER['DOCUMENT_ROOT'], '/'), '', $basedir); } else { throw new \Exception(sprintf('Unable to determine URL to cache directory. Please set option: `%1$s`.', __FUNCTION__.'_'.$type)); } if ($base_only) { $url = $baseurl; // Caller wants only the base directory. } else { $url = $baseurl; // Start with the base URL. $url .= '/'.trim(preg_replace('/[^a-z0-9]/ui', '-', $this->currentUrlHost()), '-'); $url .= $checksum ? '/'.implode('/', str_split($checksum)) : ''; } return $this->cache[__FUNCTION__.'_'.$cache_key] = $url; }
Get (and possibly create) the cache dir URL. @since 140417 Initial release. @param string $type One of `$this::public_type` or `$this::private_type`. @param string $checksum Optional. If supplied, we'll build a nested sub-directory based on the checksum. @param bool $base_only Defaults to a FALSE value. If TRUE, return only the base directory. i.e. Do NOT suffix the directory in any way. No host and no checksum. @throws \Exception If unable to create the cache dir. @throws \Exception If cache directory is not readable/writable. @throws \Exception If unable to determine the URL for any reason. @return string URL to server-side cache directory.
entailment
protected function cleanupCacheDirs() { if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) { $time = microtime(true); } $public_cache_dir = $this->cacheDir($this::DIR_PUBLIC_TYPE); $private_cache_dir = $this->cacheDir($this::DIR_PRIVATE_TYPE); $min_mtime = strtotime('-'.$this->cache_expiration_time); /** @type $_dir_file \RecursiveDirectoryIterator For IDEs. */ foreach ($this->dirRegexIteration($public_cache_dir, '/\/compressor\-part\..*$/') as $_dir_file) { if (($_dir_file->isFile() || $_dir_file->isLink()) && $_dir_file->getMTime() < $min_mtime - 3600) { if ($_dir_file->isWritable()) { unlink($_dir_file->getPathname()); } } } /** @type $_dir_file \RecursiveDirectoryIterator For IDEs. */ foreach ($this->dirRegexIteration($private_cache_dir, '/\/compressor\-parts\..*$/') as $_dir_file) { if (($_dir_file->isFile() || $_dir_file->isLink()) && $_dir_file->getMTime() < $min_mtime) { if ($_dir_file->isWritable()) { unlink($_dir_file->getPathname()); } } } // unset($_dir_file); // Housekeeping. if ($benchmark && !empty($time)) { $this->benchmark->addTime( __FUNCTION__, $time, // Caller, start time, task performed. 'cleaning up the public/private cache directories' ); } }
Cache cleanup routine. @since 140417 Initial release. @note This routine is always host-specific. i.e. We cleanup cache files for the current host only.
entailment
protected function dirRegexIteration($dir, $regex) { $dir = (string) $dir; $regex = (string) $regex; $dir_iterator = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_SELF | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS); $iterator_iterator = new \RecursiveIteratorIterator($dir_iterator, \RecursiveIteratorIterator::CHILD_FIRST); $regex_iterator = new \RegexIterator($iterator_iterator, $regex, \RegexIterator::MATCH, \RegexIterator::USE_KEY); return $regex_iterator; }
Regex directory iterator. @since 140417 Initial release. @param string $dir Path to a directory. @param string $regex Regular expression. @return \RegexIterator
entailment
protected function nDirSeps($dir_file, $allow_trailing_slash = false) { if (($dir_file = (string) $dir_file) === '') { return $dir_file; // Nothing to do. } if (mb_strpos($dir_file, '://' !== false)) { if (preg_match('/^(?P<stream_wrapper>[a-z0-9]+)\:\/\//ui', $dir_file, $stream_wrapper)) { $dir_file = preg_replace('/^(?P<stream_wrapper>[a-z0-9]+)\:\/\//ui', '', $dir_file); } if (mb_strpos($dir_file, ':' !== false)) { if (preg_match('/^(?P<drive_letter>[a-z])\:[\/\\\\]/ui', $dir_file)) { $dir_file = preg_replace_callback('/^(?P<drive_letter>[a-z])\:[\/\\\\]/ui', create_function('$m', 'return mb_strtoupper($m[0]);'), $dir_file); } $dir_file = preg_replace('/\/+/u', '/', str_replace([DIRECTORY_SEPARATOR, '\\', '/'], '/', $dir_file)); } $dir_file = ($allow_trailing_slash) ? $dir_file : rtrim($dir_file, '/'); // Strip trailing slashes. } if (!empty($stream_wrapper[0])) { $dir_file = mb_strtolower($stream_wrapper[0]).$dir_file; } return $dir_file; // Normalized now. }
Normalizes directory/file separators. @since 140417 Initial release. @param string $dir_file Directory/file path. @param bool $allow_trailing_slash Defaults to FALSE. If TRUE; and `$dir_file` contains a trailing slash; we'll leave it there. @return string Normalized directory/file path.
entailment
protected function currentUrlSsl() { if (isset(static::$static[__FUNCTION__])) { return static::$static[__FUNCTION__]; } if (!empty($_SERVER['SERVER_PORT'])) { if ((int) $_SERVER['SERVER_PORT'] === 443) { return static::$static[__FUNCTION__] = true; } } if (!empty($_SERVER['HTTPS'])) { if (filter_var($_SERVER['HTTPS'], FILTER_VALIDATE_BOOLEAN)) { return static::$static[__FUNCTION__] = true; } } if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) { if (strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0) { return static::$static[__FUNCTION__] = true; } } return static::$static[__FUNCTION__] = false; }
Is the current request over SSL? @since 140417 Initial release. @return bool TRUE if over SSL; else FALSE.
entailment
protected function currentUrlScheme() { if (isset(static::$static[__FUNCTION__])) { return static::$static[__FUNCTION__]; } if (!empty($this->options['current_url_scheme'])) { return static::$static[__FUNCTION__] = $this->nUrlScheme($this->options['current_url_scheme']); }/* See https://github.com/websharks/html-compressor/issues/73 if (!empty($_SERVER['REQUEST_SCHEME'])) { return (static::$static[__FUNCTION__] = $this->nUrlScheme($_SERVER['REQUEST_SCHEME'])); }*/ return static::$static[__FUNCTION__] = ($this->currentUrlSsl()) ? 'https' : 'http'; }
Gets the current scheme (via environment variables). @since 140417 Initial release. @throws \Exception If unable to determine the current scheme. @return string The current scheme, else an exception is thrown on failure.
entailment
protected function currentUrlHost() { if (isset(static::$static[__FUNCTION__])) { return static::$static[__FUNCTION__]; } if (!empty($this->options['current_url_host'])) { return static::$static[__FUNCTION__] = $this->nUrlHost($this->options['current_url_host']); } if (empty($_SERVER['HTTP_HOST'])) { throw new \Exception('Missing required `$_SERVER[\'HTTP_HOST\']`.'); } return static::$static[__FUNCTION__] = $this->nUrlHost($_SERVER['HTTP_HOST']); }
Gets the current host name (via environment variables). @since 140417 Initial release. @throws \Exception If `$_SERVER['HTTP_HOST']` is empty. @return string The current host name, else an exception is thrown on failure.
entailment
protected function currentUrlUri() { if (isset(static::$static[__FUNCTION__])) { return static::$static[__FUNCTION__]; } if (!empty($this->options['current_url_uri'])) { return static::$static[__FUNCTION__] = $this->mustParseUri($this->options['current_url_uri']); } if (empty($_SERVER['REQUEST_URI'])) { throw new \Exception('Missing required `$_SERVER[\'REQUEST_URI\']`.'); } return static::$static[__FUNCTION__] = $this->mustParseUri($_SERVER['REQUEST_URI']); }
Gets the current URI (via environment variables). @since 140417 Initial release. @throws \Exception If unable to determine the current URI. @return string The current URI, else an exception is thrown on failure.
entailment
protected function isCurrentUrlUriExcluded() { if ($this->regex_uri_exclusions && preg_match($this->regex_uri_exclusions, $this->currentUrlUri())) { return true; } elseif ($this->built_in_regex_uri_exclusions && preg_match($this->built_in_regex_uri_exclusions, $this->currentUrlUri())) { return true; } return false; }
Current URI is excluded? @since 160117 Adding support for URI exclusions. @return bool Returns `TRUE` if current URI matches an exclusion rule.
entailment
protected function currentUrl() { if (isset(static::$static[__FUNCTION__])) { return static::$static[__FUNCTION__]; } $url = $this->currentUrlScheme().'://'; $url .= $this->currentUrlHost(); $url .= $this->currentUrlUri(); return static::$static[__FUNCTION__] = $url; }
URL to current request. @since 140417 Initial release. @return string The current URL.
entailment
protected function nUrlScheme($scheme) { if (!($scheme = (string) $scheme)) { return $scheme; // Nothing to do. } if (mb_strpos($scheme, ':') !== false) { $scheme = strstr($scheme, ':', true); } return mb_strtolower($scheme); }
Normalizes a URL scheme. @since 140417 Initial release. @param string $scheme An input URL scheme. @return string A normalized URL scheme (always lowercase).
entailment
protected function nUrlAmps($url_uri_query_fragment) { if (!($url_uri_query_fragment = (string) $url_uri_query_fragment)) { return $url_uri_query_fragment; // Nothing to do. } if (mb_strpos($url_uri_query_fragment, '&') === false) { return $url_uri_query_fragment; // Nothing to do. } return preg_replace('/&amp;|&#0*38;|&#[xX]0*26;/u', '&', $url_uri_query_fragment); }
Converts all ampersand entities in a URL (or a URI/query/fragment only); to just `&`. @since 140417 Initial release. @param string $url_uri_query_fragment A full URL; or a partial URI; or only a query string, or only a fragment. Any of these can be normalized here. @return string Input URL (or a URI/query/fragment only); after having been normalized by this routine.
entailment
protected function nUrlPathSeps($url_uri_query_fragment, $allow_trailing_slash = false) { if (($url_uri_query_fragment = (string) $url_uri_query_fragment) === '') { return $url_uri_query_fragment; // Nothing to do. } if (!($parts = $this->parseUrl($url_uri_query_fragment, null, 0))) { $parts['path'] = $url_uri_query_fragment; } if ($parts['path'] !== '') { // Normalize directory separators. $parts['path'] = $this->nDirSeps($parts['path'], $allow_trailing_slash); } return $this->unparseUrl($parts, 0); // Back together again. }
Normalizes a URL path from a URL (or a URI/query/fragment only). @since 140417 Initial release. @param string $url_uri_query_fragment A full URL; or a partial URI; or only a query string, or only a fragment. Any of these can be normalized here. @param bool $allow_trailing_slash Defaults to a FALSE value. If TRUE, and `$url_uri_query_fragment` contains a trailing slash; we'll leave it there. @return string Normalized URL (or a URI/query/fragment only).
entailment
protected function setUrlScheme($url, $scheme = '') { if (!($url = (string) $url)) { return $url; // Nothing to do. } $scheme = (string) $scheme; if (!$scheme) { $scheme = $this->currentUrlScheme(); } if ($scheme !== '//') { $scheme = $this->nUrlScheme($scheme).'://'; } return preg_replace('/^(?:[a-z0-9]+\:)?\/\//ui', $this->escRefs($scheme), $url); }
Sets a particular scheme. @since 140417 Initial release. @param string $url A full URL. @param string $scheme Optional. The scheme to use (i.e. `//`, `https`, `http`). Use `//` to use a cross-protocol compatible scheme. Defaults to the current scheme. @return string The full URL w/ `$scheme`.
entailment
protected function isUrlExternal($url_uri_query_fragment) { if (mb_strpos($url_uri_query_fragment, '//') === false) { return false; // Relative. } return mb_stripos($url_uri_query_fragment, '//'.$this->currentUrlHost()) === false; }
Checks if a given URL is local or external to the current host. @since 140417 Initial release. @note Care should be taken when calling upon this method. We need to be 100% sure we are NOT calling this against a nested remote/relative URL, URI, query or fragment. This method assumes the URL being analyzed is from the HTML source code. @param string $url_uri_query_fragment A full URL; or a partial URI; or only a query string, or only a fragment. Any of these can be checked here. @return bool TRUE if external; else FALSE.
entailment
protected function parseUrl($url_uri_query_fragment, $component = null, $normalize = null) { $url_uri_query_fragment = (string) $url_uri_query_fragment; if (!isset($normalize)) { $normalize = $this::URL_SCHEME | $this::URL_HOST | $this::URL_PATH; } if (mb_strpos($url_uri_query_fragment, '//') === 0) { $url_uri_query_fragment = $this->currentUrlScheme().':'.$url_uri_query_fragment; // So URL is parsed properly. // Works around a bug in `parse_url()` prior to PHP v5.4.7. See: <http://php.net/manual/en/function.parse-url.php>. $x_protocol_scheme = true; // Flag this, so we can remove scheme below. } else { $x_protocol_scheme = false; // No scheme; or scheme is NOT cross-protocol compatible. } $parsed = @parse_url($url_uri_query_fragment, !isset($component) ? -1 : $component); if ($x_protocol_scheme) { if (!isset($component) && is_array($parsed)) { $parsed['scheme'] = ''; // No scheme. } elseif ($component === PHP_URL_SCHEME) { $parsed = ''; // No scheme. } } if ($normalize & $this::URL_SCHEME) { if (!isset($component) && is_array($parsed)) { if (!isset($parsed['scheme'])) { $parsed['scheme'] = ''; // No scheme. } $parsed['scheme'] = $this->nUrlScheme($parsed['scheme']); } elseif ($component === PHP_URL_SCHEME) { if (!is_string($parsed)) { $parsed = ''; // No scheme. } $parsed = $this->nUrlScheme($parsed); } } if ($normalize & $this::URL_HOST) { if (!isset($component) && is_array($parsed)) { if (!isset($parsed['host'])) { $parsed['host'] = ''; // No host. } $parsed['host'] = $this->nUrlHost($parsed['host']); } elseif ($component === PHP_URL_HOST) { if (!is_string($parsed)) { $parsed = ''; // No scheme. } $parsed = $this->nUrlHost($parsed); } } if ($normalize & $this::URL_PATH) { if (!isset($component) && is_array($parsed)) { if (!isset($parsed['path'])) { $parsed['path'] = '/'; // Home directory. } $parsed['path'] = $this->nUrlPathSeps($parsed['path'], true); if (mb_strpos($parsed['path'], '/') !== 0) { $parsed['path'] = '/'.$parsed['path']; } } elseif ($component === PHP_URL_PATH) { if (!is_string($parsed)) { $parsed = '/'; // Home directory. } $parsed = $this->nUrlPathSeps($parsed, true); if (mb_strpos($parsed, '/') !== 0) { $parsed = '/'.$parsed; } } } if (in_array(gettype($parsed), ['array', 'string', 'integer'], true)) { if (is_array($parsed)) { $defaults = [ 'fragment' => '', 'host' => '', 'pass' => '', 'path' => '', 'port' => 0, 'query' => '', 'scheme' => '', 'user' => '', ]; $parsed = array_merge($defaults, $parsed); $parsed['port'] = (int) $parsed['port']; ksort($parsed); // Sort by key. } return $parsed; // A `string|integer|array`. } return; // Default return value. }
Parses a URL (or a URI/query/fragment only) into an array. @since 140417 Initial release. @param string $url_uri_query_fragment A full URL; or a partial URI; or only a query string, or only a fragment. Any of these can be parsed here. @note A query string or fragment MUST be prefixed with the appropriate delimiters. This is bad `name=value` (interpreted as path). This is good `?name=value` (query string). This is bad `anchor` (interpreted as path). This is good `#fragment` (fragment). @param null|int $component Same as PHP's `parse_url()` component. Defaults to NULL; which defaults to an internal value of `-1` before we pass to PHP's `parse_url()`. @param null|int $normalize A bitmask. Defaults to NULL (indicating a default bitmask). Defaults include: {@link self::url_scheme}, {@link self::url_host}, {@link self::url_path}. However, we DO allow a trailing slash (even if path is being normalized by this parameter). @return array|string|int|null If a component is requested, returns a string component (or an integer in the case of `PHP_URL_PORT`). If a specific component is NOT requested, this returns a full array, of all component values. Else, this returns NULL on any type of failure (even if a component was requested). @note Arrays returned by this method, will include a value for each component (a bit different from PHP's `parse_url()` function). We start with an array of defaults (i.e. all empty strings, and `0` for the port number). Components found in the URL are then merged into these default values. The array is also sorted by key (e.g. alphabetized).
entailment
protected function unparseUrl(array $parsed, $normalize = null) { $unparsed = ''; // Initialize string value. if (!isset($normalize)) { $normalize = $this::URL_SCHEME | $this::URL_HOST | $this::URL_PATH; } if ($normalize & $this::URL_SCHEME) { if (!isset($parsed['scheme'])) { $parsed['scheme'] = ''; // No scheme. } $parsed['scheme'] = $this->nUrlScheme($parsed['scheme']); } if (!empty($parsed['scheme'])) { $unparsed .= $parsed['scheme'].'://'; } elseif (isset($parsed['scheme']) && !empty($parsed['host'])) { $unparsed .= '//'; // Cross-protocol compatible. } if (!empty($parsed['user'])) { $unparsed .= $parsed['user']; if (!empty($parsed['pass'])) { $unparsed .= ':'.$parsed['pass']; } $unparsed .= '@'; } if ($normalize & $this::URL_HOST) { if (!isset($parsed['host'])) { $parsed['host'] = ''; // No host. } $parsed['host'] = $this->nUrlHost($parsed['host']); } if (!empty($parsed['host'])) { $unparsed .= $parsed['host']; } if (!empty($parsed['port'])) { $unparsed .= ':'.$parsed['port']; } // A `0` value is excluded here. if ($normalize & $this::URL_PATH) { if (!isset($parsed['path'])) { $parsed['path'] = '/'; // Home directory. } $parsed['path'] = $this->nUrlPathSeps($parsed['path'], true); if (mb_strpos($parsed['path'], '/') !== 0) { $parsed['path'] = '/'.$parsed['path']; } } if (isset($parsed['path'])) { $unparsed .= $parsed['path']; } if (!empty($parsed['query'])) { $unparsed .= '?'.$parsed['query']; } if (!empty($parsed['fragment'])) { $unparsed .= '#'.$parsed['fragment']; } return $unparsed; }
Unparses a URL (putting it all back together again). @since 140417 Initial release. @param array $parsed An array with at least one URL component. @param null|int $normalize A bitmask. Defaults to NULL (indicating a default bitmask). Defaults include: {@link self::url_scheme}, {@link self::url_host}, {@link self::url_path}. However, we DO allow a trailing slash (even if path is being normalized by this parameter). @return string A full or partial URL, based on components provided in the `$parsed` array. It IS possible to receive an empty string, when/if `$parsed` does NOT contain any portion of a URL.
entailment
protected function mustUnparseUrl() // Arguments are NOT listed here. { if (($unparsed = call_user_func_array([$this, 'unparseUrl'], func_get_args())) === '') { throw new \Exception(sprintf('Unable to unparse: `%1$s`.', print_r(func_get_arg(0), true))); } return $unparsed; }
Unparses a URL (putting it all back together again). @since 140417 Initial release. @throws \Exception If unable to unparse. @return string @see unparseUrl() unparseUrl()
entailment
protected function parseUriParts($url_uri_query_fragment, $normalize = null) { if (($parts = $this->parseUrl($url_uri_query_fragment, null, $normalize))) { return ['path' => $parts['path'], 'query' => $parts['query'], 'fragment' => $parts['fragment']]; } return; // Default return value. }
Parses URI parts from a URL (or a URI/query/fragment only). @since 140417 Initial release. @param string $url_uri_query_fragment A full URL; or a partial URI; or only a query string, or only a fragment. Any of these can be parsed here. @param null|int $normalize A bitmask. Defaults to NULL (indicating a default bitmask). Defaults include: {@link self::url_scheme}, {@link self::url_host}, {@link self::url_path}. However, we DO allow a trailing slash (even if path is being normalized by this parameter). @return array|null An array with the following components, else NULL on any type of failure. • `path`(string) Possible URI path. • `query`(string) A possible query string. • `fragment`(string) A possible fragment.
entailment
protected function mustParseUriParts() // Arguments are NOT listed here. { if (is_null($parts = call_user_func_array([$this, 'parseUriParts'], func_get_args()))) { throw new \Exception(sprintf('Unable to parse: `%1$s`.', (string) func_get_arg(0))); } return $parts; }
Parses URI parts from a URL (or a URI/query/fragment only). @since 140417 Initial release. @throws \Exception If unable to parse. @return array|null @see parseUriParts() parseUriParts()
entailment
protected function parseUri($url_uri_query_fragment, $normalize = null, $include_fragment = true) { if (($parts = $this->parseUriParts($url_uri_query_fragment, $normalize))) { if (!$include_fragment) { unset($parts['fragment']); } return $this->unparseUrl($parts, $normalize); } return; // Default return value. }
Parses a URI from a URL (or a URI/query/fragment only). @since 140417 Initial release. @param string $url_uri_query_fragment A full URL; or a partial URI; or only a query string, or only a fragment. Any of these can be parsed here. @param null|int $normalize A bitmask. Defaults to NULL (indicating a default bitmask). Defaults include: {@link self::url_scheme}, {@link self::url_host}, {@link self::url_path}. However, we DO allow a trailing slash (even if path is being normalized by this parameter). @param bool $include_fragment Defaults to TRUE. Include a possible fragment? @return string|null A URI (i.e. a URL path), else NULL on any type of failure.
entailment
protected function mustParseUri() // Arguments are NOT listed here. { if (is_null($parsed = call_user_func_array([$this, 'parseUri'], func_get_args()))) { throw new \Exception(sprintf('Unable to parse: `%1$s`.', (string) func_get_arg(0))); } return $parsed; }
Parses a URI from a URL (or a URI/query/fragment only). @since 140417 Initial release. @throws \Exception If unable to parse. @return string|null @see parseUri() parseUri()
entailment
protected function resolveRelativeUrl($relative_url_uri_query_fragment, $base_url = '') { $relative_url_uri_query_fragment = (string) $relative_url_uri_query_fragment; $base_url = (string) $base_url; if (!$base_url) { $base_url = $this->currentUrl(); } // Auto-detects current URL/location. $relative_parts = $this->mustParseUrl($relative_url_uri_query_fragment, null, 0); $relative_parts['path'] = $this->nUrlPathSeps($relative_parts['path'], true); $base_parts = $parts = $this->mustParseUrl($base_url); if ($relative_parts['host']) { if (!$relative_parts['scheme']) { $relative_parts['scheme'] = $base_parts['scheme']; } return $this->mustUnparseUrl($relative_parts); } if (!$base_parts['host']) { throw new \Exception(sprintf('Unable to parse (missing base host name): `%1$s`.', $base_url)); } if (isset($relative_parts['path'][0])) { if (mb_strpos($relative_parts['path'], '/') === 0) { $parts['path'] = ''; // Reduce to nothing if relative is absolute. } else { $parts['path'] = preg_replace('/\/[^\/]*$/u', '', $parts['path']).'/'; // Reduce to nearest `/`. } // Replace `/./` and `/foo/../` with `/` (resolve relatives). for ($_i = 1, $parts['path'] = $parts['path'].$relative_parts['path']; $_i > 0;) { $parts['path'] = preg_replace(['/\/\.\//u', '/\/(?!\.\.)[^\/]+\/\.\.\//u'], '/', $parts['path'], -1, $_i); } // unset($_i); // Just a little housekeeping. // We can ditch any unresolvable `../` patterns now. // For instance, if there were too many `../../../../../` back references. $parts['path'] = str_replace('../', '', $parts['path']); $parts['query'] = $relative_parts['query']; // Use relative query. } elseif (isset($relative_parts['query'][0])) { $parts['query'] = $relative_parts['query']; } // Relative query string supersedes base. $parts['fragment'] = $relative_parts['fragment']; // Always changes. return $this->mustUnparseUrl($parts); // Resolved now. }
Resolves a relative URL into a full URL from a base. @since 140417 Initial release. @param string $relative_url_uri_query_fragment A full URL; or a partial URI; or only a query string, or only a fragment. Any of these can be parsed here. @param string $base_url A base URL. Optional. Defaults to current location. This defaults to the current URL. See: {@link current_url()}. @throws \Exception If unable to parse `$relative_url_uri_query_fragment`. @throws \Exception If there is no `$base`, and we're unable to detect current location. @throws \Exception If unable to parse `$base` (or if `$base` has no host name). @return string A full URL; else an exception will be thrown.
entailment
protected function mustGetUrl($url) { $url = (string) $url; // Force string value. $response = $this->remote($url, '', 5, 15, [], '', true, true); if ($response['code'] >= 400) { throw new \Exception(sprintf('HTTP response code: `%1$s`. Unable to get URL: `%2$s`.', $response['code'], $url)); } return $response['body']; }
Remote HTTP communication. @since 150820 Improving HTTP connection handling. @param string $url A URL to connect to. @throws \Exception If unable to get the URL; i.e., if the response code is >= 400. @return string Output data from the HTTP response; excluding headers (i.e., body only). @note By throwing an exception on any failure, we can avoid a circumstance where multiple failures and/or timeouts occur in succession against the same host. Any connection failure stops compression and a caller should catch the exception and fail softly; using the exception message for debugging purposes.
entailment
protected function remote($url, $body = '', $max_con_secs = 5, $max_stream_secs = 15, array $headers = [], $cookie_file = '', $fail_on_error = true, $return_array = false) { $can_follow = !filter_var(ini_get('safe_mode'), FILTER_VALIDATE_BOOLEAN) && !ini_get('open_basedir'); if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) { $time = microtime(true); } $response_body = ''; // Initialize. $response_code = 0; // Initialize. $custom_request_method = ''; $url = (string) $url; $max_con_secs = (int) $max_con_secs; $max_stream_secs = (int) $max_stream_secs; if (!is_array($headers)) { $headers = []; } $cookie_file = (string) $cookie_file; $custom_request_regex = // e.g.`PUT::http://www.example.com/` '/^(?P<custom_request_method>(?:GET|POST|PUT|PATCH|DELETE))\:{2}(?P<url>.+)/ui'; if (preg_match($custom_request_regex, $url, $_url_parts)) { $url = $_url_parts['url']; // URL after `::`. $custom_request_method = mb_strtoupper($_url_parts['custom_request_method']); } // unset($_url_parts); // Housekeeping. if (is_array($body)) { $body = http_build_query($body, '', '&'); } else { $body = (string) $body; } if (!$url) { goto finale; } // Nothing to do here. /* ---------------------------------------------------------- */ curl_transport: // cURL transport layer (recommended). if (!extension_loaded('curl') || !is_callable('curl_version') || (mb_stripos($url, 'https:') === 0 && !(is_array($curl_version = curl_version()) && $curl_version['features'] & CURL_VERSION_SSL)) ) { goto fopen_transport; // cURL will not work in this case. } $curl_opts = [ CURLOPT_URL => $url, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CONNECTTIMEOUT => $max_con_secs, CURLOPT_TIMEOUT => $max_stream_secs, // See: <http://jas.xyz/1gZKj8v> CURLOPT_FOLLOWLOCATION => $can_follow, CURLOPT_MAXREDIRS => $can_follow ? 5 : 0, CURLOPT_ENCODING => '', CURLOPT_HTTPHEADER => $headers, CURLOPT_REFERER => $this->currentUrl(), CURLOPT_AUTOREFERER => true, // On redirects. CURLOPT_USERAGENT => $this->product_title, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_VERBOSE => false, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_FAILONERROR => $fail_on_error, ]; if ($body) { if ($custom_request_method) { $curl_opts += [CURLOPT_CUSTOMREQUEST => $custom_request_method, CURLOPT_POSTFIELDS => $body]; } else { $curl_opts += [CURLOPT_POST => true, CURLOPT_POSTFIELDS => $body]; } } elseif ($custom_request_method) { $curl_opts += [CURLOPT_CUSTOMREQUEST => $custom_request_method]; } if ($cookie_file) { $curl_opts += [CURLOPT_COOKIEJAR => $cookie_file, CURLOPT_COOKIEFILE => $cookie_file]; } if (!($curl = curl_init()) || !curl_setopt_array($curl, $curl_opts)) { throw new \Exception(sprintf('Failed to initialize cURL for remote connection to: `%1$s`.', $url). sprintf(' The following cURL options were necessary: `%1$s`.', print_r($curl_opts, true))); } $response_body = trim((string) curl_exec($curl)); $response_code = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($benchmark) { $this->benchmark->addData( __FUNCTION__, ['curl_getinfo' => curl_getinfo($curl)] ); } curl_close($curl); // Close the resource handle now. if ($fail_on_error && $response_code >= 400) { $response_body = ''; // Fail silently. } goto finale; // All done here, jump to finale. /* ---------------------------------------------------------- */ fopen_transport: // Depends on `allow_url_fopen` in `php.ini`. if (!filter_var(ini_get('allow_url_fopen'), FILTER_VALIDATE_BOOLEAN) || $cookie_file || (mb_stripos($url, 'https:') === 0 && !in_array('ssl', stream_get_transports(), true)) ) { throw new \Exception('Unable to find a workable transport layer for remote HTTP communication.'. ' Please install the cURL & OpenSSL extensions for PHP.'); } $stream_options = [ 'http' => [ 'protocol_version' => 1.1, 'method' => $custom_request_method ? $custom_request_method : ($body ? 'POST' : 'GET'), 'follow_location' => $can_follow, 'max_redirects' => $can_follow ? 5 : 0, 'header' => array_merge($headers, ['Referer: '.$this->currentUrl()]), 'user_agent' => $this->product_title, 'ignore_errors' => $fail_on_error, 'timeout' => $max_stream_secs, 'content' => $body, ], ]; if (!($stream_context = stream_context_create($stream_options)) || !($stream = fopen($url, 'rb', false, $stream_context))) { $response_code = 404; // Connection failure. $response_body = ''; // Connection failure; empty. goto finale; // All done here, jump to finale. } $response_body = trim((string) stream_get_contents($stream)); $stream_meta_data = stream_get_meta_data($stream); if (!empty($stream_meta_data['timed_out'])) { // Based on `$max_stream_secs`. $response_code = 408; // Request timeout. $response_body = ''; // Connection timed out; ignore. } elseif (!empty($stream_meta_data['wrapper_data']) && is_array($stream_meta_data['wrapper_data'])) { foreach (array_reverse($stream_meta_data['wrapper_data']) as $_response_header /* Looking for the last one. */) { if (is_string($_response_header) && mb_stripos($_response_header, 'HTTP/') === 0 && mb_strpos($_response_header, ' ')) { list(, $response_code) = explode(' ', $_response_header, 3); $response_code = (int) trim($response_code); break; // Got the last status code. } } } if ($benchmark) { $this->benchmark->addData( __FUNCTION__, compact('stream_meta_data') ); } fclose($stream); // Close the resource handle now. if ($fail_on_error && $response_code >= 400) { $response_body = ''; // Fail silently. } goto finale; // All done here, jump to finale. /* ---------------------------------------------------------- */ finale: // Target point; finale/return value. if ($benchmark && !empty($time) && $url) { $this->benchmark->addTime( __FUNCTION__, $time, // Caller, start time, task performed. sprintf('fetching remote resource: `%1$s`; `%2$s` bytes received;', $url, strlen($response_body)) ); } return $return_array ? ['code' => $response_code, 'body' => $response_body] : $response_body; }
Remote HTTP communication. @since 140417 Initial release. @param string $url A URL to connect to. @param string|array $body Optional request body. @param int $max_con_secs Defaults to `20` seconds. @param int $max_stream_secs Defaults to `20` seconds. @param array $headers Any additional headers to send with the request. @param string $cookie_file If cookies are to be collected, store them here. @param bool $fail_on_error Defaults to a value of TRUE; fail on status >= `400`. @param bool $return_array Defaults to a value of FALSE; response body returned only. @throws \Exception If unable to find a workable HTTP transport layer. Supported transports include: `curl` and `fopen`. @return string|array Output data from the HTTP response; excluding headers (i.e., body only).
entailment
public function blockFencedCodeComplete($block) { $text = print_r($block, true); $matches = array(); preg_match('/\[class\] => language-([a-zA-Z]+)/', $text, $matches); if (count($matches) > 1 && $matches[1] === 'shell') { $block['element']['text']['text'] = $this->minimalHighlighter->highlight($block['element']['text']['text']); } else { $block['element']['text']['text'] = $this->highlighter->highlight($block['element']['text']['text']); } return $block; }
Use new highlighters for code blocks. @param unknown $block @return unknown
entailment
public function getAtom(User $user, $key, bool $detachFromEntityManager = true) { if ($atom = $this->getRepository()->findOneBy(['user_id' => $user->getId(), 'key' => $key])) { if ($detachFromEntityManager) { $this->getEntityManager()->detach($atom); } return $atom; } return null; }
Get an atomic piece of user data @param User $user @param $key @param bool $detachFromEntityManager @return UserAtom|null
entailment
public function setAtom(User $user, $key, $value) { $conn = $this->getEntityManager()->getConnection(); $stmt = $conn->prepare('INSERT INTO users_atoms ( user_id, `key`, `value`) VALUES( ?, ?, ? ) ON DUPLICATE KEY UPDATE `value`=VALUES(`value`)'); $user_id = $user->getId(); $stmt->bindParam(1, $user_id); $stmt->bindParam(2, $key); $stmt->bindParam(3, $value); $stmt->execute(); }
Set a particular atom on a user @param User $user @param $key @param $value @throws \Doctrine\DBAL\DBALException
entailment
public function search(string $key, string $value) { return $this->getRepository()->findBy(['key' => $key, 'value' => $value]); }
Key-value pair search. @param string $key @param string $value @return array
entailment
public function getPermissions($string) : array { $query = $this->getRepository()->createQueryBuilder('r') ->select('r') ->where('r.resource_class = :resourceClass AND r.resource_id=:resourceId') ->setParameter('resourceClass', 'string') ->setParameter('resourceId', $string) ->getQuery(); return $query->getResult(); }
@param $string @return GroupPermissionInterface[]
entailment
public function getResourcePermissions(ResourceInterface $resource) : array { $query = $this->getRepository()->createQueryBuilder('r') ->select('r') ->where('r.resource_class = :resourceClass AND r.resource_id=:resourceId') ->setParameter('resourceClass', $resource->getClass()) ->setParameter('resourceId', $resource->getId()) ->getQuery(); return $query->getResult(); }
@param ResourceInterface $resource @return array|\CirclicalUser\Provider\GroupPermissionInterface[]
entailment
public function getResourcePermissionsByClass($resourceClass) : array { $query = $this->getRepository()->createQueryBuilder('r') ->select('r') ->where('r.resource_class = :resourceClass') ->setParameter('resourceClass', $resourceClass) ->getQuery(); return $query->getResult(); }
@param $resourceClass @return array
entailment
public function authenticate(string $email, string $pass) { return $this->authenticationService->authenticate($email, $pass); }
Pass me an email/username combo and I'll start the user session @param $email @param $pass @return User @throws \CirclicalUser\Exception\BadPasswordException @throws \CirclicalUser\Exception\NoSuchUserException
entailment
public function create(User $user, $username, $password) { $this->authenticationService->create($user, $username, $password); }
Give me a user and password, and I'll create authentication records for you @param User $user @param string $username Can be an email address or username, should be validated prior @param string $password
entailment
public function createProject( $projectData, $format = 'php', $odm = null ) { // Note: might want to clone error handler, in case state variables // have been added that should differ for different uses, e.g., // a user message that is displayed where you have multiple project // objects $data = array( 'token' => $this->superToken, 'content' => 'project', 'returnFormat' => 'json' ); #--------------------------------------------- # Process the arguments #--------------------------------------------- $legalFormats = array('csv', 'json', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $data['data'] = $this->processImportDataArgument($projectData, 'projectData', $format); if (isset($odm)) { $data['odm'] = $this->processOdmArgument($odm); } #--------------------------------------- # Create the project #--------------------------------------- $apiToken = $this->connection->callWithArray($data); $this->processNonExportResult($apiToken); $connection = clone $this->connection; $errorHandler = clone $this->errorHandler; $projectConstructorCallback = $this->projectConstructorCallback; $project = call_user_func( $projectConstructorCallback, $apiUrl = null, $apiToken, $sslVerify = null, $caCertificateFile = null, $errorHandler, $connection ); return $project; }
Creates a REDCap project with the specified data. The data fields that can be set are as follows: <ul> <li> <b>project_title</b> - the title of the project. </li> <li> <b>purpose</b> - the purpose of the project: <ul> <li>0 - Practice/Just for fun</li> <li>1 - Other</li> <li>2 - Research</li> <li>3 - Quality Improvement</li> <li>4 - Operational Support</li> </ul> </li> <li> <b>purpose_other</b> - text descibing purpose if purpose above is specified as 1. </li> <li> <b>project_notes</b> - notes about the project. </li> <li> <b>is_longitudinal</b> - indicates if the project is longitudinal (0 = False [default], 1 = True). </li> <li> <b>surveys_enabled</b> - indicates if surveys are enabled (0 = False [default], 1 = True). </li> <li> <b>record_autonumbering_enabled</b> - indicates id record autonumbering is enabled (0 = False [default], 1 = True). </li> </ul> @param mixed $projectData the data used for project creation. Note that if 'php' format is used, the data needs to be an array where the keys are the field names and the values are the field values. @param $format string the format used to export the arm data. <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> </ul> @param string $odm @return RedCapProject the project that was created.
entailment
public function getProject($apiToken) { $apiToken = $this->processApiTokenArgument($apiToken); $connection = clone $this->connection; $errorHandler = clone $this->errorHandler; $projectConstructorCallback = $this->projectConstructorCallback; # By default, this creates a RedCapProject $project = call_user_func( $projectConstructorCallback, $apiUrl = null, $apiToken, $sslVerify = null, $caCertificateFile = null, $errorHandler, $connection ); return $project; }
Gets the REDCap project for the specified API token. @param string $apiToken the API token for the project to get. @return \IU\PHPCap\RedCapProject the project for the specified API token.
entailment
private function httpBuildQuery($params) { $query = []; foreach ($params as $key => $param) { if (!is_array($param)) { continue; } // when a param has many values, it generate the query string separated to join late foreach ($param as $subParam) { $query[] = http_build_query([$key => $subParam]); } unset($params[$key]); } // join queries strings $query[] = http_build_query($params); $query = implode('&', $query); return $query; }
Create a query string @param array $params @return string
entailment
public function getInheritanceList(): array { $roleList = [$this]; $role = $this; while ($parentRole = $role->getParent()) { $roleList[] = $parentRole; $role = $parentRole; } return $roleList; }
Return all inherited roles, including the start role, in this to-root traversal. @return array
entailment
function it_can_grant_access_to_roles_by_appending_actions($resourceObject, $groupRules, $groupActionRule) { $role = $this->getRoleWithName('user'); $groupRules->update(Argument::any())->shouldBeCalled(); $groupActionRule->addAction('foo')->shouldBeCalled(); $this->grantRoleAccess($role, $resourceObject, 'foo'); }
Give a role, access to a resource
entailment
public function exportArms($format = 'php', $arms = []) { $data = array( 'token' => $this->apiToken, 'content' => 'arm', 'returnFormat' => 'json' ); $legalFormats = array('csv', 'json', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $data['arms'] = $this->processArmsArgument($arms); $arms = $this->connection->callWithArray($data); $arms = $this->processExportResult($arms, $format); return $arms; }
Exports the numbers and names of the arms in the project. @param $format string the format used to export the arm data. <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> </ul> @param array $arms array of integers or numeric strings that are the numbers of the arms to export. If no arms are specified, then information for all arms will be returned. @return mixed For 'php' format, array of arrays that have the following keys: <ul> <li>'arm_num'</li> <li>'name'</li> </ul>
entailment
public function importArms($arms, $format = 'php', $override = false) { $data = array( 'token' => $this->apiToken, 'content' => 'arm', 'action' => 'import', 'returnFormat' => 'json' ); #--------------------------------------- # Process arguments #--------------------------------------- $legalFormats = array('csv', 'json', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $data['data'] = $this->processImportDataArgument($arms, 'arms', $format); $data['override'] = $this->processOverrideArgument($override); $result = $this->connection->callWithArray($data); $this->processNonExportResult($result); return (integer) $result; }
Imports the specified arms into the project. @param mixed $arms the arms to import. This will be a PHP array of associative arrays if no format, or 'php' format was specified, and a string otherwise. The field names (keys) used in both cases are: arm_num, name @param string $format the format for the export. <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> </ul> @param boolean $override <ul> <li> false - [default] don't delete existing arms; only add new arms or renames existing arms. </li> <li> true - delete all existing arms before importing.</li> </ul> @throws PhpCapException if an error occurs. @return integer the number of arms imported.
entailment
public function deleteArms($arms) { $data = array ( 'token' => $this->apiToken, 'content' => 'arm', 'action' => 'delete', 'returnFormat' => 'json', ); $data['arms'] = $this->processArmsArgument($arms, $required = true); $result = $this->connection->callWithArray($data); $this->processNonExportResult($result); return (integer) $result; }
Deletes the specified arms from the project. @param array $arms array of arm numbers to delete. @throws PhpCapException if an error occurs, including if the arms array is null or empty @return integer the number of arms deleted.
entailment
public function exportEvents($format = 'php', $arms = []) { $data = array( 'token' => $this->apiToken, 'content' => 'event', 'returnFormat' => 'json' ); #--------------------------------------- # Process arguments #--------------------------------------- $legalFormats = array('csv', 'json', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $data['arms'] = $this->processArmsArgument($arms); #------------------------------------------------------ # Get and process events #------------------------------------------------------ $events = $this->connection->callWithArray($data); $events = $this->processExportResult($events, $format); return $events; }
Exports information about the specified events. Example usage: <code> #export information about all events in CSV (Comma-Separated Values) format. $eventInfo = $project->exportEvents('csv'); # export events in XML format for arms 1 and 2. $eventInfo = $project->exportEvents('xml', [1, 2]); </code> @param string $format the format for the export. <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> </ul> @param array $arms array of integers or numeric strings that are the arm numbers for which events should be exported. If no arms are specified, then all events will be returned. @return array information about the specified events. Each element of the array is an associative array with the following keys: 'event_name', 'arm_num', 'day_offset', 'offset_min', 'offset_max', 'unique_event_name', 'custom_event_label'
entailment
public function importEvents($events, $format = 'php', $override = false) { $data = array( 'token' => $this->apiToken, 'content' => 'event', 'action' => 'import', 'returnFormat' => 'json' ); #--------------------------------------- # Process arguments #--------------------------------------- $data['data'] = $this->processImportDataArgument($events, 'arms', $format); $legalFormats = array('csv', 'json', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $data['override'] = $this->processOverrideArgument($override); $result = $this->connection->callWithArray($data); $this->processNonExportResult($result); return (integer) $result; }
Imports the specified events into the project. @param mixed $events the events to import. This will be a PHP array of associative arrays if no format, or 'php' format is specified, and a string otherwise. The field names (keys) used in both cases are: event_name, arm_num @param string $format the format for the export. <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> </ul> @param boolean $override <ul> <li> false - [default] don't delete existing arms; only add new arms or renames existing arms. </li> <li> true - delete all existing arms before importing.</li> </ul> @throws PhpCapException if an error occurs. @return integer the number of events imported.
entailment
public function deleteEvents($events) { $data = array ( 'token' => $this->apiToken, 'content' => 'event', 'action' => 'delete', 'returnFormat' => 'json', ); $data['events'] = $this->processEventsArgument($events, $required = true); $result = $this->connection->callWithArray($data); $this->processNonExportResult($result); return (integer) $result; }
Deletes the specified events from the project. @param array $events array of event names of events to delete. @throws PhpCapException if an error occurs, including if the events array is null or empty. @return integer the number of events deleted.
entailment
public function exportFieldNames($format = 'php', $field = null) { $data = array( 'token' => $this->apiToken, 'content' => 'exportFieldNames', 'returnFormat' => 'json' ); #--------------------------------------- # Process arguments #--------------------------------------- $legalFormats = array('csv', 'json', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $data['field'] = $this->processFieldArgument($field, $required = false); $fieldNames = $this->connection->callWithArray($data); $fieldNames = $this->processExportResult($fieldNames, $format); return $fieldNames; }
Exports the fields names for a project. @param string $format the format for the export. <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> </ul> @param string $field the name of the field for which to export field name information. If no field is specified, information for all fields is exported. @return mixed information on the field specified, or all fields if no field was specified. If 'php' or no format was specified, results will be returned as a PHP array of maps (associative arrays), where the keys for the maps: <ul> <li>original_field_name</li> <li>choice_value</li> <li>export_field_name</li> </ul>
entailment
public function exportFile($recordId, $field, $event = null, $repeatInstance = null) { $data = array( 'token' => $this->apiToken, 'content' => 'file', 'action' => 'export', 'returnFormat' => 'json' ); #-------------------------------------------- # Process arguments #-------------------------------------------- $data['record'] = $this->processRecordIdArgument($recordId); $data['field'] = $this->processFieldArgument($field); $data['event'] = $this->processEventArgument($event); $data['repeat_instance'] = $this->processRepeatInstanceArgument($repeatInstance); #------------------------------- # Get and process file #------------------------------- $file = $this->connection->callWithArray($data); $file = $this->processExportResult($file, $format = 'file'); return $file; }
Exports the specified file. @param string $recordId the record ID for the file to be exported. @param string $field the name of the field containing the file to export. @param string $event name of event for file export (for longitudinal studies). @param integer $repeatInstance @throws PhpCapException if an error occurs. @return string the contents of the file that was exported.
entailment
public function importFile($filename, $recordId, $field, $event = null, $repeatInstance = null) { $data = array ( 'token' => $this->apiToken, 'content' => 'file', 'action' => 'import', 'returnFormat' => 'json' ); #---------------------------------------- # Process non-file arguments #---------------------------------------- $data['file'] = $this->processFilenameArgument($filename); $data['record'] = $this->processRecordIdArgument($recordId); $data['field'] = $this->processFieldArgument($field); $data['event'] = $this->processEventArgument($event); $data['repeat_instance'] = $this->processRepeatInstanceArgument($repeatInstance); #--------------------------------------------------------------------- # For unknown reasons, "call" (instead of "callWithArray") needs to # be used here (probably something to do with the 'file' data). # REDCap's "API Playground" (also) makes no data conversion for this # method. #--------------------------------------------------------------------- $result = $this->connection->call($data); $this->processNonExportResult($result); }
Imports the file into the field of the record with the specified event and/or repeat istance, if any. Example usage: <code> ... $file = '../data/consent1001.txt'; $recordId = '1001'; $field = 'patient_document'; $event = 'enrollment_arm_1'; $project->importFile($file, $recordId, $field, $event); ... </code> @param string $filename the name of the file to import. @param string $recordId the record ID of the record to import the file into. @param string $field the field of the record to import the file into. @param string $event the event of the record to import the file into (only for longitudinal studies). @param integer $repeatInstance the repeat instance of the record to import the file into (only for studies that have repeating events and/or instruments). @throws PhpCapException
entailment
public function deleteFile($recordId, $field, $event = null, $repeatInstance = null) { $data = array ( 'token' => $this->apiToken, 'content' => 'file', 'action' => 'delete', 'returnFormat' => 'json' ); #---------------------------------------- # Process arguments #---------------------------------------- $data['record'] = $this->processRecordIdArgument($recordId); $data['field'] = $this->processFieldArgument($field); $data['event'] = $this->processEventArgument($event); $data['repeat_instance'] = $this->processRepeatInstanceArgument($repeatInstance); $result = $this->connection->callWithArray($data); $this->processNonExportResult($result); return $result; }
Deletes the specified file. @param string $recordId the record ID of the file to delete. @param string $field the field name of the file to delete. @param string $event the event of the file to delete (only for longitudinal studies). @param integer $repeatInstance repeat instance of the file to delete (only for studies that have repeating events and/or instruments).
entailment
public function exportInstruments($format = 'php') { $data = array( 'token' => $this->apiToken, 'content' => 'instrument', 'returnFormat' => 'json' ); $legalFormats = array('csv', 'json', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $instrumentsData = $this->connection->callWithArray($data); $instrumentsData = $this->processExportResult($instrumentsData, $format); #------------------------------------------------------ # If format is 'php', reformat the data as # a map from "instrument name" to "instrument label" #------------------------------------------------------ if ($format == 'php') { $instruments = array (); foreach ($instrumentsData as $instr) { $instruments [$instr ['instrument_name']] = $instr ['instrument_label']; } } else { $instruments = $instrumentsData; } return $instruments; }
Exports information about the instruments (data entry forms) for the project. Example usage: <code> $instruments = $project->getInstruments(); foreach ($instruments as $instrumentName => $instrumentLabel) { print "{$instrumentName} : {$instrumentLabel}\n"; } </code> @param $format string format instruments are exported in: <ul> <li>'php' - [default] returns data as a PHP array</li> <li>'csv' - string of CSV (comma-separated values)</li> <li>'json' - string of JSON encoded data</li> <li>'xml' - string of XML encoded data</li> </ul> @return mixed For the 'php' format, and array map of instrument names to instrument labels is returned. For all other formats a string is returned.
entailment
public function exportPdfFileOfInstruments( $file = null, $recordId = null, $event = null, $form = null, $allRecords = null ) { $data = array( 'token' => $this->apiToken, 'content' => 'pdf', 'returnFormat' => 'json' ); $file = $this->processFileArgument($file); $data['record'] = $this->processRecordIdArgument($recordId, $required = false); $data['event'] = $this->processEventArgument($event); $data['instrument'] = $this->processFormArgument($form); $data['allRecords'] = $this->processAllRecordsArgument($allRecords); $result = $this->connection->callWithArray($data); if (isset($file)) { FileUtil::writeStringToFile($result, $file); } return $result; }
Exports a PDF version of the requested instruments (forms). @param string $file the name of the file (possibly with a path specified also) to store the PDF instruments in. @param string $recordId if record ID is specified, the forms retrieved will be filled with values for that record. Otherwise, they will be blank. @param string $event (only for longitudinal projects) a unique event name that is used when a record ID has been specified to return only forms that are in that event (for the specified records). @param string $form if this is specified, only this form will be returned. @param boolean $allRecords if this is set to true, all forms for all records will be retrieved (the $recordId, $event, and $form arguments will be ignored). @throws PhpCapException if an error occurs. @return string PDF content of requested instruments (forms).
entailment
public function exportInstrumentEventMappings($format = 'php', $arms = []) { $data = array( 'token' => $this->apiToken, 'content' => 'formEventMapping', 'format' => 'json', 'returnFormat' => 'json' ); #------------------------------------------ # Process arguments #------------------------------------------ $legalFormats = array('csv', 'json', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $data['arms'] = $this->processArmsArgument($arms); #--------------------------------------------- # Get and process instrument-event mappings #--------------------------------------------- $instrumentEventMappings = $this->connection->callWithArray($data); $instrumentEventMappings = $this->processExportResult($instrumentEventMappings, $format); return $instrumentEventMappings; }
Gets the instrument to event mapping for the project. For example, the following code: <code> $map = $project->exportInstrumentEventMappings(); print_r($map[0]); # print first element of map </code> might generate the following output: <pre> Array ( [arm_num] => 1 [unique_event_name] => enrollment_arm_1 [form] => demographics ) </pre> @param string $format the format in which to export the records: <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> </ul> @param array $arms array of integers or numeric strings that are the numbers of the arms for which instrument/event mapping infomation should be exported. If no arms are specified, then information for all arms will be exported. @return arrray an array of arrays that have the following keys: <ul> <li>'arm_num'</li> <li>'unique_event_name'</li> <li>'form'</li> </ul>
entailment
public function importInstrumentEventMappings($mappings, $format = 'php') { $data = array( 'token' => $this->apiToken, 'content' => 'formEventMapping', 'returnFormat' => 'json' ); #--------------------------------------- # Process arguments #--------------------------------------- $data['data'] = $this->processImportDataArgument($mappings, 'mappings', $format); $legalFormats = array('csv', 'json', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $result = $this->connection->callWithArray($data); $this->processNonExportResult($result); return (integer) $result; }
Imports the specified instrument-event mappings into the project. @param mixed $mappings the mappings to import. This will be a PHP array of associative arrays if no format, or 'php' format, was specified, and a string otherwise. In all cases, the field names that are used in the mappings are: arm_num, unique_event_name, form @param string $format the format for the export. <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> </ul> @throws PhpCapException if an error occurs. @return integer the number of mappings imported.
entailment
public function exportMetadata($format = 'php', $fields = [], $forms = []) { $data = array( 'token' => $this->apiToken, 'content' => 'metadata', 'returnFormat' => 'json' ); #--------------------------------------- # Process format #--------------------------------------- $legalFormats = array('csv', 'json', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $data['forms'] = $this->processFormsArgument($forms); $data['fields'] = $this->processFieldsArgument($fields); #------------------------------------------- # Get and process metadata #------------------------------------------- $metadata = $this->connection->callWithArray($data); $metadata = $this->processExportResult($metadata, $format); return $metadata; }
Exports metadata about the project, i.e., information about the fields in the project. @param string $format the format for the export. <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> </ul> @param array $fields array of field names for which metadata should be exported @param array $forms array of form names. Metadata will be exported for all fields in the specified forms. @return array associative array (map) of metatdata for the project, which consists of information about each field. Some examples of the information provided are: 'field_name', 'form_name', 'field_type', 'field_label'. See REDCap API documentation for more information, or use the print_r function on the results of this method.
entailment
public function importMetadata($metadata, $format = 'php') { $data = array( 'token' => $this->apiToken, 'content' => 'metadata', 'returnFormat' => 'json' ); #--------------------------------------- # Process arguments #--------------------------------------- $data['data'] = $this->processImportDataArgument($metadata, 'metadata', $format); $legalFormats = array('csv', 'json', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $result = $this->connection->callWithArray($data); $this->processNonExportResult($result); return (integer) $result; }
Imports the specified metadata (field information) into the project. @param mixed $metadata the metadata to import. This will be a PHP associative array if no format, or 'php' format was specified, and a string otherwise. @param string $format the format for the export. <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> </ul> @throws PhpCapException if an error occurs. @return integer the number of fields imported.
entailment
public function exportProjectInfo($format = 'php') { $data = array( 'token' => $this->apiToken, 'content' => 'project', 'returnFormat' => 'json' ); #--------------------------------------- # Process format #--------------------------------------- $legalFormats = array('csv', 'json', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); #--------------------------------------- # Get and process project information #--------------------------------------- $projectInfo = $this->connection->callWithArray($data); $projectInfo = $this->processExportResult($projectInfo, $format); return $projectInfo; }
Exports information about the project, e.g., project ID, project title, creation time. @param string $format the format for the export. <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> </ul> @return array associative array (map) of project information. See REDCap API documentation for a list of the fields, or use the print_r function on the results of this method.
entailment
public function importProjectInfo($projectInfo, $format = 'php') { $data = array( 'token' => $this->apiToken, 'content' => 'project_settings', 'returnFormat' => 'json' ); #--------------------------------------- # Process arguments #--------------------------------------- $data['data'] = $this->processImportDataArgument($projectInfo, 'projectInfo', $format); $legalFormats = array('csv', 'json', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $result = $this->connection->callWithArray($data); $this->processNonExportResult($result); return (integer) $result; }
Imports the specified project information into the project. The valid fields that can be imported are: project_title, project_language, purpose, purpose_other, project_notes, custom_record_label, secondary_unique_field, is_longitudinal, surveys_enabled, scheduling_enabled, record_autonumbering_enabled, randomization_enabled, project_irb_number, project_grant_number, project_pi_firstname, project_pi_lastname, display_today_now_button You do not need to specify all of these fields when doing an import, only the ones that you actually want to change. For example: <code> ... # Set the project to be longitudinal and enable surveys $projectInfo = ['is_longitudinal' => 1, 'surveys_enabled' => 1]; $project->importProjectInfo($projectInfo); ... </code> @param mixed $projectInfo the project information to import. This will be a PHP associative array if no format, or 'php' format was specified, and a string otherwise. @param string $format the format for the export. <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> </ul> @throws PhpCapException if an error occurs. @return integer the number of project info values specified that were valid, whether or not each valid value actually caused an update (i.e., was different from the existing value before the method call).
entailment
public function exportProjectXml( $returnMetadataOnly = false, $recordIds = null, $fields = null, $events = null, $filterLogic = null, $exportSurveyFields = false, $exportDataAccessGroups = false, $exportFiles = false ) { $data = array( 'token' => $this->apiToken, 'content' => 'project_xml', 'returnFormat' => 'json' ); #--------------------------------------------- # Process the arguments #--------------------------------------------- $data['returnMetadataOnly'] = $this->processReturnMetadataOnlyArgument($returnMetadataOnly); $data['records'] = $this->processRecordIdsArgument($recordIds); $data['fields'] = $this->processFieldsArgument($fields); $data['events'] = $this->processEventsArgument($events); $data['filterLogic'] = $this->processFilterLogicArgument($filterLogic); $data['exportSurveyFields'] = $this->processExportSurveyFieldsArgument($exportSurveyFields); $data['exportDataAccessGroups'] = $this->processExportDataAccessGroupsArgument($exportDataAccessGroups); $data['exportFiles'] = $this->processExportFilesArgument($exportFiles); #--------------------------------------- # Get the Project XML and process it #--------------------------------------- $projectXml = $this->connection->callWithArray($data); $projectXml = $this->processExportResult($projectXml, $format = 'xml'); return $projectXml; }
Exports the specified information of project in XML format. @param boolean $returnMetadataOnly if this is set to true, only the metadata for the project is returned. If it is not set to true, the metadata and data for the project is returned. @param array $recordIds array of strings with record id's that are to be retrieved. @param array $fields array of field names to export @param array $events array of event names for which fields should be exported @param array $filterLogic logic used to restrict the records retrieved, e.g., "[last_name] = 'Smith'". @param boolean $exportSurveyFields specifies whether survey fields should be exported. <ul> <li> true - export the following survey fields: <ul> <li> survey identifier field ('redcap_survey_identifier') </li> <li> survey timestamp fields (instrument+'_timestamp') </li> </ul> </li> <li> false - [default] survey fields are not exported.</li> </ul> @param boolean $exportDataAccessGroups specifies whether the data access group field ('redcap_data_access_group') should be exported. <ul> <li> true - export the data access group field if there is at least one data access group, and the user calling the method (as identified by the API token) is not in a data access group.</li> <li> false - [default] don't export the data access group field.</li> </ul> @param boolean $exportFiles If this is set to true, files will be exported in the XML. If it is not set to true, files will not be exported. @return string the specified information for the project in XML format.
entailment
public function generateNextRecordName() { $data = array( 'token' => $this->apiToken, 'content' => 'generateNextRecordName', 'returnFormat' => 'json' ); $nextRecordName = $this->connection->callWithArray($data); $nextRecordName = $this->processExportResult($nextRecordName, $format = 'number'); return $nextRecordName; }
This method returns the next potential record ID for a project, but it does NOT actually create a new record. The record ID returned will generally be the current maximum record ID number incremented by one (but see the REDCap documentation for the case where Data Access Groups are being used). This method is intended for use with projects that have record-autonumbering enabled. @return string the next record name.
entailment
public function exportRecords( $format = 'php', $type = 'flat', $recordIds = null, $fields = null, $forms = null, $events = null, $filterLogic = null, $rawOrLabel = 'raw', $rawOrLabelHeaders = 'raw', $exportCheckboxLabel = false, $exportSurveyFields = false, $exportDataAccessGroups = false ) { $data = array( 'token' => $this->apiToken, 'content' => 'record', 'returnFormat' => 'json' ); #--------------------------------------- # Process the arguments #--------------------------------------- $legalFormats = array('php', 'csv', 'json', 'xml', 'odm'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $data['type'] = $this->processTypeArgument($type); $data['records'] = $this->processRecordIdsArgument($recordIds); $data['fields'] = $this->processFieldsArgument($fields); $data['forms'] = $this->processFormsArgument($forms); $data['events'] = $this->processEventsArgument($events); $data['rawOrLabel'] = $this->processRawOrLabelArgument($rawOrLabel); $data['rawOrLabelHeaders'] = $this->processRawOrLabelHeadersArgument($rawOrLabelHeaders); $data['exportCheckboxLabel'] = $this->processExportCheckboxLabelArgument($exportCheckboxLabel); $data['exportSurveyFields'] = $this->processExportSurveyFieldsArgument($exportSurveyFields); $data['exportDataAccessGroups'] = $this->processExportDataAccessGroupsArgument($exportDataAccessGroups); $data['filterLogic'] = $this->processFilterLogicArgument($filterLogic); #--------------------------------------- # Get the records and process them #--------------------------------------- $records = $this->connection->callWithArray($data); $records = $this->processExportResult($records, $format); return $records; }
Exports the specified records. Example usage: <code> $records = $project->exportRecords($format = 'csv', $type = 'flat'); $recordIds = [1001, 1002, 1003]; $records = $project->exportRecords('xml', 'eav', $recordIds); </code> @param string $format the format in which to export the records: <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> <li> 'odm' - string with CDISC ODM XML format, specifically ODM version 1.3.1</li> </ul> @param string $type the type of records exported: <ul> <li>'flat' - [default] exports one record per row.</li> <li>'eav' - exports one data point per row:, so, for non-longitudinal studies, each record will have the following fields: record_id, field_name, value. For longitudinal studies, each record will have the fields: record_id, field_name, value, redcap_event_name. </li> </ul> @param array $recordIds array of strings with record id's that are to be retrieved. @param array $fields array of field names to export @param array $forms array of form names for which fields should be exported @param array $events array of event names for which fields should be exported @param array $filterLogic logic used to restrict the records retrieved, e.g., "[last_name] = 'Smith'". @param string $rawOrLabel indicates what should be exported for options of multiple choice fields: <ul> <li> 'raw' - [default] export the raw coded values</li> <li> 'label' - export the labels</li> </ul> @param string $rawOrLabelHeaders when exporting with 'csv' format 'flat' type, indicates what format should be used for the CSV headers: <ul> <li> 'raw' - [default] export the variable/field names</li> <li> 'label' - export the field labels</li> </ul> @param boolean $exportCheckboxLabel specifies the format for checkbox fields for the case where $format = 'csv', $rawOrLabel = true, and $type = 'flat'. For other cases this parameter is effectively ignored. <ul> <li> true - checked checkboxes will have a value equal to the checkbox option's label (e.g., 'Choice 1'), and unchecked checkboxes will have a blank value. </li> <li> false - [default] checked checkboxes will have a value of 'Checked', and unchecked checkboxes will have a value of 'Unchecked'. </li> </ul> @param boolean $exportSurveyFields specifies whether survey fields should be exported. <ul> <li> true - export the following survey fields: <ul> <li> survey identifier field ('redcap_survey_identifier') </li> <li> survey timestamp fields (instrument+'_timestamp') </li> </ul> </li> <li> false - [default] survey fields are not exported.</li> </ul> @param boolean $exportDataAccessGroups specifies whether the data access group field ('redcap_data_access_group') should be exported. <ul> <li> true - export the data access group field if there is at least one data access group, and the user calling the method (as identified by the API token) is not in a data access group.</li> <li> false - [default] don't export the data access group field.</li> </ul> @return mixed If 'php' format is specified, an array of records will be returned where the format of the records depends on the 'type'parameter (see above). For other formats, a string is returned that contains the records in the specified format.
entailment
public function exportRecordsAp($arrayParameter = []) { if (func_num_args() > 1) { $message = __METHOD__.'() was called with '.func_num_args().' arguments, but ' .' it accepts at most 1 argument.'; $this->errorHandler->throwException($message, ErrorHandlerInterface::TOO_MANY_ARGUMENTS); } elseif (!isset($arrayParameter)) { $arrayParameter = []; } elseif (!is_array($arrayParameter)) { $message = 'The argument has type "' .gettype($arrayParameter) .'", but it needs to be an array.'; $this->errorHandler->throwException($message, ErrorHandlerInterface::INVALID_ARGUMENT); } // @codeCoverageIgnore $num = 1; foreach ($arrayParameter as $name => $value) { if (gettype($name) !== 'string') { $message = 'Argument name number '.$num.' in the array argument has type ' .gettype($name).', but it needs to be a string.'; $this->errorHandler->throwException($message, ErrorHandlerInterface::INVALID_ARGUMENT); } // @codeCoverageIgnore switch ($name) { case 'format': $format = $value; break; case 'type': $type = $value; break; case 'recordIds': $recordIds = $value; break; case 'fields': $fields = $value; break; case 'forms': $forms = $value; break; case 'events': $events = $value; break; case 'filterLogic': $filterLogic = $value; break; case 'rawOrLabel': $rawOrLabel = $value; break; case 'rawOrLabelHeaders': $rawOrLabelHeaders = $value; break; case 'exportCheckboxLabel': $exportCheckboxLabel = $value; break; case 'exportSurveyFields': $exportSurveyFields = $value; break; case 'exportDataAccessGroups': $exportDataAccessGroups = $value; break; default: $this->errorHandler->throwException( 'Unrecognized argument name "' . $name . '".', ErrorHandlerInterface::INVALID_ARGUMENT ); break; // @codeCoverageIgnore } $num++; } $records = $this->exportRecords( isset($format) ? $format : 'php', isset($type) ? $type : 'flat', isset($recordIds) ? $recordIds : null, isset($fields) ? $fields : null, isset($forms) ? $forms : null, isset($events) ? $events : null, isset($filterLogic) ? $filterLogic : null, isset($rawOrLabel) ? $rawOrLabel : 'raw', isset($rawOrLabelHeaders) ? $rawOrLabelHeaders : 'raw', isset($exportCheckboxLabel) ? $exportCheckboxLabel : false, isset($exportSurveyFields) ? $exportSurveyFields : false, isset($exportDataAccessGroups) ? $exportDataAccessGroups : false ); return $records; }
Export records using an array parameter, where the keys of the array passed to this method are the argument names, and the values are the argument values. The argument names to use correspond to the variable names in the exportRecords method. Example usage: <code> # return all records with last name "Smith" in CSV format $records = $project->exportRecordsAp(['format' => 'csv', 'filterLogic' => "[last_name] = 'Smith'"]); # export only records that have record ID 1001, 1002, or 1003 $result = $project->exportRecordsAp(['recordIds' => [1001, 1002, 1003]]); # export only the fields on the 'lab_data' form and field 'study_id' $records = $project->exportRecordsAp(['forms' => ['lab_data'], 'fields' => ['study_id']]); </code> @see exportRecords() @param array $argumentArray array of arguments. @return mixed the specified records.
entailment
public function importRecords( $records, $format = 'php', $type = 'flat', $overwriteBehavior = 'normal', $dateFormat = 'YMD', $returnContent = 'count', $forceAutoNumber = false ) { $data = array ( 'token' => $this->apiToken, 'content' => 'record', 'returnFormat' => 'json' ); #--------------------------------------- # Process format #--------------------------------------- $legalFormats = array('csv', 'json', 'odm', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $data['data'] = $this->processImportDataArgument($records, 'records', $format); $data['type'] = $this->processTypeArgument($type); $data['overwriteBehavior'] = $this->processOverwriteBehaviorArgument($overwriteBehavior); $data['forceAutoNumber'] = $this->processForceAutoNumberArgument($forceAutoNumber); $data['returnContent'] = $this->processReturnContentArgument($returnContent, $forceAutoNumber); $data['dateFormat'] = $this->processDateFormatArgument($dateFormat); $result = $this->connection->callWithArray($data); $this->processNonExportResult($result); #-------------------------------------------------------------------------- # Process result, which should either be a count of the records imported, # or a list of the record IDs that were imported # # The result should be a string in JSON for all formats. # Need to convert the result to a PHP data structure. #-------------------------------------------------------------------------- $phpResult = json_decode($result, true); // true => return as array instead of object $jsonError = json_last_error(); switch ($jsonError) { case JSON_ERROR_NONE: $result = $phpResult; # If this is a count, then just return the count, and not an # array that has a count index with the count if (isset($result) && is_array($result) && array_key_exists('count', $result)) { $result = $result['count']; } break; default: # Hopefully the REDCap API will always return valid JSON, and this # will never happen. $message = 'JSON error ('.$jsonError.') "'.json_last_error_msg(). '" while processing import return value: "'. $result.'".'; $this->errorHandler->throwException($message, ErrorHandlerInterface::JSON_ERROR); break; // @codeCoverageIgnore } return $result; }
Imports the specified records into the project. @param mixed $records If the 'php' (default) format is being used, an array of associated arrays (maps) where each key is a field name, and its value is the value to store in that field. If any other format is being used, then the records are represented by a string. @param string $format One of the following formats can be specified <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> <li> 'odm' - CDISC ODM XML format, specifically ODM version 1.3.1</li> </ul> @param string $type <ul> <li> 'flat' - [default] each data element is a record</li> <li> 'eav' - each data element is one value</li> </ul> @param string $overwriteBehavior <ul> <li>normal - [default] blank/empty values will be ignored</li> <li>overwrite - blank/empty values are valid and will overwrite data</li> </ul> @param string $dateFormat date format which can be one of the following: <ul> <li>'YMD' - [default] Y-M-D format (e.g., 2016-12-31)</li> <li>'MDY' - M/D/Y format (e.g., 12/31/2016)</li> <li>'DMY' - D/M/Y format (e.g., 31/12/2016)</li> </ul> @param string $returnContent specifies what should be returned: <ul> <li>'count' - [default] the number of records imported</li> <li>'ids' - an array of the record IDs imported is returned</li> <li>'auto_ids' - an array of comma-separated record ID pairs, with the new ID created and the corresponding ID that was sent, for the records that were imported. This can only be used if $forceAutoNumber is set to true.</li> </ul> @param boolean $forceAutoNumber enables automatic assignment of record IDs of imported records by REDCap. If this is set to true, and auto-numbering for records is enabled for the project, auto-numbering of imported records will be enabled. @return mixed if 'count' was specified for 'returnContent', then an integer will be returned that is the number of records imported. If 'ids' was specified, then an array of record IDs that were imported will be returned. If 'auto_ids' was specified, an array that maps newly created IDs to sent IDs will be returned.
entailment
public function deleteRecords($recordIds, $arm = null) { $data = array ( 'token' => $this->apiToken, 'content' => 'record', 'action' => 'delete', 'returnFormat' => 'json' ); $data['records'] = $this->processRecordIdsArgument($recordIds); $data['arm'] = $this->processArmArgument($arm); $result = $this->connection->callWithArray($data); $this->processNonExportResult($result); return $result; }
Deletes the specified records from the project. @param array $recordIds array of record IDs to delete @param string $arm if an arm is specified, only records that have one of the specified record IDs that are in that arm will be deleted. @throws PhpCapException @return integer the number of records deleted. Note that as of REDCap version 7.0.15 (at least) the number of records deleted will not be correct for the case where an arm is specified and some of the record IDs specified are not in that arm.
entailment
public function exportRepeatingInstrumentsAndEvents($format = 'php') { $data = array( 'token' => $this->apiToken, 'content' => 'repeatingFormsEvents', 'returnFormat' => 'json' ); #--------------------------------------- # Process the arguments #--------------------------------------- $legalFormats = array('php', 'csv', 'json', 'xml', 'odm'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $result = $this->connection->callWithArray($data); $this->processNonExportResult($result); return $result; }
Exports the repeating instruments and events. @param string $format the format in which to export the records: <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> <li> 'odm' - string with CDISC ODM XML format, specifically ODM version 1.3.1</li> </ul> @return mixed an array will be returned for the 'php' format, and a string for all other formats. For classic (non-longitudinal) studies, the 'form name' and 'custom form label' will be returned for each repeating form. Longitudinal studies additionally return the 'event name'. For repeating events in longitudinal studies, a blank value will be returned for the form_name. In all cases, a blank value will be returned for the 'custom form label' if it is not defined.
entailment
public function exportRedcapVersion() { $data = array( 'token' => $this->apiToken, 'content' => 'version' ); $redcapVersion = $this->connection->callWithArray($data); $recapVersion = $this->processExportResult($redcapVersion, 'string'); return $redcapVersion; }
Gets the REDCap version number of the REDCap instance being used by the project. @return string the REDCap version number of the REDCap instance being used by the project.
entailment
public function exportReports( $reportId, $format = 'php', $rawOrLabel = 'raw', $rawOrLabelHeaders = 'raw', $exportCheckboxLabel = false ) { $data = array( 'token' => $this->apiToken, 'content' => 'report', 'returnFormat' => 'json' ); #------------------------------------------------ # Process arguments #------------------------------------------------ $data['report_id'] = $this->processReportIdArgument($reportId); $legalFormats = array('csv', 'json', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $data['rawOrLabel'] = $this->processRawOrLabelArgument($rawOrLabel); $data['rawOrLabelHeaders'] = $this->processRawOrLabelHeadersArgument($rawOrLabelHeaders); $data['exportCheckboxLabel'] = $this->processExportCheckboxLabelArgument($exportCheckboxLabel); #--------------------------------------------------- # Get and process records #--------------------------------------------------- $records = $this->connection->callWithArray($data); $records = $this->processExportResult($records, $format); return $records; }
Exports the records produced by the specified report. @param mixed $reportId integer or numeric string ID of the report to use. @param string $format output data format. <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> </ul> @param string $rawOrLabel indicates what should be exported for options of multiple choice fields: <ul> <li> 'raw' - [default] export the raw coded values</li> <li> 'label' - export the labels</li> </ul> @param string $rawOrLabelHeaders when exporting with 'csv' format 'flat' type, indicates what format should be used for the CSV headers: <ul> <li> 'raw' - [default] export the variable/field names</li> <li> 'label' - export the field labels</li> </ul> @param boolean $exportCheckboxLabel specifies the format for checkbox fields for the case where $format = 'csv', $rawOrLabel = true, and $type = 'flat'. For other cases this parameter is effectively ignored. <ul> <li> true - checked checkboxes will have a value equal to the checkbox option's label (e.g., 'Choice 1'), and unchecked checkboxes will have a blank value. </li> <li> false - [default] checked checkboxes will have a value of 'Checked', and unchecked checkboxes will have a value of 'Unchecked'. </li> </ul> @return mixed the records generated by the specefied report in the specified format.
entailment
public function exportSurveyParticipants($form, $format = 'php', $event = null) { $data = array( 'token' => $this->apiToken, 'content' => 'participantList', 'returnFormat' => 'json' ); #---------------------------------------------- # Process arguments #---------------------------------------------- $legalFormats = array('csv', 'json', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $data['instrument'] = $this->ProcessFormArgument($form, $required = true); $data['event'] = $this->ProcessEventArgument($event); $surveyParticipants = $this->connection->callWithArray($data); $surveyParticipants = $this->processExportResult($surveyParticipants, $format); return $surveyParticipants; }
Exports the list of survey participants for the specified form and, for longitudinal studies, event. @param string $form the form for which the participants should be exported. @param string $format output data format. <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> </ul> @param string $event the event name for which survey participants should be exported. @return mixed for the 'php' format, an array of arrays of participant information is returned, for all other formats, the data is returned in the specified format as a string.
entailment
public function exportSurveyQueueLink($recordId) { $data = array( 'token' => $this->apiToken, 'content' => 'surveyQueueLink', 'returnFormat' => 'json' ); #---------------------------------------------- # Process arguments #---------------------------------------------- $data['record'] = $this->processRecordIdArgument($recordId, $required = true); $surveyQueueLink = $this->connection->callWithArray($data); $surveyQueueLink = $this->processExportResult($surveyQueueLink, 'string'); return $surveyQueueLink; }
Exports the survey queue link for the specified record ID. @param string $recordId the record ID of the survey queue link that should be returned. @return string survey queue link.
entailment
public function exportSurveyReturnCode($recordId, $form, $event = null, $repeatInstance = null) { $data = array( 'token' => $this->apiToken, 'content' => 'surveyReturnCode', 'returnFormat' => 'json' ); #---------------------------------------------- # Process arguments #---------------------------------------------- $data['record'] = $this->processRecordIdArgument($recordId, $required = true); $data['instrument'] = $this->ProcessFormArgument($form, $required = true); $data['event'] = $this->ProcessEventArgument($event); $data['repeat_instance'] = $this->ProcessRepeatInstanceArgument($repeatInstance); $surveyReturnCode = $this->connection->callWithArray($data); $surveyReturnCode = $this->processExportResult($surveyReturnCode, 'string'); return $surveyReturnCode; }
Exports the code for returning to a survey that was not completed. @param string $recordId the record ID for the survey to return to. @param string $form the form name of the survey to return to. @param string $event the unique event name (for longitudinal studies) for the survey to return to. @param integer $repeatInstance the repeat instance (if any) for the survey to return to. @return string survey return code.
entailment
public function exportUsers($format = 'php') { $data = array( 'token' => $this->apiToken, 'content' => 'user', 'returnFormat' => 'json' ); $legalFormats = array('csv', 'json', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); #--------------------------------------------------- # Get and process users #--------------------------------------------------- $users = $this->connection->callWithArray($data); $users = $this->processExportResult($users, $format); return $users; }
Exports the users of the project. @param string $format output data format. <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> </ul> @return mixed a list of users. For the 'php' format an array of associative arrays is returned, where the keys are the field names and the values are the field values. For all other formats, a string is returned with the data in the specified format.
entailment
public function importUsers($users, $format = 'php') { $data = array( 'token' => $this->apiToken, 'content' => 'user', 'returnFormat' => 'json' ); #---------------------------------------------------- # Process arguments #---------------------------------------------------- $legalFormats = array('csv', 'json', 'php', 'xml'); $data['format'] = $this->processFormatArgument($format, $legalFormats); $data['data'] = $this->processImportDataArgument($users, 'users', $format); #--------------------------------------------------- # Get and process users #--------------------------------------------------- $result = $this->connection->callWithArray($data); $this->processNonExportResult($result); return (integer) $result; }
Imports the specified users into the project. This method can also be used to update user priveleges by importing a users that already exist in the project and specifying new privleges for that user in the user data that is imported. The available field names for user import are: <code> username, expiration, data_access_group, design, user_rights, data_access_groups, data_export, reports, stats_and_charts, manage_survey_participants, calendar, data_import_tool, data_comparison_tool, logging, file_repository, data_quality_create, data_quality_execute, api_export, api_import, mobile_app, mobile_app_download_data, record_create, record_rename, record_delete, lock_records_customization, lock_records, lock_records_all_forms, forms </code> Privileges for fields above can be set as follows: <ul> <li><b>Data Export:</b> 0=No Access, 2=De-Identified, 1=Full Data Set</li> <li><b>Form Rights:</b> 0=No Access, 2=Read Only, 1=View records/responses and edit records (survey responses are read-only), 3=Edit survey responses</li> <li><b>Other field values:</b> 0=No Access, 1=Access.</li> </ul> See the REDCap API documentation for more information, or print the results of PHPCap's exportUsers method to see what the data looks like for the current users. @param mixed $users for 'php' format, an array should be used that maps field names to field values. For all other formats a string should be used that has the data in the correct format. @param string $format output data format. <ul> <li> 'php' - [default] array of maps of values</li> <li> 'csv' - string of CSV (comma-separated values)</li> <li> 'json' - string of JSON encoded values</li> <li> 'xml' - string of XML encoded data</li> </ul> @return integer the number of users added or updated.
entailment
public function getRecordIdBatches($batchSize = null, $filterLogic = null, $recordIdFieldName = null) { $recordIdBatches = array(); #----------------------------------- # Check arguments #----------------------------------- if (!isset($batchSize)) { $message = 'The number of batches was not specified.'; $this->errorHandler->throwException($message, ErrorHandlerInterface::INVALID_ARGUMENT); } elseif (!is_int($batchSize)) { $message = "The batch size argument has type '".gettype($batchSize).'", ' .'but it should have type integer.'; $this->errorHandler->throwException($message, ErrorHandlerInterface::INVALID_ARGUMENT); } elseif ($batchSize < 1) { $message = 'The batch size argument is less than 1. It needs to be at least 1.'; $this->errorHandler->throwException($message, ErrorHandlerInterface::INVALID_ARGUMENT); } // @codeCoverageIgnore $filterLogic = $this->processFilterLogicArgument($filterLogic); if (!isset($recordIdFieldName)) { $recordIdFieldName = $this->getRecordIdFieldName(); } $records = $this->exportRecordsAp( ['fields' => [$recordIdFieldName], 'filterLogic' => $filterLogic] ); $recordIds = array_column($records, $recordIdFieldName); $recordIds = array_unique($recordIds); # Remove duplicate record IDs $numberOfRecordIds = count($recordIds); $position = 0; for ($position = 0; $position < $numberOfRecordIds; $position += $batchSize) { $recordIdBatch = array(); $recordIdBatch = array_slice($recordIds, $position, $batchSize); array_push($recordIdBatches, $recordIdBatch); } return $recordIdBatches; }
Gets an array of record ID batches. These can be used for batch processing of records exports to lessen memory requirements, for example: <code> ... # Get all the record IDs of the project in 10 batches $recordIdBatches = $project->getRecordIdBatches(10); foreach ($recordIdBatches as $recordIdBatch) { $records = $project->exportRecordsAp(['recordIds' => $recordIdBatch]); ... } ... </code> @param integer $batchSize the batch size in number of record IDs. The last batch may have less record IDs. For example, if you had 500 record IDs and specified a batch size of 200, the first 2 batches would have 200 record IDs, and the last batch would have 100. @param array $filterLogic logic used to restrict the records retrieved, e.g., "[last_name] = 'Smith'". This could be used for batch processing a subset of the records. @param $recordIdFieldName the name of the record ID field. Specifying this is not necessary, but will speed things up, because it will eliminate the need for this method to call the REDCap API to retrieve the value. @return array an array or record ID arrays, where each record ID array is considered to be a batch. Each batch can be used as the value for the records IDs parameter for an export records method.
entailment
protected function processExportResult(& $result, $format) { if ($format == 'php') { $phpResult = json_decode($result, true); // true => return as array instead of object $jsonError = json_last_error(); switch ($jsonError) { case JSON_ERROR_NONE: $result = $phpResult; break; default: $message = "JSON error (" . $jsonError . ") \"" . json_last_error_msg() ."\" in REDCap API output." ."\nThe first 1,000 characters of output returned from REDCap are:\n" .substr($result, 0, 1000); $code = ErrorHandlerInterface::JSON_ERROR; $this->errorHandler->throwException($message, $code); break; // @codeCoverageIgnore } if (array_key_exists('error', $result)) { $this->errorHandler->throwException($result ['error'], ErrorHandlerInterface::REDCAP_API_ERROR); } // @codeCoverageIgnore } else { // If this is a format other than 'php', look for a JSON error, because // all formats return errors as JSON $matches = array(); $hasMatch = preg_match(self::JSON_RESULT_ERROR_PATTERN, $result, $matches); if ($hasMatch === 1) { // note: $matches[0] is the complete string that matched // $matches[1] is just the error message part $message = $matches[1]; $this->errorHandler->throwException($message, ErrorHandlerInterface::REDCAP_API_ERROR); } // @codeCoverageIgnore } return $result; }
Processes an export result from the REDCap API. @param string $result @param string $format @throws PhpCapException
entailment
protected function processNonExportResult(& $result) { $matches = array(); #$hasMatch = preg_match('/^[\s]*{"error":[\s]*"(.*)"}[\s]*$/', $result, $matches); $hasMatch = preg_match(self::JSON_RESULT_ERROR_PATTERN, $result, $matches); if ($hasMatch === 1) { // note: $matches[0] is the complete string that matched // $matches[1] is just the error message part $message = $matches[1]; $message = str_replace('\"', '"', $message); $message = str_replace('\n', "\n", $message); $code = ErrorHandlerInterface::REDCAP_API_ERROR; $this->errorHandler->throwException($message, $code); } // @codeCoverageIgnore }
Checks the result returned from the REDCap API for non-export methods. PHPCap is set to return errors from REDCap using JSON, so the result string is checked to see if there is a JSON format error, and if so, and exception is thrown using the error message returned from the REDCap API. @param string $result a result returned from the REDCap API, which should be for a non-export method.
entailment
private function getUser() { if (function_exists('auth') && auth()->check()) { return auth()->user()->toArray(); } if (class_exists(\Cartalyst\Sentinel\Sentinel::class) && $user = Sentinel::check()) { return $user->toArray(); } return null; }
Get the authenticated user. Supported authentication systems: Laravel, Sentinel @return array|null
entailment
public function getUsersWithRole(Role $role): array { $query = $this->getRepository()->createQueryBuilder('u') ->select('u') ->where(':role MEMBER OF u.roles') ->setParameter('role', $role) ->getQuery(); return $query->getResult() ?? []; }
Get users with a specific role, and _not_ its hierarchical parents. In other words, if you have 'admin' which inherits from 'standard' and you request 'admin', you will not list 'standard' users. @param Role $role @return array
entailment
public function getUserPermission($string, UserInterface $user) { $query = $this->getRepository()->createQueryBuilder('r') ->select('r') ->where('r.resource_class = :resourceClass AND r.resource_id=:resourceId AND r.user=:user') ->setParameter('resourceClass', 'string') ->setParameter('resourceId', $string) ->setParameter('user', $user) ->getQuery(); return $query->getOneOrNullResult(); }
Get any user-level, string (simple) permissions that are configured in the database. @param $string @param UserInterface $user @return array @throws \Doctrine\ORM\NonUniqueResultException
entailment
public function getResourceUserPermission(ResourceInterface $resource, UserInterface $user) { $query = $this->getRepository()->createQueryBuilder('r') ->select('r') ->where('r.resource_class = :resourceClass AND r.resource_id=:resourceId AND r.user=:user') ->setParameter('resourceClass', $resource->getClass()) ->setParameter('resourceId', $resource->getId()) ->setParameter('user', $user) ->getQuery(); return $query->getOneOrNullResult(); }
Get resource-type permissions from the database @param ResourceInterface $resource @param UserInterface $user @return array @throws \Doctrine\ORM\NonUniqueResultException
entailment
public function create(UserInterface $user, $resourceClass, $resourceId, array $actions) : UserPermissionInterface { return new UserPermission($user, $resourceClass, $resourceId, $actions); }
Create a user permission, not persisted, and return it. @param UserInterface $user @param $resourceClass @param $resourceId @param array $actions @return UserPermissionInterface
entailment
public function getCallInfo() { $callInfo = curl_getinfo($this->curlHandle); if ($errno = curl_errno($this->curlHandle)) { $message = curl_error($this->curlHandle); $code = ErrorHandlerInterface::CONNECTION_ERROR; $this->errorHandler->throwException($message, $code, $errno); } // @codeCoverageIgnore return $callInfo; }
Returns call information for the most recent call. @throws PhpCapException if an error occurs and the default error handler is being used. @return array an associative array of values of call information for the most recent call made. @see <a href="http://php.net/manual/en/function.curl-getinfo.php">http://php.net/manual/en/function.curl-getinfo.php</a> for information on what values are returned.
entailment
public function setCurlOption($option, $value) { $this->curlOptions[$option] = $value; $result = curl_setopt($this->curlHandle, $option, $value); return $result; }
Sets the specified cURL option to the specified value. {@internal NOTE: this method is cURL specific and is NOT part of the connection interface, and therefore should NOT be used internally by PHPCap outside of this class. } @see <a href="http://php.net/manual/en/function.curl-setopt.php">http://php.net/manual/en/function.curl-setopt.php</a> for information on cURL options. @param integer $option the cURL option that is being set. @param mixed $value the value that the cURL option is being set to. @return boolean Returns true on success and false on failure.
entailment
public function getCurlOption($option) { $optionValue = null; if (array_key_exists($option, $this->curlOptions)) { $optionValue = $this->curlOptions[$option]; } return $optionValue; }
Gets the value for the specified cURL option number. {@internal NOTE: this method is cURL specific and is NOT part of the connection interface, and therefore should NOT be used internally by PHPCap outside of this class. } @see <a href="http://php.net/manual/en/function.curl-setopt.php">http://php.net/manual/en/function.curl-setopt.php</a> for information on cURL options. @param integer $option cURL option number. @return mixed if the specified option has a value that has been set in the code, then the value is returned. If no value was set, then null is returned. Note that the cURL CURLOPT_POSTFIELDS option value is not saved, because it is reset with every call and can can be very large. As a result, null will always be returned for this cURL option.
entailment
public function boot() { if(function_exists('config_path')) { /* * Publish configuration file */ $this->publishes( [ __DIR__ . '/../config/larabug.php' => config_path( 'larabug.php' ), ] ); } $this->app['view']->addNamespace('larabug', __DIR__ . '/../resources/views'); if(class_exists(\Illuminate\Foundation\AliasLoader::class)) { $loader = \Illuminate\Foundation\AliasLoader::getInstance(); $loader->alias( 'LaraBug', 'LaraBug\Facade' ); } }
Bootstrap the application events.
entailment
public function register() { $this->mergeConfigFrom(__DIR__ . '/../config/larabug.php', 'larabug'); $this->app->singleton(LaraBug::SERVICE, function ($app) { return new LaraBug; }); }
Register the service provider.
entailment
public function addTime($function, $start_time, $task) { if (!($function = trim((string) $function))) { return; // Not possible. } if (($start_time = (float) $start_time) <= 0) { return; // Not possible. } if (($end_time = (float) microtime(true)) <= 0) { return; // Not possible. } if (!($task = trim((string) $task))) { return; // Not possible. } $time = number_format($end_time - $start_time, 5, '.', ''); $this->times[$function] = compact('function', 'time', 'task'); }
Logs a new time entry. @since 150315 Enhancing debugger. @api This method is available for public use. @param string $function Caller. @param float $start_time Start time; via `microtime(TRUE)`. @param string $task Description of the task(s) performed.
entailment
public function hasHook($hook) { $hook = (string) $hook; return $hook && !empty($this->hooks[$hook]); }
Do we have a specific hook? @since 150821 Enhancing hook support. @param string $hook The name of a filter hook. @return bool True if actions/filters exist on this hook.
entailment
public function addHook($hook, $function, $priority = 10, $accepted_args = 1) { $hook = (string) $hook; $priority = (int) $priority; $accepted_args = max(0, (int) $accepted_args); $hook_id = $this->hookId($function); $this->hooks[$hook][$priority][$hook_id] = [ 'function' => $function, 'accepted_args' => (int) $accepted_args, ]; return true; // Always returns true. }
Adds a new hook (works with both actions & filters). @since 150321 Adding hook API for plugins. @param string $hook The name of a hook to attach to. @param string|callable|mixed $function A string or a callable. @param int $priority Hook priority; defaults to `10`. @param int $accepted_args Max number of args that should be passed to the `$function`. @return bool This always returns a `TRUE` value.
entailment
public function removeHook($hook, $function, $priority = 10) { $hook = (string) $hook; $priority = (int) $priority; $hook_id = $this->hookId($function); if (!isset($this->hooks[$hook][$priority][$hook_id])) { return false; // Nothing to remove. } unset($this->hooks[$hook][$priority][$hook_id]); if (!$this->hooks[$hook][$priority]) { unset($this->hooks[$hook][$priority]); } return true; // Existed before it was removed. }
Removes a hook (works with both actions & filters). @since 150321 Adding hook API for plugins. @param string $hook The name of a hook to remove. @param string|callable|mixed $function A string or a callable. @param int $priority Hook priority; defaults to `10`. @return bool `TRUE` if removed; else `FALSE` if not removed for any reason.
entailment
public function doAction($hook) { $hook = (string) $hook; if (empty($this->hooks[$hook])) { return; // No hooks. } $hook_actions = $this->hooks[$hook]; $args = func_get_args(); ksort($hook_actions); foreach ($hook_actions as $_hook_action) { foreach ($_hook_action as $_action) { if (!isset($_action['function'], $_action['accepted_args'])) { continue; // Not a valid filter in this case. } call_user_func_array($_action['function'], array_slice($args, 1, $_action['accepted_args'])); } } unset($_hook_action, $_action); // Housekeeping. }
Runs any callables attached to an action. @since 150321 Adding hook API for plugins. @param string $hook The name of an action hook.
entailment
public function applyFilters($hook, $value) { $hook = (string) $hook; if (empty($this->hooks[$hook])) { return $value; // No hooks. } $hook_filters = $this->hooks[$hook]; $args = func_get_args(); ksort($hook_filters); foreach ($hook_filters as $_hook_filter) { foreach ($_hook_filter as $_filter) { if (!isset($_filter['function'], $_filter['accepted_args'])) { continue; // Not a valid filter in this case. } $args[1] = $value; // Continously update the argument `$value`. $value = call_user_func_array($_filter['function'], array_slice($args, 1, $_filter['accepted_args'])); } } unset($_hook_filter, $_filter); // Housekeeping. return $value; // With applied filters. }
Runs any callables attached to a filter. @since 150321 Adding hook API for plugins. @param string $hook The name of a filter hook. @param mixed $value The value to filter. @return mixed The filtered `$value`.
entailment
public static function fileToString($filename) { $errorHandler = static::getErrorHandler(); if (!file_exists($filename)) { $errorHandler->throwException( 'The input file "'.$filename.'" could not be found.', ErrorHandlerInterface::INPUT_FILE_NOT_FOUND ); } elseif (!is_readable($filename)) { $errorHandler->throwException( 'The input file "'.$filename.'" was unreadable.', ErrorHandlerInterface::INPUT_FILE_UNREADABLE ); } // @codeCoverageIgnore $contents = file_get_contents($filename); if ($contents === false) { $error = error_get_last(); $errorMessage = null; if ($error != null && array_key_exists('message', $error)) { $errorMessage = $error['message']; } if (isset($errorMessage)) { $errorHandler->throwException( 'An error occurred in input file "'.$filename.'": '.$errorMessage, ErrorHandlerInterface::INPUT_FILE_ERROR ); } else { // @codeCoverageIgnore $errorHandler->throwException( 'An error occurred in input file "'.$filename.'"', ErrorHandlerInterface::INPUT_FILE_ERROR ); } // @codeCoverageIgnore } // @codeCoverageIgnore return $contents; }
Reads the contents of the specified file and returns it as a string. @param string $filename the name of the file that is to be read. @throws PhpCapException if an error occurs while trying to read the file. @return string the contents of the specified file.
entailment
public static function writeStringToFile($string, $filename, $append = false) { $errorHandler = static::getErrorHandler(); $result = false; if ($append === true) { $result = file_put_contents($filename, $string, FILE_APPEND); } else { $result = file_put_contents($filename, $string); } if ($result === false) { $error = error_get_last(); $errorMessage = null; if ($error != null && array_key_exists('message', $error)) { $errorMessage = $error['message']; } if (isset($errorMessage)) { $errorHandler->throwException( 'An error occurred in output file "'.$filename.'": '.$errorMessage, ErrorHandlerInterface::OUTPUT_FILE_ERROR ); } else { // @codeCoverageIgnore $errorHandler->throwException( 'An error occurred in output file "'.$filename.'"', ErrorHandlerInterface::OUTPUT_FILE_ERROR ); } // @codeCoverageIgnore } // @codeCoverageIgnore return $result; }
Writes the specified string to the specified file. @param string $string the string to write to the file. @param string $filename the name of the file to write the string. @param boolean $append if true, the file is appended if it already exists. If false, the file is created if it doesn't exist, and overwritten if it does. @throws PhpCapException if an error occurs. @return mixed false on failure, and the number of bytes written on success.
entailment
public static function setErrorHandler($errorHandler) { # Get the current error handler to make sure it's set, # since it will need to be used if the passed error # handler is invalid $currentErrorHandler = static::getErrorHandler(); if (!($errorHandler instanceof ErrorHandlerInterface)) { $message = 'The error handler argument is not valid, because it doesn\'t implement ' .ErrorHandlerInterface::class.'.'; $code = ErrorHandlerInterface::INVALID_ARGUMENT; $currentErrorHandler->throwException($message, $code); } // @codeCoverageIgnore self::$errorHandler = $errorHandler; }
Sets the error handler used for methods in this class. @param ErrorHandlerInterface $errorHandler
entailment
public function loadConfiguration(): void { $builder = $this->getContainerBuilder(); $config = $this->validateConfig($this->defaults); $config = Helpers::expand($config, $builder->parameters); // Scheduler $scheduler = $builder->addDefinition($this->prefix('scheduler')) ->setFactory(LockingScheduler::class, [$config['path']]); // Commands $builder->addDefinition($this->prefix('runCommand')) ->setFactory(RunCommand::class) ->setAutowired(false); $builder->addDefinition($this->prefix('listCommand')) ->setFactory(ListCommand::class) ->setAutowired(false); $builder->addDefinition($this->prefix('helpCommand')) ->setFactory(HelpCommand::class) ->setAutowired(false); // Jobs foreach ($config['jobs'] as $key => $job) { if (is_array($job)) { $job = new Statement(CallbackJob::class, [$job['cron'], $job['callback']]); } else { $job = new Statement($job); } $scheduler->addSetup('add', [$job, $key]); } }
Register services
entailment
public function modelNotFoundException(ModelNotFoundException $exception) { $entity = $this->extractEntityName($exception->getModel()); $ids = implode($exception->getIds(), ','); $error = [[ 'status' => 404, 'code' => $this->getCode('model_not_found'), 'source' => ['pointer' => 'data/id'], 'title' => $exception->getMessage(), 'detail' => __('exception::exceptions.model_not_found.title', ['model' => $entity]), ]]; $this->jsonApiResponse->setStatus(404); $this->jsonApiResponse->setErrors($error); }
Set the response if Exception is ModelNotFound. @param ModelNotFoundException $exception
entailment
public function extractEntityName($model) { $classNames = (array) explode('\\', $model); $entityName = end($classNames); if ($this->entityHasTranslation($entityName)) { return __('exception::exceptions.models.'.$entityName); } return $entityName; }
Get entitie name based on model path to mount the message. @param string $model @return string
entailment
public function entityHasTranslation(string $entityName): bool { $hasKey = in_array($entityName, $this->translationModelKeys()); if ($hasKey) { return ! empty($hasKey); } return false; }
Check if entity returned on ModelNotFoundException has translation on exceptions file @param string $entityName The model name to check if has translation @return bool Has translation or not
entailment
public function clear() { $this->dom = null; $this->nodes = null; $this->parent = null; $this->children = null; }
clean up memory due to php5 circular references memory leak...
entailment