| Total Complexity | 54 |
| Total Lines | 431 |
| Duplicated Lines | 0 % |
| Changes | 2 | ||
| Bugs | 0 | Features | 0 |
Complex classes like SysUtility often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use SysUtility, and based on these observations, apply Extract Interface, too.
| 1 | <?php declare(strict_types=1); |
||
| 33 | class SysUtility |
||
| 34 | { |
||
| 35 | use VersionChecks; |
||
|
|
|||
| 36 | |||
| 37 | //checkVerXoops, checkVerPhp Traits |
||
| 38 | |||
| 39 | use ServerStats; |
||
| 40 | |||
| 41 | // getServerStats Trait |
||
| 42 | |||
| 43 | use FilesManagement; |
||
| 44 | |||
| 45 | // Files Management Trait |
||
| 46 | //use ModuleStats; // ModuleStats Trait |
||
| 47 | |||
| 48 | //--------------- Common module methods ----------------------------- |
||
| 49 | |||
| 50 | /** |
||
| 51 | * Access the only instance of this class |
||
| 52 | */ |
||
| 53 | public static function getInstance(): self |
||
| 54 | { |
||
| 55 | static $instance; |
||
| 56 | if (null === $instance) { |
||
| 57 | $instance = new static(); |
||
| 58 | } |
||
| 59 | |||
| 60 | return $instance; |
||
| 61 | } |
||
| 62 | |||
| 63 | public static function selectSorting(string $text, string $form_sort): string |
||
| 64 | { |
||
| 65 | global $start, $order, $sort; |
||
| 66 | |||
| 67 | $selectView = ''; |
||
| 68 | $helper = Helper::getInstance(); |
||
| 69 | |||
| 70 | //$pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getConfig('modicons16'); |
||
| 71 | $pathModIcon16 = $helper->url( |
||
| 72 | $helper->getModule() |
||
| 73 | ->getInfo('modicons16') |
||
| 74 | ); |
||
| 75 | |||
| 76 | $selectView = '<form name="form_switch" id="form_switch" action="' . Request::getString('REQUEST_URI', '', 'SERVER') . '" method="post"><span style="font-weight: bold;">' . $text . '</span>'; |
||
| 77 | //$sorts = $sort == 'asc' ? 'desc' : 'asc'; |
||
| 78 | if ($form_sort === $sort) { |
||
| 79 | $sel1 = 'asc' === $order ? 'selasc.png' : 'asc.png'; |
||
| 80 | $sel2 = 'desc' === $order ? 'seldesc.png' : 'desc.png'; |
||
| 81 | } else { |
||
| 82 | $sel1 = 'asc.png'; |
||
| 83 | $sel2 = 'desc.png'; |
||
| 84 | } |
||
| 85 | $selectView .= ' <a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=asc"><img src="' . $pathModIcon16 . '/' . $sel1 . '" title="ASC" alt="ASC"></a>'; |
||
| 86 | $selectView .= '<a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=desc"><img src="' . $pathModIcon16 . '/' . $sel2 . '" title="DESC" alt="DESC"></a>'; |
||
| 87 | $selectView .= '</form>'; |
||
| 88 | |||
| 89 | return $selectView; |
||
| 90 | } |
||
| 91 | |||
| 92 | /***************Blocks***************/ |
||
| 93 | public static function blockAddCatSelect(array $cats): string |
||
| 94 | { |
||
| 95 | $catSql = ''; |
||
| 96 | if (!empty($cats)) { |
||
| 97 | $catSql = '(' . \current($cats); |
||
| 98 | \array_shift($cats); |
||
| 99 | foreach ($cats as $cat) { |
||
| 100 | $catSql .= ',' . $cat; |
||
| 101 | } |
||
| 102 | $catSql .= ')'; |
||
| 103 | } |
||
| 104 | |||
| 105 | return $catSql; |
||
| 106 | } |
||
| 107 | |||
| 108 | public static function metaKeywords(string $content): void |
||
| 109 | { |
||
| 110 | global $xoopsTpl, $xoTheme; |
||
| 111 | $myts = \MyTextSanitizer::getInstance(); |
||
| 112 | $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content)); |
||
| 113 | if (\is_object($xoTheme)) { |
||
| 114 | $xoTheme->addMeta('meta', 'keywords', \strip_tags($content)); |
||
| 115 | } else { // Compatibility for old Xoops versions |
||
| 116 | $xoopsTpl->assign('xoops_metaKeywords', \strip_tags($content)); |
||
| 117 | } |
||
| 118 | } |
||
| 119 | |||
| 120 | public static function metaDescription(string $content): void |
||
| 121 | { |
||
| 122 | global $xoopsTpl, $xoTheme; |
||
| 123 | $myts = \MyTextSanitizer::getInstance(); |
||
| 124 | $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content)); |
||
| 125 | if (\is_object($xoTheme)) { |
||
| 126 | $xoTheme->addMeta('meta', 'description', \strip_tags($content)); |
||
| 127 | } else { // Compatibility for old Xoops versions |
||
| 128 | $xoopsTpl->assign('xoops_metaDescription', \strip_tags($content)); |
||
| 129 | } |
||
| 130 | } |
||
| 131 | |||
| 132 | public static function enumerate(string $tableName, string $columnName): ?array |
||
| 133 | { |
||
| 134 | $table = $GLOBALS['xoopsDB']->prefix($tableName); |
||
| 135 | |||
| 136 | // $result = $GLOBALS['xoopsDB']->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS |
||
| 137 | // WHERE TABLE_NAME = '" . $table . "' AND COLUMN_NAME = '" . $columnName . "'") |
||
| 138 | // || exit ($GLOBALS['xoopsDB']->error()); |
||
| 139 | |||
| 140 | $sql = 'SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $table . '" AND COLUMN_NAME = "' . $columnName . '"'; |
||
| 141 | $result = $GLOBALS['xoopsDB']->query($sql); |
||
| 142 | if (!$GLOBALS['xoopsDB']->isResultSet($result)) { |
||
| 143 | // trigger_error($GLOBALS['xoopsDB']->error()); |
||
| 144 | $logger = \XoopsLogger::getInstance(); |
||
| 145 | $logger->handleError(\E_USER_WARNING, $sql, __FILE__, __LINE__); |
||
| 146 | |||
| 147 | return null; |
||
| 148 | } |
||
| 149 | |||
| 150 | $row = $GLOBALS['xoopsDB']->fetchBoth($result); |
||
| 151 | $enumList = \explode(',', \str_replace("'", '', \mb_substr($row['COLUMN_TYPE'], 5, -6))); |
||
| 152 | |||
| 153 | return $enumList; |
||
| 154 | } |
||
| 155 | |||
| 156 | /** |
||
| 157 | * Clone a record in a dB |
||
| 158 | * |
||
| 159 | * @TODO need to exit more gracefully on error. Should throw/trigger error and then return false |
||
| 160 | * |
||
| 161 | * @param string $tableName name of dB table (without prefix) |
||
| 162 | * @param string $idField name of field (column) in dB table |
||
| 163 | * @param int $id item id to clone |
||
| 164 | */ |
||
| 165 | public static function cloneRecord(string $tableName, string $idField, int $id): ?int |
||
| 166 | { |
||
| 167 | $newId = null; |
||
| 168 | $tempTable = []; |
||
| 169 | $table = $GLOBALS['xoopsDB']->prefix($tableName); |
||
| 170 | // copy content of the record you wish to clone |
||
| 171 | $sql = "SELECT * FROM $table WHERE $idField='" . $id . "' "; |
||
| 172 | $result = $GLOBALS['xoopsDB']->query($sql); |
||
| 173 | if ($GLOBALS['xoopsDB']->isResultSet($result)) { |
||
| 174 | $tempTable = $GLOBALS['xoopsDB']->fetchArray($result, \MYSQLI_ASSOC); |
||
| 175 | } |
||
| 176 | |||
| 177 | if (!$tempTable) { |
||
| 178 | \trigger_error($GLOBALS['xoopsDB']->error()); |
||
| 179 | } |
||
| 180 | // set the auto-incremented id's value to blank. |
||
| 181 | unset($tempTable[$idField]); |
||
| 182 | // insert cloned copy of the original record |
||
| 183 | $sql = "INSERT INTO $table (" . \implode(', ', \array_keys($tempTable)) . ") VALUES ('" . \implode("', '", $tempTable) . "')"; |
||
| 184 | $result = $GLOBALS['xoopsDB']->queryF($sql); |
||
| 185 | if (!$GLOBALS['xoopsDB']->isResultSet($result)) { |
||
| 186 | \trigger_error(\sprintf(\_DB_QUERY_ERROR, $sql) . $GLOBALS['xoopsDB']->error(), \E_USER_ERROR); |
||
| 187 | } |
||
| 188 | // Return the new id |
||
| 189 | $newId = $GLOBALS['xoopsDB']->getInsertId(); |
||
| 190 | |||
| 191 | return $newId; |
||
| 192 | } |
||
| 193 | |||
| 194 | /** |
||
| 195 | * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags |
||
| 196 | * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags |
||
| 197 | * www.cakephp.org |
||
| 198 | * |
||
| 199 | * @TODO: Refactor to consider HTML5 & void (self-closing) elements |
||
| 200 | * @TODO: Consider using https://github.com/jlgrall/truncateHTML/blob/master/truncateHTML.php |
||
| 201 | * |
||
| 202 | * @param string $text String to truncate. |
||
| 203 | * @param int|null $length Length of returned string, including ellipsis. |
||
| 204 | * @param string $ending Ending to be appended to the trimmed string. |
||
| 205 | * @param bool $exact If false, $text will not be cut mid-word |
||
| 206 | * @param bool $considerHtml If true, HTML tags would be handled correctly |
||
| 207 | * |
||
| 208 | * @return string Trimmed string. |
||
| 209 | */ |
||
| 210 | public static function truncateHtml( |
||
| 211 | string $text, |
||
| 212 | ?int $length = null, |
||
| 213 | string $ending = '...', |
||
| 214 | bool $exact = false, |
||
| 215 | bool $considerHtml = true |
||
| 216 | ): string { |
||
| 217 | $length ??= 100; |
||
| 218 | $openTags = []; |
||
| 219 | if ($considerHtml) { |
||
| 220 | // if the plain text is shorter than the maximum length, return the whole text |
||
| 221 | if (\mb_strlen(\preg_replace('/<.*?' . '>/', '', $text)) <= $length) { |
||
| 222 | return $text; |
||
| 223 | } |
||
| 224 | // splits all html-tags to scanable lines |
||
| 225 | \preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, \PREG_SET_ORDER); |
||
| 226 | $totalLength = \mb_strlen($ending); |
||
| 227 | //$openTags = []; |
||
| 228 | $truncate = ''; |
||
| 229 | foreach ($lines as $lineMatchings) { |
||
| 230 | // if there is any html-tag in this line, handle it and add it (uncounted) to the output |
||
| 231 | if (!empty($lineMatchings[1])) { |
||
| 232 | // if it's an "empty element" with or without xhtml-conform closing slash |
||
| 233 | if (\preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $lineMatchings[1])) { |
||
| 234 | // do nothing |
||
| 235 | // if tag is a closing tag |
||
| 236 | } elseif (\preg_match('/^<\s*\/(\S+?)\s*>$/s', $lineMatchings[1], $tagMatchings)) { |
||
| 237 | // delete tag from $openTags list |
||
| 238 | $pos = \array_search($tagMatchings[1], $openTags, true); |
||
| 239 | if (false !== $pos) { |
||
| 240 | unset($openTags[$pos]); |
||
| 241 | } |
||
| 242 | // if tag is an opening tag |
||
| 243 | } elseif (\preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $lineMatchings[1], $tagMatchings)) { |
||
| 244 | // add tag to the beginning of $openTags list |
||
| 245 | \array_unshift($openTags, \mb_strtolower($tagMatchings[1])); |
||
| 246 | } |
||
| 247 | // add html-tag to $truncate'd text |
||
| 248 | $truncate .= $lineMatchings[1]; |
||
| 249 | } |
||
| 250 | // calculate the length of the plain text part of the line; handle entities as one character |
||
| 251 | $contentLength = \mb_strlen(\preg_replace('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', ' ', $lineMatchings[2])); |
||
| 252 | if ($totalLength + $contentLength > $length) { |
||
| 253 | // the number of characters which are left |
||
| 254 | $left = $length - $totalLength; |
||
| 255 | $entitiesLength = 0; |
||
| 256 | // search for html entities |
||
| 257 | if (\preg_match_all('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', $lineMatchings[2], $entities, \PREG_OFFSET_CAPTURE)) { |
||
| 258 | // calculate the real length of all entities in the legal range |
||
| 259 | foreach ($entities[0] as $entity) { |
||
| 260 | if ($left >= $entity[1] + 1 - $entitiesLength) { |
||
| 261 | $left--; |
||
| 262 | $entitiesLength += \mb_strlen($entity[0]); |
||
| 263 | } else { |
||
| 264 | // no more characters left |
||
| 265 | break; |
||
| 266 | } |
||
| 267 | } |
||
| 268 | } |
||
| 269 | $truncate .= \mb_substr($lineMatchings[2], 0, $left + $entitiesLength); |
||
| 270 | // maximum length is reached, so get off the loop |
||
| 271 | break; |
||
| 272 | } |
||
| 273 | $truncate .= $lineMatchings[2]; |
||
| 274 | $totalLength += $contentLength; |
||
| 275 | |||
| 276 | // if the maximum length is reached, get off the loop |
||
| 277 | if ($totalLength >= $length) { |
||
| 278 | break; |
||
| 279 | } |
||
| 280 | } |
||
| 281 | } else { |
||
| 282 | if (\mb_strlen($text) <= $length) { |
||
| 283 | return $text; |
||
| 284 | } |
||
| 285 | $truncate = \mb_substr($text, 0, $length - \mb_strlen($ending)); |
||
| 286 | } |
||
| 287 | // if the words shouldn't be cut in the middle... |
||
| 288 | if (!$exact) { |
||
| 289 | // ...search the last occurance of a space... |
||
| 290 | $spacepos = \mb_strrpos($truncate, ' '); |
||
| 291 | if (isset($spacepos)) { |
||
| 292 | // ...and cut the text in this position |
||
| 293 | $truncate = \mb_substr($truncate, 0, $spacepos); |
||
| 294 | } |
||
| 295 | } |
||
| 296 | // add the defined ending to the text |
||
| 297 | $truncate .= $ending; |
||
| 298 | if ($considerHtml) { |
||
| 299 | // close all unclosed html-tags |
||
| 300 | foreach ($openTags as $tag) { |
||
| 301 | $truncate .= '</' . $tag . '>'; |
||
| 302 | } |
||
| 303 | } |
||
| 304 | |||
| 305 | return $truncate; |
||
| 306 | } |
||
| 307 | |||
| 308 | /** |
||
| 309 | * Get correct text editor based on user rights |
||
| 310 | * |
||
| 311 | * @return \XoopsFormDhtmlTextArea|\XoopsFormEditor |
||
| 312 | */ |
||
| 313 | public static function getEditor(?\Xmf\Module\Helper $helper = null, ?array $options = null): ?\XoopsFormTextArea |
||
| 314 | { |
||
| 315 | $descEditor = null; |
||
| 316 | |||
| 317 | /** @var Helper $helper */ |
||
| 318 | if (null === $options) { |
||
| 319 | $options = []; |
||
| 320 | $options['name'] = 'Editor'; |
||
| 321 | $options['value'] = 'Editor'; |
||
| 322 | $options['rows'] = 10; |
||
| 323 | $options['cols'] = '100%'; |
||
| 324 | $options['width'] = '100%'; |
||
| 325 | $options['height'] = '400px'; |
||
| 326 | } |
||
| 327 | |||
| 328 | if (null === $helper) { |
||
| 329 | $helper = Helper::getInstance(); |
||
| 330 | } |
||
| 331 | |||
| 332 | $isAdmin = $helper->isUserAdmin(); |
||
| 333 | |||
| 334 | if (\class_exists('XoopsFormEditor')) { |
||
| 335 | if ($isAdmin) { |
||
| 336 | $descEditor = new \XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorAdmin'), $options, false, 'textarea'); |
||
| 337 | } else { |
||
| 338 | $descEditor = new \XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorUser'), $options, false, 'textarea'); |
||
| 339 | } |
||
| 340 | } else { |
||
| 341 | $descEditor = new \XoopsFormDhtmlTextArea(\ucfirst($options['name']), $options['name'], $options['value']); |
||
| 342 | } |
||
| 343 | |||
| 344 | // $form->addElement($descEditor); |
||
| 345 | |||
| 346 | return $descEditor; |
||
| 347 | } |
||
| 348 | |||
| 349 | /** |
||
| 350 | * Check if column in dB table exists |
||
| 351 | * |
||
| 352 | * @param string $fieldname name of dB table field |
||
| 353 | * @param string $table name of dB table (including prefix) |
||
| 354 | * |
||
| 355 | * @return bool true if table exists |
||
| 356 | * @deprecated |
||
| 357 | */ |
||
| 358 | public static function fieldExists(string $fieldname, string $table): bool |
||
| 359 | { |
||
| 360 | $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1); |
||
| 361 | \trigger_error(__METHOD__ . " is deprecated, use Xmf\Database\Tables instead - instantiated from {$trace[0]['file']} line {$trace[0]['line']},"); |
||
| 362 | |||
| 363 | $result = $GLOBALS['xoopsDB']->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'"); |
||
| 364 | |||
| 365 | return ($GLOBALS['xoopsDB']->getRowsNum($result) > 0); |
||
| 366 | } |
||
| 367 | |||
| 368 | /** |
||
| 369 | * Function responsible for checking if a directory exists, we can also write in and create an index.html file |
||
| 370 | * |
||
| 371 | * @param string $folder The full path of the directory to check |
||
| 372 | */ |
||
| 373 | public static function prepareFolder(string $folder): void |
||
| 374 | { |
||
| 375 | try { |
||
| 376 | if (!\mkdir($folder) && !\is_dir($folder)) { |
||
| 377 | throw new \RuntimeException(\sprintf('Unable to create the %s directory', $folder)); |
||
| 378 | } |
||
| 379 | file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>'); |
||
| 380 | } catch (\Exception $e) { |
||
| 381 | echo 'Caught exception: ', $e->getMessage(), "<br>\n"; |
||
| 382 | } |
||
| 383 | } |
||
| 384 | |||
| 385 | /** |
||
| 386 | * Check if dB table exists |
||
| 387 | * |
||
| 388 | * @param string $tablename dB tablename with prefix |
||
| 389 | * @return bool true if table exists |
||
| 390 | */ |
||
| 391 | public static function tableExists(string $tablename): bool |
||
| 392 | { |
||
| 393 | $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1); |
||
| 394 | \trigger_error(__FUNCTION__ . " is deprecated, called from {$trace[0]['file']} line {$trace[0]['line']}"); |
||
| 395 | $GLOBALS['xoopsLogger']->addDeprecated( |
||
| 396 | \basename(\dirname(__DIR__, 2)) . ' Module: ' . __FUNCTION__ . ' function is deprecated, please use Xmf\Database\Tables method(s) instead.' . " Called from {$trace[0]['file']}line {$trace[0]['line']}" |
||
| 397 | ); |
||
| 398 | $sql = "SHOW TABLES LIKE '$tablename'"; |
||
| 399 | $result = self::queryFAndCheck($GLOBALS['xoopsDB'], $sql); |
||
| 400 | |||
| 401 | return $GLOBALS['xoopsDB']->getRowsNum($result) > 0; |
||
| 402 | } |
||
| 403 | |||
| 404 | /** |
||
| 405 | * Add a field to a mysql table |
||
| 406 | * |
||
| 407 | * @return bool|\mysqli_result |
||
| 408 | */ |
||
| 409 | public static function addField(string $field, string $table) |
||
| 414 | } |
||
| 415 | |||
| 416 | /** |
||
| 417 | * Query and check if the result is a valid result set |
||
| 418 | * |
||
| 419 | * @param \XoopsMySQLDatabase $xoopsDB XOOPS Database |
||
| 420 | * @param string $sql a valid MySQL query |
||
| 421 | * @param int|null $limit number of records to return |
||
| 422 | * @param int|null $start offset of first record to return |
||
| 423 | * |
||
| 424 | * @return \mysqli_result query result |
||
| 425 | */ |
||
| 426 | public static function queryAndCheck(\XoopsMySQLDatabase $xoopsDB, string $sql, ?int $limit = null, ?int $start = null): \mysqli_result |
||
| 427 | { |
||
| 428 | $limit ??= 0; |
||
| 429 | $start ??= 0; |
||
| 430 | $result = $xoopsDB->query($sql, $limit, $start); |
||
| 431 | |||
| 432 | if (!$xoopsDB->isResultSet($result)) { |
||
| 433 | throw new \RuntimeException( |
||
| 434 | \sprintf(\_DB_QUERY_ERROR, $sql) . $xoopsDB->error(), \E_USER_ERROR |
||
| 435 | ); |
||
| 436 | } |
||
| 437 | |||
| 438 | return $result; |
||
| 439 | } |
||
| 440 | |||
| 441 | /** |
||
| 442 | * QueryF and check if the result is a valid result set |
||
| 443 | * |
||
| 444 | * @param \XoopsMySQLDatabase $xoopsDB XOOPS Database |
||
| 445 | * @param string $sql a valid MySQL query |
||
| 446 | * @param int|null $limit number of records to return |
||
| 447 | * @param int|null $start offset of first record to return |
||
| 448 | * |
||
| 449 | * @return \mysqli_result query result |
||
| 450 | */ |
||
| 451 | public static function queryFAndCheck(\XoopsMySQLDatabase $xoopsDB, string $sql, ?int $limit = null, ?int $start = null): \mysqli_result |
||
| 464 | } |
||
| 465 | } |
||
| 466 |