From b0a83aa7bd0e27d393f0b0ae08f32ed7085f5b84 Mon Sep 17 00:00:00 2001 From: Marina Glancy Date: Thu, 17 Nov 2022 16:04:24 +0100 Subject: [PATCH] MDL-76362 various: Avoid passing nulls to functions that don't allow 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 --- .../tool/analytics/classes/output/helper.php | 2 +- admin/tool/behat/cli/run.php | 2 +- admin/tool/brickfield/classes/manager.php | 2 +- .../dataprivacy/classes/data_registry.php | 2 +- .../classes/external/purpose_exporter.php | 2 +- admin/tool/log/classes/helper/reader.php | 4 +-- .../classes/local/remote_resource.php | 4 +-- analytics/classes/model.php | 2 +- backup/moodle2/backup_custom_fields.php | 2 +- .../helper/restore_decode_processor.class.php | 2 +- ...store_structure_parser_processor.class.php | 2 +- backup/util/xml/output/xml_output.class.php | 2 +- backup/util/xml/xml_writer.class.php | 2 +- badges/classes/backpack_api_mapping.php | 4 +-- cache/classes/helper.php | 2 +- .../external/course_summary_exporter.php | 2 +- course/format/classes/base.php | 2 +- .../output/local/content/frontpagesection.php | 2 +- course/user.php | 2 +- customfield/classes/field.php | 2 +- enrol/lti/classes/data_connector.php | 2 +- .../local/ltiadvantage/lib/http_client.php | 4 +-- .../singleview/classes/local/screen/user.php | 2 +- h5p/ajax.php | 2 +- h5p/classes/api.php | 2 +- h5p/classes/editor_framework.php | 2 +- lib/accesslib.php | 4 +-- .../FilesystemSkipPassedListLocator.php | 2 +- lib/classes/component.php | 2 +- lib/classes/date.php | 2 +- lib/dml/pgsql_native_moodle_database.php | 2 +- lib/evalmath/evalmath.class.php | 2 +- lib/evalmath/readme_moodle.txt | 3 ++- lib/filebrowser/file_info.php | 2 +- lib/filelib.php | 26 +++++++++---------- lib/filestorage/file_storage.php | 4 +-- lib/filestorage/file_system_filedir.php | 2 +- lib/filestorage/tgz_extractor.php | 2 +- lib/form/classes/filetypes_util.php | 2 +- lib/form/passwordunmask.php | 2 +- lib/formslib.php | 2 +- lib/html2text/lib.php | 2 +- lib/mathslib.php | 2 +- lib/navigationlib.php | 2 +- lib/outputcomponents.php | 2 +- lib/outputlib.php | 2 +- lib/setuplib.php | 1 + lib/tablelib.php | 2 +- lib/tests/behat/behat_accessibility.php | 2 +- lib/weblib.php | 9 ++++--- media/player/youtube/classes/plugin.php | 4 +-- mod/data/classes/preset.php | 4 +-- mod/data/classes/search/entry.php | 2 +- mod/data/field/latlong/field.class.php | 6 ++--- mod/data/field/number/field.class.php | 2 +- mod/data/lib.php | 10 +++---- mod/h5pactivity/classes/xapi/handler.php | 2 +- mod/lti/lib.php | 2 +- mod/lti/locallib.php | 4 +-- .../seb/classes/seb_quiz_settings.php | 2 +- mod/survey/classes/privacy/provider.php | 2 +- mod/workshop/classes/portfolio_caller.php | 2 +- .../local/request/moodle_content_writer.php | 2 +- .../classes/tests/request/content_writer.php | 2 +- question/engine/renderer.php | 2 +- question/type/calculated/db/upgradelib.php | 6 ++--- .../type/calculatedmulti/db/upgradelib.php | 6 ++--- question/type/multianswer/renderer.php | 2 +- question/type/numerical/questiontype.php | 2 +- 69 files changed, 105 insertions(+), 102 deletions(-) diff --git a/admin/tool/analytics/classes/output/helper.php b/admin/tool/analytics/classes/output/helper.php index 42025621144..c4628af2866 100644 --- a/admin/tool/analytics/classes/output/helper.php +++ b/admin/tool/analytics/classes/output/helper.php @@ -45,7 +45,7 @@ class helper { // 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 ?? ''); } /** diff --git a/admin/tool/behat/cli/run.php b/admin/tool/behat/cli/run.php index afaddd8b88d..454299e7612 100644 --- a/admin/tool/behat/cli/run.php +++ b/admin/tool/behat/cli/run.php @@ -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) { diff --git a/admin/tool/brickfield/classes/manager.php b/admin/tool/brickfield/classes/manager.php index 013a4b3f129..97fff856690 100644 --- a/admin/tool/brickfield/classes/manager.php +++ b/admin/tool/brickfield/classes/manager.php @@ -205,7 +205,7 @@ class manager { * @return string */ public static function get_contenthash(?string $content = null): string { - return sha1($content); + return sha1($content ?? ''); } /** diff --git a/admin/tool/dataprivacy/classes/data_registry.php b/admin/tool/dataprivacy/classes/data_registry.php index 75670f4953c..fcfe0d25e2c 100644 --- a/admin/tool/dataprivacy/classes/data_registry.php +++ b/admin/tool/dataprivacy/classes/data_registry.php @@ -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'; diff --git a/admin/tool/dataprivacy/classes/external/purpose_exporter.php b/admin/tool/dataprivacy/classes/external/purpose_exporter.php index 36bcb042118..42deae60689 100644 --- a/admin/tool/dataprivacy/classes/external/purpose_exporter.php +++ b/admin/tool/dataprivacy/classes/external/purpose_exporter.php @@ -109,7 +109,7 @@ class purpose_exporter extends persistent_exporter { $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))) { diff --git a/admin/tool/log/classes/helper/reader.php b/admin/tool/log/classes/helper/reader.php index 2e947748da0..ae0a376c816 100644 --- a/admin/tool/log/classes/helper/reader.php +++ b/admin/tool/log/classes/helper/reader.php @@ -74,10 +74,10 @@ trait reader { * @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); } } diff --git a/admin/tool/moodlenet/classes/local/remote_resource.php b/admin/tool/moodlenet/classes/local/remote_resource.php index e9526184b8c..a08a3bb7015 100644 --- a/admin/tool/moodlenet/classes/local/remote_resource.php +++ b/admin/tool/moodlenet/classes/local/remote_resource.php @@ -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; } diff --git a/analytics/classes/model.php b/analytics/classes/model.php index 5fc63d4b166..155cb3d66c0 100644 --- a/analytics/classes/model.php +++ b/analytics/classes/model.php @@ -1828,7 +1828,7 @@ class model { */ public function get_name() { - if (trim($this->model->name) === '') { + if (trim($this->model->name ?? '') === '') { return $this->get_target()->get_name(); } else { diff --git a/backup/moodle2/backup_custom_fields.php b/backup/moodle2/backup_custom_fields.php index 9de5ce68067..2372003b170 100644 --- a/backup/moodle2/backup_custom_fields.php +++ b/backup/moodle2/backup_custom_fields.php @@ -197,7 +197,7 @@ class encrypted_final_element extends backup_final_element { $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); diff --git a/backup/util/helper/restore_decode_processor.class.php b/backup/util/helper/restore_decode_processor.class.php index 0c7bf1e2cd7..80aa087b3f1 100644 --- a/backup/util/helper/restore_decode_processor.class.php +++ b/backup/util/helper/restore_decode_processor.class.php @@ -170,7 +170,7 @@ class restore_decode_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; } } diff --git a/backup/util/helper/restore_structure_parser_processor.class.php b/backup/util/helper/restore_structure_parser_processor.class.php index 9fc1f6e4d27..fdd9cb927bc 100644 --- a/backup/util/helper/restore_structure_parser_processor.class.php +++ b/backup/util/helper/restore_structure_parser_processor.class.php @@ -55,7 +55,7 @@ class restore_structure_parser_processor extends grouped_parser_processor { 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=) } diff --git a/backup/util/xml/output/xml_output.class.php b/backup/util/xml/output/xml_output.class.php index 159fbdb10b9..942c8ec1579 100644 --- a/backup/util/xml/output/xml_output.class.php +++ b/backup/util/xml/output/xml_output.class.php @@ -107,7 +107,7 @@ abstract class xml_output { 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; } diff --git a/backup/util/xml/xml_writer.class.php b/backup/util/xml/xml_writer.class.php index cc1f3c26b5d..39ebeeaa73d 100644 --- a/backup/util/xml/xml_writer.class.php +++ b/backup/util/xml/xml_writer.class.php @@ -260,7 +260,7 @@ class xml_writer { * 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; } diff --git a/badges/classes/backpack_api_mapping.php b/badges/classes/backpack_api_mapping.php index aa9155c4b1d..4c10f672a77 100644 --- a/badges/classes/backpack_api_mapping.php +++ b/badges/classes/backpack_api_mapping.php @@ -170,8 +170,8 @@ class backpack_api_mapping { $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; } diff --git a/cache/classes/helper.php b/cache/classes/helper.php index cf9364e30ea..e2f8b2300df 100644 --- a/cache/classes/helper.php +++ b/cache/classes/helper.php @@ -634,7 +634,7 @@ class cache_helper { */ 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. diff --git a/course/classes/external/course_summary_exporter.php b/course/classes/external/course_summary_exporter.php index 0916abda094..e50f11bdf6b 100644 --- a/course/classes/external/course_summary_exporter.php +++ b/course/classes/external/course_summary_exporter.php @@ -64,7 +64,7 @@ class course_summary_exporter extends \core\external\exporter { 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), diff --git a/course/format/classes/base.php b/course/format/classes/base.php index eae5e3caf3b..b6d2fc3cafa 100644 --- a/course/format/classes/base.php +++ b/course/format/classes/base.php @@ -618,7 +618,7 @@ abstract class base { $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 = []; diff --git a/course/format/classes/output/local/content/frontpagesection.php b/course/format/classes/output/local/content/frontpagesection.php index 50a4b47e243..ac34c59ac6c 100644 --- a/course/format/classes/output/local/content/frontpagesection.php +++ b/course/format/classes/output/local/content/frontpagesection.php @@ -84,7 +84,7 @@ class frontpagesection implements named_templatable, renderable { $sectionoutput = new $this->sectionclass($format, $section); $sectionoutput->hide_controls(); - if (trim($section->name) == '') { + if (trim($section->name ?? '') == '') { $sectionoutput->hide_title(); } diff --git a/course/user.php b/course/user.php index c6abc6f5f20..05f61885341 100644 --- a/course/user.php +++ b/course/user.php @@ -148,7 +148,7 @@ switch ($mode) { $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); diff --git a/customfield/classes/field.php b/customfield/classes/field.php index 1f7b7e1ec2c..7bd440abce1 100644 --- a/customfield/classes/field.php +++ b/customfield/classes/field.php @@ -92,6 +92,6 @@ class field extends persistent { * @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(); } } diff --git a/enrol/lti/classes/data_connector.php b/enrol/lti/classes/data_connector.php index b061da986ad..ff5a50cfb70 100644 --- a/enrol/lti/classes/data_connector.php +++ b/enrol/lti/classes/data_connector.php @@ -997,7 +997,7 @@ class data_connector extends DataConnector { $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)) { diff --git a/enrol/lti/classes/local/ltiadvantage/lib/http_client.php b/enrol/lti/classes/local/ltiadvantage/lib/http_client.php index fe9fac862d8..1911ea2e1d0 100644 --- a/enrol/lti/classes/local/ltiadvantage/lib/http_client.php +++ b/enrol/lti/classes/local/ltiadvantage/lib/http_client.php @@ -78,8 +78,8 @@ class http_client implements IHttpClient { 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) diff --git a/grade/report/singleview/classes/local/screen/user.php b/grade/report/singleview/classes/local/screen/user.php index 810bc5416a7..fb3a4b2a56a 100644 --- a/grade/report/singleview/classes/local/screen/user.php +++ b/grade/report/singleview/classes/local/screen/user.php @@ -410,7 +410,7 @@ class user extends tablelike implements selectable_items { $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)) ? diff --git a/h5p/ajax.php b/h5p/ajax.php index 04a3ae1d9b1..29cbba05fb0 100644 --- a/h5p/ajax.php +++ b/h5p/ajax.php @@ -59,7 +59,7 @@ switch ($action) { // 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, diff --git a/h5p/classes/api.php b/h5p/classes/api.php index eda8766641a..d2e9974dad2 100644 --- a/h5p/classes/api.php +++ b/h5p/classes/api.php @@ -163,7 +163,7 @@ class api { 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])) { diff --git a/h5p/classes/editor_framework.php b/h5p/classes/editor_framework.php index 0ab8b956338..45296c840fb 100644 --- a/h5p/classes/editor_framework.php +++ b/h5p/classes/editor_framework.php @@ -274,7 +274,7 @@ class editor_framework implements H5peditorStorage { 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; diff --git a/lib/accesslib.php b/lib/accesslib.php index 11c39b54f05..03253972aae 100644 --- a/lib/accesslib.php +++ b/lib/accesslib.php @@ -4560,7 +4560,7 @@ 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; @@ -4568,7 +4568,7 @@ function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLEN } 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; diff --git a/lib/behat/extension/Moodle/BehatExtension/Locator/FilesystemSkipPassedListLocator.php b/lib/behat/extension/Moodle/BehatExtension/Locator/FilesystemSkipPassedListLocator.php index 1a68338b77c..933d8a25703 100644 --- a/lib/behat/extension/Moodle/BehatExtension/Locator/FilesystemSkipPassedListLocator.php +++ b/lib/behat/extension/Moodle/BehatExtension/Locator/FilesystemSkipPassedListLocator.php @@ -64,7 +64,7 @@ final class FilesystemSkipPassedListLocator implements SpecificationLocator { * @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); } diff --git a/lib/classes/component.php b/lib/classes/component.php index 9b25c6c2bbe..bcdb940879a 100644 --- a/lib/classes/component.php +++ b/lib/classes/component.php @@ -1004,7 +1004,7 @@ $cache = '.var_export($cache, true).'; 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 ?? ''); } } diff --git a/lib/classes/date.php b/lib/classes/date.php index 14e178ddddc..747a098faaa 100644 --- a/lib/classes/date.php +++ b/lib/classes/date.php @@ -319,7 +319,7 @@ class core_date { 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 { diff --git a/lib/dml/pgsql_native_moodle_database.php b/lib/dml/pgsql_native_moodle_database.php index a61b4f89dec..247f371949c 100644 --- a/lib/dml/pgsql_native_moodle_database.php +++ b/lib/dml/pgsql_native_moodle_database.php @@ -594,7 +594,7 @@ class pgsql_native_moodle_database extends moodle_database { } 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; diff --git a/lib/evalmath/evalmath.class.php b/lib/evalmath/evalmath.class.php index 26e204bb73d..7e1a8790b30 100644 --- a/lib/evalmath/evalmath.class.php +++ b/lib/evalmath/evalmath.class.php @@ -260,7 +260,7 @@ class EvalMath { 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(); diff --git a/lib/evalmath/readme_moodle.txt b/lib/evalmath/readme_moodle.txt index c34b31d4241..b40f83b79f0 100644 --- a/lib/evalmath/readme_moodle.txt +++ b/lib/evalmath/readme_moodle.txt @@ -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 @@ -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)) \ No newline at end of file +e.g. if (and(condition_1, condition_2, ... condition_n)) diff --git a/lib/filebrowser/file_info.php b/lib/filebrowser/file_info.php index b7dcc46b47c..cba268f39b7 100644 --- a/lib/filebrowser/file_info.php +++ b/lib/filebrowser/file_info.php @@ -100,7 +100,7 @@ abstract class file_info { */ protected function build_search_files_sql($extensions, $prefix = null) { global $DB; - if (strlen($prefix)) { + if (strlen($prefix ?? '')) { $prefix = $prefix.'.'; } else { $prefix = ''; diff --git a/lib/filelib.php b/lib/filelib.php index 2fda3478737..514fb8aa3a0 100644 --- a/lib/filelib.php +++ b/lib/filelib.php @@ -518,9 +518,9 @@ function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $fil } if (!empty($options['reverse'])) { - return str_replace($baseurl, '@@PLUGINFILE@@/', $text); + return str_replace($baseurl, '@@PLUGINFILE@@/', $text ?? ''); } else { - return str_replace('@@PLUGINFILE@@/', $baseurl, $text); + return str_replace('@@PLUGINFILE@@/', $baseurl, $text ?? ''); } } @@ -785,7 +785,7 @@ function file_get_drafarea_files($draftitemid, $filepath = '/') { } // find the file this draft file was created from and count all references in local // system pointing to that file - $source = @unserialize($file->get_source()); + $source = @unserialize($file->get_source() ?? ''); if (isset($source->original)) { $item->refcount = $fs->search_references_count($source->original); } @@ -905,7 +905,7 @@ function file_get_submitted_draft_itemid($elname) { * @return stored_file */ function file_restore_source_field_from_draft_file($storedfile) { - $source = @unserialize($storedfile->get_source()); + $source = @unserialize($storedfile->get_source() ?? ''); if (!empty($source)) { if (is_object($source)) { $restoredsource = $source->source; @@ -1199,7 +1199,7 @@ function file_save_draft_area_files($draftitemid, $contextid, $component, $filea // Let's check if we can update this file or we need to delete and create. if ($newfile->is_directory()) { // Directories are always ok to just update. - } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) { + } else if (($source = @unserialize($newfile->get_source() ?? '')) && isset($source->original)) { // File has the 'original' - we need to update the file (it may even have not been changed at all). $original = file_storage::unpack_reference($source->original); if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) { @@ -1235,7 +1235,7 @@ function file_save_draft_area_files($draftitemid, $contextid, $component, $filea // Field files.source for draftarea files contains serialised object with source and original information. // We only store the source part of it for non-draft file area. $newsource = $newfile->get_source(); - if ($source = @unserialize($newfile->get_source())) { + if ($source = @unserialize($newfile->get_source() ?? '')) { $newsource = $source->source; } if ($oldfile->get_source() !== $newsource) { @@ -1269,7 +1269,7 @@ function file_save_draft_area_files($draftitemid, $contextid, $component, $filea // the size and subdirectory tests are extra safety only, the UI should prevent it foreach ($newhashes as $file) { $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time()); - if ($source = @unserialize($file->get_source())) { + if ($source = @unserialize($file->get_source() ?? '')) { // Field files.source for draftarea files contains serialised object with source and original information. // We only store the source part of it for non-draft file area. $file_record['source'] = $source->source; @@ -1478,7 +1478,7 @@ function format_postdata_for_curlcall($postdata) { $currentdata = urlencode($k); format_array_postdata_for_curlcall($v, $currentdata, $data); } else { - $data[] = urlencode($k).'='.urlencode($v); + $data[] = urlencode($k).'='.urlencode($v ?? ''); } } $convertedpostdata = implode('&', $data); @@ -1771,7 +1771,7 @@ function mimeinfo($element, $filename) { $mimeinfo = & get_mimetypes_array(); static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>''); - $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); + $filetype = strtolower(pathinfo($filename ?? '', PATHINFO_EXTENSION)); if (empty($filetype)) { $filetype = 'xxx'; // file without extension } @@ -2028,8 +2028,8 @@ function get_mimetype_description($obj, $capitalise=false) { } // MIME types may include + symbol but this is not permitted in string ids. - $safemimetype = str_replace('+', '_', $mimetype); - $safemimetypestr = str_replace('+', '_', $mimetypestr); + $safemimetype = str_replace('+', '_', $mimetype ?? ''); + $safemimetypestr = str_replace('+', '_', $mimetypestr ?? ''); $customdescription = mimeinfo('customdescription', $filename); if ($customdescription) { // Call format_string on the custom description so that multilang @@ -2919,7 +2919,7 @@ function file_overwrite_existing_draftfile(stored_file $newfile, stored_file $ex $fs = get_file_storage(); // Remember original file source field. - $source = @unserialize($existingfile->get_source()); + $source = @unserialize($existingfile->get_source() ?? ''); // Remember the original sortorder. $sortorder = $existingfile->get_sortorder(); if ($newfile->is_external_file()) { @@ -2943,7 +2943,7 @@ function file_overwrite_existing_draftfile(stored_file $newfile, stored_file $ex $newfile = $fs->create_file_from_storedfile($newfilerecord, $newfile); // Preserve original file location (stored in source field) for handling references. if (isset($source->original)) { - if (!($newfilesource = @unserialize($newfile->get_source()))) { + if (!($newfilesource = @unserialize($newfile->get_source() ?? ''))) { $newfilesource = new stdClass(); } $newfilesource->original = $source->original; diff --git a/lib/filestorage/file_storage.php b/lib/filestorage/file_storage.php index 71361d665d3..8fe268de6ca 100644 --- a/lib/filestorage/file_storage.php +++ b/lib/filestorage/file_storage.php @@ -1800,7 +1800,7 @@ class file_storage { // the latter of which can go to 100, we need to make sure that quality here is // in a safe range or PHP WILL CRASH AND DIE. You have been warned. $quality = $quality > 9 ? (int)(max(1.0, (float)$quality / 100.0) * 9.0) : $quality; - imagepng($img, NULL, $quality, NULL); + imagepng($img, NULL, $quality, PNG_NO_FILTER); break; default: @@ -2462,6 +2462,6 @@ class file_storage { * @return string The file's content hash */ public static function hash_from_string($content) { - return sha1($content); + return sha1($content ?? ''); } } diff --git a/lib/filestorage/file_system_filedir.php b/lib/filestorage/file_system_filedir.php index 8f9eb56e089..19418514937 100644 --- a/lib/filestorage/file_system_filedir.php +++ b/lib/filestorage/file_system_filedir.php @@ -426,7 +426,7 @@ class file_system_filedir extends file_system { $contenthash = file_storage::hash_from_string($content); // Binary length. - $filesize = strlen($content); + $filesize = strlen($content ?? ''); $hashpath = $this->get_fulldir_from_hash($contenthash); $hashfile = $this->get_local_path_from_hash($contenthash, false); diff --git a/lib/filestorage/tgz_extractor.php b/lib/filestorage/tgz_extractor.php index 0fb40ba38a0..4d1bc370fb2 100644 --- a/lib/filestorage/tgz_extractor.php +++ b/lib/filestorage/tgz_extractor.php @@ -493,7 +493,7 @@ class tgz_extractor { unlink($this->currentfile); } else { // For index file, get number of files and delete temp file. - $contents = file_get_contents($this->currentfile, null, null, null, 128); + $contents = file_get_contents($this->currentfile, false, null, 0, 128); $matches = array(); if (preg_match('~^' . preg_quote(tgz_packer::ARCHIVE_INDEX_COUNT_PREFIX) . '([0-9]+)~', $contents, $matches)) { diff --git a/lib/form/classes/filetypes_util.php b/lib/form/classes/filetypes_util.php index 6dc4c74ea8d..f11791bd1b7 100644 --- a/lib/form/classes/filetypes_util.php +++ b/lib/form/classes/filetypes_util.php @@ -62,7 +62,7 @@ class filetypes_util { */ public function normalize_file_types($types) { - if ($types === '') { + if ($types === '' || $types === null) { return []; } diff --git a/lib/form/passwordunmask.php b/lib/form/passwordunmask.php index e90ee4df89f..f82d12f4131 100644 --- a/lib/form/passwordunmask.php +++ b/lib/form/passwordunmask.php @@ -86,7 +86,7 @@ class MoodleQuickForm_passwordunmask extends MoodleQuickForm_password { */ public function export_for_template(renderer_base $output) { $context = parent::export_for_template($output); - $context['valuechars'] = array_fill(0, strlen($context['value']), 'x'); + $context['valuechars'] = array_fill(0, strlen($context['value'] ?? ''), 'x'); return $context; } diff --git a/lib/formslib.php b/lib/formslib.php index 7995f206d6d..4bb23d26df1 100644 --- a/lib/formslib.php +++ b/lib/formslib.php @@ -3261,7 +3261,7 @@ class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{ $html = str_replace('{type}', $element->getType(), $html); $html = str_replace('{name}', $element->getName(), $html); $html = str_replace('{groupname}', '', $html); - $html = str_replace('{class}', $element->getAttribute('class'), $html); + $html = str_replace('{class}', $element->getAttribute('class') ?? '', $html); $emptylabel = ''; if ($element->getLabel() == '') { $emptylabel = 'femptylabel'; diff --git a/lib/html2text/lib.php b/lib/html2text/lib.php index 18972d4c700..6c4588e22a6 100644 --- a/lib/html2text/lib.php +++ b/lib/html2text/lib.php @@ -52,7 +52,7 @@ class core_html2text extends \Html2Text\Html2Text { */ function __construct($html = '', $options = array()) { // Call the parent constructor. - parent::__construct($html, $options); + parent::__construct($html ?? '', $options); // MDL-27736: Trailing spaces before newline or tab. $this->entSearch[] = '/[ ]+([\n\t])/'; diff --git a/lib/mathslib.php b/lib/mathslib.php index 8753695cc16..0b33da3b9d7 100644 --- a/lib/mathslib.php +++ b/lib/mathslib.php @@ -123,7 +123,7 @@ class calc_formula { * @return string localised formula */ public static function localize($formula) { - $formula = str_replace('.', '$', $formula); // temp placeholder + $formula = str_replace('.', '$', $formula ?? ''); // temp placeholder $formula = str_replace(',', get_string('listsep', 'langconfig'), $formula); $formula = str_replace('$', get_string('decsep', 'langconfig'), $formula); return $formula; diff --git a/lib/navigationlib.php b/lib/navigationlib.php index 2209a3efaf6..eb5f5dcd730 100644 --- a/lib/navigationlib.php +++ b/lib/navigationlib.php @@ -5836,7 +5836,7 @@ class navigation_json { } if ($child->forcetitle || $child->title !== $child->text) { - $attributes['title'] = htmlentities($child->title, ENT_QUOTES, 'UTF-8'); + $attributes['title'] = htmlentities($child->title ?? '', ENT_QUOTES, 'UTF-8'); } if (array_key_exists($child->key.':'.$child->type, $this->expandable)) { $attributes['expandable'] = $child->key; diff --git a/lib/outputcomponents.php b/lib/outputcomponents.php index ecc89afcacf..8d3ade3e57c 100644 --- a/lib/outputcomponents.php +++ b/lib/outputcomponents.php @@ -2352,7 +2352,7 @@ class html_writer { if (!is_null($for)) { $attributes = array_merge($attributes, array('for' => $for)); } - $text = trim($text); + $text = trim($text ?? ''); $label = self::tag('label', $text, $attributes); // TODO MDL-12192 $colonize disabled for now yet diff --git a/lib/outputlib.php b/lib/outputlib.php index 6dc24b30054..1bbd202dfd2 100644 --- a/lib/outputlib.php +++ b/lib/outputlib.php @@ -1854,7 +1854,7 @@ class theme_config { // Now resolve all theme settings or do any other postprocessing. // This needs to be done before calling core parser, since the parser strips [[settings]] tags. $csspostprocess = $this->csspostprocess; - if (function_exists($csspostprocess)) { + if ($csspostprocess && function_exists($csspostprocess)) { $css = $csspostprocess($css, $this); } diff --git a/lib/setuplib.php b/lib/setuplib.php index 10e002a89bb..6e7c6f0f366 100644 --- a/lib/setuplib.php +++ b/lib/setuplib.php @@ -634,6 +634,7 @@ function get_docs_url($path = null) { $path = ''; } + $path = $path ?? ''; // Absolute URLs are used unmodified. if (substr($path, 0, 7) === 'http://' || substr($path, 0, 8) === 'https://') { return $path; diff --git a/lib/tablelib.php b/lib/tablelib.php index f81bb10717d..bf099cd9066 100644 --- a/lib/tablelib.php +++ b/lib/tablelib.php @@ -1463,7 +1463,7 @@ class flexible_table { // Load any existing user preferences. if ($this->persistent) { - $this->prefs = json_decode(get_user_preferences('flextable_' . $this->uniqueid), true); + $this->prefs = json_decode(get_user_preferences('flextable_' . $this->uniqueid) ?? '', true); $oldprefs = $this->prefs; } else if (isset($SESSION->flextable[$this->uniqueid])) { $this->prefs = $SESSION->flextable[$this->uniqueid]; diff --git a/lib/tests/behat/behat_accessibility.php b/lib/tests/behat/behat_accessibility.php index 7aa8d426f3f..022a7aed7f1 100644 --- a/lib/tests/behat/behat_accessibility.php +++ b/lib/tests/behat/behat_accessibility.php @@ -131,7 +131,7 @@ return (() => { EOF; for ($i = 0; $i < self::get_extended_timeout() * 10; $i++) { - $results = json_decode($this->evaluate_script($getresults)); + $results = json_decode($this->evaluate_script($getresults) ?? ''); if ($results) { break; } diff --git a/lib/weblib.php b/lib/weblib.php index f6eb931851a..1607c47a24e 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -97,7 +97,7 @@ function s($var) { } return preg_replace('/&#(\d+|x[0-9a-f]+);/i', '&#$1;', - htmlspecialchars($var, ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE)); + htmlspecialchars($var ?? '', ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE)); } /** @@ -149,7 +149,7 @@ function addslashes_js($var) { */ function strip_querystring($url) { - if ($commapos = strpos($url, '?')) { + if ($commapos = strpos($url ?? '', '?')) { return substr($url, 0, $commapos); } else { return $url; @@ -336,6 +336,7 @@ class moodle_url { $this->anchor = $url->anchor; } else { + $url = $url ?? ''; // Detect if anchor used. $apos = strpos($url, '#'); if ($apos !== false) { @@ -1127,7 +1128,7 @@ function validate_email($address) { require_once("{$CFG->libdir}/phpmailer/moodle_phpmailer.php"); - return moodle_phpmailer::validateAddress($address) && !preg_match('/[<>]/', $address); + return moodle_phpmailer::validateAddress($address ?? '') && !preg_match('/[<>]/', $address); } /** @@ -1540,7 +1541,7 @@ function format_string($string, $striplinks = true, $options = null) { * @return string */ function replace_ampersands_not_followed_by_entity($string) { - return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $string); + return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $string ?? ''); } /** diff --git a/media/player/youtube/classes/plugin.php b/media/player/youtube/classes/plugin.php index dd1478981e5..9537ae94138 100644 --- a/media/player/youtube/classes/plugin.php +++ b/media/player/youtube/classes/plugin.php @@ -63,7 +63,7 @@ class media_youtube_plugin extends core_media_player_external { protected function embed_external(moodle_url $url, $name, $width, $height, $options) { - $info = trim($name); + $info = trim($name ?? ''); if (empty($info) or strpos($info, 'http') === 0) { $info = get_string('pluginname', 'media_youtube'); } @@ -125,7 +125,7 @@ OET; if (is_numeric($rawtime)) { // Start time already specified as a number of seconds; ensure it's an integer. $seconds = $rawtime; - } else if (preg_match('/(\d+?h)?(\d+?m)?(\d+?s)?/i', $rawtime, $matches)) { + } else if (preg_match('/(\d+?h)?(\d+?m)?(\d+?s)?/i', $rawtime ?? '', $matches)) { // Convert into a raw number of seconds, as that's all embedded players accept. for ($i = 1; $i < count($matches); $i++) { if (empty($matches[$i])) { diff --git a/mod/data/classes/preset.php b/mod/data/classes/preset.php index fdeef6d8182..8f2c5ec1935 100644 --- a/mod/data/classes/preset.php +++ b/mod/data/classes/preset.php @@ -310,7 +310,7 @@ class preset { $instance = $this->manager->get_instance(); foreach (manager::TEMPLATES_LIST as $templatename => $templatefilename) { $templatefile = fopen("$exportdir/$templatefilename", 'w'); - fwrite($templatefile, $instance->{$templatename}); + fwrite($templatefile, $instance->{$templatename} ?? ''); fclose($templatefile); } @@ -710,7 +710,7 @@ class preset { $presetxmldata = "\n\n"; // Add description. - $presetxmldata .= '' . htmlspecialchars($this->description, ENT_COMPAT) . "\n\n"; + $presetxmldata .= '' . htmlspecialchars($this->description ?? '', ENT_COMPAT) . "\n\n"; // Add settings. // Raw settings are not preprocessed during saving of presets. diff --git a/mod/data/classes/search/entry.php b/mod/data/classes/search/entry.php index 95ee8a0a95c..7cf20be4d71 100644 --- a/mod/data/classes/search/entry.php +++ b/mod/data/classes/search/entry.php @@ -304,7 +304,7 @@ class entry extends \core_search\base_mod { continue; } $content->priority = $classname::get_priority(); - $content->addtemplateposition = strpos($template, '[['.$content->fldname.']]'); + $content->addtemplateposition = strpos($template ?? '', '[['.$content->fldname.']]'); } $orderqueue = new \SPLPriorityQueue(); diff --git a/mod/data/field/latlong/field.class.php b/mod/data/field/latlong/field.class.php index 19d094ee2fd..4d25d261ecc 100644 --- a/mod/data/field/latlong/field.class.php +++ b/mod/data/field/latlong/field.class.php @@ -170,11 +170,11 @@ class data_field_latlong extends data_field_base { } $lat = $content->content; - if (strlen($lat) < 1) { + if (strlen($lat ?? '') < 1) { return ''; } $long = $content->content1; - if (strlen($long) < 1) { + if (strlen($long ?? '') < 1) { return ''; } // We use format_float to display in the regional format. @@ -254,7 +254,7 @@ class data_field_latlong extends data_field_base { // When updating these values (which might be region formatted) we should format // the float to allow for a consistent float format in the database. $value = unformat_float($value); - $value = trim($value); + $value = trim($value ?? ''); if (strlen($value) > 0) { $value = floatval($value); } else { diff --git a/mod/data/field/number/field.class.php b/mod/data/field/number/field.class.php index df75243ad8f..e3053c8ba5b 100644 --- a/mod/data/field/number/field.class.php +++ b/mod/data/field/number/field.class.php @@ -68,7 +68,7 @@ class data_field_number extends data_field_base { return ''; } $number = $content->content; - $decimals = trim($this->field->param1); + $decimals = trim($this->field->param1 ?? ''); // Only apply number formatting if param1 contains an integer number >= 0. if (preg_match("/^\d+$/", $decimals)) { $decimals = $decimals * 1; diff --git a/mod/data/lib.php b/mod/data/lib.php index 355483a30f7..9ab3f3c45a8 100644 --- a/mod/data/lib.php +++ b/mod/data/lib.php @@ -840,19 +840,19 @@ function data_replace_field_in_templates($data, $searchfieldname, $newfieldname) $newdata = new stdClass(); $newdata->id = $data->id; $newdata->singletemplate = str_ireplace('[['.$searchfieldname.']]', - $prestring.$newfieldname.$poststring, $data->singletemplate); + $prestring.$newfieldname.$poststring, $data->singletemplate ?? ''); $newdata->listtemplate = str_ireplace('[['.$searchfieldname.']]', - $prestring.$newfieldname.$poststring, $data->listtemplate); + $prestring.$newfieldname.$poststring, $data->listtemplate ?? ''); $newdata->addtemplate = str_ireplace('[['.$searchfieldname.']]', - $prestring.$newfieldname.$poststring, $data->addtemplate); + $prestring.$newfieldname.$poststring, $data->addtemplate ?? ''); $newdata->addtemplate = str_ireplace('[['.$searchfieldname.'#id]]', - $prestring.$newfieldname.$idpart.$poststring, $data->addtemplate); + $prestring.$newfieldname.$idpart.$poststring, $data->addtemplate ?? ''); $newdata->rsstemplate = str_ireplace('[['.$searchfieldname.']]', - $prestring.$newfieldname.$poststring, $data->rsstemplate); + $prestring.$newfieldname.$poststring, $data->rsstemplate ?? ''); return $DB->update_record('data', $newdata); } diff --git a/mod/h5pactivity/classes/xapi/handler.php b/mod/h5pactivity/classes/xapi/handler.php index b05a9102377..358f6a52eea 100644 --- a/mod/h5pactivity/classes/xapi/handler.php +++ b/mod/h5pactivity/classes/xapi/handler.php @@ -83,7 +83,7 @@ class handler extends handler_base { // H5P add some extra params to ID to define subcontents. $parts = explode('?', $xapiobject, 2); $contextid = array_shift($parts); - $subcontent = str_replace('subContentId=', '', array_shift($parts)); + $subcontent = str_replace('subContentId=', '', array_shift($parts) ?? ''); if (empty($contextid) || !is_numeric($contextid)) { return null; } diff --git a/mod/lti/lib.php b/mod/lti/lib.php index bfe7cd71e28..c2a74c11e99 100644 --- a/mod/lti/lib.php +++ b/mod/lti/lib.php @@ -318,7 +318,7 @@ function mod_lti_get_all_content_items(\core_course\local\entity\content_item $d $type->name = 'lti_type_' . $ltitype->id; // Clean the name. We don't want tags here. $type->title = clean_param($ltitype->name, PARAM_NOTAGS); - $trimmeddescription = trim($ltitype->description); + $trimmeddescription = trim($ltitype->description ?? ''); $type->help = ''; if ($trimmeddescription != '') { // Clean the description. We don't want tags here. diff --git a/mod/lti/locallib.php b/mod/lti/locallib.php index 7bd5073ebd4..0a1ef823d57 100644 --- a/mod/lti/locallib.php +++ b/mod/lti/locallib.php @@ -2437,7 +2437,7 @@ function lti_get_configured_types($courseid, $sectionreturn = 0) { $type->name = 'lti_type_' . $ltitype->id; // Clean the name. We don't want tags here. $type->title = clean_param($ltitype->name, PARAM_NOTAGS); - $trimmeddescription = trim($ltitype->description); + $trimmeddescription = trim($ltitype->description ?? ''); if ($trimmeddescription != '') { // Clean the description. We don't want tags here. $type->help = clean_param($trimmeddescription, PARAM_NOTAGS); @@ -2454,7 +2454,7 @@ function lti_get_configured_types($courseid, $sectionreturn = 0) { function lti_get_domain_from_url($url) { $matches = array(); - if (preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)) { + if (preg_match(LTI_URL_DOMAIN_REGEX, $url ?? '', $matches)) { return $matches[1]; } } diff --git a/mod/quiz/accessrule/seb/classes/seb_quiz_settings.php b/mod/quiz/accessrule/seb/classes/seb_quiz_settings.php index b702acfc9bc..fb2d043dc33 100644 --- a/mod/quiz/accessrule/seb/classes/seb_quiz_settings.php +++ b/mod/quiz/accessrule/seb/classes/seb_quiz_settings.php @@ -662,7 +662,7 @@ class seb_quiz_settings extends persistent { * @return array of string, the separate keys. */ private function split_keys($keys) : array { - $keys = preg_split('~[ \t\n\r,;]+~', $keys, -1, PREG_SPLIT_NO_EMPTY); + $keys = preg_split('~[ \t\n\r,;]+~', $keys ?? '', -1, PREG_SPLIT_NO_EMPTY); foreach ($keys as $i => $key) { $keys[$i] = strtolower($key); } diff --git a/mod/survey/classes/privacy/provider.php b/mod/survey/classes/privacy/provider.php index b545e4b7883..d31ffb99c1b 100644 --- a/mod/survey/classes/privacy/provider.php +++ b/mod/survey/classes/privacy/provider.php @@ -227,7 +227,7 @@ class provider implements 'options' => $record->qoptions ]); $qtype = $record->qtype; - $options = explode(',', $q->options); + $options = explode(',', $q->options ?? ''); $carry[] = [ 'question' => array_merge((array) $q, [ diff --git a/mod/workshop/classes/portfolio_caller.php b/mod/workshop/classes/portfolio_caller.php index 740a041822e..eb618fb7192 100644 --- a/mod/workshop/classes/portfolio_caller.php +++ b/mod/workshop/classes/portfolio_caller.php @@ -342,7 +342,7 @@ class mod_workshop_portfolio_caller extends portfolio_module_caller_base { } if ($this->workshop->overallfeedbackmode) { - if ($assessment->feedbackauthorattachment or trim($assessment->feedbackauthor) !== '') { + if ($assessment->feedbackauthorattachment or trim($assessment->feedbackauthor ?? '') !== '') { $output .= html_writer::tag('h3', get_string('overallfeedback', 'mod_workshop')); $content = $this->format_exported_text($assessment->feedbackauthor, $assessment->feedbackauthorformat); $content = portfolio_rewrite_pluginfile_urls($content, $this->workshop->context->id, 'mod_workshop', diff --git a/privacy/classes/local/request/moodle_content_writer.php b/privacy/classes/local/request/moodle_content_writer.php index 88c95c434bc..c50720a6b45 100644 --- a/privacy/classes/local/request/moodle_content_writer.php +++ b/privacy/classes/local/request/moodle_content_writer.php @@ -179,7 +179,7 @@ class moodle_content_writer implements content_writer { $returnstring = $path . DIRECTORY_SEPARATOR . $this->get_files_target_url($component, $filearea, $itemid) . '/'; $returnstring = clean_param($returnstring, PARAM_PATH); - return str_replace('@@PLUGINFILE@@/', $returnstring, $text); + return str_replace('@@PLUGINFILE@@/', $returnstring, $text ?? ''); } /** diff --git a/privacy/classes/tests/request/content_writer.php b/privacy/classes/tests/request/content_writer.php index 7b2b9b85847..c6e9d3d080f 100644 --- a/privacy/classes/tests/request/content_writer.php +++ b/privacy/classes/tests/request/content_writer.php @@ -382,7 +382,7 @@ class content_writer implements \core_privacy\local\request\content_writer { * @return string The processed string */ public function rewrite_pluginfile_urls(array $subcontext, $component, $filearea, $itemid, $text) : string { - return str_replace('@@PLUGINFILE@@/', 'files/', $text); + return str_replace('@@PLUGINFILE@@/', 'files/', $text ?? ''); } /** diff --git a/question/engine/renderer.php b/question/engine/renderer.php index 4ce0e7c193c..b2f77b7e5f9 100644 --- a/question/engine/renderer.php +++ b/question/engine/renderer.php @@ -149,7 +149,7 @@ class core_question_renderer extends plugin_renderer_base { * @return HTML fragment. */ protected function number($number) { - if (trim($number) === '') { + if (trim($number ?? '') === '') { return ''; } $numbertext = ''; diff --git a/question/type/calculated/db/upgradelib.php b/question/type/calculated/db/upgradelib.php index 09803be12d7..9c8b2d7bbab 100644 --- a/question/type/calculated/db/upgradelib.php +++ b/question/type/calculated/db/upgradelib.php @@ -270,7 +270,7 @@ class qtype_calculated_qe2_attempt_updater extends question_qtype_attempt_update * corresponding value. */ protected function substitute_values_for_eval($expression) { - return str_replace($this->search, $this->safevalue, $expression); + return str_replace($this->search ?? '', $this->safevalue ?? '', $expression ?? ''); } /** @@ -282,7 +282,7 @@ class qtype_calculated_qe2_attempt_updater extends question_qtype_attempt_update * corresponding value. */ protected function substitute_values_pretty($text) { - return str_replace($this->search, $this->prettyvalue, $text); + return str_replace($this->search ?? '', $this->prettyvalue ?? '', $text ?? ''); } /** @@ -296,7 +296,7 @@ class qtype_calculated_qe2_attempt_updater extends question_qtype_attempt_update $text = preg_replace_callback('~\{=([^{}]*(?:\{[^{}]+}[^{}]*)*)}~', function ($matches) use ($vs, $format, $length) { return $vs->format_float($vs->calculate($matches[1]), $length, $format); - }, $text); + }, $text ?? ''); return $this->substitute_values_pretty($text); } } diff --git a/question/type/calculatedmulti/db/upgradelib.php b/question/type/calculatedmulti/db/upgradelib.php index d17d43c1aa6..543fbbf8b65 100644 --- a/question/type/calculatedmulti/db/upgradelib.php +++ b/question/type/calculatedmulti/db/upgradelib.php @@ -294,7 +294,7 @@ class qtype_calculatedmulti_qe2_attempt_updater extends question_qtype_attempt_u * corresponding value. */ protected function substitute_values_for_eval($expression) { - return str_replace($this->search, $this->safevalue, $expression); + return str_replace($this->search ?? '', $this->safevalue ?? '', $expression ?? ''); } /** @@ -306,7 +306,7 @@ class qtype_calculatedmulti_qe2_attempt_updater extends question_qtype_attempt_u * corresponding value. */ protected function substitute_values_pretty($text) { - return str_replace($this->search, $this->prettyvalue, $text); + return str_replace($this->search ?? '', $this->prettyvalue ?? '', $text ?? ''); } /** @@ -320,7 +320,7 @@ class qtype_calculatedmulti_qe2_attempt_updater extends question_qtype_attempt_u $text = preg_replace_callback(qtype_calculated::FORMULAS_IN_TEXT_REGEX, function ($matches) use ($vs, $format, $length) { return $vs->format_float($vs->calculate($matches[1]), $length, $format); - }, $text); + }, $text ?? ''); return $this->substitute_values_pretty($text); } } diff --git a/question/type/multianswer/renderer.php b/question/type/multianswer/renderer.php index aa4a444bec3..a935ed9bd5a 100644 --- a/question/type/multianswer/renderer.php +++ b/question/type/multianswer/renderer.php @@ -235,7 +235,7 @@ class qtype_multianswer_textfield_renderer extends qtype_multianswer_subq_render } // Work out a good input field size. - $size = max(1, core_text::strlen(trim($response)) + 1); + $size = max(1, core_text::strlen(trim($response ?? '')) + 1); foreach ($subq->answers as $ans) { $size = max($size, core_text::strlen(trim($ans->answer))); } diff --git a/question/type/numerical/questiontype.php b/question/type/numerical/questiontype.php index ccf62b1bea6..3aa8a2e8f9e 100644 --- a/question/type/numerical/questiontype.php +++ b/question/type/numerical/questiontype.php @@ -653,7 +653,7 @@ class qtype_numerical_answer_processor { public function apply_units($response, $separateunit = null) { // Strip spaces (which may be thousands separators) and change other forms // of writing e to e. - $response = str_replace(' ', '', $response); + $response = str_replace(' ', '', $response ?? ''); $response = preg_replace('~(?:e|E|(?:x|\*|×)10(?:\^|\*\*))([+-]?\d+)~', 'e$1', $response); // If a . is present or there are multiple , (i.e. 2,456,789 ) assume ,