PluginProbe ʕ •ᴥ•ʔ
AI Copilot – Content Generator / 1.2.0
AI Copilot – Content Generator v1.2.0
1.5.4 1.4.21 1.4.18 1.4.19 1.4.20 trunk 1.0.4 1.1.0 1.2.0 1.2.1 1.2.10 1.2.11 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8 1.2.9 1.3.0 1.3.1 1.3.2 1.4.0 1.4.1 1.4.10 1.4.11 1.4.12 1.4.13 1.4.14 1.4.15 1.4.17 1.4.2 1.4.3 1.4.4 1.4.5 1.4.6 1.4.7 1.4.9
ai-copilot-content-generator / classes / utils.php
ai-copilot-content-generator / classes Last commit date
tables 1 year ago assets.php 1 year ago baseObject.php 1 year ago cache.php 1 year ago controller.php 1 year ago date.php 1 year ago db.php 1 year ago dispatcher.php 1 year ago errors.php 1 year ago field.php 1 year ago fieldAdapter.php 1 year ago frame.php 1 year ago helper.php 1 year ago html.php 1 year ago installer.php 1 year ago installerDbUpdater.php 1 year ago modInstaller.php 1 year ago model.php 1 year ago module.php 1 year ago req.php 1 year ago response.php 1 year ago table.php 1 year ago uri.php 1 year ago user.php 1 year ago utils.php 1 year ago validator.php 1 year ago view.php 1 year ago
utils.php
982 lines
1 <?php
2 if ( ! defined( 'ABSPATH' ) ) {
3 exit;
4 }
5 class WaicUtils {
6 public static $currentTZ = null;
7 public static $currentDateFormat = null;
8 public static $currentDateFormatDB = 'Y-m-d';
9
10 public static function jsonEncode( $arr, $ent = false ) {
11 return ( is_array($arr) || is_object($arr) ) ? waicJsonEncodeUTFnormal($arr, $ent) : waicJsonEncodeUTFnormal(array());
12 }
13 public static function jsonDecode( $str ) {
14 if (is_array($str)) {
15 return $str;
16 }
17 if (is_object($str)) {
18 return (array) $str;
19 }
20 return empty($str) ? array() : json_decode($str, true);
21 }
22 public static function unserialize( $data ) {
23 return unserialize($data);
24 }
25 public static function serialize( $data ) {
26 return serialize($data);
27 }
28 public static function createDir( $path, $params = array('chmod' => null, 'httpProtect' => false) ) {
29 if (@mkdir($path)) {
30 if (!is_null($params['chmod'])) {
31 @chmod($path, $params['chmod']);
32 }
33 if (!empty($params['httpProtect'])) {
34 self::httpProtectDir($path);
35 }
36 return true;
37 }
38 return false;
39 }
40 public static function httpProtectDir( $path ) {
41 $content = 'DENY FROM ALL';
42 if (strrpos($path, WAIC_DS) != strlen($path)) {
43 $path .= WAIC_DS;
44 }
45 if (file_put_contents($path . '.htaccess', $content)) {
46 return true;
47 }
48 return false;
49 }
50 /**
51 * Copy all files from one directory ($source) to another ($destination)
52 *
53 * @param string $source path to source directory
54 * @params string $destination path to destination directory
55 */
56 public static function copyDirectories( $source, $destination ) {
57 if (is_dir($source)) {
58 @mkdir($destination);
59 $directory = dir($source);
60 while ( false !== ( $readdirectory = $directory->read() ) ) {
61 if ( ( '.' == $readdirectory ) || ( '..' == $readdirectory ) ) {
62 continue;
63 }
64 $PathDir = $source . '/' . $readdirectory;
65 if (is_dir($PathDir)) {
66 self::copyDirectories( $PathDir, $destination . '/' . $readdirectory );
67 continue;
68 }
69 copy( $PathDir, $destination . '/' . $readdirectory );
70 }
71 $directory->close();
72 } else {
73 copy( $source, $destination );
74 }
75 }
76 public static function getIP() {
77 $res = '';
78 if (!isset($_SERVER['HTTP_CLIENT_IP']) || empty($_SERVER['HTTP_CLIENT_IP'])) {
79 if (!isset($_SERVER['HTTP_X_REAL_IP']) || empty($_SERVER['HTTP_X_REAL_IP'])) {
80 if (!isset($_SERVER['HTTP_X_SUCURI_CLIENTIP']) || empty($_SERVER['HTTP_X_SUCURI_CLIENTIP'])) {
81 if (!isset($_SERVER['HTTP_X_FORWARDED_FOR']) || empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
82 $res = empty($_SERVER['REMOTE_ADDR']) ? '' : sanitize_text_field($_SERVER['REMOTE_ADDR']);
83 } else {
84 $res = sanitize_text_field($_SERVER['HTTP_X_FORWARDED_FOR']);
85 }
86 } else {
87 $res = sanitize_text_field($_SERVER['HTTP_X_SUCURI_CLIENTIP']);
88 }
89 } else {
90 $res = sanitize_text_field($_SERVER['HTTP_X_REAL_IP']);
91 }
92 } else {
93 $res = sanitize_text_field($_SERVER['HTTP_CLIENT_IP']);
94 }
95
96 return $res;
97 }
98
99 /**
100 * Parse xml file into simpleXML object
101 *
102 * @param string $path path to xml file
103 * @return mixed object SimpleXMLElement if success, else - false
104 */
105 public static function getXml( $path ) {
106 if (is_file($path)) {
107 return simplexml_load_file($path);
108 }
109 return false;
110 }
111 /**
112 * Check if the element exists in array
113 *
114 * @param array $param
115 */
116 public static function xmlAttrToStr( $param, $element ) {
117 if (isset($param[$element])) {
118 // convert object element to string
119 return (string) $param[$element];
120 } else {
121 return '';
122 }
123 }
124 public static function xmlNodeAttrsToArr( $node ) {
125 $arr = array();
126 foreach ($node->attributes() as $a => $b) {
127 $arr[$a] = self::xmlAttrToStr($node, $a);
128 }
129 return $arr;
130 }
131 public static function deleteFile( $str ) {
132 return @unlink($str);
133 }
134 public static function deleteDir( $str ) {
135 if (is_file($str)) {
136 return self::deleteFile($str);
137 } elseif (is_dir($str)) {
138 $scan = glob(rtrim($str, '/') . '/*');
139 foreach ($scan as $index => $path) {
140 self::deleteDir($path);
141 }
142 return @rmdir($str);
143 }
144 }
145 /**
146 * Retrives list of directories ()
147 */
148 public static function getDirList( $path ) {
149 $res = array();
150 if (is_dir($path)) {
151 $files = scandir($path);
152 foreach ($files as $f) {
153 if ( ( '.' == $f ) || ( '..' == $f ) || ( '.svn' == $f ) ) {
154 continue;
155 }
156 if (!is_dir($path . $f)) {
157 continue;
158 }
159 $res[$f] = array('path' => $path . $f . WAIC_DS);
160 }
161 }
162 return $res;
163 }
164 /**
165 * Retrives list of files
166 */
167 public static function getFilesList( $path ) {
168 $files = array();
169 if (is_dir($path)) {
170 $dirHandle = opendir($path);
171 while ( ( $file = readdir($dirHandle) ) !== false ) {
172 if ( ( '.' != $file ) && ( '..' != $file ) && ( '.svn' != $f ) && is_file($path . WAIC_DS . $file) ) {
173 $files[] = $file;
174 }
175 }
176 }
177 return $files;
178 }
179 /**
180 * Check if $var is object or something another in future
181 */
182 public static function is( $var, $what = '' ) {
183 if (!is_object($var)) {
184 return false;
185 }
186 if (get_class($var) == $what) {
187 return true;
188 }
189 return false;
190 }
191 /**
192 * Get array with all monthes of year, uses in paypal pro and sagepay payment modules for now, than - who knows)
193 *
194 * @return array monthes
195 */
196 public static function getMonthesArray() {
197 static $monthsArray = array();
198 //Some cache
199 if (!empty($monthsArray)) {
200 return $monthsArray;
201 }
202 for ($i = 1; $i < 13; $i++) {
203 $monthsArray[sprintf('%02d', $i)] = strftime('%B', mktime(0, 0, 0, $i, 1, 2000));
204 }
205 return $monthsArray;
206 }
207 public static function getWeekDaysArray() {
208 $timestamp = strtotime('next Sunday');
209 $days = array();
210 for ($i = 0; $i < 7; $i++) {
211 $day = strftime('%A', $timestamp);
212 $days[ strtolower($day) ] = $day;
213 $timestamp = strtotime('+1 day', $timestamp);
214 }
215 return $days;
216 }
217 /**
218 * Get an array with years range from current year
219 *
220 * @param int $from - how many years from today ago
221 * @param int $to - how many years in future
222 * @param $formatKey - format for keys in array, @see strftime
223 * @param $formatVal - format for values in array, @see strftime
224 * @return array - years
225 */
226 public static function getYearsArray( $from, $to, $formatKey = '%Y', $formatVal = '%Y' ) {
227 $today = getdate();
228 $yearsArray = array();
229 for ($i = $today['year'] - $from; $i <= $today['year'] + $to; $i++) {
230 $yearsArray[strftime($formatKey, mktime(0, 0, 0, 1, 1, $i))] = strftime($formatVal, mktime(0, 0, 0, 1, 1, $i));
231 }
232 return $yearsArray;
233 }
234 /**
235 * Make replacement in $text, where it will be find all keys with prefix ":" and replace it with corresponding value
236 *
237 * @see email_templatesModel::renderContent()
238 * @see checkoutView::getSuccessPage()
239 */
240 public static function makeVariablesReplacement( $text, $variables ) {
241 if (!empty($text) && !empty($variables) && is_array($variables)) {
242 foreach ($variables as $k => $v) {
243 $text = str_replace(':' . $k, $v, $text);
244 }
245 return $text;
246 }
247 return false;
248 }
249 /**
250 * Retrive full directory of plugin
251 *
252 * @param string $name - plugin name
253 * @return string full path in file system to plugin directory
254 */
255 public static function getPluginDir( $name = '' ) {
256 return WP_PLUGIN_DIR . WAIC_DS . $name . WAIC_DS;
257 }
258 public static function getPluginPath( $name = '' ) {
259 $path = plugins_url($name) . '/';
260 if (substr($path, 0, 4) != 'http') {
261 $home = home_url();
262 if (is_ssl() && substr($home, 0, 5) != 'https') {
263 $home = 'https' . substr($home, 4);
264 }
265 $path = $home . ( substr($path, 0, 1) == '/' ? '' : '/' ) . $path;
266 }
267 return $path;
268 }
269 public static function getExtModDir( $plugName ) {
270 return self::getPluginDir($plugName);
271 }
272 public static function getExtModPath( $plugName ) {
273 return self::getPluginPath($plugName);
274 }
275 public static function getCurrentWPThemePath() {
276 return get_template_directory_uri();
277 }
278 public static function isThisCommercialEdition() {
279 foreach (WaicFrame::_()->getModules() as $m) {
280 if (is_object($m) && $m->isExternal()) {
281 return true;
282 }
283 }
284 return false;
285 }
286 public static function checkNum( $val, $default = 0 ) {
287 if (!empty($val) && is_numeric($val)) {
288 return $val;
289 }
290 return $default;
291 }
292 public static function checkString( $val, $default = '' ) {
293 if (!empty($val) && is_string($val)) {
294 return $val;
295 }
296 return $default;
297 }
298 /**
299 * Retrives extension of file
300 *
301 * @param string $path - path to a file
302 * @return string - file extension
303 */
304 public static function getFileExt( $path ) {
305 return strtolower( pathinfo($path, PATHINFO_EXTENSION) );
306 }
307 public static function getRandStr( $length = 10, $allowedChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', $params = array() ) {
308 $result = '';
309 $allowedCharsLen = strlen($allowedChars);
310 if (isset($params['only_lowercase']) && $params['only_lowercase']) {
311 $allowedChars = strtolower($allowedChars);
312 }
313 while (strlen($result) < $length) {
314 $result .= substr($allowedChars, rand(0, $allowedCharsLen), 1);
315 }
316
317 return $result;
318 }
319 /**
320 * Get current host location
321 *
322 * @return string host string
323 */
324 public static function getHost() {
325 return empty($_SERVER['HTTP_HOST']) ? '' : sanitize_text_field($_SERVER['HTTP_HOST']);
326 }
327 /**
328 * Check if device is mobile
329 *
330 * @return bool true if user are watching this site from mobile device
331 */
332 public static function isMobile() {
333 waicImportClass('Mobile_Detect', WAIC_HELPERS_DIR . 'mobileDetect.php');
334 $mobileDetect = new Mobile_Detect();
335 return $mobileDetect->isMobile();
336 }
337 /**
338 * Check if device is tablet
339 *
340 * @return bool true if user are watching this site from tablet device
341 */
342 public static function isTablet() {
343 waicImportClass('Mobile_Detect', WAIC_HELPERS_DIR . 'mobileDetect.php');
344 $mobileDetect = new Mobile_Detect();
345 return $mobileDetect->isTablet();
346 }
347 public static function getUploadsDir() {
348 $uploadDir = wp_upload_dir();
349 return $uploadDir['basedir'];
350 }
351 public static function getUploadsPath() {
352 $uploadDir = wp_upload_dir();
353 return $uploadDir['baseurl'];
354 }
355 public static function arrToCss( $data ) {
356 $res = '';
357 if (!empty($data)) {
358 foreach ($data as $k => $v) {
359 $res .= $k . ':' . $v . ';';
360 }
361 }
362 return $res;
363 }
364 /**
365 * Activate all CSP Plugins
366 *
367 * @return NULL Check if it's site or multisite and activate.
368 */
369 public static function activatePlugin() {
370 global $wpdb;
371 if (WAIC_TEST_MODE) {
372 add_action('activated_plugin', array(WaicFrame::_(), 'savePluginActivationErrors'));
373 }
374 if (function_exists('is_multisite') && is_multisite()) {
375 $blog_id = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs");
376 foreach ($blog_id as $id) {
377 if (switch_to_blog($id)) {
378 WaicInstaller::init();
379 }
380 }
381 restore_current_blog();
382 return;
383 } else {
384 WaicInstaller::init();
385 }
386 }
387
388 /**
389 * Delete All CSP Plugins
390 *
391 * @return NULL Check if it's site or multisite and decativate it.
392 */
393 public static function deletePlugin() {
394 global $wpdb;
395 if (function_exists('is_multisite') && is_multisite()) {
396 $blog_id = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs");
397 foreach ($blog_id as $id) {
398 if (switch_to_blog($id)) {
399 WaicInstaller::delete();
400 }
401 }
402 restore_current_blog();
403 return;
404 } else {
405 WaicInstaller::delete();
406 }
407 }
408 public static function deactivatePlugin() {
409 global $wpdb;
410 if (function_exists('is_multisite') && is_multisite()) {
411 $blog_id = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs");
412 foreach ($blog_id as $id) {
413 if (switch_to_blog($id)) {
414 WaicInstaller::deactivate();
415 }
416 }
417 restore_current_blog();
418 return;
419 } else {
420 WaicInstaller::deactivate();
421 }
422 }
423 public static function isWritable( $filename ) {
424 return is_writable($filename);
425 }
426
427 public static function isReadable( $filename ) {
428 return is_readable($filename);
429 }
430
431 public static function fileExists( $filename ) {
432 return file_exists($filename);
433 }
434 public static function isPluginsPage() {
435 return ( basename(WaicReq::getVar('SCRIPT_NAME', 'server')) === 'plugins.php' );
436 }
437 public static function isSessionStarted() {
438 if (version_compare(PHP_VERSION, '5.4.0') >= 0 && function_exists('session_status')) {
439 return !( session_status() == PHP_SESSION_NONE );
440 } else {
441 return !( session_id() == '' );
442 }
443 }
444 public static function generateBgStyle( $data ) {
445 $stageBgStyles = array();
446 $stageBgStyle = '';
447 switch ($data['type']) {
448 case 'color':
449 $stageBgStyles[] = 'background-color: ' . $data['color'];
450 $stageBgStyles[] = 'opacity: ' . $data['opacity'];
451 break;
452 case 'img':
453 $stageBgStyles[] = 'background-image: url(' . $data['img'] . ')';
454 switch ($data['img_pos']) {
455 case 'center':
456 $stageBgStyles[] = 'background-repeat: no-repeat';
457 $stageBgStyles[] = 'background-position: center center';
458 break;
459 case 'tile':
460 $stageBgStyles[] = 'background-repeat: repeat';
461 break;
462 case 'stretch':
463 $stageBgStyles[] = 'background-repeat: no-repeat';
464 $stageBgStyles[] = '-moz-background-size: 100% 100%';
465 $stageBgStyles[] = '-webkit-background-size: 100% 100%';
466 $stageBgStyles[] = '-o-background-size: 100% 100%';
467 $stageBgStyles[] = 'background-size: 100% 100%';
468 break;
469 }
470 break;
471 }
472 if (!empty($stageBgStyles)) {
473 $stageBgStyle = implode(';', $stageBgStyles);
474 }
475 return $stageBgStyle;
476 }
477 /**
478 * Parse wordpress post/page/custom post type content for images and return it's IDs if there are images
479 *
480 * @param string $content Post/page/custom post type content
481 * @return array List of images IDs from content
482 */
483 public static function parseImgIds( $content ) {
484 $res = array();
485 preg_match_all('/wp-image-(?<ID>\d+)/', $content, $matches);
486 if ($matches && isset($matches['ID']) && !empty($matches['ID'])) {
487 $res = $matches['ID'];
488 }
489 return $res;
490 }
491 /**
492 * Retrive file path in file system from provided URL, it should be in wp-content/uploads
493 *
494 * @param string $url File url path, should be in wp-content/uploads
495 * @return string Path in file system to file
496 */
497 public static function getUploadFilePathFromUrl( $url ) {
498 $uploadsPath = self::getUploadsPath();
499 $uploadsDir = self::getUploadsDir();
500 return str_replace($uploadsPath, $uploadsDir, $url);
501 }
502 /**
503 * Retrive file URL from provided file system path, it should be in wp-content/uploads
504 *
505 * @param string $path File path, should be in wp-content/uploads
506 * @return string URL to file
507 */
508 public static function getUploadUrlFromFilePath( $path ) {
509 $uploadsPath = self::getUploadsPath();
510 $uploadsDir = self::getUploadsDir();
511 return str_replace($uploadsDir, $uploadsPath, $path);
512 }
513 public static function getUserBrowserString() {
514 return isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field($_SERVER['HTTP_USER_AGENT']) : false;
515 }
516 public static function getBrowser() {
517 $u_agent = self::getUserBrowserString();
518 $bname = 'Unknown';
519 $platform = 'Unknown';
520 $version = '';
521 $pattern = '';
522
523 if ($u_agent) {
524 //First get the platform?
525 if (preg_match('/linux/i', $u_agent)) {
526 $platform = 'linux';
527 } elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
528 $platform = 'mac';
529 } elseif (preg_match('/windows|win32/i', $u_agent)) {
530 $platform = 'windows';
531 }
532 // Next get the name of the useragent yes seperately and for good reason
533 if ( ( preg_match('/MSIE/i', $u_agent) && !preg_match('/Opera/i', $u_agent) ) || ( strpos($u_agent, 'Trident/7.0; rv:11.0') !== false ) ) {
534 $bname = 'Internet Explorer';
535 $ub = 'MSIE';
536 } elseif (preg_match('/Firefox/i', $u_agent)) {
537 $bname = 'Mozilla Firefox';
538 $ub = 'Firefox';
539 } elseif (preg_match('/Chrome/i', $u_agent)) {
540 $bname = 'Google Chrome';
541 $ub = 'Chrome';
542 } elseif (preg_match('/Safari/i', $u_agent)) {
543 $bname = 'Apple Safari';
544 $ub = 'Safari';
545 } elseif (preg_match('/Opera/i', $u_agent)) {
546 $bname = 'Opera';
547 $ub = 'Opera';
548 } elseif (preg_match('/Netscape/i', $u_agent)) {
549 $bname = 'Netscape';
550 $ub = 'Netscape';
551 }
552
553 // finally get the correct version number
554 $known = array('Version', $ub, 'other');
555 $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
556
557 // see how many we have
558 $i = count($matches['browser']);
559 if (1 != $i) {
560 //we will have two since we are not using 'other' argument yet
561 //see if version is before or after the name
562 if ( strripos($u_agent, 'Version') < strripos($u_agent, $ub) ) {
563 $version = $matches['version'][0];
564 } else {
565 $version = $matches['version'][1];
566 }
567 } else {
568 $version = $matches['version'][0];
569 }
570 }
571
572 // check if we have a number
573 if ( ( null == $version ) || ( '' == $version ) ) {
574 $version = '?';
575 }
576
577 return array(
578 'userAgent' => $u_agent,
579 'name' => $bname,
580 'version' => $version,
581 'platform' => $platform,
582 'pattern' => $pattern
583 );
584 }
585 public static function getBrowsersList() {
586 return array(
587 'Unknown', 'Internet Explorer', 'Mozilla Firefox', 'Google Chrome', 'Apple Safari',
588 'Opera', 'Netscape',
589 );
590 }
591 public static function getLangCode2Letter() {
592 $langCode = self::getLangCode();
593 return strlen($langCode) > 2 ? substr($langCode, 0, 2) : $langCode;
594 }
595 public static function getLangCode() {
596 return get_locale();
597 }
598 public static function getBrowserLangCode() {
599 return isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && !empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])
600 ? strtolower(substr(sanitize_text_field($_SERVER['HTTP_ACCEPT_LANGUAGE']), 0, 2))
601 : self::getLangCode2Letter();
602 }
603 public static function getTimeRange() {
604 $time = array();
605 $hours = range(1, 11);
606 array_unshift($hours, 12);
607 $k = 0;
608 $count = count($hours);
609 for ($i = 0; $i < 4 * $count; $i++) {
610 $newItem = $hours[ $k ];
611 $newItem .= ':' . ( ( $i % 2 ) ? '30' : '00' );
612 $newItem .= ( $i < $count * 2 ) ? 'am' : 'pm';
613 if ($i % 2) {
614 $k++;
615 }
616 if ($i == $count * 2 - 1) {
617 $k = 0;
618 }
619 $time[] = $newItem;
620 }
621 return array_combine($time, $time);
622 }
623 public static function getSearchEnginesList() {
624 return array(
625 'google.com' => array('label' => 'Google'),
626 'yahoo.com' => array('label' => 'Yahoo!'),
627 'youdao.com' => array('label' => 'Youdao'),
628 'yandex' => array('label' => 'Yandex'),
629 'sogou.com' => array('label' => 'Sogou'),
630 'qwant.com' => array('label' => 'Qwant'),
631 'bing.com' => array('label' => 'Bing'),
632 'munax.com' => array('label' => 'Munax'),
633 );
634 }
635 public static function getSocialList() {
636 return array(
637 'facebook.com' => array('label' => 'Facebook'),
638 'pinterest.com' => array('label' => 'Pinterest'),
639 'instagram.com' => array('label' => 'Instagram'),
640 'yelp.com' => array('label' => 'Yelp'),
641 'vk.com' => array('label' => 'VKontakte'),
642 'myspace.com' => array('label' => 'Myspace'),
643 'linkedin.com' => array('label' => 'LinkedIn'),
644 'plus.google.com' => array('label' => 'Google+'),
645 'google.com' => array('label' => 'Google'),
646 );
647 }
648 public static function getReferalUrl() {
649 // Simple for now
650 return WaicReq::getVar('HTTP_REFERER', 'server');
651 }
652 public static function getReferalHost() {
653 $refUrl = self::getReferalUrl();
654 if (!empty($refUrl)) {
655 $refer = parse_url( $refUrl );
656 if ($refer && isset($refer['host']) && !empty($refer['host'])) {
657 return $refer['host'];
658 }
659 }
660 return false;
661 }
662 public static function getCurrentUserRole() {
663 $roles = self::getCurrentUserRoleList();
664 if ($roles) {
665 $ncaps = count($roles);
666 $role = $roles[$ncaps - 1];
667 return $role;
668 }
669 return false;
670 }
671 public static function getCurrentUserRoleList() {
672 global $current_user, $wpdb;
673 if ($current_user) {
674 $roleKey = $wpdb->prefix . 'capabilities';
675 if (isset($current_user->$roleKey) && !empty($current_user->$roleKey)) {
676 return array_keys($current_user->$roleKey);
677 }
678 }
679 return false;
680 }
681 public static function getAllUserRoles() {
682 return get_editable_roles();
683 }
684 public static function getAllUserRolesList() {
685 $res = array();
686 $roles = self::getAllUserRoles();
687 if (!empty($roles)) {
688 foreach ($roles as $k => $data) {
689 $res[ $k ] = $data['name'];
690 }
691 }
692 return $res;
693 }
694 public static function rgbToArray( $rgb ) {
695 $rgb = array_map('trim', explode(',', trim(str_replace(array('rgb', 'a', '(', ')'), '', $rgb))));
696 return $rgb;
697 }
698 public static function hexToRgb( $hex ) {
699 if (strpos($hex, 'rgb') !== false) { // Maybe it's already in rgb format - just return it as array
700 return self::rgbToArray($hex);
701 }
702 $hex = str_replace('#', '', $hex);
703
704 if (strlen($hex) == 3) {
705 $r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
706 $g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
707 $b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
708 } else {
709 $r = hexdec(substr($hex, 0, 2));
710 $g = hexdec(substr($hex, 2, 2));
711 $b = hexdec(substr($hex, 4, 2));
712 }
713 $rgb = array($r, $g, $b);
714 return $rgb; // returns an array with the rgb values
715 }
716 public static function hexToRgbaStr( $hex, $alpha = 1 ) {
717 $rgbArr = self::hexToRgb($hex);
718 return 'rgba(' . implode(',', $rgbArr) . ',' . $alpha . ')';
719 }
720
721 /**
722 * $typ: 1 - numeric, 2 - array
723 */
724
725 public static function getArrayValue( $params, $name, $default = '', $typ = 0, $arr = false, $zero = false, $leer = false ) {
726 if (!isset($params[$name])) {
727 return $default;
728 }
729 if (empty($params[$name])) {
730 return ( $zero && ( '0' === $params[$name] || 0 === $params[$name] ) ) ? 0 : ( $leer && '' === $params[$name] ? '' : $default );
731 }
732 $value = $params[$name];
733 if (1 == $typ) {
734 if (!is_numeric($value)) {
735 return $default;
736 }
737 } elseif (2 == $typ) {
738 if (!is_array($value)) {
739 return $default;
740 }
741 }
742 if (( false !== $arr ) && !in_array($value, $arr)) {
743 return $default;
744 }
745 return $value;
746 }
747
748 public static function controlNumericValues( $values, $field = 'int' ) {
749 foreach ($values as $k => $val) {
750 $values[$k] = ( 'dec' == $field ? (float) $val : (int) $val );
751 }
752 return $values;
753 }
754 public static function getTimeZone() {
755 if (is_null(self::$currentTZ)) {
756 $tz = wp_timezone_string();
757 if (strpos($tz, ':')) {
758 $offset = $tz;
759 list($hours, $minutes) = explode(':', $offset);
760 if (is_numeric($hours) && is_numeric($minutes)) {
761 $seconds = $hours * 60 * 60 + $minutes * 60;
762 $tz = timezone_name_from_abbr('', $seconds, 1);
763 if (false === $tz) {
764 $tz = timezone_name_from_abbr('', $seconds, 0);
765 }
766 }
767 }
768 self::$currentTZ = ( false !== $tz ? new DateTimeZone($tz) : new DateTimeZone() );
769 }
770 return self::$currentTZ;
771 }
772 public static function getCurrentDateFormatDB() {
773 return self::$currentDateFormatDB;
774 }
775 public static function getCurrentDateFormat() {
776 if (is_null(self::$currentDateFormat)) {
777 $format = WaicFrame::_()->getModule('options')->get('plugin', 'date_format');
778 self::$currentDateFormat = empty($format) ? WAIC_DATE_FORMAT : $format;
779 }
780 return self::$currentDateFormat;
781 }
782 public static function getCurrentDateTimeFormat() {
783 return self::getCurrentDateFormat() . ' H:i';
784 }
785 public static function getCurrentDateTimeFormatDB() {
786 return self::getCurrentDateFormatDB() . ' H:i';
787 }
788
789 public static function getJSDateFormat( $format = '' ) {
790 if (empty($format)) {
791 $format = self::getCurrentDateFormat();
792 }
793 return str_replace(array('Y', 'm', 'd'), array('yy', 'mm', 'dd'), $format);
794 }
795 public static function getJSTimeFormat( $format = 'H:i' ) {
796 return str_replace(array('H', 'i'), array('HH', 'mm'), $format);
797 }
798 public static function getFormatedDateTime( $dt, $format = '' ) {
799 if (empty($format)) {
800 $format = self::getCurrentDateTimeFormat();
801 }
802 return gmdate($format, $dt);
803 }
804 public static function getFormatedDateTimeDB( $dt, $format = '' ) {
805 if (empty($format)) {
806 $format = self::getCurrentDateTimeFormatDB() . ':s';
807 }
808 return gmdate($format, $dt);
809 }
810 public static function getFirstDateMonthDB( $dt = false ) {
811 $format = 'Y-m-01';
812 if (false == $dt) {
813 $data = new DateTime('now', self::getTimeZone());
814 return $data->format($format);
815 }
816 return gmdate($format, $dt);
817 }
818 public static function getConvertedDate( $dt = false, $format = '' ) {
819 if ('' === $format) {
820 $format = self::getCurrentDateFormat();
821 }
822 if (false == $dt) {
823 $data = new DateTime('now', self::getTimeZone());
824 return $data->format($format);
825 }
826 return gmdate($format, $dt);
827 }
828
829 public static function addDays( $days, $format = '', $years = 0 ) {
830 if ('' === $format) {
831 $format = self::getCurrentDateTimeFormat();
832 }
833 $data = new DateTime('now', self::getTimeZone());
834 $days = (int) $days;
835 if (!empty($days)) {
836 if ($days > 0) {
837 $data->add(DateInterval::createFromDateString($days . ' days'));
838 } else {
839 $data->sub(DateInterval::createFromDateString(( $days * ( -1 ) ) . ' days'));
840 }
841 }
842 $years = (int) $years;
843 if (!empty($years)) {
844 if ($years > 0) {
845 $data->add(DateInterval::createFromDateString($years . ' years'));
846 } else {
847 $data->sub(DateInterval::createFromDateString(( $years * ( -1 ) ) . ' years'));
848 }
849 }
850 return $format ? $data->format($format) : $data->format('U') + $data->format('Z');
851
852 }
853 public static function getTimestamp() {
854 $data = new DateTime('now', self::getTimeZone());
855 return $data->format('U') + $data->format('Z');
856 }
857 public static function getTimestampDB() {
858 return self::getFormatedDateTime(self::getTimestamp(), 'Y-m-d H:i:s');
859 }
860 public static function getTimestampFrom( $dt ) {
861 return self::checkDateTime($dt, self::getCurrentDateTimeFormatDB());
862 }
863 public static function checkDateTime( $dt, $format = '' ) {
864 if (empty($format)) {
865 $format = self::getCurrentDateTimeFormat();
866 }
867 $data = date_create_from_format($format, $dt, self::getTimeZone());
868 return $data ? $data->format('U') + $data->format('Z') : false;
869 }
870 public static function convertDateFormat( $dt, $from = '', $to = 'Y-m-d' ) {
871 if (empty($dt)) {
872 return $dt;
873 }
874 if (empty($from)) {
875 $from = self::getCurrentDateFormat();
876 }
877 if ($from == $to) {
878 return $dt;
879 }
880 $dt = self::checkDateTime($dt, $from);
881 return $dt ? self::getFormatedDateTime($dt, $to) : false;
882 }
883 public static function convertDateTimeFormat( $dt, $from = '', $to = '' ) {
884 if (empty($dt)) {
885 return $dt;
886 }
887 if (empty($from)) {
888 $from = self::getCurrentDateTimeFormat();
889 }
890 if (empty($to)) {
891 $to = self::getCurrentDateTimeFormatDB();
892 }
893 if ($from == $to) {
894 return $dt;
895 }
896 $dt = self::checkDateTime($dt, $from);
897 return $dt ? self::getFormatedDateTime($dt, $to) : false;
898 }
899 public static function convertDateTimeToFront( $dt ) {
900 return self::convertDateTimeFormat($dt, self::getCurrentDateTimeFormatDB(), self::getCurrentDateTimeFormat());
901 }
902 public static function convertDateTimeToDB( $dt ) {
903 return self::convertDateTimeFormat($dt);
904 }
905
906 public static function colourBrightness( $hex, $percent ) {
907 // Work out if hash given
908 $hash = '';
909 if (stristr($hex, '#')) {
910 $hex = str_replace('#', '', $hex);
911 $hash = '#';
912 }
913 /// HEX TO RGB
914 $rgb = [hexdec(substr($hex, 0, 2)), hexdec(substr($hex, 2, 2)), hexdec(substr($hex, 4, 2))];
915 //// CALCULATE
916 for ($i = 0; $i < 3; $i++) {
917 // See if brighter or darker
918 if ($percent > 0) {
919 // Lighter
920 $rgb[$i] = round($rgb[$i] * $percent) + round(255 * ( 1 - $percent ));
921 } else {
922 // Darker
923 $positivePercent = $percent - ( $percent * 2 );
924 $rgb[$i] = round($rgb[$i] * ( 1 - $positivePercent )); // round($rgb[$i] * (1-$positivePercent));
925 }
926 // In case rounding up causes us to go to 256
927 if ($rgb[$i] > 255) {
928 $rgb[$i] = 255;
929 }
930 }
931 //// RBG to Hex
932 $hex = '';
933 for ($i = 0; $i < 3; $i++) {
934 // Convert the decimal digit to hex
935 $hexDigit = dechex($rgb[$i]);
936 // Add a leading zero if necessary
937 if (strlen($hexDigit) == 1) {
938 $hexDigit = '0' . $hexDigit;
939 }
940 // Append to the hex string
941 $hex .= $hexDigit;
942 }
943 return $hash . $hex;
944 }
945 public static function isHPOS() {
946 if ( class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class ) ) {
947 return \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled();
948 }
949 return false;
950 }
951 public static function isExistMB() {
952 return function_exists('mb_substr');
953 }
954 public static function mbstrlen($s) {
955 return function_exists('mb_strlen') ? mb_strlen($s) : strlen($s);
956 }
957 public static function mbsubstr($s, $i, $l = null) {
958 return function_exists('mb_substr') ? mb_substr($s, $i, $l) : substr($s, $i, $l);
959 }
960 public static function mbstrrpos($h, $n, $o = 0) {
961 return function_exists('mb_strrpos') ? mb_strrpos($h, $n, $o) : strrpos($h, $n, $o);
962 }
963 public static function mbstrpos($h, $n, $o = 0) {
964 return function_exists('mb_strpos') ? mb_strpos($h, $n, $o) : strpos($h, $n, $o);
965 }
966 public static function getRealUserIp() {
967 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
968 $ip = $_SERVER['HTTP_CLIENT_IP'];
969 } elseif (!empty($_SERVER['HTTP_X_GT_VIEWER_IP'])) {
970 $ip = $_SERVER['HTTP_X_GT_VIEWER_IP'];
971 } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
972 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
973 } elseif (!empty($_SERVER['REMOTE_ADDR'])) {
974 $ip = $_SERVER['REMOTE_ADDR'];
975 } else {
976 $ip = '127.0.0.1';
977 }
978 $part = explode(':', $ip);
979 return $part[0];
980 }
981 }
982