| Total Complexity | 50 |
| Total Lines | 367 |
| 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); |
||
| 34 | class SysUtility |
||
| 35 | { |
||
| 36 | use VersionChecks; //checkVerXoops, checkVerPhp Traits |
||
|
|
|||
| 37 | use ServerStats; // getServerStats Trait |
||
| 38 | use FilesManagement; // Files Management Trait |
||
| 39 | // use ModuleStats; // ModuleStats Trait |
||
| 40 | |||
| 41 | //--------------- Common module methods ----------------------------- |
||
| 42 | |||
| 43 | /** |
||
| 44 | * Access the only instance of this class |
||
| 45 | */ |
||
| 46 | public static function getInstance(): self |
||
| 47 | { |
||
| 48 | static $instance; |
||
| 49 | if (null === $instance) { |
||
| 50 | $instance = new static(); |
||
| 51 | } |
||
| 52 | |||
| 53 | return $instance; |
||
| 54 | } |
||
| 55 | |||
| 56 | public static function selectSorting(string $text, string $form_sort): string |
||
| 57 | { |
||
| 58 | global $start, $order, $sort; |
||
| 59 | |||
| 60 | $selectView = ''; |
||
| 61 | $helper = Helper::getInstance(); |
||
| 62 | |||
| 63 | //$pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getConfig('modicons16'); |
||
| 64 | $pathModIcon16 = $helper->url($helper->getModule()->getInfo('modicons16')); |
||
| 65 | |||
| 66 | $selectView = '<form name="form_switch" id="form_switch" action="' . Request::getString('REQUEST_URI', '', 'SERVER') . '" method="post"><span style="font-weight: bold;">' . $text . '</span>'; |
||
| 67 | //$sorts = $sort == 'asc' ? 'desc' : 'asc'; |
||
| 68 | if ($form_sort == $sort) { |
||
| 69 | $sel1 = 'asc' === $order ? 'selasc.png' : 'asc.png'; |
||
| 70 | $sel2 = 'desc' === $order ? 'seldesc.png' : 'desc.png'; |
||
| 71 | } else { |
||
| 72 | $sel1 = 'asc.png'; |
||
| 73 | $sel2 = 'desc.png'; |
||
| 74 | } |
||
| 75 | $selectView .= ' <a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=asc"><img src="' . $pathModIcon16 . '/' . $sel1 . '" title="ASC" alt="ASC"></a>'; |
||
| 76 | $selectView .= '<a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=desc"><img src="' . $pathModIcon16 . '/' . $sel2 . '" title="DESC" alt="DESC"></a>'; |
||
| 77 | $selectView .= '</form>'; |
||
| 78 | |||
| 79 | return $selectView; |
||
| 80 | } |
||
| 81 | |||
| 82 | /***************Blocks***************/ |
||
| 83 | public static function blockAddCatSelect(array $cats): string |
||
| 84 | { |
||
| 85 | $catSql = ''; |
||
| 86 | if (!empty($cats)) { |
||
| 87 | $catSql = '(' . \current($cats); |
||
| 88 | \array_shift($cats); |
||
| 89 | foreach ($cats as $cat) { |
||
| 90 | $catSql .= ',' . $cat; |
||
| 91 | } |
||
| 92 | $catSql .= ')'; |
||
| 93 | } |
||
| 94 | |||
| 95 | return $catSql; |
||
| 96 | } |
||
| 97 | |||
| 98 | public static function metaKeywords(string $content): void |
||
| 99 | { |
||
| 100 | global $xoopsTpl, $xoTheme; |
||
| 101 | $myts = \MyTextSanitizer::getInstance(); |
||
| 102 | $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content)); |
||
| 103 | if (\is_object($xoTheme)) { |
||
| 104 | $xoTheme->addMeta('meta', 'keywords', \strip_tags($content)); |
||
| 105 | } else { // Compatibility for old Xoops versions |
||
| 106 | $xoopsTpl->assign('xoops_metaKeywords', \strip_tags($content)); |
||
| 107 | } |
||
| 108 | } |
||
| 109 | |||
| 110 | public static function metaDescription(string $content): void |
||
| 111 | { |
||
| 112 | global $xoopsTpl, $xoTheme; |
||
| 113 | $myts = \MyTextSanitizer::getInstance(); |
||
| 114 | $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content)); |
||
| 115 | if (\is_object($xoTheme)) { |
||
| 116 | $xoTheme->addMeta('meta', 'description', \strip_tags($content)); |
||
| 117 | } else { // Compatibility for old Xoops versions |
||
| 118 | $xoopsTpl->assign('xoops_metaDescription', \strip_tags($content)); |
||
| 119 | } |
||
| 120 | } |
||
| 121 | |||
| 122 | public static function enumerate(string $tableName, string $columnName): ?array |
||
| 123 | { |
||
| 124 | $table = $GLOBALS['xoopsDB']->prefix($tableName); |
||
| 125 | |||
| 126 | // $result = $GLOBALS['xoopsDB']->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS |
||
| 127 | // WHERE TABLE_NAME = '" . $table . "' AND COLUMN_NAME = '" . $columnName . "'") |
||
| 128 | // || exit ($GLOBALS['xoopsDB']->error()); |
||
| 129 | |||
| 130 | $sql = 'SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $table . '" AND COLUMN_NAME = "' . $columnName . '"'; |
||
| 131 | $result = $GLOBALS['xoopsDB']->query($sql); |
||
| 132 | if (!$result instanceof \mysqli_result) { |
||
| 133 | // trigger_error($GLOBALS['xoopsDB']->error()); |
||
| 134 | $logger = \XoopsLogger::getInstance(); |
||
| 135 | $logger->handleError(\E_USER_WARNING, $sql, __FILE__, __LINE__); |
||
| 136 | |||
| 137 | return null; |
||
| 138 | } |
||
| 139 | |||
| 140 | $row = $GLOBALS['xoopsDB']->fetchBoth($result); |
||
| 141 | $enumList = \explode(',', \str_replace("'", '', \mb_substr($row['COLUMN_TYPE'], 5, -6))); |
||
| 142 | |||
| 143 | return $enumList; |
||
| 144 | } |
||
| 145 | |||
| 146 | /** |
||
| 147 | * Clone a record in a dB |
||
| 148 | * |
||
| 149 | * @TODO need to exit more gracefully on error. Should throw/trigger error and then return false |
||
| 150 | * |
||
| 151 | * @param string $tableName name of dB table (without prefix) |
||
| 152 | * @param string $idField name of field (column) in dB table |
||
| 153 | * @param int $id item id to clone |
||
| 154 | */ |
||
| 155 | public static function cloneRecord(string $tableName, string $idField, int $id): ?int |
||
| 181 | } |
||
| 182 | |||
| 183 | /** |
||
| 184 | * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags |
||
| 185 | * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags |
||
| 186 | * www.cakephp.org |
||
| 187 | * |
||
| 188 | * @TODO: Refactor to consider HTML5 & void (self-closing) elements |
||
| 189 | * @TODO: Consider using https://github.com/jlgrall/truncateHTML/blob/master/truncateHTML.php |
||
| 190 | * |
||
| 191 | * @param string $text String to truncate. |
||
| 192 | * @param int|null $length Length of returned string, including ellipsis. |
||
| 193 | * @param string $ending Ending to be appended to the trimmed string. |
||
| 194 | * @param bool $exact If false, $text will not be cut mid-word |
||
| 195 | * @param bool $considerHtml If true, HTML tags would be handled correctly |
||
| 196 | * |
||
| 197 | * @return string Trimmed string. |
||
| 198 | */ |
||
| 199 | public static function truncateHtml( |
||
| 200 | string $text, |
||
| 201 | ?int $length = 100, |
||
| 202 | string $ending = '...', |
||
| 203 | bool $exact = false, |
||
| 204 | bool $considerHtml = true |
||
| 205 | ): string { |
||
| 206 | $openTags = []; |
||
| 207 | if ($considerHtml) { |
||
| 208 | // if the plain text is shorter than the maximum length, return the whole text |
||
| 209 | if (\mb_strlen(\preg_replace('/<.*?' . '>/', '', $text)) <= $length) { |
||
| 210 | return $text; |
||
| 211 | } |
||
| 212 | // splits all html-tags to scanable lines |
||
| 213 | \preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, \PREG_SET_ORDER); |
||
| 214 | $totalLength = \mb_strlen($ending); |
||
| 215 | //$openTags = []; |
||
| 216 | $truncate = ''; |
||
| 217 | foreach ($lines as $lineMatchings) { |
||
| 218 | // if there is any html-tag in this line, handle it and add it (uncounted) to the output |
||
| 219 | if (!empty($lineMatchings[1])) { |
||
| 220 | // if it's an "empty element" with or without xhtml-conform closing slash |
||
| 221 | if (\preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $lineMatchings[1])) { |
||
| 222 | // do nothing |
||
| 223 | // if tag is a closing tag |
||
| 224 | } elseif (\preg_match('/^<\s*\/(\S+?)\s*>$/s', $lineMatchings[1], $tagMatchings)) { |
||
| 225 | // delete tag from $openTags list |
||
| 226 | $pos = \array_search($tagMatchings[1], $openTags, true); |
||
| 227 | if (false !== $pos) { |
||
| 228 | unset($openTags[$pos]); |
||
| 229 | } |
||
| 230 | // if tag is an opening tag |
||
| 231 | } elseif (\preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $lineMatchings[1], $tagMatchings)) { |
||
| 232 | // add tag to the beginning of $openTags list |
||
| 233 | \array_unshift($openTags, \mb_strtolower($tagMatchings[1])); |
||
| 234 | } |
||
| 235 | // add html-tag to $truncate'd text |
||
| 236 | $truncate .= $lineMatchings[1]; |
||
| 237 | } |
||
| 238 | // calculate the length of the plain text part of the line; handle entities as one character |
||
| 239 | $contentLength = \mb_strlen(\preg_replace('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', ' ', $lineMatchings[2])); |
||
| 240 | if ($totalLength + $contentLength > $length) { |
||
| 241 | // the number of characters which are left |
||
| 242 | $left = $length - $totalLength; |
||
| 243 | $entitiesLength = 0; |
||
| 244 | // search for html entities |
||
| 245 | if (\preg_match_all('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', $lineMatchings[2], $entities, \PREG_OFFSET_CAPTURE)) { |
||
| 246 | // calculate the real length of all entities in the legal range |
||
| 247 | foreach ($entities[0] as $entity) { |
||
| 248 | if ($left >= $entity[1] + 1 - $entitiesLength) { |
||
| 249 | $left--; |
||
| 250 | $entitiesLength += \mb_strlen($entity[0]); |
||
| 251 | } else { |
||
| 252 | // no more characters left |
||
| 253 | break; |
||
| 254 | } |
||
| 255 | } |
||
| 256 | } |
||
| 257 | $truncate .= \mb_substr($lineMatchings[2], 0, $left + $entitiesLength); |
||
| 258 | // maximum length is reached, so get off the loop |
||
| 259 | break; |
||
| 260 | } |
||
| 261 | $truncate .= $lineMatchings[2]; |
||
| 262 | $totalLength += $contentLength; |
||
| 263 | |||
| 264 | // if the maximum length is reached, get off the loop |
||
| 265 | if ($totalLength >= $length) { |
||
| 266 | break; |
||
| 267 | } |
||
| 268 | } |
||
| 269 | } else { |
||
| 270 | if (\mb_strlen($text) <= $length) { |
||
| 271 | return $text; |
||
| 272 | } |
||
| 273 | $truncate = \mb_substr($text, 0, $length - \mb_strlen($ending)); |
||
| 274 | } |
||
| 275 | // if the words shouldn't be cut in the middle... |
||
| 276 | if (!$exact) { |
||
| 277 | // ...search the last occurance of a space... |
||
| 278 | $spacepos = \mb_strrpos($truncate, ' '); |
||
| 279 | if (isset($spacepos)) { |
||
| 280 | // ...and cut the text in this position |
||
| 281 | $truncate = \mb_substr($truncate, 0, $spacepos); |
||
| 282 | } |
||
| 283 | } |
||
| 284 | // add the defined ending to the text |
||
| 285 | $truncate .= $ending; |
||
| 286 | if ($considerHtml) { |
||
| 287 | // close all unclosed html-tags |
||
| 288 | foreach ($openTags as $tag) { |
||
| 289 | $truncate .= '</' . $tag . '>'; |
||
| 290 | } |
||
| 291 | } |
||
| 292 | |||
| 293 | return $truncate; |
||
| 294 | } |
||
| 295 | |||
| 296 | /** |
||
| 297 | * Get correct text editor based on user rights |
||
| 298 | * |
||
| 299 | * @return \XoopsFormDhtmlTextArea|\XoopsFormEditor |
||
| 300 | */ |
||
| 301 | public static function getEditor(?\Xmf\Module\Helper $helper = null, ?array $options = null): ?\XoopsFormTextArea |
||
| 335 | } |
||
| 336 | |||
| 337 | /** |
||
| 338 | * Check if column in dB table exists |
||
| 339 | * |
||
| 340 | * @param string $fieldname name of dB table field |
||
| 341 | * @param string $table name of dB table (including prefix) |
||
| 342 | * |
||
| 343 | * @return bool true if table exists |
||
| 344 | * @deprecated |
||
| 345 | */ |
||
| 346 | public static function fieldExists(string $fieldname, string $table): bool |
||
| 347 | { |
||
| 348 | $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1); |
||
| 349 | \trigger_error(__METHOD__ . " is deprecated, use Xmf\Database\Tables instead - instantiated from {$trace[0]['file']} line {$trace[0]['line']},"); |
||
| 350 | |||
| 351 | $result = $GLOBALS['xoopsDB']->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'"); |
||
| 352 | |||
| 353 | return ($GLOBALS['xoopsDB']->getRowsNum($result) > 0); |
||
| 354 | } |
||
| 355 | |||
| 356 | /** |
||
| 357 | * Function responsible for checking if a directory exists, we can also write in and create an index.html file |
||
| 358 | * |
||
| 359 | * @param string $folder The full path of the directory to check |
||
| 360 | */ |
||
| 361 | public static function prepareFolder(string $folder): void |
||
| 362 | { |
||
| 363 | try { |
||
| 364 | if (!@\mkdir($folder) && !\is_dir($folder)) { |
||
| 365 | throw new \RuntimeException(\sprintf('Unable to create the %s directory', $folder)); |
||
| 366 | } |
||
| 367 | file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>'); |
||
| 368 | } catch (\Throwable $e) { |
||
| 369 | echo 'Caught exception: ', $e->getMessage(), "\n", '<br>'; |
||
| 370 | } |
||
| 371 | } |
||
| 372 | |||
| 373 | /** |
||
| 374 | * Check if dB table exists |
||
| 375 | * |
||
| 376 | * @param string $tablename dB tablename with prefix |
||
| 377 | * @return bool true if table exists |
||
| 378 | */ |
||
| 379 | public static function tableExists(string $tablename): bool |
||
| 380 | { |
||
| 381 | $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1); |
||
| 382 | \trigger_error(__FUNCTION__ . " is deprecated, called from {$trace[0]['file']} line {$trace[0]['line']}"); |
||
| 383 | $GLOBALS['xoopsLogger']->addDeprecated( |
||
| 384 | \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']}" |
||
| 385 | ); |
||
| 386 | $result = $GLOBALS['xoopsDB']->queryF("SHOW TABLES LIKE '$tablename'"); |
||
| 387 | |||
| 388 | return $GLOBALS['xoopsDB']->getRowsNum($result) > 0; |
||
| 389 | } |
||
| 390 | |||
| 391 | /** |
||
| 392 | * Add a field to a mysql table |
||
| 393 | * |
||
| 394 | * @return bool|\mysqli_result |
||
| 395 | */ |
||
| 396 | public static function addField(string $field, string $table) |
||
| 401 | } |
||
| 402 | } |
||
| 403 |