Total Complexity | 50 |
Total Lines | 373 |
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; |
||
|
|||
40 | |||
41 | //checkVerXoops, checkVerPhp Traits |
||
42 | |||
43 | use ServerStats; |
||
44 | |||
45 | // getServerStats Trait |
||
46 | |||
47 | use FilesManagement; |
||
48 | |||
49 | // Files Management Trait |
||
50 | // use ModuleStats; // ModuleStats Trait |
||
51 | |||
52 | //--------------- Common module methods ----------------------------- |
||
53 | |||
54 | /** |
||
55 | * Access the only instance of this class |
||
56 | * |
||
57 | * |
||
58 | */ |
||
59 | public static function getInstance(): SysUtility |
||
60 | { |
||
61 | static $instance; |
||
62 | if (null === $instance) { |
||
63 | $instance = new static(); |
||
64 | } |
||
65 | |||
66 | return $instance; |
||
67 | } |
||
68 | |||
69 | public static function selectSorting(string $text, string $form_sort): string |
||
70 | { |
||
71 | global $start, $order, $sort; |
||
72 | |||
73 | $selectView = ''; |
||
74 | $helper = Helper::getInstance(); |
||
75 | |||
76 | //$pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getConfig('modicons16'); |
||
77 | $pathModIcon16 = $helper->url($helper->getModule()->getInfo('modicons16')); |
||
78 | |||
79 | $selectView = '<form name="form_switch" id="form_switch" action="' . Request::getString('REQUEST_URI', '', 'SERVER') . '" method="post"><span style="font-weight: bold;">' . $text . '</span>'; |
||
80 | //$sorts = $sort == 'asc' ? 'desc' : 'asc'; |
||
81 | if ($form_sort == $sort) { |
||
82 | $sel1 = 'asc' === $order ? 'selasc.png' : 'asc.png'; |
||
83 | $sel2 = 'desc' === $order ? 'seldesc.png' : 'desc.png'; |
||
84 | } else { |
||
85 | $sel1 = 'asc.png'; |
||
86 | $sel2 = 'desc.png'; |
||
87 | } |
||
88 | $selectView .= ' <a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=asc"><img src="' . $pathModIcon16 . '/' . $sel1 . '" title="ASC" alt="ASC"></a>'; |
||
89 | $selectView .= '<a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=desc"><img src="' . $pathModIcon16 . '/' . $sel2 . '" title="DESC" alt="DESC"></a>'; |
||
90 | $selectView .= '</form>'; |
||
91 | |||
92 | return $selectView; |
||
93 | } |
||
94 | |||
95 | /***************Blocks***************/ |
||
96 | public static function blockAddCatSelect(array $cats): string |
||
109 | } |
||
110 | |||
111 | public static function metaKeywords(string $content): void |
||
112 | { |
||
113 | global $xoopsTpl, $xoTheme; |
||
114 | $myts = \MyTextSanitizer::getInstance(); |
||
115 | $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content)); |
||
116 | if (\is_object($xoTheme)) { |
||
117 | $xoTheme->addMeta('meta', 'keywords', \strip_tags($content)); |
||
118 | } else { // Compatibility for old Xoops versions |
||
119 | $xoopsTpl->assign('xoops_metaKeywords', \strip_tags($content)); |
||
120 | } |
||
121 | } |
||
122 | |||
123 | public static function metaDescription(string $content): void |
||
124 | { |
||
125 | global $xoopsTpl, $xoTheme; |
||
126 | $myts = \MyTextSanitizer::getInstance(); |
||
127 | $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content)); |
||
128 | if (\is_object($xoTheme)) { |
||
129 | $xoTheme->addMeta('meta', 'description', \strip_tags($content)); |
||
130 | } else { // Compatibility for old Xoops versions |
||
131 | $xoopsTpl->assign('xoops_metaDescription', \strip_tags($content)); |
||
132 | } |
||
133 | } |
||
134 | |||
135 | public static function enumerate(string $tableName, string $columnName): ?array |
||
136 | { |
||
137 | $table = $GLOBALS['xoopsDB']->prefix($tableName); |
||
138 | |||
139 | // $result = $GLOBALS['xoopsDB']->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS |
||
140 | // WHERE TABLE_NAME = '" . $table . "' AND COLUMN_NAME = '" . $columnName . "'") |
||
141 | // || exit ($GLOBALS['xoopsDB']->error()); |
||
142 | |||
143 | $sql = 'SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $table . '" AND COLUMN_NAME = "' . $columnName . '"'; |
||
144 | $result = $GLOBALS['xoopsDB']->query($sql); |
||
145 | if (!$result instanceof \mysqli_result) { |
||
146 | // exit($GLOBALS['xoopsDB']->error()); |
||
147 | $logger = \XoopsLogger::getInstance(); |
||
148 | $logger->handleError(\E_USER_WARNING, $sql, __FILE__, __LINE__); |
||
149 | return null; |
||
150 | } |
||
151 | |||
152 | $row = $GLOBALS['xoopsDB']->fetchBoth($result); |
||
153 | $enumList = \explode(',', \str_replace("'", '', \mb_substr($row['COLUMN_TYPE'], 5, -6))); |
||
154 | return $enumList; |
||
155 | } |
||
156 | |||
157 | /** |
||
158 | * Clone a record in a dB |
||
159 | * |
||
160 | * @TODO need to exit more gracefully on error. Should throw/trigger error and then return false |
||
161 | * |
||
162 | * @param string $tableName name of dB table (without prefix) |
||
163 | * @param string $idField name of field (column) in dB table |
||
164 | * @param int $id item id to clone |
||
165 | */ |
||
166 | public static function cloneRecord(string $tableName, string $idField, int $id): ?int |
||
167 | { |
||
168 | $newId = null; |
||
169 | $tempTable = ''; |
||
170 | $table = $GLOBALS['xoopsDB']->prefix($tableName); |
||
171 | // copy content of the record you wish to clone |
||
172 | $sql = "SELECT * FROM $table WHERE $idField='" . $id . "' "; |
||
173 | $result = $GLOBALS['xoopsDB']->query($sql); |
||
174 | |||
175 | if ($result instanceof \mysqli_result) { |
||
176 | $tempTable = $GLOBALS['xoopsDB']->fetchArray($result, \MYSQLI_ASSOC); |
||
177 | } |
||
178 | |||
179 | if (!$tempTable) { |
||
180 | exit($GLOBALS['xoopsDB']->error()); |
||
181 | } |
||
182 | // set the auto-incremented id's value to blank. |
||
183 | unset($tempTable[$idField]); |
||
184 | // insert cloned copy of the original record |
||
185 | $sql = "INSERT INTO $table (" . \implode(', ', \array_keys($tempTable)) . ") VALUES ('" . \implode("', '", $tempTable) . "')"; |
||
186 | $result = $GLOBALS['xoopsDB']->queryF($sql); |
||
187 | if (!$result) { |
||
188 | exit($GLOBALS['xoopsDB']->error()); |
||
189 | } |
||
190 | // Return the new id |
||
191 | $newId = $GLOBALS['xoopsDB']->getInsertId(); |
||
192 | return $newId; |
||
193 | } |
||
194 | |||
195 | /** |
||
196 | * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags |
||
197 | * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags |
||
198 | * www.cakephp.org |
||
199 | * |
||
200 | * @TODO: Refactor to consider HTML5 & void (self-closing) elements |
||
201 | * @TODO: Consider using https://github.com/jlgrall/truncateHTML/blob/master/truncateHTML.php |
||
202 | * |
||
203 | * @param string $text String to truncate. |
||
204 | * @param int|null $length Length of returned string, including ellipsis. |
||
205 | * @param string $ending Ending to be appended to the trimmed string. |
||
206 | * @param bool $exact If false, $text will not be cut mid-word |
||
207 | * @param bool $considerHtml If true, HTML tags would be handled correctly |
||
208 | * |
||
209 | * @return string Trimmed string. |
||
210 | */ |
||
211 | public static function truncateHtml( |
||
212 | string $text, |
||
213 | ?int $length = 100, |
||
214 | string $ending = '...', |
||
215 | bool $exact = false, |
||
216 | bool $considerHtml = true |
||
217 | ): string { |
||
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 |
||
346 | } |
||
347 | |||
348 | /** |
||
349 | * Check if column in dB table exists |
||
350 | * |
||
351 | * @param string $fieldname name of dB table field |
||
352 | * @param string $table name of dB table (including prefix) |
||
353 | * |
||
354 | * @return bool true if table exists |
||
355 | * @deprecated |
||
356 | */ |
||
357 | public static function fieldExists(string $fieldname, string $table): bool |
||
358 | { |
||
359 | $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1); |
||
360 | \trigger_error(__METHOD__ . " is deprecated, use Xmf\Database\Tables instead - instantiated from {$trace[0]['file']} line {$trace[0]['line']},"); |
||
361 | |||
362 | $result = $GLOBALS['xoopsDB']->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'"); |
||
363 | return ($GLOBALS['xoopsDB']->getRowsNum($result) > 0); |
||
364 | } |
||
365 | |||
366 | /** |
||
367 | * Function responsible for checking if a directory exists, we can also write in and create an index.html file |
||
368 | * |
||
369 | * @param string $folder The full path of the directory to check |
||
370 | */ |
||
371 | public static function prepareFolder(string $folder): void |
||
372 | { |
||
373 | try { |
||
374 | if (!@\mkdir($folder) && !\is_dir($folder)) { |
||
375 | throw new \RuntimeException(\sprintf('Unable to create the %s directory', $folder)); |
||
376 | } |
||
377 | file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>'); |
||
378 | } catch (\Exception $e) { |
||
379 | echo 'Caught exception: ', $e->getMessage(), "\n", '<br>'; |
||
380 | } |
||
381 | } |
||
382 | |||
383 | /** |
||
384 | * Check if dB table exists |
||
385 | * |
||
386 | * @param string $tablename dB tablename with prefix |
||
387 | * @return bool true if table exists |
||
388 | */ |
||
389 | public static function tableExists(string $tablename): bool |
||
399 | } |
||
400 | |||
401 | /** |
||
402 | * Add a field to a mysql table |
||
403 | * |
||
404 | * @return bool|\mysqli_result |
||
405 | */ |
||
406 | public static function addField(string $field, string $table) |
||
410 | } |
||
411 | } |
||
412 |