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