code
stringlengths 17
247k
| docstring
stringlengths 30
30.3k
| func_name
stringlengths 1
89
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
153
| url
stringlengths 51
209
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) {
if ( \count( $parameters ) === 1 ) {
return;
}
/*
* We already know that there will be a valid open+close parenthesis, otherwise the sniff
* would have bowed out long before.
*/
$opener = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true );
$closer = $this->tokens[ $opener ]['parenthesis_closer'];
$data = array(
$matched_content,
$this->target_functions[ $matched_content ],
GetTokensAsString::compact( $this->phpcsFile, $stackPtr, $closer, true ),
);
$this->phpcsFile->addWarning(
'%s() expects only a $text parameter. Did you mean to use %s() ? Found: %s',
$stackPtr,
'Found',
$data
);
} | Process the parameters of a matched function.
@since 2.2.0
@param int $stackPtr The position of the current token in the stack.
@param string $group_name The name of the group which was matched.
@param string $matched_content The token content (function name) which was matched
in lowercase.
@param array $parameters Array with information about the parameters.
@return void | process_parameters | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/CodeAnalysis/EscapedNotTranslatedSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/CodeAnalysis/EscapedNotTranslatedSniff.php | MIT |
private function find_token_in_multiline_string( $stackPtr, $content, $match_offset ) {
$newline_count = 0;
if ( $match_offset > 0 ) {
$newline_count = substr_count( $content, "\n", 0, $match_offset );
}
// Account for heredoc/nowdoc text starting at the token *after* the opener.
if ( isset( Tokens::$heredocTokens[ $this->tokens[ $stackPtr ]['code'] ] ) === true ) {
++$newline_count;
}
return ( $stackPtr + $newline_count );
} | Find the exact token on which the error should be reported for multi-line strings.
@param int $stackPtr The position of the current token in the stack.
@param string $content The complete, potentially multi-line, text string.
@param int $match_offset The offset within the content at which the match was found.
@return int The stack pointer to the token containing the start of the match. | find_token_in_multiline_string | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/EnqueuedResourcesSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/EnqueuedResourcesSniff.php | MIT |
public function register() {
$this->false_tokens += Tokens::$emptyTokens;
$this->safe_tokens += Tokens::$emptyTokens;
$this->safe_tokens += Tokens::$assignmentTokens;
$this->safe_tokens += Tokens::$comparisonTokens;
$this->safe_tokens += Tokens::$operators;
$this->safe_tokens += Tokens::$booleanOperators;
$this->safe_tokens += Tokens::$castTokens;
return parent::register();
} | Returns an array of tokens this test wants to listen for.
Overloads and calls the parent method to allow for adding additional tokens to the $safe_tokens property.
@return array | register | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/EnqueuedResourceParametersSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/EnqueuedResourceParametersSniff.php | MIT |
protected function is_falsy( $start, $end ) {
// Find anything excluding the false tokens.
$has_non_false = $this->phpcsFile->findNext( $this->false_tokens, $start, ( $end + 1 ), true );
// If no non-false tokens are found, we are good.
if ( false === $has_non_false ) {
return true;
}
$code_string = '';
for ( $i = $start; $i <= $end; $i++ ) {
if ( isset( $this->safe_tokens[ $this->tokens[ $i ]['code'] ] ) === false ) {
// Function call/variable or other token which makes it neigh impossible
// to determine whether the actual value would evaluate to false.
return false;
}
if ( isset( Tokens::$emptyTokens[ $this->tokens[ $i ]['code'] ] ) === true ) {
continue;
}
// Make sure that PHP 7.4 numeric literals and PHP 8.1 explicit octals don't cause problems.
if ( \T_LNUMBER === $this->tokens[ $i ]['code'] || \T_DNUMBER === $this->tokens[ $i ]['code'] ) {
$number_info = Numbers::getCompleteNumber( $this->phpcsFile, $i );
$code_string .= $number_info['decimal'];
$i = $number_info['last_token'];
continue;
}
$code_string .= $this->tokens[ $i ]['content'];
}
if ( '' === $code_string ) {
return false;
}
// Evaluate the argument to figure out the outcome is false or not.
// phpcs:ignore Squiz.PHP.Eval -- No harm here.
return ( false === eval( "return (bool) $code_string;" ) );
} | Determine if a range has a falsy value.
@param int $start The position to start looking from.
@param int $end The position to stop looking (inclusive).
@return bool True if the parameter is falsy.
False if the parameter is not falsy or when it
couldn't be reliably determined. | is_falsy | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/EnqueuedResourceParametersSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/EnqueuedResourceParametersSniff.php | MIT |
public function callback( $key, $val, $line, $group ) {
$stripped_val = TextStrings::stripQuotes( $val );
if ( '' === $stripped_val ) {
return false;
}
if ( $val !== $stripped_val ) {
// The value was a text string. For text strings, we only accept purely numeric values.
if ( preg_match( '`^[0-9]+$`', $stripped_val ) !== 1 ) {
// Not a purely numeric value, so any comparison would be a false comparison.
return false;
}
// Purely numeric string, treat it as an integer from here on out.
$val = $stripped_val;
}
$first_char = $val[0];
if ( '-' === $first_char || '+' === $first_char ) {
$val = ltrim( $val, '-+' );
} else {
$first_char = '';
}
$real_value = Numbers::getDecimalValue( $val );
if ( false === $real_value ) {
// This wasn't a purely numeric value, so any comparison would be a false comparison.
return false;
}
$val = $first_char . $real_value;
return ( (int) $val > (int) $this->posts_per_page );
} | Callback to process each confirmed key, to check value.
@param string $key Array index / key.
@param mixed $val Assigned value.
@param int $line Token line.
@param array $group Group definition.
@return bool FALSE if no match, TRUE if matches. | callback | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/PostsPerPageSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/PostsPerPageSniff.php | MIT |
public function getGroups() {
// Make sure all array keys are lowercase.
$this->deprecated_classes = array_change_key_case( $this->deprecated_classes, \CASE_LOWER );
return array(
'deprecated_classes' => array(
'classes' => array_keys( $this->deprecated_classes ),
),
);
} | Groups of classes to restrict.
@return array | getGroups | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/DeprecatedClassesSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/DeprecatedClassesSniff.php | MIT |
public function process_matched_token( $stackPtr, $group_name, $matched_content ) {
$this->set_minimum_wp_version();
$class_name = ltrim( strtolower( $matched_content ), '\\' );
$message = 'The %s class has been deprecated since WordPress version %s.';
$data = array(
ltrim( $matched_content, '\\' ),
$this->deprecated_classes[ $class_name ]['version'],
);
if ( ! empty( $this->deprecated_classes[ $class_name ]['alt'] ) ) {
$message .= ' Use %s instead.';
$data[] = $this->deprecated_classes[ $class_name ]['alt'];
}
MessageHelper::addMessage(
$this->phpcsFile,
$message,
$stackPtr,
( $this->wp_version_compare( $this->deprecated_classes[ $class_name ]['version'], $this->minimum_wp_version, '<' ) ),
MessageHelper::stringToErrorcode( $class_name . 'Found' ),
$data
);
} | Process a matched token.
@param int $stackPtr The position of the current token in the stack.
@param string $group_name The name of the group which was matched. Will
always be 'deprecated_classes'.
@param string $matched_content The token content (class name) which was matched
in its original case.
@return void | process_matched_token | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/DeprecatedClassesSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/DeprecatedClassesSniff.php | MIT |
public function getGroups() {
return array(
'curl' => array(
'type' => 'warning',
'message' => 'Using cURL functions is highly discouraged. Use wp_remote_get() instead.',
'since' => '2.7.0',
'functions' => array(
'curl_*',
),
'allow' => array(
'curl_version' => true,
),
),
'parse_url' => array(
'type' => 'warning',
'message' => '%s() is discouraged because of inconsistency in the output across PHP versions; use wp_parse_url() instead.',
'since' => '4.4.0',
'functions' => array(
'parse_url',
),
),
'json_encode' => array(
'type' => 'warning',
'message' => '%s() is discouraged. Use wp_json_encode() instead.',
'since' => '4.1.0',
'functions' => array(
'json_encode',
),
),
'file_get_contents' => array(
'type' => 'warning',
'message' => '%s() is discouraged. Use wp_remote_get() for remote URLs instead.',
'since' => '2.7.0',
'functions' => array(
'file_get_contents',
),
),
'unlink' => array(
'type' => 'warning',
'message' => '%s() is discouraged. Use wp_delete_file() to delete a file.',
'since' => '4.2.0',
'functions' => array(
'unlink',
),
),
'rename' => array(
'type' => 'warning',
'message' => '%s() is discouraged. Use WP_Filesystem::move() to rename a file.',
'since' => '2.5.0',
'functions' => array(
'rename',
),
),
'file_system_operations' => array(
'type' => 'warning',
'message' => 'File operations should use WP_Filesystem methods instead of direct PHP filesystem calls. Found: %s().',
'since' => '2.5.0',
'functions' => array(
'chgrp',
'chmod',
'chown',
'fclose',
'file_put_contents',
'fopen',
'fputs',
'fread',
'fsockopen',
'fwrite',
'is_writable',
'is_writeable',
'mkdir',
'pfsockopen',
'readfile',
'rmdir',
'touch',
),
),
'strip_tags' => array(
'type' => 'warning',
'message' => '%s() is discouraged. Use the more comprehensive wp_strip_all_tags() instead.',
'since' => '2.9.0',
'functions' => array(
'strip_tags',
),
),
'rand_seeding' => array(
'type' => 'warning',
'message' => '%s() is discouraged. Rand seeding is not necessary when using the wp_rand() function (as you should).',
'since' => '2.6.2',
'functions' => array(
'mt_srand',
'srand',
),
),
'rand' => array(
'type' => 'warning',
'message' => '%s() is discouraged. Use the far less predictable wp_rand() instead.',
'since' => '2.6.2',
'functions' => array(
'mt_rand',
'rand',
),
),
);
} | Groups of functions to restrict.
Example: groups => array(
'lambda' => array(
'type' => 'error' | 'warning',
'message' => 'Use anonymous functions instead please!',
'since' => '4.9.0', //=> the WP version in which the alternative became available.
'functions' => array( 'file_get_contents', 'create_function' ),
)
)
@return array | getGroups | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/AlternativeFunctionsSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/AlternativeFunctionsSniff.php | MIT |
protected function is_local_data_stream( $clean_param_value ) {
$stripped = TextStrings::stripQuotes( $clean_param_value );
if ( isset( $this->allowed_local_streams[ $stripped ] )
|| isset( $this->allowed_local_stream_constants[ $clean_param_value ] )
) {
return true;
}
foreach ( $this->allowed_local_stream_partials as $partial ) {
if ( strpos( $stripped, $partial ) === 0 ) {
return true;
}
}
return false;
} | Determine based on the "clean" parameter value, whether a file parameter points to
a local data stream.
@param string $clean_param_value Parameter value without comments.
@return bool True if this is a local data stream. False otherwise. | is_local_data_stream | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/AlternativeFunctionsSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/AlternativeFunctionsSniff.php | MIT |
public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) {
$condition = $this->target_functions[ $matched_content ]['condition'];
$recommended = $this->target_functions[ $matched_content ]['recommended'];
$meta_key = PassedParameters::getParameterFromStack( $parameters, $condition['position'], $condition['param_name'] );
if ( ! is_array( $meta_key ) ) {
return;
}
$single = PassedParameters::getParameterFromStack( $parameters, $recommended['position'], $recommended['param_name'] );
if ( is_array( $single ) ) {
$this->phpcsFile->recordMetric( $stackPtr, self::METRIC_NAME, 'yes' );
return;
}
$this->phpcsFile->recordMetric( $stackPtr, self::METRIC_NAME, 'no' );
$tokens = $this->phpcsFile->getTokens();
$message_data = array(
$condition['param_name'],
$tokens[ $stackPtr ]['content'],
$recommended['param_name'],
);
$this->phpcsFile->addWarning(
'When passing the $%s parameter to %s(), it is recommended to also pass the $%s parameter to explicitly indicate whether a single value or multiple values are expected to be returned.',
$stackPtr,
'Missing',
$message_data
);
} | Process the parameters of a matched function.
@since 3.2.0
@param int $stackPtr The position of the current token in the stack.
@param string $group_name The name of the group which was matched.
@param string $matched_content The token content (function name) which was matched
in lowercase.
@param array $parameters Array with information about the parameters.
@return void | process_parameters | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/GetMetaSingleSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/GetMetaSingleSniff.php | MIT |
protected function retrieve_misspellings( $match_stack ) {
$misspelled = array();
foreach ( $match_stack as $match ) {
// Deal with multi-dimensional arrays when capturing offset.
if ( \is_array( $match ) ) {
$match = $match[0];
}
if ( 'WordPress' !== $match ) {
$misspelled[] = $match;
}
}
return $misspelled;
} | Retrieve a list of misspellings based on an array of matched variations on the target word.
@param array $match_stack Array of matched variations of the target word.
@return array Array containing only the misspelled variants. | retrieve_misspellings | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/CapitalPDangitSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/CapitalPDangitSniff.php | MIT |
public function process_matched_token( $stackPtr, $group_name, $matched_content ) {
$matched_unqualified = ltrim( $matched_content, '\\' );
$matched_lowercase = strtolower( $matched_unqualified );
$matched_proper_case = $this->get_proper_case( $matched_lowercase );
if ( $matched_unqualified === $matched_proper_case ) {
// Already using proper case, nothing to do.
return;
}
$warning = 'It is strongly recommended to refer to classes by their properly cased name. Expected: %s Found: %s';
$data = array(
$matched_proper_case,
$matched_unqualified,
);
$this->phpcsFile->addWarning( $warning, $stackPtr, 'Incorrect', $data );
} | Process a matched token.
@since 3.0.0
@param int $stackPtr The position of the current token in the stack.
@param string $group_name The name of the group which was matched. Will
always be 'wp_classes'.
@param string $matched_content The token content (class name) which was matched.
in its original case.
@return void | process_matched_token | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/ClassNameCaseSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/ClassNameCaseSniff.php | MIT |
private function get_proper_case( $matched_lc ) {
foreach ( $this->class_groups as $name ) {
$current = $this->$name; // Needed to prevent issues with PHP < 7.0.
if ( isset( $current[ $matched_lc ] ) ) {
return $current[ $matched_lc ];
}
}
// Shouldn't be possible.
return ''; // @codeCoverageIgnore
} | Match a lowercase class name to its proper cased name.
@since 3.0.0
@param string $matched_lc Lowercase class name.
@return string | get_proper_case | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/ClassNameCaseSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/ClassNameCaseSniff.php | MIT |
public function process_token( $stackPtr ) {
// Reset defaults.
$this->text_domain_contains_default = false;
$this->text_domain_is_default = false;
// Allow overruling the text_domain set in a ruleset via the command line.
$cl_text_domain = Helper::getConfigData( 'text_domain' );
if ( ! empty( $cl_text_domain ) ) {
$cl_text_domain = trim( $cl_text_domain );
if ( '' !== $cl_text_domain ) {
$this->text_domain = array_filter( array_map( 'trim', explode( ',', $cl_text_domain ) ) );
}
}
$this->text_domain = RulesetPropertyHelper::merge_custom_array( $this->text_domain, array(), false );
if ( ! empty( $this->text_domain ) ) {
if ( \in_array( 'default', $this->text_domain, true ) ) {
$this->text_domain_contains_default = true;
if ( \count( $this->text_domain ) === 1 ) {
$this->text_domain_is_default = true;
}
}
}
// Prevent exclusion of the i18n group.
$this->exclude = array();
parent::process_token( $stackPtr );
} | Processes this test, when one of its tokens is encountered.
@since 1.0.0 Defers to the abstractFunctionRestriction sniff for determining
whether something is a function call. The logic after that has
been split off to the `process_matched_token()` method.
@param int $stackPtr The position of the current token in the stack.
@return void | process_token | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/I18nSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php | MIT |
public function process_matched_token( $stackPtr, $group_name, $matched_content ) {
$func_open_paren_token = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true );
if ( ! isset( $this->tokens[ $func_open_paren_token ]['parenthesis_closer'] ) ) {
// Live coding, parse error or not a function call.
return;
}
if ( 'typos' === $group_name && '_' === $matched_content ) {
$this->phpcsFile->addError(
'Found single-underscore "_()" function when double-underscore expected.',
$stackPtr,
'SingleUnderscoreGetTextFunction'
);
return;
}
if ( 'translate' === $matched_content || 'translate_with_gettext_context' === $matched_content ) {
$this->phpcsFile->addWarning(
'Use of the "%s()" function is reserved for low-level API usage.',
$stackPtr,
'LowLevelTranslationFunction',
array( $matched_content )
);
}
parent::process_matched_token( $stackPtr, $group_name, $matched_content );
} | Process a matched token.
@since 1.0.0 Logic split off from the `process_token()` method.
@param int $stackPtr The position of the current token in the stack.
@param string $group_name The name of the group which was matched.
@param string $matched_content The token content (function name) which was matched
in lowercase.
@return void | process_matched_token | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/I18nSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php | MIT |
private function check_argument_count( $stackPtr, $matched_content, $parameters, $expected_count ) {
$actual_count = count( $parameters );
if ( $actual_count > $expected_count ) {
$this->phpcsFile->addError(
'Too many parameters passed to function "%s()". Expected: %s parameters, received: %s',
$stackPtr,
'TooManyFunctionArgs',
array( $matched_content, $expected_count, $actual_count )
);
}
} | Verify that there are no superfluous function arguments.
@since 3.0.0 Check moved from the `process_matched_token()` method to this method.
@param int $stackPtr The position of the current token in the stack.
@param string $matched_content The token content (function name) which was matched
in lowercase.
@param array $parameters The parameters array.
@param int $expected_count The expected number of passed arguments.
@return void | check_argument_count | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/I18nSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php | MIT |
private function check_textdomain_matches( $matched_content, $param_name, $param_info ) {
$stripped_content = TextStrings::stripQuotes( $param_info['clean'] );
if ( empty( $this->text_domain ) && '' === $stripped_content ) {
$first_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $param_info['start'], ( $param_info['end'] + 1 ), true );
$this->phpcsFile->addError(
'The passed $domain should never be an empty string. Either pass a text domain or remove the parameter.',
$first_non_empty,
'EmptyTextDomain'
);
}
if ( empty( $this->text_domain ) ) {
// Nothing more to do, the other checks all depend on a text domain being known.
return;
}
if ( ! \in_array( $stripped_content, $this->text_domain, true ) ) {
$first_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $param_info['start'], ( $param_info['end'] + 1 ), true );
$this->phpcsFile->addError(
'Mismatched text domain. Expected \'%s\' but got %s.',
$first_non_empty,
'TextDomainMismatch',
array( implode( "' or '", $this->text_domain ), $param_info['clean'] )
);
return;
}
if ( true === $this->text_domain_is_default && 'default' === $stripped_content ) {
$fixable = false;
$error = 'No need to supply the text domain in function call to %s() when the only accepted text domain is "default".';
$error_code = 'SuperfluousDefaultTextDomain';
$data = array( $matched_content );
$first_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $param_info['start'], ( $param_info['end'] + 1 ), true );
// Prevent removing comments when auto-fixing.
$remove_from = ( $param_info['start'] - 1 );
$remove_to = $first_non_empty;
if ( isset( $param_info['name_token'] ) ) {
$remove_from = $this->phpcsFile->findPrevious( Tokens::$emptyTokens, ( $param_info['name_token'] - 1 ), null, true );
if ( \T_OPEN_PARENTHESIS === $this->tokens[ $remove_from ]['code'] ) {
++$remove_from; // Don't remove the open parenthesis.
/*
* Named param as first param in the function call, if we fix this, we need to
* remove the comma _after_ the parameter as well to prevent creating a parse error.
*/
$remove_to = $param_info['end'];
if ( \T_COMMA === $this->tokens[ ( $param_info['end'] + 1 ) ]['code'] ) {
++$remove_to; // Include the comma.
}
}
}
// Now, make sure there are no comments in the tokens we want to remove.
if ( $this->phpcsFile->findNext( Tokens::$commentTokens, $remove_from, ( $remove_to + 1 ) ) === false ) {
$fixable = true;
}
if ( false === $fixable ) {
$this->phpcsFile->addWarning( $error, $first_non_empty, $error_code, $data );
return;
}
$fix = $this->phpcsFile->addFixableWarning( $error, $first_non_empty, $error_code, $data );
if ( true === $fix ) {
$this->phpcsFile->fixer->beginChangeset();
for ( $i = $remove_from; $i <= $remove_to; $i++ ) {
$this->phpcsFile->fixer->replaceToken( $i, '' );
}
$this->phpcsFile->fixer->endChangeset();
}
}
} | Check the correct text domain is being used.
@since 3.0.0 The logic in this method used to be contained in the, now removed, `check_argument_tokens()` method.
@param string $matched_content The token content (function name) which was matched
in lowercase.
@param string $param_name The name of the parameter being examined.
@param array|false $param_info Parameter info array for an individual parameter,
as received from the PassedParameters class.
@return void | check_textdomain_matches | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/I18nSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php | MIT |
private function check_placeholders_in_string( $matched_content, $param_name, $param_info ) {
$content = $param_info['clean'];
// UnorderedPlaceholders: Check for multiple unordered placeholders.
$unordered_matches_count = preg_match_all( self::UNORDERED_SPRINTF_PLACEHOLDER_REGEX, $content, $unordered_matches );
$unordered_matches = $unordered_matches[0];
$all_matches_count = preg_match_all( self::SPRINTF_PLACEHOLDER_REGEX, $content, $all_matches );
if ( $unordered_matches_count > 0
&& $unordered_matches_count !== $all_matches_count
&& $all_matches_count > 1
) {
$first_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $param_info['start'], ( $param_info['end'] + 1 ), true );
$error_code = MessageHelper::stringToErrorcode( 'MixedOrderedPlaceholders' . ucfirst( $param_name ) );
$this->phpcsFile->addError(
'Multiple placeholders in translatable strings should be ordered. Mix of ordered and non-ordered placeholders found. Found: "%s" in %s.',
$first_non_empty,
$error_code,
array( implode( ', ', $all_matches[0] ), $param_info['clean'] )
);
return;
}
if ( $unordered_matches_count >= 2 ) {
$first_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $param_info['start'], ( $param_info['end'] + 1 ), true );
$error_code = MessageHelper::stringToErrorcode( 'UnorderedPlaceholders' . ucfirst( $param_name ) );
$suggestions = array();
$replace_regexes = array();
$replacements = array();
for ( $i = 0; $i < $unordered_matches_count; $i++ ) {
$to_insert = ( $i + 1 );
$to_insert .= ( '"' !== $content[0] ) ? '$' : '\$';
$suggestions[ $i ] = substr_replace( $unordered_matches[ $i ], $to_insert, 1, 0 );
// Prepare the strings for use in a regex.
$replace_regexes[ $i ] = '`\Q' . $unordered_matches[ $i ] . '\E`';
// Note: the initial \\ is a literal \, the four \ in the replacement translate also to a literal \.
$replacements[ $i ] = str_replace( '\\', '\\\\', $suggestions[ $i ] );
// Note: the $ needs escaping to prevent numeric sequences after the $ being interpreted as match replacements.
$replacements[ $i ] = str_replace( '$', '\\$', $replacements[ $i ] );
}
$fix = $this->phpcsFile->addFixableError(
'Multiple placeholders in translatable strings should be ordered. Expected "%s", but got "%s" in %s.',
$first_non_empty,
$error_code,
array( implode( ', ', $suggestions ), implode( ', ', $unordered_matches ), $param_info['clean'] )
);
if ( true === $fix ) {
$this->phpcsFile->fixer->beginChangeset();
$fixed_str = preg_replace( $replace_regexes, $replacements, $content, 1 );
$this->phpcsFile->fixer->replaceToken( $first_non_empty, $fixed_str );
$i = ( $first_non_empty + 1 );
while ( $i <= $param_info['end'] && isset( Tokens::$stringTokens[ $this->tokens[ $i ]['code'] ] ) ) {
$this->phpcsFile->fixer->replaceToken( $i, '' );
++$i;
}
$this->phpcsFile->fixer->endChangeset();
}
}
} | Check the placeholders used in translatable text for common problems.
@since 3.0.0 The logic in this method used to be contained in the, now removed, `check_text()` method.
@param string $matched_content The token content (function name) which was matched
in lowercase.
@param string $param_name The name of the parameter being examined.
@param array|false $param_info Parameter info array for an individual parameter,
as received from the PassedParameters class.
@return void | check_placeholders_in_string | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/I18nSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php | MIT |
private function check_string_has_translatable_content( $matched_content, $param_name, $param_info ) {
// Strip placeholders and surrounding quotes.
$content_without_quotes = trim( TextStrings::stripQuotes( $param_info['clean'] ) );
$non_placeholder_content = preg_replace( self::SPRINTF_PLACEHOLDER_REGEX, '', $content_without_quotes );
if ( '' === $non_placeholder_content ) {
$first_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $param_info['start'], ( $param_info['end'] + 1 ), true );
$this->phpcsFile->addError(
'The $%s text string should have translatable content. Found: %s',
$first_non_empty,
'NoEmptyStrings',
array( $param_name, $param_info['clean'] )
);
return false;
}
return true;
} | Check if a parameter which is supposed to hold translatable text actually has translatable text.
@since 3.0.0 The logic in this method used to be contained in the, now removed, `check_text()` method.
@param string $matched_content The token content (function name) which was matched
in lowercase.
@param string $param_name The name of the parameter being examined.
@param array|false $param_info Parameter info array for an individual parameter,
as received from the PassedParameters class.
@return bool Whether or not the text string has translatable content. | check_string_has_translatable_content | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/I18nSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php | MIT |
private function check_string_has_no_html_wrapper( $matched_content, $param_name, $param_info ) {
// Strip surrounding quotes.
$content_without_quotes = trim( TextStrings::stripQuotes( $param_info['clean'] ) );
$reader = new XMLReader();
$reader->XML( $content_without_quotes, 'UTF-8', \LIBXML_NOERROR | \LIBXML_ERR_NONE | \LIBXML_NOWARNING );
// Is the first node an HTML element?
if ( ! $reader->read() || XMLReader::ELEMENT !== $reader->nodeType ) {
return;
}
// If the opening HTML element includes placeholders in its attributes, we don't warn.
// E.g. '<option id="%1$s" value="%2$s">Translatable option name</option>'.
$i = 0;
while ( $attr = $reader->getAttributeNo( $i ) ) {
if ( preg_match( self::SPRINTF_PLACEHOLDER_REGEX, $attr ) === 1 ) {
return;
}
++$i;
}
// We don't flag strings wrapped in `<a href="...">...</a>`, as the link target might actually need localization.
if ( 'a' === $reader->name && $reader->getAttribute( 'href' ) ) {
return;
}
// Does the entire string only consist of this HTML node?
if ( $reader->readOuterXml() === $content_without_quotes ) {
$first_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $param_info['start'], ( $param_info['end'] + 1 ), true );
$this->phpcsFile->addWarning(
'Translatable string should not be wrapped in HTML. Found: %s',
$first_non_empty,
'NoHtmlWrappedStrings',
array( $param_info['clean'] )
);
}
} | Ensure that a translatable text string is not wrapped in HTML code.
If the text is wrapped in HTML, the HTML should be moved out of the translatable text string.
@since 3.0.0 The logic in this method used to be contained in the, now removed, `check_text()` method.
@param string $matched_content The token content (function name) which was matched
in lowercase.
@param string $param_name The name of the parameter being examined.
@param array|false $param_info Parameter info array for an individual parameter,
as received from the PassedParameters class.
@return void | check_string_has_no_html_wrapper | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/I18nSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php | MIT |
private function compare_single_and_plural_arguments( $stackPtr, $param_info_single, $param_info_plural ) {
$single_content = $param_info_single['clean'];
$plural_content = $param_info_plural['clean'];
preg_match_all( self::SPRINTF_PLACEHOLDER_REGEX, $single_content, $single_placeholders );
$single_placeholders = $single_placeholders[0];
preg_match_all( self::SPRINTF_PLACEHOLDER_REGEX, $plural_content, $plural_placeholders );
$plural_placeholders = $plural_placeholders[0];
// English conflates "singular" with "only one", described in the codex:
// https://codex.wordpress.org/I18n_for_WordPress_Developers#Plurals .
if ( \count( $single_placeholders ) < \count( $plural_placeholders ) ) {
$error_string = 'Missing singular placeholder, needed for some languages. See https://codex.wordpress.org/I18n_for_WordPress_Developers#Plurals';
$first_non_empty_single = $this->phpcsFile->findNext( Tokens::$emptyTokens, $param_info_single['start'], ( $param_info_single['end'] + 1 ), true );
$this->phpcsFile->addError( $error_string, $first_non_empty_single, 'MissingSingularPlaceholder' );
return;
}
// Reordering is fine, but mismatched placeholders is probably wrong.
sort( $single_placeholders, \SORT_NATURAL );
sort( $plural_placeholders, \SORT_NATURAL );
if ( $single_placeholders !== $plural_placeholders ) {
$this->phpcsFile->addWarning( 'Mismatched placeholders is probably an error', $stackPtr, 'MismatchedPlaceholders' );
}
} | Check for inconsistencies in the placeholders between single and plural form of the translatable text string.
@since 3.0.0 - The parameter names and expected format for the $param_info_single
and the $param_info_plural parameters has changed.
- The method visibility has been changed from `protected` to `private`.
@param int $stackPtr The position of the function call token in the stack.
@param array $param_info_single Parameter info array for the `$single` parameter,
as received from the PassedParameters class.
@param array $param_info_plural Parameter info array for the `$plural` parameter,
as received from the PassedParameters class.
@return void | compare_single_and_plural_arguments | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/I18nSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php | MIT |
private function check_for_translator_comment( $stackPtr, $matched_content, $parameters ) {
$needs_translators_comment = false;
foreach ( $parameters as $param_name => $param_info ) {
if ( false === \in_array( $param_name, array( 'text', 'single', 'singular', 'plural' ), true ) ) {
continue;
}
if ( false === $param_info || false === $param_info['is_string_literal'] ) {
continue;
}
if ( preg_match( self::SPRINTF_PLACEHOLDER_REGEX, $param_info['clean'] ) === 1 ) {
$needs_translators_comment = true;
break;
}
}
if ( false === $needs_translators_comment ) {
// No text string with placeholders found, no translation comment needed.
return;
}
$previous_comment = $this->phpcsFile->findPrevious( Tokens::$commentTokens, ( $stackPtr - 1 ) );
if ( false !== $previous_comment ) {
/*
* Check that the comment is either on the line before the gettext call or
* if it's not, that there is only whitespace between.
*/
$correctly_placed = false;
if ( ( $this->tokens[ $previous_comment ]['line'] + 1 ) === $this->tokens[ $stackPtr ]['line'] ) {
$correctly_placed = true;
} else {
$next_non_whitespace = $this->phpcsFile->findNext( \T_WHITESPACE, ( $previous_comment + 1 ), $stackPtr, true );
if ( false === $next_non_whitespace || $this->tokens[ $next_non_whitespace ]['line'] === $this->tokens[ $stackPtr ]['line'] ) {
// No non-whitespace found or next non-whitespace is on same line as gettext call.
$correctly_placed = true;
}
unset( $next_non_whitespace );
}
/*
* Check that the comment starts with 'translators:'.
*/
if ( true === $correctly_placed ) {
if ( \T_COMMENT === $this->tokens[ $previous_comment ]['code'] ) {
$comment_text = trim( $this->tokens[ $previous_comment ]['content'] );
// If it's multi-line /* */ comment, collect all the parts.
if ( '*/' === substr( $comment_text, -2 ) && '/*' !== substr( $comment_text, 0, 2 ) ) {
for ( $i = ( $previous_comment - 1 ); 0 <= $i; $i-- ) {
if ( \T_COMMENT !== $this->tokens[ $i ]['code'] ) {
break;
}
$comment_text = trim( $this->tokens[ $i ]['content'] ) . $comment_text;
}
}
if ( true === $this->is_translators_comment( $comment_text ) ) {
// Comment is ok.
return;
}
}
if ( \T_DOC_COMMENT_CLOSE_TAG === $this->tokens[ $previous_comment ]['code'] ) {
// If it's docblock comment (wrong style) make sure that it's a translators comment.
if ( isset( $this->tokens[ $previous_comment ]['comment_opener'] ) ) {
$db_start = $this->tokens[ $previous_comment ]['comment_opener'];
} else {
$db_start = $this->phpcsFile->findPrevious( \T_DOC_COMMENT_OPEN_TAG, ( $previous_comment - 1 ) );
}
$db_first_text = $this->phpcsFile->findNext( \T_DOC_COMMENT_STRING, ( $db_start + 1 ), $previous_comment );
if ( true === $this->is_translators_comment( $this->tokens[ $db_first_text ]['content'] ) ) {
$this->phpcsFile->addWarning(
'A "translators:" comment must be a "/* */" style comment. Docblock comments will not be picked up by the tools to generate a ".pot" file.',
$stackPtr,
'TranslatorsCommentWrongStyle'
);
return;
}
}
}
}
// Found placeholders but no translators comment.
$this->phpcsFile->addWarning(
'A function call to %s() with texts containing placeholders was found, but was not accompanied by a "translators:" comment on the line above to clarify the meaning of the placeholders.',
$stackPtr,
'MissingTranslatorsComment',
array( $matched_content )
);
} | Check for the presence of a translators comment if one of the text strings contains a placeholder.
@since 3.0.0 - The parameter names and expected format for the $parameters parameter has changed.
- The method visibility has been changed from `protected` to `private`.
@param int $stackPtr The position of the gettext call token in the stack.
@param string $matched_content The token content (function name) which was matched
in lowercase.
@param array $parameters Array with information about the parameters.
@return void | check_for_translator_comment | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/I18nSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php | MIT |
private function is_translators_comment( $content ) {
if ( preg_match( '`^(?:(?://|/\*{1,2}) )?translators:`i', $content ) === 1 ) {
return true;
}
return false;
} | Check if a (collated) comment string starts with 'translators:'.
@since 0.11.0
@param string $content Comment string content.
@return bool | is_translators_comment | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/I18nSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php | MIT |
public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) {
$function_details = $this->target_functions[ $matched_content ];
$parameter = PassedParameters::getParameterFromStack(
$parameters,
$function_details['position'],
$function_details['name']
);
if ( false === $parameter ) {
return;
}
// If the parameter is anything other than T_CONSTANT_ENCAPSED_STRING throw a warning and bow out.
$first_non_empty = null;
for ( $i = $parameter['start']; $i <= $parameter['end']; $i++ ) {
if ( isset( Tokens::$emptyTokens[ $this->tokens[ $i ]['code'] ] ) ) {
continue;
}
if ( \T_CONSTANT_ENCAPSED_STRING !== $this->tokens[ $i ]['code']
|| null !== $first_non_empty
) {
// Throw warning at low severity.
$this->phpcsFile->addWarning(
'Couldn\'t determine the value passed to the $%s parameter in function call to %s(). Please check if it matches a valid capability. Found: %s',
$i,
'Undetermined',
array(
$function_details['name'],
$matched_content,
$parameter['clean'],
),
3 // Message severity set to below default.
);
return;
}
$first_non_empty = $i;
}
if ( null === $first_non_empty ) {
// Parse error. Bow out.
return;
}
/*
* As of this point we know that the `$capabilities` parameter only contains the one token
* and that that token is a `T_CONSTANT_ENCAPSED_STRING`.
*/
$matched_parameter = TextStrings::stripQuotes( $this->tokens[ $first_non_empty ]['content'] );
if ( isset( $this->core_capabilities[ $matched_parameter ] ) ) {
return;
}
if ( empty( $matched_parameter ) ) {
$this->phpcsFile->addError(
'An empty string is not a valid capability. Empty string found as the $%s parameter in a function call to %s()"',
$first_non_empty,
'Invalid',
array(
$function_details['name'],
$matched_content,
)
);
return;
}
// Check if additional capabilities were registered via the ruleset and if the found capability matches any of those.
$custom_capabilities = RulesetPropertyHelper::merge_custom_array( $this->custom_capabilities, array() );
if ( isset( $custom_capabilities[ $matched_parameter ] ) ) {
return;
}
if ( isset( $this->deprecated_capabilities[ $matched_parameter ] ) ) {
$this->set_minimum_wp_version();
$is_error = $this->wp_version_compare( $this->deprecated_capabilities[ $matched_parameter ], $this->minimum_wp_version, '<' );
$data = array(
$matched_parameter,
$matched_content,
$this->deprecated_capabilities[ $matched_parameter ],
);
MessageHelper::addMessage(
$this->phpcsFile,
'The capability "%s", found in the function call to %s(), has been deprecated since WordPress version %s.',
$first_non_empty,
$is_error,
'Deprecated',
$data
);
return;
}
if ( isset( $this->core_roles[ $matched_parameter ] ) ) {
$this->phpcsFile->addError(
'Capabilities should be used instead of roles. Found "%s" in function call to %s()',
$first_non_empty,
'RoleFound',
array(
$matched_parameter,
$matched_content,
)
);
return;
}
$this->phpcsFile->addWarning(
'Found unknown capability "%s" in function call to %s(). Please check the spelling of the capability. If this is a custom capability, please verify the capability is registered with WordPress via a call to WP_Role(s)->add_cap().' . \PHP_EOL . 'Custom capabilities can be made known to this sniff by setting the "custom_capabilities" property in the PHPCS ruleset.',
$first_non_empty,
'Unknown',
array(
$matched_parameter,
$matched_content,
)
);
} | Process the parameters of a matched function.
@since 3.0.0
@param int $stackPtr The position of the current token in the stack.
@param string $group_name The name of the group which was matched.
@param string $matched_content The token content (function name) which was matched
in lowercase.
@param array $parameters Array with information about the parameters.
@return void | process_parameters | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/CapabilitiesSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/CapabilitiesSniff.php | MIT |
private function find_function_by_name( $functionName ) {
$functionPtr = false;
for ( $ptr = 0; $ptr < $this->phpcsFile->numTokens; $ptr++ ) {
if ( \T_FUNCTION === $this->tokens[ $ptr ]['code'] ) {
$foundName = FunctionDeclarations::getName( $this->phpcsFile, $ptr );
if ( $foundName === $functionName ) {
$functionPtr = $ptr;
break;
} elseif ( isset( $this->tokens[ $ptr ]['scope_closer'] ) ) {
// Skip to the end of the function definition.
$ptr = $this->tokens[ $ptr ]['scope_closer'];
}
}
}
return $functionPtr;
} | Find a declared function in a file based on the function name.
@param string $functionName The name of the function to find.
@return int|false Integer stack pointer to the function keyword token or
false if not found. | find_function_by_name | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/CronIntervalSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/CronIntervalSniff.php | MIT |
public function confused( $stackPtr ) {
$this->phpcsFile->addWarning(
'Detected changing of cron_schedules, but could not detect the interval value.',
$stackPtr,
'ChangeDetected'
);
} | Add warning about unclear cron schedule change.
@param int $stackPtr The position of the current token in the stack.
@return void | confused | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/CronIntervalSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/CronIntervalSniff.php | MIT |
public function process_matched_token( $stackPtr, $group_name, $matched_content ) {
$this->set_minimum_wp_version();
$message = '%s() has been deprecated since WordPress version %s.';
$data = array(
$this->tokens[ $stackPtr ]['content'],
$this->deprecated_functions[ $matched_content ]['version'],
);
if ( ! empty( $this->deprecated_functions[ $matched_content ]['alt'] ) ) {
$message .= ' Use %s instead.';
$data[] = $this->deprecated_functions[ $matched_content ]['alt'];
}
MessageHelper::addMessage(
$this->phpcsFile,
$message,
$stackPtr,
( $this->wp_version_compare( $this->deprecated_functions[ $matched_content ]['version'], $this->minimum_wp_version, '<' ) ),
MessageHelper::stringToErrorcode( $matched_content . 'Found' ),
$data
);
} | Process a matched token.
@param int $stackPtr The position of the current token in the stack.
@param string $group_name The name of the group which was matched. Will
always be 'deprecated_functions'.
@param string $matched_content The token content (function name) which was matched
in lowercase.
@return void | process_matched_token | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/DeprecatedFunctionsSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/DeprecatedFunctionsSniff.php | MIT |
protected function process_parameter( $matched_content, $parameter, $parameter_args ) {
$parameter_position = $this->phpcsFile->findNext(
Tokens::$emptyTokens,
$parameter['start'],
$parameter['end'] + 1,
true
);
if ( false === $parameter_position ) {
return;
}
$matched_parameter = TextStrings::stripQuotes( $this->tokens[ $parameter_position ]['content'] );
if ( ! isset( $parameter_args[ $matched_parameter ] ) ) {
return;
}
$message = 'The parameter value "%s" has been deprecated since WordPress version %s.';
$data = array(
$matched_parameter,
$parameter_args[ $matched_parameter ]['version'],
);
if ( ! empty( $parameter_args[ $matched_parameter ]['alt'] ) ) {
$message .= ' Use %s instead.';
$data[] = $parameter_args[ $matched_parameter ]['alt'];
}
$is_error = $this->wp_version_compare( $parameter_args[ $matched_parameter ]['version'], $this->minimum_wp_version, '<' );
MessageHelper::addMessage(
$this->phpcsFile,
$message,
$parameter_position,
$is_error,
'Found',
$data
);
} | Process the parameter of a matched function.
@since 1.0.0
@param string $matched_content The token content (function name) which was matched
in lowercase.
@param array $parameter Array with start and end token position of the parameter.
@param array $parameter_args Array with alternative and WordPress deprecation version of the parameter.
@return void | process_parameter | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/DeprecatedParameterValuesSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/DeprecatedParameterValuesSniff.php | MIT |
public function process_arbitrary_tstring( $stackPtr ) {
$content = $this->tokens[ $stackPtr ]['content'];
if ( ! isset( $this->discouraged_constants[ $content ] ) ) {
return;
}
if ( ConstantsHelper::is_use_of_global_constant( $this->phpcsFile, $stackPtr ) === false ) {
return;
}
$this->phpcsFile->addWarning(
'Found usage of constant "%s". Use %s instead.',
$stackPtr,
MessageHelper::stringToErrorcode( $content . 'UsageFound' ),
array(
$content,
$this->discouraged_constants[ $content ],
)
);
} | Process an arbitrary T_STRING token to determine whether it is one of the target constants.
@since 0.14.0
@param int $stackPtr The position of the current token in the stack.
@return void | process_arbitrary_tstring | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/DiscouragedConstantsSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/DiscouragedConstantsSniff.php | MIT |
public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) {
$target_param = $this->target_functions[ $matched_content ];
// Was the target parameter passed ?
$found_param = PassedParameters::getParameterFromStack( $parameters, $target_param['position'], $target_param['name'] );
if ( false === $found_param ) {
return;
}
$clean_content = TextStrings::stripQuotes( $found_param['clean'] );
if ( isset( $this->discouraged_constants[ $clean_content ] ) ) {
$first_non_empty = $this->phpcsFile->findNext(
Tokens::$emptyTokens,
$found_param['start'],
( $found_param['end'] + 1 ),
true
);
$this->phpcsFile->addWarning(
'Found declaration of constant "%s". Use %s instead.',
$first_non_empty,
MessageHelper::stringToErrorcode( $clean_content . 'DeclarationFound' ),
array(
$clean_content,
$this->discouraged_constants[ $clean_content ],
)
);
}
} | Process the parameters of a matched `define` function call.
@since 0.14.0
@param int $stackPtr The position of the current token in the stack.
@param string $group_name The name of the group which was matched.
@param string $matched_content The token content (function name) which was matched
in lowercase.
@param array $parameters Array with information about the parameters.
@return void | process_parameters | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/DiscouragedConstantsSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/DiscouragedConstantsSniff.php | MIT |
public function register() {
$targets = array(
\T_GLOBAL,
\T_VARIABLE,
);
$targets += Collections::listOpenTokensBC();
// Only used to skip over test classes.
$targets += Tokens::$ooScopeTokens;
return $targets;
} | Returns an array of tokens this test wants to listen for.
@since 0.3.0
@since 1.1.0 Added class tokens for improved test classes skipping.
@return array | register | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/GlobalVariablesOverrideSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/GlobalVariablesOverrideSniff.php | MIT |
protected function process_variable_assignment( $stackPtr, $in_list = false ) {
$token = $this->tokens[ $stackPtr ];
$var_name = substr( $token['content'], 1 ); // Strip the dollar sign.
$data = array();
// Determine the variable name for `$GLOBALS['array_key']`.
if ( 'GLOBALS' === $var_name ) {
$bracketPtr = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true );
if ( false === $bracketPtr
|| \T_OPEN_SQUARE_BRACKET !== $this->tokens[ $bracketPtr ]['code']
|| ! isset( $this->tokens[ $bracketPtr ]['bracket_closer'] )
) {
return;
}
// Retrieve the array key and avoid getting tripped up by some simple obfuscation.
$var_name = '';
$start = ( $bracketPtr + 1 );
for ( $ptr = $start; $ptr < $this->tokens[ $bracketPtr ]['bracket_closer']; $ptr++ ) {
/*
* If the globals array key contains a variable, constant, function call
* or interpolated variable, bow out.
*/
if ( \T_VARIABLE === $this->tokens[ $ptr ]['code']
|| \T_STRING === $this->tokens[ $ptr ]['code']
|| \T_DOUBLE_QUOTED_STRING === $this->tokens[ $ptr ]['code']
) {
return;
}
if ( \T_CONSTANT_ENCAPSED_STRING === $this->tokens[ $ptr ]['code'] ) {
$var_name .= TextStrings::stripQuotes( $this->tokens[ $ptr ]['content'] );
}
}
if ( '' === $var_name ) {
// Shouldn't happen, but just in case.
return;
}
// Set up the data for the error message.
$data[] = '$GLOBALS[\'' . $var_name . '\']';
}
/*
* Is this one of the WP global variables ?
*/
if ( WPGlobalVariablesHelper::is_wp_global( $var_name ) === false ) {
return;
}
/*
* Is this one of the WP global variables which are allowed to be overwritten ?
*/
if ( isset( $this->override_allowed[ $var_name ] ) === true ) {
return;
}
/*
* Check if the variable value is being changed.
*/
if ( false === $in_list
&& false === VariableHelper::is_assignment( $this->phpcsFile, $stackPtr )
&& Context::inForeachCondition( $this->phpcsFile, $stackPtr ) !== 'afterAs'
) {
return;
}
/*
* Function parameters with the same name as a WP global variable are fine,
* including when they are being assigned a default value.
*/
if ( false === $in_list ) {
$functionPtr = Parentheses::getLastOwner( $this->phpcsFile, $stackPtr, Collections::functionDeclarationTokens() );
if ( false !== $functionPtr ) {
return;
}
unset( $functionPtr );
}
/*
* Class property declarations with the same name as WP global variables are fine.
*/
if ( false === $in_list && true === Scopes::isOOProperty( $this->phpcsFile, $stackPtr ) ) {
return;
}
// Still here ? In that case, the WP global variable is being tampered with.
$this->add_error( $stackPtr, $data );
} | Check that defined global variables are prefixed.
@since 1.1.0 Logic was previously contained in the process_token() method.
@param int $stackPtr The position of the current token in the stack.
@param bool $in_list Whether or not this is a variable in a list assignment.
Defaults to false.
@return void | process_variable_assignment | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/GlobalVariablesOverrideSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/GlobalVariablesOverrideSniff.php | MIT |
protected function process_global_statement( $stackPtr, $in_function_scope ) {
/*
* Collect the variables to watch for.
*/
$search = array();
$ptr = ( $stackPtr + 1 );
$end_of_statement = $this->phpcsFile->findNext( array( \T_SEMICOLON, \T_CLOSE_TAG ), $ptr );
while ( isset( $this->tokens[ $ptr ] ) && $ptr < $end_of_statement ) {
if ( \T_VARIABLE === $this->tokens[ $ptr ]['code'] ) {
$var_name = substr( $this->tokens[ $ptr ]['content'], 1 );
if ( WPGlobalVariablesHelper::is_wp_global( $var_name )
&& isset( $this->override_allowed[ $var_name ] ) === false
) {
$search[ $this->tokens[ $ptr ]['content'] ] = true;
}
}
++$ptr;
}
if ( empty( $search ) ) {
return;
}
/*
* Search for assignments to the imported global variables within the relevant scope.
*/
$start = $ptr;
if ( true === $in_function_scope ) {
$functionPtr = Conditions::getLastCondition( $this->phpcsFile, $stackPtr, Collections::functionDeclarationTokens() );
if ( isset( $this->tokens[ $functionPtr ]['scope_closer'] ) === false ) {
// Live coding or parse error.
return;
}
$end = $this->tokens[ $functionPtr ]['scope_closer'];
} else {
// Global statement in the global namespace in a file which is being treated as scoped.
$end = $this->phpcsFile->numTokens;
}
for ( $ptr = $start; $ptr < $end; $ptr++ ) {
// Skip over nested functions, classes and the likes.
if ( isset( Collections::closedScopes()[ $this->tokens[ $ptr ]['code'] ] ) ) {
if ( ! isset( $this->tokens[ $ptr ]['scope_closer'] ) ) {
// Live coding or parse error.
break;
}
$ptr = $this->tokens[ $ptr ]['scope_closer'];
continue;
}
// Make sure to recognize assignments to variables in a list construct.
if ( isset( Collections::listOpenTokensBC()[ $this->tokens[ $ptr ]['code'] ] ) ) {
$list_open_close = Lists::getOpenClose( $this->phpcsFile, $ptr );
if ( false === $list_open_close ) {
// Short array, not short list.
continue;
}
$var_pointers = ListHelper::get_list_variables( $this->phpcsFile, $ptr );
foreach ( $var_pointers as $ptr ) {
$var_name = $this->tokens[ $ptr ]['content'];
if ( '$GLOBALS' === $var_name ) {
$var_name = '$' . TextStrings::stripQuotes( VariableHelper::get_array_access_key( $this->phpcsFile, $ptr ) );
}
if ( isset( $search[ $var_name ] ) ) {
$this->process_variable_assignment( $ptr, true );
}
}
// No need to re-examine these variables.
$ptr = $list_open_close['closer'];
continue;
}
if ( \T_VARIABLE !== $this->tokens[ $ptr ]['code'] ) {
continue;
}
if ( isset( $search[ $this->tokens[ $ptr ]['content'] ] ) === false ) {
// Not one of the variables we're interested in.
continue;
}
// Don't throw false positives for static class properties.
if ( ContextHelper::has_object_operator_before( $this->phpcsFile, $ptr ) === true ) {
continue;
}
if ( true === VariableHelper::is_assignment( $this->phpcsFile, $ptr ) ) {
$this->add_error( $ptr );
continue;
}
// Check if this is a variable assignment within a `foreach()` declaration.
if ( Context::inForeachCondition( $this->phpcsFile, $ptr ) === 'afterAs' ) {
$this->add_error( $ptr );
}
}
} | Check that global variables imported into a function scope using a global statement
are not being overruled.
@since 1.1.0 Logic was previously contained in the process_token() method.
@param int $stackPtr The position of the current token in the stack.
@param bool $in_function_scope Whether the global statement is within a scoped function/closure.
@return void | process_global_statement | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/WP/GlobalVariablesOverrideSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/GlobalVariablesOverrideSniff.php | MIT |
public function add_unslash_error( File $phpcsFile, $stackPtr ) {
$tokens = $phpcsFile->getTokens();
$var_name = $tokens[ $stackPtr ]['content'];
if ( isset( $this->slashed_superglobals[ $var_name ] ) === false ) {
// WP doesn't slash these, so they don't need unslashing.
return;
}
// We know there will be array keys as that's checked in the process_token() method.
$array_keys = VariableHelper::get_array_access_keys( $phpcsFile, $stackPtr );
$error_data = array( $var_name . '[' . implode( '][', $array_keys ) . ']' );
$phpcsFile->addError(
'%s not unslashed before sanitization. Use wp_unslash() or similar',
$stackPtr,
'MissingUnslash',
$error_data
);
} | Add an error for missing use of unslashing.
@since 0.5.0
@since 3.0.0 - Moved from the `Sniff` class to this class.
- The `$phpcsFile` parameter was added.
@param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
@param int $stackPtr The index of the token in the stack
which is missing unslashing.
@return void | add_unslash_error | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/Security/ValidatedSanitizedInputSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/ValidatedSanitizedInputSniff.php | MIT |
protected function needs_nonce_check( $stackPtr, array $cache_keys ) {
$in_nonce_check = ContextHelper::is_in_function_call( $this->phpcsFile, $stackPtr, $this->nonceVerificationFunctions );
if ( false !== $in_nonce_check ) {
// This *is* the nonce check, so bow out, but do store to cache.
// @todo Change to use arg unpacking once PHP < 5.6 has been dropped.
$this->set_cache( $cache_keys['file'], $cache_keys['start'], $cache_keys['end'], $in_nonce_check );
return false;
}
if ( Context::inUnset( $this->phpcsFile, $stackPtr ) ) {
// Variable is only being unset, no nonce check needed.
return false;
}
if ( VariableHelper::is_assignment( $this->phpcsFile, $stackPtr, false ) ) {
// Overwriting the value of a superglobal.
return false;
}
$needs_nonce = 'before';
if ( ContextHelper::is_in_isset_or_empty( $this->phpcsFile, $stackPtr )
|| ContextHelper::is_in_type_test( $this->phpcsFile, $stackPtr )
|| VariableHelper::is_comparison( $this->phpcsFile, $stackPtr )
|| VariableHelper::is_assignment( $this->phpcsFile, $stackPtr, true )
|| ContextHelper::is_in_array_comparison( $this->phpcsFile, $stackPtr )
|| ContextHelper::is_in_function_call( $this->phpcsFile, $stackPtr, UnslashingFunctionsHelper::get_functions() ) !== false
|| $this->is_only_sanitized( $this->phpcsFile, $stackPtr )
) {
$needs_nonce = 'after';
}
return $needs_nonce;
} | Determine whether or not a nonce check is needed for the current superglobal.
@since 3.0.0
@param int $stackPtr The position of the current token in the stack of tokens.
@param array $cache_keys The keys for the applicable cache (to potentially set).
@return string|false String "before" or "after" if a nonce check is needed.
FALSE when no nonce check is needed. | needs_nonce_check | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/Security/NonceVerificationSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/NonceVerificationSniff.php | MIT |
private function has_nonce_check( $stackPtr, array $cache_keys, $allow_nonce_after = false ) {
$start = $cache_keys['start'];
$end = $cache_keys['end'];
// We allow for certain actions, such as an isset() check to come before the nonce check.
// If this superglobal is inside such a check, look for the nonce after it as well,
// all the way to the end of the scope.
if ( true === $allow_nonce_after ) {
$end = ( 0 === $start ) ? $this->phpcsFile->numTokens : $this->tokens[ $start ]['scope_closer'];
}
// Check against the cache.
$current_cache = $this->get_cache( $cache_keys['file'], $start );
if ( false !== $current_cache['nonce'] ) {
// If we have already found a nonce check in this scope, we just
// need to check whether it comes before this token. It is OK if the
// check is after the token though, if this was only an isset() check.
return ( true === $allow_nonce_after || $current_cache['nonce'] < $stackPtr );
} elseif ( $end <= $current_cache['end'] ) {
// If not, we can still go ahead and return false if we've already
// checked to the end of the search area.
return false;
}
$search_start = $start;
if ( $current_cache['end'] > $start ) {
// We haven't checked this far yet, but we can still save work by
// skipping over the part we've already checked.
$search_start = $this->cached_results['cache'][ $start ]['end'];
}
// Loop through the tokens looking for nonce verification functions.
for ( $i = $search_start; $i < $end; $i++ ) {
// Skip over nested closed scope constructs.
if ( isset( Collections::closedScopes()[ $this->tokens[ $i ]['code'] ] )
|| \T_FN === $this->tokens[ $i ]['code']
) {
if ( isset( $this->tokens[ $i ]['scope_closer'] ) ) {
$i = $this->tokens[ $i ]['scope_closer'];
}
continue;
}
// If this isn't a function name, skip it.
if ( \T_STRING !== $this->tokens[ $i ]['code'] ) {
continue;
}
// If this is one of the nonce verification functions, we can bail out.
if ( isset( $this->nonceVerificationFunctions[ $this->tokens[ $i ]['content'] ] ) ) {
/*
* Now, make sure it is a call to a global function.
*/
if ( ContextHelper::has_object_operator_before( $this->phpcsFile, $i ) === true ) {
continue;
}
if ( ContextHelper::is_token_namespaced( $this->phpcsFile, $i ) === true ) {
continue;
}
$this->set_cache( $cache_keys['file'], $start, $end, $i );
return true;
}
}
// We're still here, so no luck.
$this->set_cache( $cache_keys['file'], $start, $end, false );
return false;
} | Check if this token has an associated nonce check.
@since 0.5.0
@since 3.0.0 - Moved from the generic `Sniff` class to this class.
- Visibility changed from `protected` to `private.
- New `$cache_keys` parameter.
- New `$allow_nonce_after` parameter.
@param int $stackPtr The position of the current token in the stack of tokens.
@param array $cache_keys The keys for the applicable cache.
@param bool $allow_nonce_after Whether the nonce check _must_ be before the $stackPtr or
is allowed _after_ the $stackPtr.
@return bool | has_nonce_check | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/Security/NonceVerificationSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/NonceVerificationSniff.php | MIT |
private function get_cache( $filename, $start ) {
if ( is_array( $this->cached_results )
&& $filename === $this->cached_results['file']
&& isset( $this->cached_results['cache'][ $start ] )
) {
return $this->cached_results['cache'][ $start ];
}
return array(
'end' => 0,
'nonce' => false,
);
} | Helper function to retrieve results from the cache.
@since 3.0.0
@param string $filename The name of the current file.
@param int $start The stack pointer searches started from.
@return array<string, mixed> | get_cache | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/Security/NonceVerificationSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/NonceVerificationSniff.php | MIT |
private function set_cache( $filename, $start, $end, $nonce ) {
if ( is_array( $this->cached_results ) === false
|| $filename !== $this->cached_results['file']
) {
$this->cached_results = array(
'file' => $filename,
'cache' => array(
$start => array(
'end' => $end,
'nonce' => $nonce,
),
),
);
return;
}
// Okay, so we know the current cache is for the current file. Check if we've seen this start pointer before.
if ( isset( $this->cached_results['cache'][ $start ] ) === false ) {
$this->cached_results['cache'][ $start ] = array(
'end' => $end,
'nonce' => $nonce,
);
return;
}
// Update existing entry.
if ( $end > $this->cached_results['cache'][ $start ]['end'] ) {
$this->cached_results['cache'][ $start ]['end'] = $end;
}
$this->cached_results['cache'][ $start ]['nonce'] = $nonce;
} | Helper function to store results to the cache.
@since 3.0.0
@param string $filename The name of the current file.
@param int $start The stack pointer searches started from.
@param int $end The stack pointer searched stopped at.
@param int|bool $nonce Stack pointer to the nonce verification function call or false if none was found.
@return void | set_cache | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/Security/NonceVerificationSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/NonceVerificationSniff.php | MIT |
public function register() {
// Enrich the list of "safe components" tokens.
$this->safe_components += Tokens::$comparisonTokens;
$this->safe_components += Tokens::$operators;
$this->safe_components += Tokens::$booleanOperators;
$this->safe_components += Collections::incrementDecrementOperators();
// Set up the tokens the sniff should listen to.
$targets = array_merge( parent::register(), $this->target_keywords );
$targets[] = \T_ECHO;
$targets[] = \T_OPEN_TAG_WITH_ECHO;
return $targets;
} | Returns an array of tokens this test wants to listen for.
@return string|int[] | register | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/Security/EscapeOutputSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/EscapeOutputSniff.php | MIT |
public function getGroups() {
// Make sure all array keys are lowercase (could contain user-provided function names).
$printing_functions = array_change_key_case( $this->get_printing_functions(), \CASE_LOWER );
// Remove the unsafe printing functions to prevent duplicate notices.
$printing_functions = array_diff_key( $printing_functions, $this->unsafePrintingFunctions );
return array(
'unsafe_printing_functions' => array(
'functions' => array_keys( $this->unsafePrintingFunctions ),
),
'printing_functions' => array(
'functions' => array_keys( $printing_functions ),
),
);
} | Groups of functions this sniff is looking for.
@since 3.0.0
@return array | getGroups | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/Security/EscapeOutputSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/EscapeOutputSniff.php | MIT |
private function find_long_ternary( $start, $end ) {
for ( $i = $start; $i < $end; $i++ ) {
// Ignore anything within square brackets.
if ( isset( $this->tokens[ $i ]['bracket_opener'], $this->tokens[ $i ]['bracket_closer'] )
&& $i === $this->tokens[ $i ]['bracket_opener']
) {
$i = $this->tokens[ $i ]['bracket_closer'];
continue;
}
// Skip past nested arrays, function calls and arbitrary groupings.
if ( \T_OPEN_PARENTHESIS === $this->tokens[ $i ]['code']
&& isset( $this->tokens[ $i ]['parenthesis_closer'] )
) {
$i = $this->tokens[ $i ]['parenthesis_closer'];
continue;
}
// Skip past closures, anonymous classes and anything else scope related.
if ( isset( $this->tokens[ $i ]['scope_condition'], $this->tokens[ $i ]['scope_closer'] )
&& $this->tokens[ $i ]['scope_condition'] === $i
) {
$i = $this->tokens[ $i ]['scope_closer'];
continue;
}
if ( \T_INLINE_THEN !== $this->tokens[ $i ]['code'] ) {
continue;
}
/*
* Okay, we found a ternary and it should be at the correct nesting level.
* If this is a short ternary, it shouldn't be ignored though.
*/
if ( Operators::isShortTernary( $this->phpcsFile, $i ) === true ) {
return false;
}
return $i;
}
return false;
} | Check whether there is a ternary token at the right nesting level in an arbitrary set of tokens.
@since 3.0.0 Split off from the process_token() method.
@param int $start The position to start checking from.
@param int $end The position to stop the check at.
@return int|false Stack pointer to the ternary or FALSE if no ternary was found or
if this is a short ternary. | find_long_ternary | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/Security/EscapeOutputSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/EscapeOutputSniff.php | MIT |
public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) {
$delimiter = PassedParameters::getParameterFromStack( $parameters, 2, 'delimiter' );
if ( false !== $delimiter ) {
return;
}
$this->phpcsFile->addWarning(
'Passing the $delimiter parameter to preg_quote() is strongly recommended.',
$stackPtr,
'Missing'
);
} | Process the parameters of a matched function.
@since 1.0.0
@param int $stackPtr The position of the current token in the stack.
@param string $group_name The name of the group which was matched.
@param string $matched_content The token content (function name) which was matched
in lowercase.
@param array $parameters Array with information about the parameters.
@return void | process_parameters | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/PHP/PregQuoteDelimiterSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/PregQuoteDelimiterSniff.php | MIT |
public function getGroups() {
return array(
'create_function' => array(
'type' => 'error',
'message' => '%s() is deprecated as of PHP 7.2 and removed in PHP 8.0. Please use declared named or anonymous functions instead.',
'functions' => array(
'create_function',
),
),
);
} | Groups of functions to forbid.
Example: groups => array(
'lambda' => array(
'type' => 'error' | 'warning',
'message' => 'Use anonymous functions instead please!',
'functions' => array( 'file_get_contents', 'create_function' ),
)
)
@return array | getGroups | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/PHP/RestrictedPHPFunctionsSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/RestrictedPHPFunctionsSniff.php | MIT |
public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) {
$option_param = PassedParameters::getParameterFromStack( $parameters, 1, 'option' );
$value_param = PassedParameters::getParameterFromStack( $parameters, 2, 'value' );
if ( false === $option_param || false === $value_param ) {
// Missing required param. Not the concern of this sniff. Bow out.
return;
}
$option_name = TextStrings::stripQuotes( $option_param['clean'] );
$option_value = TextStrings::stripQuotes( $value_param['clean'] );
if ( isset( $this->safe_options[ $option_name ] ) ) {
$safe_option = $this->safe_options[ $option_name ];
if ( empty( $safe_option['valid_values'] ) || in_array( strtolower( $option_value ), $safe_option['valid_values'], true ) ) {
return;
}
}
if ( isset( $this->disallowed_options[ $option_name ] ) ) {
$disallowed_option = $this->disallowed_options[ $option_name ];
if ( empty( $disallowed_option['invalid_values'] )
|| in_array( strtolower( $option_value ), $disallowed_option['invalid_values'], true )
) {
$this->phpcsFile->addError(
'Found: %s(%s, %s). %s',
$stackPtr,
MessageHelper::stringToErrorcode( $option_name . '_Disallowed' ),
array(
$matched_content,
$option_param['clean'],
$value_param['clean'],
$disallowed_option['message'],
)
);
return;
}
}
$this->phpcsFile->addWarning(
'Changing configuration values at runtime is strongly discouraged. Found: %s(%s, %s)',
$stackPtr,
'Risky',
array(
$matched_content,
$option_param['clean'],
$value_param['clean'],
)
);
} | Process the parameter of a matched function.
Errors if an option is found in the disallow-list. Warns as
'risky' when the option is not found in the safe-list.
@since 2.1.0
@param int $stackPtr The position of the current token in the stack.
@param string $group_name The name of the group which was matched.
@param string $matched_content The token content (function name) which was matched
in lowercase.
@param array $parameters Array with information about the parameters.
@return void | process_parameters | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/PHP/IniSetSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/IniSetSniff.php | MIT |
public function getGroups() {
return array(
'serialize' => array(
'type' => 'warning',
'message' => '%s() found. Serialized data has known vulnerability problems with Object Injection. JSON is generally a better approach for serializing data. See https://www.owasp.org/index.php/PHP_Object_Injection',
'functions' => array(
'serialize',
'unserialize',
),
),
'urlencode' => array(
'type' => 'warning',
'message' => '%s() should only be used when dealing with legacy applications rawurlencode() should now be used instead. See https://www.php.net/function.rawurlencode and http://www.faqs.org/rfcs/rfc3986.html',
'functions' => array(
'urlencode',
),
),
'runtime_configuration' => array(
'type' => 'warning',
'message' => '%s() found. Changing configuration values at runtime is strongly discouraged.',
'functions' => array(
'error_reporting',
'ini_restore',
'apache_setenv',
'putenv',
'set_include_path',
'restore_include_path',
// This alias was DEPRECATED in PHP 5.3.0, and REMOVED as of PHP 7.0.0.
'magic_quotes_runtime',
// Warning This function was DEPRECATED in PHP 5.3.0, and REMOVED as of PHP 7.0.0.
'set_magic_quotes_runtime',
// Warning This function was removed from most SAPIs in PHP 5.3.0, and was removed from PHP-FPM in PHP 7.0.0.
'dl',
),
),
'system_calls' => array(
'type' => 'warning',
'message' => '%s() found. PHP system calls are often disabled by server admins.',
'functions' => array(
'exec',
'passthru',
'proc_open',
'shell_exec',
'system',
'popen',
),
),
'obfuscation' => array(
'type' => 'warning',
'message' => '%s() can be used to obfuscate code which is strongly discouraged. Please verify that the function is used for benign reasons.',
'functions' => array(
'base64_decode',
'base64_encode',
'convert_uudecode',
'convert_uuencode',
'str_rot13',
),
),
);
} | Groups of functions to discourage.
Example: groups => array(
'lambda' => array(
'type' => 'error' | 'warning',
'message' => 'Use anonymous functions instead please!',
'functions' => array( 'file_get_contents', 'create_function' ),
)
)
@return array | getGroups | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/PHP/DiscouragedPHPFunctionsSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/DiscouragedPHPFunctionsSniff.php | MIT |
public function register() {
$this->empty_tokens = Tokens::$emptyTokens;
$this->empty_tokens[ \T_NS_SEPARATOR ] = \T_NS_SEPARATOR;
$this->empty_tokens[ \T_BITWISE_AND ] = \T_BITWISE_AND;
return array(
\T_ASPERAND,
);
} | Returns an array of tokens this test wants to listen for.
@since 1.1.0
@return array | register | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/PHP/NoSilencedErrorsSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/NoSilencedErrorsSniff.php | MIT |
public function process_token( $stackPtr ) {
// Handle the user-defined custom function list.
$this->customAllowedFunctionsList = RulesetPropertyHelper::merge_custom_array( $this->customAllowedFunctionsList, array(), false );
$this->customAllowedFunctionsList = array_map( 'strtolower', $this->customAllowedFunctionsList );
/*
* Check if the error silencing is done for one of the allowed functions.
*
* @internal The function call name determination is done even when there is no allow list active
* to allow the metrics to be more informative.
*/
$next_non_empty = $this->phpcsFile->findNext( $this->empty_tokens, ( $stackPtr + 1 ), null, true, null, true );
if ( false !== $next_non_empty && \T_STRING === $this->tokens[ $next_non_empty ]['code'] ) {
$has_parenthesis = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $next_non_empty + 1 ), null, true, null, true );
if ( false !== $has_parenthesis && \T_OPEN_PARENTHESIS === $this->tokens[ $has_parenthesis ]['code'] ) {
$function_name = strtolower( $this->tokens[ $next_non_empty ]['content'] );
if ( ( true === $this->usePHPFunctionsList
&& isset( $this->allowedFunctionsList[ $function_name ] ) === true )
|| ( ! empty( $this->customAllowedFunctionsList )
&& in_array( $function_name, $this->customAllowedFunctionsList, true ) === true )
) {
$this->phpcsFile->recordMetric( $stackPtr, 'Error silencing', 'silencing allowed function call: ' . $function_name );
return;
}
}
}
$this->context_length = (int) $this->context_length;
$context_length = $this->context_length;
if ( $this->context_length <= 0 ) {
$context_length = 2;
}
// Prepare the "Found" string to display.
$end_of_statement = BCFile::findEndOfStatement( $this->phpcsFile, $stackPtr, \T_COMMA );
if ( ( $end_of_statement - $stackPtr ) < $context_length ) {
$context_length = ( $end_of_statement - $stackPtr );
}
$found = GetTokensAsString::compact( $this->phpcsFile, $stackPtr, ( $stackPtr + $context_length - 1 ), true ) . '...';
$error_msg = 'Silencing errors is strongly discouraged. Use proper error checking instead.';
$data = array();
if ( $this->context_length > 0 ) {
$error_msg .= ' Found: %s';
$data[] = $found;
}
$this->phpcsFile->addWarning(
$error_msg,
$stackPtr,
'Discouraged',
$data
);
if ( isset( $function_name ) ) {
$this->phpcsFile->recordMetric( $stackPtr, 'Error silencing', '@' . $function_name );
} else {
$this->phpcsFile->recordMetric( $stackPtr, 'Error silencing', $found );
}
} | Processes this test, when one of its tokens is encountered.
@since 1.1.0
@param int $stackPtr The position of the current token in the stack. | process_token | php | WordPress/WordPress-Coding-Standards | WordPress/Sniffs/PHP/NoSilencedErrorsSniff.php | https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/NoSilencedErrorsSniff.php | MIT |
public function __construct(private string $resourceDir)
{
} | Create a new Coverage Processor for the specified directory
@throws void | __construct | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
public function delete($name)
{
unset($this->_data[$name]);
$this->_needSave = true;
} | Delete an item from the session
@param $name | delete | php | gotzmann/comet | src/Session.php | https://github.com/gotzmann/comet/blob/master/src/Session.php | MIT |
public function pull($name, $default = null)
{
$value = $this->get($name, $default);
$this->delete($name);
return $value;
} | Retrieve and delete an item from the session
@param $name
@param null $default
@return mixed|null | pull | php | gotzmann/comet | src/Session.php | https://github.com/gotzmann/comet/blob/master/src/Session.php | MIT |
public function all()
{
return $this->_data;
} | Retrieve all the data in the session
@return array | all | php | gotzmann/comet | src/Session.php | https://github.com/gotzmann/comet/blob/master/src/Session.php | MIT |
public function flush()
{
$this->_needSave = true;
$this->_data = array();
} | Remove all data from the session
@return void | flush | php | gotzmann/comet | src/Session.php | https://github.com/gotzmann/comet/blob/master/src/Session.php | MIT |
public function has($name)
{
return isset($this->_data[$name]);
} | Determining If An Item Exists In The Session
@param $name
@return bool | has | php | gotzmann/comet | src/Session.php | https://github.com/gotzmann/comet/blob/master/src/Session.php | MIT |
public function exists($name)
{
return \array_key_exists($name, $this->_data);
} | To determine if an item is present in the session, even if its value is null
@param $name
@return bool | exists | php | gotzmann/comet | src/Session.php | https://github.com/gotzmann/comet/blob/master/src/Session.php | MIT |
public function __construct($stream, array $options = [])
{
if (!is_resource($stream)) {
throw new \InvalidArgumentException('Stream must be a resource');
}
if (isset($options['size'])) {
$this->size = $options['size'];
}
$this->customMetadata = $options['metadata'] ?? [];
$this->stream = $stream;
$meta = stream_get_meta_data($this->stream);
$this->seekable = $meta['seekable'];
$this->readable = (bool)preg_match(self::READABLE_MODES, $meta['mode']);
$this->writable = (bool)preg_match(self::WRITABLE_MODES, $meta['mode']);
$this->uri = $this->getMetadata('uri');
} | This constructor accepts an associative array of options.
- size: (int) If a read stream would otherwise have an indeterminate
size, but the size is known due to foreknowledge, then you can
provide that size, in bytes.
- metadata: (array) Any additional metadata to return when the metadata
of the stream is accessed.
@param resource $stream Stream resource to wrap.
@param array{size?: int, metadata?: array} $options Associative array of options.
@throws \InvalidArgumentException if the stream is not a stream resource | __construct | php | gotzmann/comet | src/Stream.php | https://github.com/gotzmann/comet/blob/master/src/Stream.php | MIT |
public function __destruct()
{
$this->close();
} | Closes the stream when the destructed | __destruct | php | gotzmann/comet | src/Stream.php | https://github.com/gotzmann/comet/blob/master/src/Stream.php | MIT |
private static function createUploadedFileFromSpec(array $value)
{
if (is_array($value['tmp_name'])) {
return self::normalizeNestedFileSpec($value);
}
return new UploadedFile(
$value['tmp_name'],
(int) $value['size'],
(int) $value['error'],
$value['name'],
$value['type']
);
} | Create and return an UploadedFile instance from a $_FILES specification.
If the specification represents an array of values, this method will
delegate to normalizeNestedFileSpec() and return that return value.
@param array $value $_FILES struct
@return array|UploadedFileInterface | createUploadedFileFromSpec | php | gotzmann/comet | src/Request.php | https://github.com/gotzmann/comet/blob/master/src/Request.php | MIT |
public static function fromGlobals()
{
throw new InvalidArgumentException('Do not use fromGlobals() method for Comet\Request objects!');
} | We should not allow creating requests from GLOBALS with Workerman-based framework
@throws InvalidArgumentException | fromGlobals | php | gotzmann/comet | src/Request.php | https://github.com/gotzmann/comet/blob/master/src/Request.php | MIT |
public function getConfig(string $key = "") {
if (!$key) {
return self::$config;
} else if (array_key_exists($key, self::$config)) {
return self::$config[$key];
} else {
return null;
}
} | Return config param value or the config at whole
@param string $key | getConfig | php | gotzmann/comet | src/Comet.php | https://github.com/gotzmann/comet/blob/master/src/Comet.php | MIT |
public function init (callable $init)
{
self::$init = $init;
} | Set up worker initialization code if needed
@param callable $init | init | php | gotzmann/comet | src/Comet.php | https://github.com/gotzmann/comet/blob/master/src/Comet.php | MIT |
public function addJob(int $interval, callable $job, array $params = [], callable|null $init = null, string $name = '', int $workers = 1)
{
self::$jobs[] = [
'interval' => $interval,
'job' => $job,
'params' => $params,
'init' => $init,
'name' => $name,
'workers' => $workers,
];
} | Add periodic $job executed every $interval of seconds
@param int $interval
@param callable $job
@param array $params
@param callable $init
@param int $workers
@param string $name | addJob | php | gotzmann/comet | src/Comet.php | https://github.com/gotzmann/comet/blob/master/src/Comet.php | MIT |
public function serveStatic(string $dir, array $extensions = [])
{
self::$serveStatic = true;
// If dir specified as UNIX absolute path, or contains Windows disk name, thats enough
// In other case we should concatenate full path of two parts
if ($dir[0] == '/' || strpos($dir, ':')) {
self::$staticDir = $dir;
} else {
self::$staticDir = self::$rootDir . '/' . $dir;
}
self::$staticExtensions = $extensions;
} | Set folder to serve as root for static files
@param string $dir
@param array|null $extensions | serveStatic | php | gotzmann/comet | src/Comet.php | https://github.com/gotzmann/comet/blob/master/src/Comet.php | MIT |
public function __call (string $name, array $args)
{
return self::$app->$name(...$args);
} | Magic call to any of the Slim App methods like add, addMidleware, handle, run, etc...
See the full list of available methods: https://github.com/slimphp/Slim/blob/4.x/Slim/App.php
@param string $name
@param array $args
@return mixed | __call | php | gotzmann/comet | src/Comet.php | https://github.com/gotzmann/comet/blob/master/src/Comet.php | MIT |
private static function parse(string $url)
{
/* FIXME Disable IPv6
// If IPv6
$prefix = '';
if (preg_match('%^(.*://\[[0-9:a-f]+\])(.*?)$%', $url, $matches)) {
$prefix = $matches[1];
$url = $matches[2];
} */
$encodedUrl = preg_replace_callback(
'%[^:/@?&=#]+%usD',
static function ($matches) {
return urlencode($matches[0]);
},
$url
);
$result = parse_url($prefix . $encodedUrl);
if ($result === false) {
return false;
}
return array_map('urldecode', $result);
} | UTF-8 aware \parse_url() replacement.
The internal function produces broken output for non ASCII domain names
(IDN) when used with locales other than "C".
On the other hand, cURL understands IDN correctly only when UTF-8 locale
is configured ("C.UTF-8", "en_US.UTF-8", etc.).
@see https://bugs.php.net/bug.php?id=52923
@see https://www.php.net/manual/en/function.parse-url.php#114817
@see https://curl.haxx.se/libcurl/c/CURLOPT_URL.html#ENCODING
@return array|false | parse | php | gotzmann/comet | src/Uri.php | https://github.com/gotzmann/comet/blob/master/src/Uri.php | MIT |
public function __construct($config)
{
if (false === extension_loaded('redis')) {
throw new \RuntimeException('Please install redis extension.');
}
$this->_maxLifeTime = (int)ini_get('session.gc_maxlifetime');
if (!isset($config['timeout'])) {
$config['timeout'] = 2;
}
$this->_redis = new \Redis();
if (false === $this->_redis->connect($config['host'], $config['port'], $config['timeout'])) {
throw new \RuntimeException("Redis connect {$config['host']}:{$config['port']} fail.");
}
if (!empty($config['auth'])) {
$this->_redis->auth($config['auth']);
}
if (!empty($config['database'])) {
$this->_redis->select($config['database']);
}
if (empty($config['prefix'])) {
$config['prefix'] = 'redis_session_';
}
$this->_redis->setOption(\Redis::OPT_PREFIX, $config['prefix']);
} | RedisSessionHandler constructor.
@param $config = [
'host' => '127.0.0.1',
'port' => 6379,
'timeout' => 2,
'auth' => '******',
'database' => 2,
'prefix' => 'redis_session_',
] | __construct | php | gotzmann/comet | src/Session/RedisSessionHandler.php | https://github.com/gotzmann/comet/blob/master/src/Session/RedisSessionHandler.php | MIT |
public function __get(string $name)
{
if ($name === 'stream') {
$this->stream = $this->createStream();
return $this->stream;
}
throw new \UnexpectedValueException("$name not found on class");
} | Magic method used to create a new stream if streams are not added in
the constructor of a decorator (e.g., LazyOpenStream).
@return StreamInterface | __get | php | gotzmann/comet | src/Psr/StreamDecoratorTrait.php | https://github.com/gotzmann/comet/blob/master/src/Psr/StreamDecoratorTrait.php | MIT |
public function __call(string $method, array $args)
{
/** @var callable $callable */
$callable = [$this->stream, $method];
$result = call_user_func_array($callable, $args);
// Always return the wrapped object if the result is a return $this
return $result === $this->stream ? $this : $result;
} | Allow decorators to implement custom methods
@return mixed | __call | php | gotzmann/comet | src/Psr/StreamDecoratorTrait.php | https://github.com/gotzmann/comet/blob/master/src/Psr/StreamDecoratorTrait.php | MIT |
public function __construct(callable $source, array $options = [])
{
$this->source = $source;
$this->size = $options['size'] ?? null;
$this->metadata = $options['metadata'] ?? [];
$this->buffer = new BufferStream();
} | @param callable(int): (string|null|false) $source Source of the stream data. The callable MAY
accept an integer argument used to control the
amount of data to return. The callable MUST
return a string when called, or false|null on error
or EOF.
@param array{size?: int, metadata?: array} $options Stream options:
- metadata: Hash of metadata to use with stream.
- size: Size of the stream, if known. | __construct | php | gotzmann/comet | src/Psr/PumpStream.php | https://github.com/gotzmann/comet/blob/master/src/Psr/PumpStream.php | MIT |
private function trimHeaderValues(array $values)
{
return array_map(function ($value) {
if (!is_scalar($value) && null !== $value) {
throw new \InvalidArgumentException(sprintf(
'Header value must be scalar or null but %s provided.',
is_object($value) ? get_class($value) : gettype($value)
));
}
return trim((string) $value, " \t");
}, array_values($values));
} | @deprecated
Trims whitespace from the header values.
Spaces and tabs ought to be excluded by parsers when extracting the field value from a header field.
header-field = field-name ":" OWS field-value OWS
OWS = *( SP / HTAB )
@param string[] $values Header values
@return string[] Trimmed header values
@see https://tools.ietf.org/html/rfc7230#section-3.2.4 | trimHeaderValues | php | gotzmann/comet | src/Psr/MessageTrait.php | https://github.com/gotzmann/comet/blob/master/src/Psr/MessageTrait.php | MIT |
public function getErrors()
{
$errors = [];
foreach ($this->errors->toArray() as $key => $error) {
foreach ($error as $rule => $message) {
$errors[$key] = $message;
}
}
return $errors;
} | Return errors from ErrorBag as array
@return array | getErrors | php | gotzmann/comet | src/Validation/Validation.php | https://github.com/gotzmann/comet/blob/master/src/Validation/Validation.php | MIT |
public function get(string $key)
{
$this->assertInit();
return $this->data['parsed_data'][$key] ?? '';
} | Get specific value from session by key.
@param string $key The key of a data field.
@return mixed | get | php | terrylinooo/shieldon | src/Firewall/Session.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Session.php | MIT |
protected function parsedData()
{
$data = $this->data['data'] ?? '{}';
$this->data['parsed_data'] = json_decode($data, true);
} | Parse JSON data and store it into parsed_data field.
@return void | parsedData | php | terrylinooo/shieldon | src/Firewall/Session.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Session.php | MIT |
protected function setRouteBase(string $base)
{
if (!defined('SHIELDON_PANEL_BASE')) {
// @codeCoverageIgnoreStart
define('SHIELDON_PANEL_BASE', $base);
// @codeCoverageIgnoreEnd
}
} | Set the base route for the panel.
@param string $base The base path.
@return void | setRouteBase | php | terrylinooo/shieldon | src/Firewall/Panel.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Panel.php | MIT |
public function __call($method, $args)
{
if (property_exists($this, $method)) {
$callable = $this->{$method};
if (isset($args[0]) && $args[0] instanceof ResponseInterface) {
return $callable($args[0]);
}
}
// @codeCoverageIgnoreStart
} | Magic method.
Helps the property `$resolver` to work like a function.
@param string $method The method name.
@param array $args The arguments.
@return mixed | __call | php | terrylinooo/shieldon | src/Firewall/Panel.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Panel.php | MIT |
function create_new_session_instance(string $sessionId)
{
Container::set('session_id', $sessionId, true);
$session = Container::get('session');
if ($session instanceof Session) {
$session->setId($sessionId);
set_session_instance($session);
}
} | For unit testing purpose. Not use in production.
Create new session by specifying a session ID.
@param string $sessionId A session ID string.
@return void | create_new_session_instance | php | terrylinooo/shieldon | src/Firewall/Helpers.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Helpers.php | MIT |
public function getConfig(string $field)
{
$v = explode('.', $field);
$c = count($v);
switch ($c) {
case 1:
return $this->configuration[$v[0]] ?? '';
case 2:
return $this->configuration[$v[0]][$v[1]] ?? '';
case 3:
return $this->configuration[$v[0]][$v[1]][$v[2]] ?? '';
case 4:
return $this->configuration[$v[0]][$v[1]][$v[2]][$v[3]] ?? '';
case 5:
return $this->configuration[$v[0]][$v[1]][$v[2]][$v[3]][$v[4]] ?? '';
}
return '';
} | Get a variable from configuration.
@param string $field The field of the configuration.
@return mixed | getConfig | php | terrylinooo/shieldon | src/Firewall/FirewallTrait.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/FirewallTrait.php | MIT |
protected function getOption(string $option, string $section = '')
{
if (!empty($this->configuration[$section][$option])) {
return $this->configuration[$section][$option];
}
if (!empty($this->configuration[$option]) && $section === '') {
return $this->configuration[$option];
}
return false;
} | Get options from the configuration file.
This method is same as `$this->getConfig()` but returning value from array directly.
@param string $option The option of the section in the the configuration.
@param string $section The section in the configuration.
@return mixed | getOption | php | terrylinooo/shieldon | src/Firewall/FirewallTrait.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/FirewallTrait.php | MIT |
public static function get(string $id)
{
if (self::has($id)) {
return self::$instances[$id];
}
return null;
} | Find an entry of the container by its identifier and returns it.
@param string $id Identifier of the entry to look for.
@return mixed Entry. | get | php | terrylinooo/shieldon | src/Firewall/Container.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Container.php | MIT |
public function getDeniedItem(string $key)
{
return $this->deniedList[$key] ?? '';
} | Get an item from the blacklist pool.
@param string $key The key of the data field.
@return string|array | getDeniedItem | php | terrylinooo/shieldon | src/Firewall/Component/DeniedTrait.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Component/DeniedTrait.php | MIT |
public function getAllowedItem(string $key)
{
return $this->allowedList[$key] ?? '';
} | Get an item from the whitelist pool.
@return string|array | getAllowedItem | php | terrylinooo/shieldon | src/Firewall/Component/AllowedTrait.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Component/AllowedTrait.php | MIT |
public function addTrustedBot(string $name, string $useragent, string $rdns)
{
$this->setAllowedItem(
[
'userAgent' => $useragent,
'rdns' => $rdns,
],
$name
);
} | Add new items to the allowed list.
@param string $name The key for this inforamtion.
@param string $useragent A piece of user-agent string that can identify.
@param string $rdns The RDNS inforamtion of the bot.
@return void | addTrustedBot | php | terrylinooo/shieldon | src/Firewall/Component/TrustedBot.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Component/TrustedBot.php | MIT |
public function before(Request $request)
{
if ($request->isCLI()) {
return;
}
// CodeIgniter 4 is not a PSR-7 compatible framework, therefore we don't
// pass the Reqest and Reposne to Firewall instance.
// Shieldon will create them by its HTTP factory.
$firewall = new Firewall();
$firewall->configure($this->storage);
$firewall->controlPanel($this->panelUri);
// Pass CodeIgniter CSRF Token to Captcha form.
$firewall->getKernel()->setCaptcha(
new Csrf([
'name' => csrf_token(),
'value' => csrf_hash(),
])
);
$response = $firewall->run();
if ($response->getStatusCode() !== 200) {
$httpResolver = new HttpResolver();
$httpResolver($response);
}
} | Shieldon middleware invokable class.
@param Request $request
@return mixed | before | php | terrylinooo/shieldon | src/Firewall/Integration/CodeIgniter4.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Integration/CodeIgniter4.php | MIT |
public function after(Request $request, Response $response)
{
// We don't have anything to do here.
} | We don't have anything to do here.
@param Response $request
@param Response $response
@return mixed | after | php | terrylinooo/shieldon | src/Firewall/Integration/CodeIgniter4.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Integration/CodeIgniter4.php | MIT |
public function __construct(string $storage = '', string $requestUri = '')
{
// Prevent possible issues occur in CLI command line.
if (isset($_SERVER['REQUEST_URI'])) {
$serverRequestUri = $_SERVER['REQUEST_URI'];
$scriptFilename = $_SERVER['SCRIPT_FILENAME'];
if ('' === $storage) {
// The storage folder should be placed above www-root for best security,
// this folder must be writable.
$storage = dirname($scriptFilename) . '/../shieldon_firewall';
}
if ('' === $requestUri) {
$requestUri = '/firewall/panel/';
}
$firewall = new Firewall();
$firewall->configure($storage);
$firewall->controlPanel($requestUri);
if ($requestUri !== '' &&
strpos($serverRequestUri, $requestUri) === 0
) {
// Get into the Firewall Panel.
$panel = new Panel();
$panel->entry();
}
}
} | Constuctor.
@param string $storage The absolute path of the storage where stores
Shieldon generated data.
@param string $requestUri The entry URL of Firewall Panel.
@return void | __construct | php | terrylinooo/shieldon | src/Firewall/Integration/Bootstrap.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Integration/Bootstrap.php | MIT |
public static function get(array $setting)
{
$instance = null;
try {
$host = 'mysql' .
':host=' . $setting['host'] .
';dbname=' . $setting['dbname'] .
';charset=' . $setting['charset'];
$user = (string) $setting['user'];
$pass = (string) $setting['pass'];
// Create a PDO instance.
$pdoInstance = new PDO($host, $user, $pass);
// Use MySQL data driver.
$instance = new MysqlDriver($pdoInstance);
// @codeCoverageIgnoreStart
} catch (PDOException $e) {
echo $e->getMessage();
}
// @codeCoverageIgnoreEnd
return $instance;
} | Initialize and get the instance.
@param array $setting The configuration of that driver.
@return MysqlDriver|null | get | php | terrylinooo/shieldon | src/Firewall/Firewall/Driver/ItemMysqlDriver.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Firewall/Driver/ItemMysqlDriver.php | MIT |
public static function get(array $setting)
{
$instance = null;
if (empty($setting['directory_path'])) {
return null;
}
try {
// Specify the sqlite file location.
$sqliteLocation = $setting['directory_path'] . '/shieldon.sqlite3';
$pdoInstance = new PDO('sqlite:' . $sqliteLocation);
$instance = new SqliteDriver($pdoInstance);
// @codeCoverageIgnoreStart
} catch (PDOException $e) {
echo $e->getMessage();
}
// @codeCoverageIgnoreEnd
return $instance;
} | Initialize and get the instance.
@param array $setting The configuration of that driver.
@return SqliteDriver|null | get | php | terrylinooo/shieldon | src/Firewall/Firewall/Driver/ItemSqliteDriver.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Firewall/Driver/ItemSqliteDriver.php | MIT |
public static function get(array $setting)
{
$instance = null;
try {
$host = '127.0.0.1';
$port = 6379;
if (!empty($setting['host'])) {
$host = $setting['host'];
}
if (!empty($setting['port'])) {
$port = $setting['port'];
}
// Create a Redis instance.
$redis = new Redis();
if (empty($setting['port'])) {
$redis->connect($host);
} else {
$redis->connect($host, $port);
}
if (!empty($setting['auth'])) {
// @codeCoverageIgnoreStart
$redis->auth($setting['auth']);
// @codeCoverageIgnoreEnd
}
// Use Redis data driver.
$instance = new RedisDriver($redis);
// @codeCoverageIgnoreStart
} catch (Exception $e) {
echo $e->getMessage();
}
// @codeCoverageIgnoreEnd
return $instance;
} | Initialize and get the instance.
@param array $setting The configuration of that driver.
@return RedisDriver|null | get | php | terrylinooo/shieldon | src/Firewall/Firewall/Driver/ItemRedisDriver.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Firewall/Driver/ItemRedisDriver.php | MIT |
public static function get(array $setting)
{
$instance = null;
if (empty($setting['directory_path'])) {
return $instance;
}
$instance = new FileDriver($setting['directory_path']);
return $instance;
} | Initialize and get the instance.
@param array $setting The configuration of that driver.
@return FileDriver|null | get | php | terrylinooo/shieldon | src/Firewall/Firewall/Driver/ItemFileDriver.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Firewall/Driver/ItemFileDriver.php | MIT |
private function overviewFormPost()
{
$postParams = get_request()->getParsedBody();
if (!isset($postParams['action_type'])) {
return;
}
switch ($postParams['action_type']) {
case 'reset_data_circle':
$this->setConfig('cronjob.reset_circle.config.last_update', date('Y-m-d H:i:s'));
$this->kernel->driver->rebuild();
sleep(2);
unset_superglobal('action_type', 'post');
$this->saveConfig();
$this->pushMessage(
'success',
__(
'panel',
'reset_data_circle',
'Data circle tables have been reset.'
)
);
break;
case 'reset_action_logs':
$this->kernel->logger->purgeLogs();
sleep(2);
$this->pushMessage(
'success',
__(
'panel',
'reset_action_logs',
'Action logs have been removed.'
)
);
break;
}
} | Detect and handle form post action.
@return void | overviewFormPost | php | terrylinooo/shieldon | src/Firewall/Panel/Home.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Panel/Home.php | MIT |
public function __construct()
{
$firewall = Container::get('firewall');
if (!($firewall instanceof Firewall)) {
throw new RuntimeException(
'The Firewall instance should be initialized first.'
);
}
$this->mode = 'managed';
$this->kernel = $firewall->getKernel();
$this->configuration = $firewall->getConfiguration();
$this->directory = $firewall->getDirectory();
$this->filename = $firewall->getFilename();
$this->base = SHIELDON_PANEL_BASE;
if (!empty($this->kernel->logger)) {
// We need to know where the logs stored in.
$logDirectory = $this->kernel->logger->getDirectory();
// Load ActionLogParser for parsing log files.
$this->parser = new ActionLogParser($logDirectory);
$this->pageAvailability['logs'] = true;
}
$flashMessage = get_session_instance()->get('flash_messages');
// Flash message, use it when redirecting page.
if (!empty($flashMessage) && is_array($flashMessage)) {
$this->messages = $flashMessage;
get_session_instance()->remove('flash_messages');
}
$this->locate = get_user_lang();
} | Firewall panel base controller. | __construct | php | terrylinooo/shieldon | src/Firewall/Panel/BaseController.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Panel/BaseController.php | MIT |
protected function isRuleExist()
{
$ipRule = $this->driver->get($this->ip, 'rule');
if (empty($ipRule)) {
return false;
}
$this->reason = $ipRule['reason'];
$ruleType = (int) $ipRule['type'];
// Apply the status code.
$this->setResultCode($ruleType);
if ($ruleType === Enum::ACTION_ALLOW) {
return true;
}
// Current visitor has been blocked. If he still attempts accessing the site,
// then we can drop him into the permanent block list.
$attempts = $ipRule['attempts'] ?? 0;
$attempts = (int) $attempts;
$now = time();
$logData = [];
$handleType = 0;
$logData['log_ip'] = $ipRule['log_ip'];
$logData['ip_resolve'] = $ipRule['ip_resolve'];
$logData['time'] = $now;
$logData['type'] = $ipRule['type'];
$logData['reason'] = $ipRule['reason'];
$logData['attempts'] = $attempts;
// @since 0.2.0
$attemptPeriod = $this->properties['record_attempt_detection_period'];
$attemptReset = $this->properties['reset_attempt_counter'];
$lastTimeDiff = $now - $ipRule['time'];
if ($lastTimeDiff <= $attemptPeriod) {
$logData['attempts'] = ++$attempts;
}
if ($lastTimeDiff > $attemptReset) {
$logData['attempts'] = 0;
}
if ($ruleType === Enum::ACTION_TEMPORARILY_DENY) {
$ratd = $this->determineAttemptsTemporaryDeny($logData, $handleType, $attempts);
$logData = $ratd['log_data'];
$handleType = $ratd['handle_type'];
}
if ($ruleType === Enum::ACTION_DENY) {
$rapd = $this->determineAttemptsPermanentDeny($logData, $handleType, $attempts);
$logData = $rapd['log_data'];
$handleType = $rapd['handle_type'];
}
// We only update data when `deny_attempt_enable` is enable.
// Because we want to get the last visited time and attempt counter.
// Otherwise, we don't update it everytime to avoid wasting CPU resource.
if ($this->event['update_rule_table']) {
$this->driver->save($this->ip, $logData, 'rule');
}
// Notify this event to messenger.
if ($this->event['trigger_messengers']) {
$message = $this->prepareMessengerBody($logData, $handleType);
// Method from MessageTrait.
$this->setMessageBody($message);
}
return true;
} | Look up the rule table.
If a specific IP address doesn't exist, return false.
Otherwise, return true.
@return bool | isRuleExist | php | terrylinooo/shieldon | src/Firewall/Kernel/RuleTrait.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Kernel/RuleTrait.php | MIT |
public function getComponent(string $name)
{
if (!isset($this->component[$name])) {
return null;
}
return $this->component[$name];
} | Get a component instance from component's container.
@param string $name The component's class name.
@return ComponentProvider|null | getComponent | php | terrylinooo/shieldon | src/Firewall/Kernel/ComponentTrait.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Kernel/ComponentTrait.php | MIT |
public function __construct(array $config = [])
{
$defaults = [
'img_width' => 250,
'img_height' => 50,
'word_length' => 8,
'font_spacing' => 10,
'pool' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'colors' => [
'background' => [255, 255, 255],
'border' => [153, 200, 255],
'text' => [51, 153, 255],
'grid' => [153, 200, 255],
],
];
foreach ($defaults as $k => $v) {
if (isset($config[$k])) {
$this->properties[$k] = $config[$k];
} else {
$this->properties[$k] = $defaults[$k];
}
}
if (!is_array($this->properties['colors'])) {
$this->properties['colors'] = $defaults['colors'];
}
foreach ($defaults['colors'] as $k => $v) {
if (!is_array($this->properties['colors'][$k])) {
$this->properties['colors'][$k] = $defaults['colors'][$k];
}
}
} | Constructor.
It will implement default configuration settings here.
@param array $config The settings for creating Captcha.
@return void | __construct | php | terrylinooo/shieldon | src/Firewall/Captcha/ImageCaptcha.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Captcha/ImageCaptcha.php | MIT |
private function createRandomWords()
{
$this->word = '';
$poolLength = strlen($this->properties['pool']);
$randMax = $poolLength - 1;
for ($i = 0; $i < $this->properties['word_length']; $i++) {
$this->word .= $this->properties['pool'][random_int(0, $randMax)];
}
$this->length = strlen($this->word);
} | Prepare the random words that want to display to front.
@return void | createRandomWords | php | terrylinooo/shieldon | src/Firewall/Captcha/ImageCaptcha.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Captcha/ImageCaptcha.php | MIT |
private function createCanvas(int $imgWidth, int $imgHeight)
{
if (function_exists('imagecreatetruecolor')) {
$this->im = imagecreatetruecolor($imgWidth, $imgHeight);
// @codeCoverageIgnoreStart
} else {
$this->im = imagecreate($imgWidth, $imgHeight);
}
// @codeCoverageIgnoreEnd
} | Create a canvas.
This method initialize the $im.
@param int $imgWidth The width of the image.
@param int $imgHeight The height of the image.
@return void | createCanvas | php | terrylinooo/shieldon | src/Firewall/Captcha/ImageCaptcha.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Captcha/ImageCaptcha.php | MIT |
private function writeText(int $imgWidth, int $imgHeight, $textColor)
{
$im = $this->getImageResource();
$z = (int) ($imgWidth / ($this->length / 3));
$x = mt_rand(0, $z);
// $y = 0;
for ($i = 0; $i < $this->length; $i++) {
$y = mt_rand(0, $imgHeight / 2);
imagestring($im, 5, $x, $y, $this->word[$i], $textColor);
$x += ($this->properties['font_spacing'] * 2);
}
} | Write the text into the image canvas.
@param int $imgWidth The width of the image.
@param int $imgHeight The height of the image.
@param int $textColor The RGB color for the grid of the image.
@return void | writeText | php | terrylinooo/shieldon | src/Firewall/Captcha/ImageCaptcha.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Captcha/ImageCaptcha.php | MIT |
public function __construct(array $config = [])
{
parent::__construct();
foreach ($config as $k => $v) {
if (isset($this->{$k})) {
$this->{$k} = $v;
}
}
} | Constructor.
It will implement default configuration settings here.
@param array $config The field of the CSRF configuration.
@return void | __construct | php | terrylinooo/shieldon | src/Firewall/Captcha/Csrf.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Captcha/Csrf.php | MIT |
public function __construct()
{
parent::__construct();
} | Constructor.
It will implement default configuration settings here.
@array $config
@return void | __construct | php | terrylinooo/shieldon | src/Firewall/Captcha/Foundation.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Captcha/Foundation.php | MIT |
public function __construct(array $config = [])
{
parent::__construct();
foreach ($config as $k => $v) {
if (isset($this->{$k})) {
$this->{$k} = $v;
}
}
} | Constructor.
It will implement default configuration settings here.
@param array $config The settings of Google ReCpatcha.
@return void | __construct | php | terrylinooo/shieldon | src/Firewall/Captcha/ReCaptcha.php | https://github.com/terrylinooo/shieldon/blob/master/src/Firewall/Captcha/ReCaptcha.php | MIT |
public function mockUserSession($key = '', $value = '')
{
$sessionId = '624689c34690a1d0a8c5658db66cf73d';
$_COOKIE['_shieldon'] = $sessionId;
$data['id'] = $sessionId;
$data['ip'] = '192.168.95.1';
$data['time'] = '1597028827';
$data['microtimestamp'] = '159702882767804400';
$data['parsed_data']['shieldon_ui_lang'] = 'en';
$data['parsed_data']['shieldon_user_login'] = true;
if (is_string($key) && $key !== '') {
$data['parsed_data'][$key] = $value;
}
if (is_array($key)) {
foreach ($key as $k => $v) {
$data['parsed_data'][$k] = $v;
}
}
$data['data'] = json_encode($data['parsed_data']);
$json = json_encode($data);
$dir = BOOTSTRAP_DIR . '/../tmp/shieldon/data_driver_file/shieldon_sessions';
$file = $dir . '/' . $sessionId . '.json';
$originalUmask = umask(0);
if (!is_dir($dir)) {
mkdir($dir, 0777, true);
}
umask($originalUmask);
file_put_contents($file, $json);
} | Mock the user session for tests which need session to test.
@param string|array $key
@param string $value
@return void | mockUserSession | php | terrylinooo/shieldon | tests/Firewall/ShieldonTestCase.php | https://github.com/terrylinooo/shieldon/blob/master/tests/Firewall/ShieldonTestCase.php | MIT |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.