Skip to content

Commit

Permalink
MDL-76362 various: Avoid passing nulls to functions that don't allow …
Browse files Browse the repository at this point in the history
…nulls

PHP 8.1 is more strict on the parameter type. Functions such as trim(), strlen(), str_replace(), etc
show notice when null is passed as an argument
  • Loading branch information
marinaglancy authored and andrewnicols committed Jan 23, 2023
1 parent 491ed7b commit b0a83aa
Show file tree
Hide file tree
Showing 69 changed files with 105 additions and 102 deletions.
2 changes: 1 addition & 1 deletion admin/tool/analytics/classes/output/helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public static function class_to_option($class) {
// Form field is PARAM_ALPHANUMEXT and we are sending fully qualified class names
// as option names, but replacing the backslash for a string that is really unlikely
// to ever be part of a class name.
return str_replace('\\', '__', $class);
return str_replace('\\', '__', $class ?? '');
}

/**
Expand Down
2 changes: 1 addition & 1 deletion admin/tool/behat/cli/run.php
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,7 @@ function print_combined_run_output($processes, $stoponfail = false) {
$process->stop(0);
}

$strlentoprint = strlen($update);
$strlentoprint = strlen($update ?? '');

// If not enough dots printed on line then just print.
if ($strlentoprint < $remainingprintlen) {
Expand Down
2 changes: 1 addition & 1 deletion admin/tool/brickfield/classes/manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ function($classname) {
* @return string
*/
public static function get_contenthash(?string $content = null): string {
return sha1($content);
return sha1($content ?? '');
}

/**
Expand Down
2 changes: 1 addition & 1 deletion admin/tool/dataprivacy/classes/data_registry.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ class data_registry {
* @return string[]
*/
public static function var_names_from_context($classname, $pluginname = '') {
$pluginname = trim($pluginname);
$pluginname = trim($pluginname ?? '');
if (!empty($pluginname)) {
$categoryvar = $classname . '_' . $pluginname . '_category';
$purposevar = $classname . '_' . $pluginname . '_purpose';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ protected function get_other_values(renderer_base $output) {
$values['formattedlawfulbases'] = $formattedbases;

$formattedsensitivereasons = [];
$sensitivereasons = explode(',', $this->persistent->get('sensitivedatareasons'));
$sensitivereasons = explode(',', $this->persistent->get('sensitivedatareasons') ?? '');
if (!empty($sensitivereasons)) {
foreach ($sensitivereasons as $reason) {
if (empty(trim($reason))) {
Expand Down
4 changes: 2 additions & 2 deletions admin/tool/log/classes/helper/reader.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,10 @@ public function get_description() {
* @return mixed Decoded value
*/
public static function decode_other(?string $other) {
if ($other === 'N;' || preg_match('~^.:~', $other)) {
if ($other === 'N;' || preg_match('~^.:~', $other ?? '')) {
return unserialize($other);
} else {
return json_decode($other, true);
return json_decode($other ?? '', true);
}
}

Expand Down
4 changes: 2 additions & 2 deletions admin/tool/moodlenet/classes/local/remote_resource.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ class remote_resource {
public function __construct(\curl $curl, url $url, \stdClass $metadata) {
$this->curl = $curl;
$this->url = $url;
$this->filename = pathinfo($this->url->get_path(), PATHINFO_FILENAME);
$this->extension = pathinfo($this->url->get_path(), PATHINFO_EXTENSION);
$this->filename = pathinfo($this->url->get_path() ?? '', PATHINFO_FILENAME);
$this->extension = pathinfo($this->url->get_path() ?? '', PATHINFO_EXTENSION);
$this->metadata = $metadata;
}

Expand Down
2 changes: 1 addition & 1 deletion analytics/classes/model.php
Original file line number Diff line number Diff line change
Expand Up @@ -1828,7 +1828,7 @@ public function clear() {
*/
public function get_name() {

if (trim($this->model->name) === '') {
if (trim($this->model->name ?? '') === '') {
return $this->get_target()->get_name();

} else {
Expand Down
2 changes: 1 addition & 1 deletion backup/moodle2/backup_custom_fields.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ public function set_value($value) {
$iv = self::generate_encryption_random_key(openssl_cipher_iv_length(backup::CIPHER));

// Everything is ready, let's encrypt and prepend the 1-shot iv.
$value = $iv . openssl_encrypt($value, backup::CIPHER, $this->key, OPENSSL_RAW_DATA, $iv);
$value = $iv . openssl_encrypt($value ?? '', backup::CIPHER, $this->key, OPENSSL_RAW_DATA, $iv);

// Calculate the hmac of the value (iv + encrypted) and prepend it.
$hmac = hash_hmac('sha256', $value, $this->key, true);
Expand Down
2 changes: 1 addition & 1 deletion backup/util/helper/restore_decode_processor.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ public static function register_link_decoders($processor) {
*/
protected function precheck_content($content) {
// Look for $@ in content (all interlinks contain that)
return (strpos($content, '$@') === false) ? false : $content;
return (strpos($content ?? '', '$@') === false) ? false : $content;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public function process_cdata($cdata) {
return '';
} else if (is_numeric($cdata)) {
return $cdata;
} else if (strlen($cdata) < 32) { // Impossible to have one link in 32cc
} else if (strlen($cdata ?? '') < 32) { // Impossible to have one link in 32cc
return $cdata; // (http://10.0.0.1/file.php/1/1.jpg, http://10.0.0.1/mod/url/view.php?id=)
}

Expand Down
2 changes: 1 addition & 1 deletion backup/util/xml/output/xml_output.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public function write($content) {
if (!$this->running) {
throw new xml_output_exception('xml_output_not_started');
}
$lenc = strlen($content); // Get length in bytes
$lenc = strlen($content ?? ''); // Get length in bytes
if ($lenc == 0) { // 0 length contents, nothing to do
return;
}
Expand Down
2 changes: 1 addition & 1 deletion backup/util/xml/xml_writer.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ protected function xml_safe_text_content($content) {
* ignores the rest of characters. Also normalize linefeeds and return chars.
*/
protected function xml_safe_utf8($content) {
$content = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $content); // clean CTRL chars
$content = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $content ?? ''); // clean CTRL chars
$content = preg_replace("/\r\n|\r/", "\n", $content); // Normalize line&return=>line
return $content;
}
Expand Down
4 changes: 2 additions & 2 deletions badges/classes/backpack_api_mapping.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,8 +170,8 @@ private function get_url($apiurl, $param1, $param2) {
$url = str_replace('[SCHEME]', $urlscheme, $url);
$url = str_replace('[HOST]', $urlhost, $url);
$url = str_replace('[URL]', $apiurl, $url);
$url = str_replace('[PARAM1]', $param1, $url);
$url = str_replace('[PARAM2]', $param2, $url);
$url = str_replace('[PARAM1]', $param1 ?? '', $url);
$url = str_replace('[PARAM2]', $param2 ?? '', $url);

return $url;
}
Expand Down
2 changes: 1 addition & 1 deletion cache/classes/helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -634,7 +634,7 @@ public static function get_definition_name($definition) {
*/
public static function hash_key($key, cache_definition $definition) {
if ($definition->uses_simple_keys()) {
if (debugging() && preg_match('#[^a-zA-Z0-9_]#', $key)) {
if (debugging() && preg_match('#[^a-zA-Z0-9_]#', $key ?? '')) {
throw new coding_exception('Cache definition '.$definition->get_id().' requires simple keys. Invalid key provided.', $key);
}
// We put the key first so that we can be sure the start of the key changes.
Expand Down
2 changes: 1 addition & 1 deletion course/classes/external/course_summary_exporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ protected function get_other_values(renderer_base $output) {
if ($progress === 0 || $progress > 0) {
$hasprogress = true;
}
$progress = floor($progress);
$progress = floor($progress ?? 0);
$coursecategory = \core_course_category::get($this->data->category, MUST_EXIST, true);
return array(
'fullnamedisplay' => get_course_display_name_for_list($this->data),
Expand Down
2 changes: 1 addition & 1 deletion course/format/classes/base.php
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,7 @@ public function get_sections_preferences_by_preference(): array {
$course = $this->get_course();
try {
$sectionpreferences = (array) json_decode(
get_user_preferences('coursesectionspreferences_' . $course->id, null, $USER->id)
get_user_preferences('coursesectionspreferences_' . $course->id, null, $USER->id) ?? ''
);
if (empty($sectionpreferences)) {
$sectionpreferences = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public function export_for_template(\renderer_base $output): stdClass {
$sectionoutput = new $this->sectionclass($format, $section);
$sectionoutput->hide_controls();

if (trim($section->name) == '') {
if (trim($section->name ?? '') == '') {
$sectionoutput->hide_title();
}

Expand Down
2 changes: 1 addition & 1 deletion course/user.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@
$coursenode->collapse = true;
$coursenode->make_inactive();

if (!preg_match('/^user\d{0,}$/', $activenode->key)) { // No user name found.
if (!preg_match('/^user\d{0,}$/', $activenode->key ?? '')) { // No user name found.
$userurl = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $course->id));
// Add the user name.
$usernode = $activenode->add(fullname($user), $userurl, navigation_node::TYPE_SETTING);
Expand Down
2 changes: 1 addition & 1 deletion customfield/classes/field.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,6 @@ protected static function define_properties() : array {
* @return array
*/
protected function get_configdata() : array {
return json_decode($this->raw_get('configdata'), true) ?? array();
return json_decode($this->raw_get('configdata') ?? '', true) ?? array();
}
}
2 changes: 1 addition & 1 deletion enrol/lti/classes/data_connector.php
Original file line number Diff line number Diff line change
Expand Up @@ -997,7 +997,7 @@ protected function build_tool_consumer_object($record, ToolConsumer $consumer) {
$consumer->consumerName = $record->consumername;
$consumer->consumerVersion = $record->consumerversion;
$consumer->consumerGuid = $record->consumerguid;
$consumer->profile = json_decode($record->profile);
$consumer->profile = json_decode($record->profile ?? '');
$consumer->toolProxy = $record->toolproxy;
$settings = unserialize($record->settings);
if (!is_array($settings)) {
Expand Down
4 changes: 2 additions & 2 deletions enrol/lti/classes/local/ltiadvantage/lib/http_client.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ function(&$val, $key) {
if (!$this->curlclient->get_errno() && !$this->curlclient->error) {
// No errors, so format the response.
$headersize = $info['header_size'];
$resheaders = substr($res, 0, $headersize);
$resbody = substr($res, $headersize);
$resheaders = substr($res ?? '', 0, $headersize);
$resbody = substr($res ?? '', $headersize);
$headerlines = array_filter(explode("\r\n", $resheaders));
$parsedresponseheaders = [
'httpstatus' => array_shift($headerlines)
Expand Down
2 changes: 1 addition & 1 deletion grade/report/singleview/classes/local/screen/user.php
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ public function process($data): stdClass {

$isscale = ($gradeitem->gradetype == GRADE_TYPE_SCALE);

$empties = (trim($value) === '' or ($isscale and $value == -1));
$empties = (trim($value ?? '') === '' or ($isscale and $value == -1));

if ($filter == 'all' or $empties) {
$data->$varname = ($isscale and empty($insertvalue)) ?
Expand Down
2 changes: 1 addition & 1 deletion h5p/ajax.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@

// Normalise Moodle language using underscore, as opposed to H5P which uses dash.
$language = optional_param('default-language', null, PARAM_RAW);
$language = clean_param(str_replace('-', '_', $language), PARAM_LANG);
$language = clean_param(str_replace('-', '_', $language ?? ''), PARAM_LANG);

if (!empty($name)) {
$editor->ajax->action(H5PEditorEndpoints::SINGLE_LIBRARY, $name,
Expand Down
2 changes: 1 addition & 1 deletion h5p/classes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ public static function get_contenttype_libraries(?string $fields = ''): array {
unset($library->major_version);
$library->minorVersion = (int) $library->minorversion;
unset($library->minorversion);
$library->metadataSettings = json_decode($library->metadatasettings);
$library->metadataSettings = json_decode($library->metadatasettings ?? '');

// If we already add this library means that it is an old version,as the previous query was sorted by version.
if (isset($added[$library->name])) {
Expand Down
2 changes: 1 addition & 1 deletion h5p/classes/editor_framework.php
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ public function getLibraries($libraries = null): ?array {
if ($details) {
$library->title = $details->title;
$library->runnable = $details->runnable;
$library->metadataSettings = json_decode($details->metadatasettings);
$library->metadataSettings = json_decode($details->metadatasettings ?? '');
$library->example = $details->example;
$library->tutorial = $details->tutorial;
$librariesin[] = $library;
Expand Down
4 changes: 2 additions & 2 deletions lib/accesslib.php
Original file line number Diff line number Diff line change
Expand Up @@ -4560,15 +4560,15 @@ function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLEN
}

if ($rolenamedisplay == ROLENAME_ALIAS) {
if ($coursecontext and trim($role->coursealias) !== '') {
if ($coursecontext and trim($role->coursealias ?? '') !== '') {
return format_string($role->coursealias, true, array('context'=>$coursecontext));
} else {
return $original;
}
}

if ($rolenamedisplay == ROLENAME_BOTH) {
if ($coursecontext and trim($role->coursealias) !== '') {
if ($coursecontext and trim($role->coursealias ?? '') !== '') {
return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
} else {
return $original;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public function getLocatorExamples() {
* @return SpecificationIterator
*/
public function locateSpecifications(Suite $suite, $locator) {
if (!is_file($locator) || 'passed' !== pathinfo($locator, PATHINFO_EXTENSION)) {
if (!$locator || !is_file($locator) || 'passed' !== pathinfo($locator, PATHINFO_EXTENSION)) {
return new NoSpecificationsIterator($suite);
}

Expand Down
2 changes: 1 addition & 1 deletion lib/classes/component.php
Original file line number Diff line number Diff line change
Expand Up @@ -1004,7 +1004,7 @@ public static function is_valid_plugin_name($plugintype, $pluginname) {
return (bool)preg_match('/^[a-z][a-z0-9]*$/', $pluginname);

} else {
return (bool)preg_match('/^[a-z](?:[a-z0-9_](?!__))*[a-z0-9]+$/', $pluginname);
return (bool)preg_match('/^[a-z](?:[a-z0-9_](?!__))*[a-z0-9]+$/', $pluginname ?? '');
}
}

Expand Down
2 changes: 1 addition & 1 deletion lib/classes/date.php
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ public static function phpunit_override_default_php_timezone($tz) {
if (!defined('PHPUNIT_TEST')) {
throw new coding_exception('core_date::phpunit_override_default_php_timezone() must be used only from unit tests');
}
$result = timezone_open($tz); // This triggers error if $tz invalid.
$result = timezone_open($tz ?? ''); // This triggers error if $tz invalid.
if ($result !== false) {
self::$defaultphptimezone = $tz;
} else {
Expand Down
2 changes: 1 addition & 1 deletion lib/dml/pgsql_native_moodle_database.php
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,7 @@ protected function fetch_columns(string $table): array {

} else if (preg_match('/int(\d)/i', $rawcolumn->type, $matches)) {
$info->type = 'int';
if (strpos($rawcolumn->adsrc, 'nextval') === 0) {
if (strpos($rawcolumn->adsrc ?? '', 'nextval') === 0) {
$info->primary_key = true;
$info->meta_type = 'R';
$info->unique = true;
Expand Down
2 changes: 1 addition & 1 deletion lib/evalmath/evalmath.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ function nfx($expr) {
if (is_null($o2)) return $this->trigger(get_string('unexpectedclosingbracket', 'mathslib'));
else $output[] = $o2;
}
if (preg_match('/^('.self::$namepat.')\($/', $stack->last(2), $matches)) { // did we just close a function?
if (preg_match('/^('.self::$namepat.')\($/', $stack->last(2) ?? '', $matches)) { // did we just close a function?
$fnn = $matches[1]; // get the function name
$arg_count = $stack->pop(); // see how many arguments there were (cleverly stored on the stack, thank you)
$fn = $stack->pop();
Expand Down
3 changes: 2 additions & 1 deletion lib/evalmath/readme_moodle.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Our changes:
* added round, ceil and floor functions.
* EvalMath::EvalMath() changed to EvalMath::__construct() and there is a new EvalMath::EvalMath
function to maintain backwards compatibility
* Ensure a string is passed to preg_match in EvalMath::nfx.

To see all changes diff against version 1.1, available from:
http://www.phpclasses.org/browse/package/2695.html
Expand All @@ -27,4 +28,4 @@ Changes by Stefan Erlachner, Thomas Niedermaier (MDL-64414):
* add function or:
e.g. if (or(condition_1, condition_2, ... condition_n))
* add function and:
e.g. if (and(condition_1, condition_2, ... condition_n))
e.g. if (and(condition_1, condition_2, ... condition_n))
2 changes: 1 addition & 1 deletion lib/filebrowser/file_info.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public abstract function get_children();
*/
protected function build_search_files_sql($extensions, $prefix = null) {
global $DB;
if (strlen($prefix)) {
if (strlen($prefix ?? '')) {
$prefix = $prefix.'.';
} else {
$prefix = '';
Expand Down
Loading

0 comments on commit b0a83aa

Please sign in to comment.