From b1ca6469af219c3b33191d68ed7a0b31ad095ab5 Mon Sep 17 00:00:00 2001
From: Alexander Schnitzler <git@alexanderschnitzler.de>
Date: Sat, 26 Sep 2020 19:16:20 +0200
Subject: [PATCH] [TASK] Fix phpstan checkFunctionArgumentTypes errors in
 ext:indexed_search

This patch fixes incompatible type usage in function arguments
and is preparatory work for introducing native type hints and
strict mode in all core files.

Resolves: #92169
Releases: master, 10.4
Change-Id: Id15bec5732e08aa3891759e1a92e7ac6a2e295f1
Reviewed-on: https://review.typo3.org/c/Packages/TYPO3.CMS/+/65909
Tested-by: Andreas Fernandez <a.fernandez@scripting-base.de>
Tested-by: TYPO3com <noreply@typo3.com>
Tested-by: Oliver Bartsch <bo@cedev.de>
Tested-by: Benni Mack <benni@typo3.org>
Reviewed-by: Andreas Fernandez <a.fernandez@scripting-base.de>
Reviewed-by: Oliver Klee <typo3-coding@oliverklee.de>
Reviewed-by: Oliver Bartsch <bo@cedev.de>
Reviewed-by: Benni Mack <benni@typo3.org>
---
 .../Classes/Controller/SearchController.php   | 23 ++++++++++---------
 .../Repository/IndexSearchRepository.php      |  2 +-
 .../Classes/FileContentParser.php             |  9 +++++---
 .../Classes/Hook/CrawlerHook.php              | 12 +++++-----
 .../sysext/indexed_search/Classes/Indexer.php |  3 ++-
 .../Classes/Utility/IndexedSearchUtility.php  | 12 +++++-----
 .../PageBrowsingResultsViewHelper.php         |  2 +-
 .../ViewHelpers/PageBrowsingViewHelper.php    |  6 ++---
 8 files changed, 37 insertions(+), 32 deletions(-)

diff --git a/typo3/sysext/indexed_search/Classes/Controller/SearchController.php b/typo3/sysext/indexed_search/Classes/Controller/SearchController.php
index 554d0136e3b1..af38a6ec9f13 100644
--- a/typo3/sysext/indexed_search/Classes/Controller/SearchController.php
+++ b/typo3/sysext/indexed_search/Classes/Controller/SearchController.php
@@ -358,13 +358,13 @@ class SearchController extends ActionController
                 // could we get this in the view?
                 if ($this->searchData['group'] === 'sections' && $freeIndexUid <= 0) {
                     $resultSectionsCount = count($this->resultSections);
-                    $result['sectionText'] = sprintf(LocalizationUtility::translate('result.' . ($resultSectionsCount > 1 ? 'inNsections' : 'inNsection'), 'IndexedSearch'), $resultSectionsCount);
+                    $result['sectionText'] = sprintf(LocalizationUtility::translate('result.' . ($resultSectionsCount > 1 ? 'inNsections' : 'inNsection'), 'IndexedSearch') ?? '', $resultSectionsCount);
                 }
             }
         }
         // Print a message telling which words in which sections we searched for
         if (strpos($this->searchData['sections'], 'rl') === 0) {
-            $result['searchedInSectionInfo'] = LocalizationUtility::translate('result.inSection', 'IndexedSearch') . ' "' . $this->getPathFromPageId(substr($this->searchData['sections'], 4)) . '"';
+            $result['searchedInSectionInfo'] = (LocalizationUtility::translate('result.inSection', 'IndexedSearch') ?? '') . ' "' . $this->getPathFromPageId((int)substr($this->searchData['sections'], 4)) . '"';
         }
 
         if ($hookObj = $this->hookRequest('getDisplayResults_postProc')) {
@@ -429,7 +429,7 @@ class SearchController extends ActionController
                     $theId = $rlParts[0];
                     $theRLid = '0';
                 }
-                $sectionName = $this->getPathFromPageId($theId);
+                $sectionName = $this->getPathFromPageId((int)$theId);
                 $sectionName = ltrim($sectionName, '/');
                 if (!trim($sectionName)) {
                     $sectionTitleLinked = LocalizationUtility::translate('result.unnamedSection', 'IndexedSearch') . ':';
@@ -564,7 +564,7 @@ class SearchController extends ActionController
                 $lockedIcon = PathUtility::getAbsoluteWebPath($lockedIcon);
                 $resultData['access'] = '<img src="' . htmlspecialchars($lockedIcon) . '"'
                     . ' width="12" height="15" vspace="5" title="'
-                    . sprintf(LocalizationUtility::translate('result.memberGroups', 'IndexedSearch'), implode(',', array_unique($this->requiredFrontendUsergroups[$pathId])))
+                    . sprintf(LocalizationUtility::translate('result.memberGroups', 'IndexedSearch') ?? '', implode(',', array_unique($this->requiredFrontendUsergroups[$pathId])))
                     . '" alt="" />';
             }
         }
@@ -791,10 +791,11 @@ class SearchController extends ActionController
         $regExString = '(' . implode('|', $swForReg) . ')';
         // Split and combine:
         $parts = preg_split('/' . $regExString . '/i', ' ' . $str . ' ', 20000, PREG_SPLIT_DELIM_CAPTURE);
+        $parts = $parts ?: [];
         // Constants:
         $summaryMax = $this->settings['results.']['markupSW_summaryMax'];
-        $postPreLgd = $this->settings['results.']['markupSW_postPreLgd'];
-        $postPreLgd_offset = $this->settings['results.']['markupSW_postPreLgd_offset'];
+        $postPreLgd = (int)$this->settings['results.']['markupSW_postPreLgd'];
+        $postPreLgd_offset = (int)$this->settings['results.']['markupSW_postPreLgd_offset'];
         $divider = $this->settings['results.']['markupSW_divider'];
         $occurrences = (count($parts) - 1) / 2;
         if ($occurrences) {
@@ -950,9 +951,9 @@ class SearchController extends ActionController
                     ['-', 'AND NOT'],
                     // Add operators for various languages
                     // Converts the operators to lowercase
-                    [mb_strtolower(LocalizationUtility::translate('localizedOperandAnd', 'IndexedSearch'), 'utf-8'), 'AND'],
-                    [mb_strtolower(LocalizationUtility::translate('localizedOperandOr', 'IndexedSearch'), 'utf-8'), 'OR'],
-                    [mb_strtolower(LocalizationUtility::translate('localizedOperandNot', 'IndexedSearch'), 'utf-8'), 'AND NOT']
+                    [mb_strtolower(LocalizationUtility::translate('localizedOperandAnd', 'IndexedSearch') ?? '', 'utf-8'), 'AND'],
+                    [mb_strtolower(LocalizationUtility::translate('localizedOperandOr', 'IndexedSearch') ?? '', 'utf-8'), 'OR'],
+                    [mb_strtolower(LocalizationUtility::translate('localizedOperandNot', 'IndexedSearch') ?? '', 'utf-8'), 'AND NOT']
                 ];
                 $swordArray = IndexedSearchUtility::getExplodedSearchString($searchWords, $defaultOperator == 1 ? 'OR' : 'AND', $operatorTranslateTable);
                 if (is_array($swordArray)) {
@@ -1160,7 +1161,7 @@ class SearchController extends ActionController
         // Creating levels for section menu:
         // This selects the first and secondary menus for the "sections" selector - so we can search in sections and sub sections.
         if ($this->settings['displayLevel1Sections']) {
-            $firstLevelMenu = $this->getMenuOfPages($this->searchRootPageIdList);
+            $firstLevelMenu = $this->getMenuOfPages((int)$this->searchRootPageIdList);
             $labelLevel1 = LocalizationUtility::translate('sections.rootLevel1', 'IndexedSearch');
             $labelLevel2 = LocalizationUtility::translate('sections.rootLevel2', 'IndexedSearch');
             foreach ($firstLevelMenu as $firstLevelKey => $menuItem) {
@@ -1306,7 +1307,7 @@ class SearchController extends ActionController
     {
         $allOptions = [];
         if (count($this->availableResultsNumbers) > 1) {
-            $allOptions = array_combine($this->availableResultsNumbers, $this->availableResultsNumbers);
+            $allOptions = array_combine($this->availableResultsNumbers, $this->availableResultsNumbers) ?: [];
         }
         // disable single entries by TypoScript
         $allOptions = $this->removeOptionsFromOptionList($allOptions, $this->settings['blind']['numberOfResults']);
diff --git a/typo3/sysext/indexed_search/Classes/Domain/Repository/IndexSearchRepository.php b/typo3/sysext/indexed_search/Classes/Domain/Repository/IndexSearchRepository.php
index 9e88d418e79d..f84799beb8ba 100644
--- a/typo3/sysext/indexed_search/Classes/Domain/Repository/IndexSearchRepository.php
+++ b/typo3/sysext/indexed_search/Classes/Domain/Repository/IndexSearchRepository.php
@@ -231,7 +231,7 @@ class IndexSearchRepository
             // Total search-result count
             $count = $result->rowCount();
             // The pointer is set to the result page that is currently being viewed
-            $pointer = MathUtility::forceIntegerInRange($this->resultpagePointer, 0, floor($count / $this->numberOfResults));
+            $pointer = MathUtility::forceIntegerInRange($this->resultpagePointer, 0, (int)floor($count / $this->numberOfResults));
             // Initialize result accumulation variables:
             $c = 0;
             // Result pointer: Counts up the position in the current search-result
diff --git a/typo3/sysext/indexed_search/Classes/FileContentParser.php b/typo3/sysext/indexed_search/Classes/FileContentParser.php
index 70a7ed4f2d8d..f9425c60be73 100644
--- a/typo3/sysext/indexed_search/Classes/FileContentParser.php
+++ b/typo3/sysext/indexed_search/Classes/FileContentParser.php
@@ -485,7 +485,7 @@ class FileContentParser
                         $cmd = $this->app['pdftotext'] . ' -f ' . $low . ' -l ' . $high . ' -enc UTF-8 -q ' . escapeshellarg($absFile) . ' ' . $tempFileName;
                         CommandUtility::exec($cmd);
                         if (@is_file($tempFileName)) {
-                            $content = file_get_contents($tempFileName);
+                            $content = (string)file_get_contents($tempFileName);
                             unlink($tempFileName);
                         } else {
                             $content = '';
@@ -565,6 +565,9 @@ class FileContentParser
                             // Read sheet1.xml:
                             $cmd = $this->app['unzip'] . ' -p ' . escapeshellarg($absFile) . ' xl/worksheets/sheet1.xml';
                             break;
+                        default:
+                            $cmd = '';
+                            break;
                     }
                     CommandUtility::exec($cmd, $res);
                     $content_xml = implode(LF, $res);
@@ -728,7 +731,7 @@ class FileContentParser
             if ($this->lastLocale !== null) {
                 throw new \RuntimeException('Cannot set new locale as locale has already been changed before.', 1357064437);
             }
-            $this->lastLocale = setlocale(LC_CTYPE, 0);
+            $this->lastLocale = setlocale(LC_CTYPE, '0');
             setlocale(LC_CTYPE, $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLocale']);
         }
     }
@@ -806,7 +809,7 @@ class FileContentParser
      */
     public function removeEndJunk($string)
     {
-        return trim(preg_replace('/[' . LF . chr(12) . ']*$/', '', $string));
+        return trim((string)preg_replace('/[' . LF . chr(12) . ']*$/', '', $string));
     }
 
     /************************
diff --git a/typo3/sysext/indexed_search/Classes/Hook/CrawlerHook.php b/typo3/sysext/indexed_search/Classes/Hook/CrawlerHook.php
index f20fb455d7fc..747cf51f8bbe 100644
--- a/typo3/sysext/indexed_search/Classes/Hook/CrawlerHook.php
+++ b/typo3/sysext/indexed_search/Classes/Hook/CrawlerHook.php
@@ -353,7 +353,7 @@ class CrawlerHook
                 // Select files and directories in path:
                 $extList = implode(',', GeneralUtility::trimExplode(',', $cfgRec['extensions'], true));
                 $fileArr = [];
-                $files = GeneralUtility::getAllFilesAndFoldersInPath($fileArr, $readpath, $extList, 0, 0);
+                $files = GeneralUtility::getAllFilesAndFoldersInPath($fileArr, $readpath, $extList, false, 0);
                 $directoryList = GeneralUtility::get_dirs($readpath);
                 if (is_array($directoryList) && $params['depth'] < $cfgRec['depth']) {
                     foreach ($directoryList as $subdir) {
@@ -589,7 +589,7 @@ class CrawlerHook
      */
     public function checkUrl($url, $urlLog, $baseUrl)
     {
-        $url = preg_replace('/\\/\\/$/', '/', $url);
+        $url = (string)preg_replace('/\\/\\/$/', '/', $url);
         [$url] = explode('#', $url);
         if (strpos($url, '../') === false) {
             if (GeneralUtility::isFirstPartOfStr($url, $baseUrl)) {
@@ -625,7 +625,7 @@ class CrawlerHook
         if (!$baseHref) {
             // Extract base href from current URL
             $baseHref = $baseAbsoluteHref;
-            $baseHref .= substr($url_qParts['path'], 0, strrpos($url_qParts['path'], '/'));
+            $baseHref .= substr($url_qParts['path'], 0, (int)strrpos($url_qParts['path'], '/'));
         }
         $baseHref = rtrim($baseHref, '/');
         // Get URLs on this page:
@@ -726,7 +726,7 @@ class CrawlerHook
             $aMidNight = mktime(0, 0, 0) - 1 * 24 * 3600;
         } else {
             $lastTime = $cfgRec['timer_next_indexing'] ?: $GLOBALS['EXEC_TIME'];
-            $aMidNight = mktime(0, 0, 0, date('m', $lastTime), date('d', $lastTime), date('y', $lastTime));
+            $aMidNight = mktime(0, 0, 0, (int)date('m', $lastTime), (int)date('d', $lastTime), (int)date('y', $lastTime));
         }
         // Find last offset time plus frequency in seconds:
         $lastSureOffset = $aMidNight + MathUtility::forceIntegerInRange($cfgRec['timer_offset'], 0, 86400);
@@ -843,7 +843,7 @@ class CrawlerHook
     {
         // Clean up the index
         if ($command === 'delete' && $table === 'pages') {
-            $this->deleteFromIndex($id);
+            $this->deleteFromIndex((int)$id);
         }
     }
 
@@ -867,7 +867,7 @@ class CrawlerHook
             $id = $pObj->substNEWwithIDs[$id];
         } elseif ($table === 'pages' && $status === 'update' && (array_key_exists('hidden', $fieldArray) && $fieldArray['hidden'] == 1 || array_key_exists('no_search', $fieldArray) && $fieldArray['no_search'] == 1)) {
             // If the page should be hidden or not indexed after update, delete index for this page
-            $this->deleteFromIndex($id);
+            $this->deleteFromIndex((int)$id);
         }
         // Get full record and if exists, search for indexing configurations:
         $currentRecord = BackendUtility::getRecord($table, $id);
diff --git a/typo3/sysext/indexed_search/Classes/Indexer.php b/typo3/sysext/indexed_search/Classes/Indexer.php
index f8d5b3064e97..fd41a40d5165 100644
--- a/typo3/sysext/indexed_search/Classes/Indexer.php
+++ b/typo3/sysext/indexed_search/Classes/Indexer.php
@@ -487,7 +487,7 @@ class Indexer
         [$paramList, $isTagInText] = explode('>', substr($isTagInText, strlen($startTag)), 2);
         $afterTagInText = stristr($isTagInText, $endTag);
         if ($afterTagInText) {
-            $stringBefore = substr($string, 0, strpos(strtolower($string), strtolower($startTag)));
+            $stringBefore = substr($string, 0, (int)strpos(strtolower($string), strtolower($startTag)));
             $tagContent = substr($isTagInText, 0, strlen($isTagInText) - strlen($afterTagInText));
             $stringAfter = $stringBefore . substr($afterTagInText, strlen($endTag));
         } else {
@@ -506,6 +506,7 @@ class Indexer
     public function typoSearchTags(&$body)
     {
         $expBody = preg_split('/\\<\\!\\-\\-[\\s]?TYPO3SEARCH_/', $body);
+        $expBody = $expBody ?: [];
         if (count($expBody) > 1) {
             $body = '';
             $prev = '';
diff --git a/typo3/sysext/indexed_search/Classes/Utility/IndexedSearchUtility.php b/typo3/sysext/indexed_search/Classes/Utility/IndexedSearchUtility.php
index b28888c90450..6aaee57afb5c 100644
--- a/typo3/sysext/indexed_search/Classes/Utility/IndexedSearchUtility.php
+++ b/typo3/sysext/indexed_search/Classes/Utility/IndexedSearchUtility.php
@@ -104,18 +104,18 @@ class IndexedSearchUtility
             // There was a double-quote and we will then look for the ending quote.
             if (preg_match('/^"/', $sword)) {
                 // Removes first double-quote
-                $sword = preg_replace('/^"/', '', $sword);
+                $sword = (string)preg_replace('/^"/', '', $sword);
                 // Removes everything till next double-quote
                 preg_match('/^[^"]*/', $sword, $reg);
                 // reg[0] is the value, should not be trimmed
                 $value[] = $reg[0];
-                $sword = preg_replace('/^' . preg_quote($reg[0], '/') . '/', '', $sword);
+                $sword = (string)preg_replace('/^' . preg_quote($reg[0], '/') . '/', '', $sword);
                 // Removes last double-quote
-                $sword = trim(preg_replace('/^"/', '', $sword));
+                $sword = trim((string)preg_replace('/^"/', '', $sword));
             } elseif (preg_match('/^' . $specs . '/', $sword, $reg)) {
                 $value[] = $reg[0];
                 // Removes = sign
-                $sword = trim(preg_replace('/^' . $specs . '/', '', $sword));
+                $sword = trim((string)preg_replace('/^' . $specs . '/', '', $sword));
             } elseif (preg_match('/[\\+\\-]/', $sword)) {
                 // Check if $sword contains + or -
                 // + and - shall only be interpreted as $specchars when there's whitespace before it
@@ -123,7 +123,7 @@ class IndexedSearchUtility
                 // explode $sword to single words
                 $a_sword = explode(' ', $sword);
                 // get first word
-                $word = array_shift($a_sword);
+                $word = (string)array_shift($a_sword);
                 // Delete $delchars at end of string
                 $word = rtrim($word, $delchars);
                 // add searchword to values
@@ -136,7 +136,7 @@ class IndexedSearchUtility
                 // Delete $delchars at end of string
                 $word = rtrim(trim($reg[0]), $delchars);
                 $value[] = $word;
-                $sword = trim(preg_replace('/^' . preg_quote($reg[0], '/') . '/', '', $sword));
+                $sword = trim((string)preg_replace('/^' . preg_quote($reg[0], '/') . '/', '', $sword));
             }
         }
         return $value;
diff --git a/typo3/sysext/indexed_search/Classes/ViewHelpers/PageBrowsingResultsViewHelper.php b/typo3/sysext/indexed_search/Classes/ViewHelpers/PageBrowsingResultsViewHelper.php
index 7e55681c2fb9..15f8a53ac281 100644
--- a/typo3/sysext/indexed_search/Classes/ViewHelpers/PageBrowsingResultsViewHelper.php
+++ b/typo3/sysext/indexed_search/Classes/ViewHelpers/PageBrowsingResultsViewHelper.php
@@ -59,7 +59,7 @@ class PageBrowsingResultsViewHelper extends AbstractViewHelper
 
         $firstResultOnPage = $currentPage * $resultsPerPage + 1;
         $lastResultOnPage = $currentPage * $resultsPerPage + $resultsPerPage;
-        $label = LocalizationUtility::translate('displayResults', 'IndexedSearch');
+        $label = LocalizationUtility::translate('displayResults', 'IndexedSearch') ?? '';
         return sprintf($label, $firstResultOnPage, min([$numberOfResults, $lastResultOnPage]), $numberOfResults);
     }
 }
diff --git a/typo3/sysext/indexed_search/Classes/ViewHelpers/PageBrowsingViewHelper.php b/typo3/sysext/indexed_search/Classes/ViewHelpers/PageBrowsingViewHelper.php
index 9825b7564acf..2079999c2845 100644
--- a/typo3/sysext/indexed_search/Classes/ViewHelpers/PageBrowsingViewHelper.php
+++ b/typo3/sysext/indexed_search/Classes/ViewHelpers/PageBrowsingViewHelper.php
@@ -79,7 +79,7 @@ class PageBrowsingViewHelper extends AbstractTagBasedViewHelper
         // prev page
         // show on all pages after the 1st one
         if ($currentPage > 0) {
-            $label = LocalizationUtility::translate('displayResults.previous', 'IndexedSearch');
+            $label = LocalizationUtility::translate('displayResults.previous', 'IndexedSearch') ?? '';
             $content .= '<li>' . $this->makecurrentPageSelector_link($label, $currentPage - 1, $freeIndexUid) . '</li>';
         }
         // Check if $maximumNumberOfResultPages is in range
@@ -107,7 +107,7 @@ class PageBrowsingViewHelper extends AbstractTagBasedViewHelper
         }
         // next link
         if ($currentPage < $pageCount - 1) {
-            $label = LocalizationUtility::translate('displayResults.next', 'IndexedSearch');
+            $label = LocalizationUtility::translate('displayResults.next', 'IndexedSearch') ?? '';
             $content .= '<li>' . self::makecurrentPageSelector_link($label, $currentPage + 1, $freeIndexUid) . '</li>';
         }
 
@@ -129,7 +129,7 @@ class PageBrowsingViewHelper extends AbstractTagBasedViewHelper
      */
     protected function makecurrentPageSelector_link($str, $p, $freeIndexUid)
     {
-        $onclick = 'document.getElementById(' . GeneralUtility::quoteJSvalue(self::$prefixId . '_pointer') . ').value=' . GeneralUtility::quoteJSvalue($p) . ';';
+        $onclick = 'document.getElementById(' . GeneralUtility::quoteJSvalue(self::$prefixId . '_pointer') . ').value=' . GeneralUtility::quoteJSvalue((string)$p) . ';';
         if ($freeIndexUid !== null) {
             $onclick .= 'document.getElementById(' . GeneralUtility::quoteJSvalue(self::$prefixId . '_freeIndexUid') . ').value=' . GeneralUtility::quoteJSvalue($freeIndexUid) . ';';
         }
-- 
GitLab