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