helpers
1 month ago
tables
1 month ago
aIProviderInterface.php
1 month ago
assets.php
1 month ago
baseObject.php
1 month ago
builderBlock.php
1 month ago
controller.php
1 month ago
date.php
1 month ago
db.php
1 month ago
dispatcher.php
1 month ago
errors.php
1 month ago
field.php
1 month ago
fieldAdapter.php
1 month ago
frame.php
1 month ago
helper.php
1 month ago
html.php
1 month ago
installer.php
1 month ago
installerDbUpdater.php
1 month ago
integration.php
1 month ago
modInstaller.php
1 month ago
model.php
1 month ago
module.php
1 month ago
req.php
1 month ago
response.php
1 month ago
table.php
1 month ago
uri.php
1 month ago
user.php
1 month ago
utils.php
1 month ago
validator.php
1 month ago
view.php
1 month ago
utils.php
1226 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(wp_unslash($_SERVER['REMOTE_ADDR'])); |
| 83 | } else { |
| 84 | $res = sanitize_text_field(wp_unslash($_SERVER['HTTP_X_FORWARDED_FOR'])); |
| 85 | } |
| 86 | } else { |
| 87 | $res = sanitize_text_field(wp_unslash($_SERVER['HTTP_X_SUCURI_CLIENTIP'])); |
| 88 | } |
| 89 | } else { |
| 90 | $res = sanitize_text_field(wp_unslash($_SERVER['HTTP_X_REAL_IP'])); |
| 91 | } |
| 92 | } else { |
| 93 | $res = sanitize_text_field(wp_unslash($_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 wp_delete_file($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, wp_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(wp_unslash($_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( $networkwide ) { |
| 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() && $networkwide) { |
| 375 | $blog_id = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs"); // phpcs:ignore WordPress.DB.DirectDatabaseQuery |
| 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"); // phpcs:ignore WordPress.DB.DirectDatabaseQuery |
| 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( $networkwide ) { |
| 409 | global $wpdb; |
| 410 | if (function_exists('is_multisite') && is_multisite() && $networkwide) { |
| 411 | $blog_id = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs"); // phpcs:ignore WordPress.DB.DirectDatabaseQuery |
| 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 getUserAgent() { |
| 514 | $userAgent = self::getUserBrowserString(); |
| 515 | if (strpos($userAgent, 'Mozilla') !== false) { |
| 516 | $userAgent = 'Mozilla/5.0'; |
| 517 | } else if (strpos($userAgent, 'python-httpx') !== false) { |
| 518 | $userAgent = 'python-httpx/0.27.0'; |
| 519 | } else if (strpos($userAgent, 'node') !== false) { |
| 520 | $userAgent = 'node'; |
| 521 | } |
| 522 | return $userAgent; |
| 523 | } |
| 524 | public static function setAdminUser() { |
| 525 | $users = get_users(array('role' => 'administrator')); |
| 526 | $admin = !empty($users) ? $users[0] : false; |
| 527 | if ($admin) { |
| 528 | wp_set_current_user($admin->ID, $admin->user_login); |
| 529 | } |
| 530 | } |
| 531 | public static function getUserBrowserString() { |
| 532 | return isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : false; |
| 533 | } |
| 534 | public static function getBrowser() { |
| 535 | $u_agent = self::getUserBrowserString(); |
| 536 | $bname = 'Unknown'; |
| 537 | $platform = 'Unknown'; |
| 538 | $version = ''; |
| 539 | $pattern = ''; |
| 540 | |
| 541 | if ($u_agent) { |
| 542 | //First get the platform? |
| 543 | if (preg_match('/linux/i', $u_agent)) { |
| 544 | $platform = 'linux'; |
| 545 | } elseif (preg_match('/macintosh|mac os x/i', $u_agent)) { |
| 546 | $platform = 'mac'; |
| 547 | } elseif (preg_match('/windows|win32/i', $u_agent)) { |
| 548 | $platform = 'windows'; |
| 549 | } |
| 550 | // Next get the name of the useragent yes seperately and for good reason |
| 551 | if ( ( preg_match('/MSIE/i', $u_agent) && !preg_match('/Opera/i', $u_agent) ) || ( strpos($u_agent, 'Trident/7.0; rv:11.0') !== false ) ) { |
| 552 | $bname = 'Internet Explorer'; |
| 553 | $ub = 'MSIE'; |
| 554 | } elseif (preg_match('/Firefox/i', $u_agent)) { |
| 555 | $bname = 'Mozilla Firefox'; |
| 556 | $ub = 'Firefox'; |
| 557 | } elseif (preg_match('/Chrome/i', $u_agent)) { |
| 558 | $bname = 'Google Chrome'; |
| 559 | $ub = 'Chrome'; |
| 560 | } elseif (preg_match('/Safari/i', $u_agent)) { |
| 561 | $bname = 'Apple Safari'; |
| 562 | $ub = 'Safari'; |
| 563 | } elseif (preg_match('/Opera/i', $u_agent)) { |
| 564 | $bname = 'Opera'; |
| 565 | $ub = 'Opera'; |
| 566 | } elseif (preg_match('/Netscape/i', $u_agent)) { |
| 567 | $bname = 'Netscape'; |
| 568 | $ub = 'Netscape'; |
| 569 | } |
| 570 | |
| 571 | // finally get the correct version number |
| 572 | $known = array('Version', $ub, 'other'); |
| 573 | $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#'; |
| 574 | |
| 575 | // see how many we have |
| 576 | $i = count($matches['browser']); |
| 577 | if (1 != $i) { |
| 578 | //we will have two since we are not using 'other' argument yet |
| 579 | //see if version is before or after the name |
| 580 | if ( strripos($u_agent, 'Version') < strripos($u_agent, $ub) ) { |
| 581 | $version = $matches['version'][0]; |
| 582 | } else { |
| 583 | $version = $matches['version'][1]; |
| 584 | } |
| 585 | } else { |
| 586 | $version = $matches['version'][0]; |
| 587 | } |
| 588 | } |
| 589 | |
| 590 | // check if we have a number |
| 591 | if ( ( null == $version ) || ( '' == $version ) ) { |
| 592 | $version = '?'; |
| 593 | } |
| 594 | |
| 595 | return array( |
| 596 | 'userAgent' => $u_agent, |
| 597 | 'name' => $bname, |
| 598 | 'version' => $version, |
| 599 | 'platform' => $platform, |
| 600 | 'pattern' => $pattern, |
| 601 | ); |
| 602 | } |
| 603 | public static function getBrowsersList() { |
| 604 | return array('Unknown', 'Internet Explorer', 'Mozilla Firefox', 'Google Chrome', 'Apple Safari', 'Opera', 'Netscape'); |
| 605 | } |
| 606 | public static function getLangCode2Letter() { |
| 607 | $langCode = self::getLangCode(); |
| 608 | return strlen($langCode) > 2 ? substr($langCode, 0, 2) : $langCode; |
| 609 | } |
| 610 | public static function getLangCode() { |
| 611 | return get_locale(); |
| 612 | } |
| 613 | public static function getBrowserLangCode() { |
| 614 | return isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) |
| 615 | ? strtolower(substr(sanitize_text_field(wp_unslash($_SERVER['HTTP_ACCEPT_LANGUAGE'])), 0, 2)) |
| 616 | : self::getLangCode2Letter(); |
| 617 | } |
| 618 | public static function getTimeRange() { |
| 619 | $time = array(); |
| 620 | $hours = range(1, 11); |
| 621 | array_unshift($hours, 12); |
| 622 | $k = 0; |
| 623 | $count = count($hours); |
| 624 | for ($i = 0; $i < 4 * $count; $i++) { |
| 625 | $newItem = $hours[ $k ]; |
| 626 | $newItem .= ':' . ( ( $i % 2 ) ? '30' : '00' ); |
| 627 | $newItem .= ( $i < $count * 2 ) ? 'am' : 'pm'; |
| 628 | if ($i % 2) { |
| 629 | $k++; |
| 630 | } |
| 631 | if ($i == $count * 2 - 1) { |
| 632 | $k = 0; |
| 633 | } |
| 634 | $time[] = $newItem; |
| 635 | } |
| 636 | return array_combine($time, $time); |
| 637 | } |
| 638 | public static function getSearchEnginesList() { |
| 639 | return array( |
| 640 | 'google.com' => array('label' => 'Google'), |
| 641 | 'yahoo.com' => array('label' => 'Yahoo!'), |
| 642 | 'youdao.com' => array('label' => 'Youdao'), |
| 643 | 'yandex' => array('label' => 'Yandex'), |
| 644 | 'sogou.com' => array('label' => 'Sogou'), |
| 645 | 'qwant.com' => array('label' => 'Qwant'), |
| 646 | 'bing.com' => array('label' => 'Bing'), |
| 647 | 'munax.com' => array('label' => 'Munax'), |
| 648 | ); |
| 649 | } |
| 650 | public static function getSocialList() { |
| 651 | return array( |
| 652 | 'facebook.com' => array('label' => 'Facebook'), |
| 653 | 'pinterest.com' => array('label' => 'Pinterest'), |
| 654 | 'instagram.com' => array('label' => 'Instagram'), |
| 655 | 'yelp.com' => array('label' => 'Yelp'), |
| 656 | 'vk.com' => array('label' => 'VKontakte'), |
| 657 | 'myspace.com' => array('label' => 'Myspace'), |
| 658 | 'linkedin.com' => array('label' => 'LinkedIn'), |
| 659 | 'plus.google.com' => array('label' => 'Google+'), |
| 660 | 'google.com' => array('label' => 'Google'), |
| 661 | ); |
| 662 | } |
| 663 | public static function getReferalUrl() { |
| 664 | // Simple for now |
| 665 | return WaicReq::getVar('HTTP_REFERER', 'server'); |
| 666 | } |
| 667 | public static function getReferalHost() { |
| 668 | $refUrl = self::getReferalUrl(); |
| 669 | if (!empty($refUrl)) { |
| 670 | $refer = wp_parse_url( $refUrl ); |
| 671 | if ($refer && isset($refer['host']) && !empty($refer['host'])) { |
| 672 | return $refer['host']; |
| 673 | } |
| 674 | } |
| 675 | return false; |
| 676 | } |
| 677 | public static function getCurrentUserRole() { |
| 678 | $roles = self::getCurrentUserRoleList(); |
| 679 | if ($roles) { |
| 680 | $ncaps = count($roles); |
| 681 | $role = $roles[$ncaps - 1]; |
| 682 | return $role; |
| 683 | } |
| 684 | return false; |
| 685 | } |
| 686 | public static function getCurrentUserRoleList() { |
| 687 | global $current_user, $wpdb; |
| 688 | if ($current_user) { |
| 689 | $roleKey = $wpdb->prefix . 'capabilities'; |
| 690 | if (isset($current_user->$roleKey) && !empty($current_user->$roleKey)) { |
| 691 | return array_keys($current_user->$roleKey); |
| 692 | } |
| 693 | } |
| 694 | return false; |
| 695 | } |
| 696 | public static function getAllUserRoles() { |
| 697 | return get_editable_roles(); |
| 698 | } |
| 699 | public static function getAllUserRolesList() { |
| 700 | $res = array(); |
| 701 | $roles = self::getAllUserRoles(); |
| 702 | if (!empty($roles)) { |
| 703 | foreach ($roles as $k => $data) { |
| 704 | $res[ $k ] = $data['name']; |
| 705 | } |
| 706 | } |
| 707 | return $res; |
| 708 | } |
| 709 | public static function rgbToArray( $rgb ) { |
| 710 | $rgb = array_map('trim', explode(',', trim(str_replace(array('rgb', 'a', '(', ')'), '', $rgb)))); |
| 711 | return $rgb; |
| 712 | } |
| 713 | public static function hexToRgb( $hex ) { |
| 714 | if (strpos($hex, 'rgb') !== false) { // Maybe it's already in rgb format - just return it as array |
| 715 | return self::rgbToArray($hex); |
| 716 | } |
| 717 | $hex = str_replace('#', '', $hex); |
| 718 | |
| 719 | if (strlen($hex) == 3) { |
| 720 | $r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1)); |
| 721 | $g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1)); |
| 722 | $b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1)); |
| 723 | } else { |
| 724 | $r = hexdec(substr($hex, 0, 2)); |
| 725 | $g = hexdec(substr($hex, 2, 2)); |
| 726 | $b = hexdec(substr($hex, 4, 2)); |
| 727 | } |
| 728 | $rgb = array($r, $g, $b); |
| 729 | return $rgb; // returns an array with the rgb values |
| 730 | } |
| 731 | public static function hexToRgbaStr( $hex, $alpha = 1 ) { |
| 732 | $rgbArr = self::hexToRgb($hex); |
| 733 | return 'rgba(' . implode(',', $rgbArr) . ',' . $alpha . ')'; |
| 734 | } |
| 735 | |
| 736 | /** |
| 737 | * $typ: 1 - numeric, 2 - array |
| 738 | */ |
| 739 | |
| 740 | public static function getArrayValue( $params, $name, $default = '', $typ = 0, $arr = false, $zero = false, $leer = false ) { |
| 741 | if (!isset($params[$name])) { |
| 742 | return $default; |
| 743 | } |
| 744 | if (empty($params[$name])) { |
| 745 | return ( $zero && ( '0' === $params[$name] || 0 === $params[$name] ) ) ? 0 : ( $leer && '' === $params[$name] ? '' : $default ); |
| 746 | } |
| 747 | $value = $params[$name]; |
| 748 | if (1 == $typ) { |
| 749 | if (!is_numeric($value)) { |
| 750 | return $default; |
| 751 | } |
| 752 | } elseif (2 == $typ) { |
| 753 | if (!is_array($value)) { |
| 754 | return $default; |
| 755 | } |
| 756 | } |
| 757 | if (( false !== $arr ) && !in_array($value, $arr)) { |
| 758 | return $default; |
| 759 | } |
| 760 | return $value; |
| 761 | } |
| 762 | |
| 763 | public static function controlNumericValues( $values, $field = 'int' ) { |
| 764 | foreach ($values as $k => $val) { |
| 765 | $values[$k] = ( 'dec' == $field ? (float) $val : (int) $val ); |
| 766 | } |
| 767 | return $values; |
| 768 | } |
| 769 | public static function getTimeZone() { |
| 770 | if (is_null(self::$currentTZ)) { |
| 771 | $tz = wp_timezone_string(); |
| 772 | if (strpos($tz, ':')) { |
| 773 | $offset = $tz; |
| 774 | list($hours, $minutes) = explode(':', $offset); |
| 775 | if (is_numeric($hours) && is_numeric($minutes)) { |
| 776 | $seconds = $hours * 60 * 60 + $minutes * 60; |
| 777 | $tz = timezone_name_from_abbr('', $seconds, 1); |
| 778 | if (false === $tz) { |
| 779 | $tz = timezone_name_from_abbr('', $seconds, 0); |
| 780 | } |
| 781 | } |
| 782 | } |
| 783 | self::$currentTZ = ( false !== $tz ? new DateTimeZone($tz) : new DateTimeZone() ); |
| 784 | } |
| 785 | return self::$currentTZ; |
| 786 | } |
| 787 | public static function getCurrentDateFormatDB() { |
| 788 | return self::$currentDateFormatDB; |
| 789 | } |
| 790 | public static function getCurrentDateFormat() { |
| 791 | if (is_null(self::$currentDateFormat)) { |
| 792 | $format = WaicFrame::_()->getModule('options')->get('plugin', 'date_format'); |
| 793 | self::$currentDateFormat = empty($format) ? WAIC_DATE_FORMAT : $format; |
| 794 | } |
| 795 | return self::$currentDateFormat; |
| 796 | } |
| 797 | public static function getCurrentDateTimeFormat() { |
| 798 | return self::getCurrentDateFormat() . ' H:i'; |
| 799 | } |
| 800 | public static function getCurrentDateTimeFormatDB() { |
| 801 | return self::getCurrentDateFormatDB() . ' H:i'; |
| 802 | } |
| 803 | |
| 804 | public static function getJSDateFormat( $format = '' ) { |
| 805 | if (empty($format)) { |
| 806 | $format = self::getCurrentDateFormat(); |
| 807 | } |
| 808 | return str_replace(array('Y', 'm', 'd'), array('yy', 'mm', 'dd'), $format); |
| 809 | } |
| 810 | public static function getJSTimeFormat( $format = 'H:i' ) { |
| 811 | return str_replace(array('H', 'i'), array('HH', 'mm'), $format); |
| 812 | } |
| 813 | public static function getFormatedDateTime( $dt, $format = '' ) { |
| 814 | if (empty($format)) { |
| 815 | $format = self::getCurrentDateTimeFormat(); |
| 816 | } |
| 817 | return gmdate($format, $dt); |
| 818 | } |
| 819 | public static function getFormatedDateTimeDB( $dt, $format = '' ) { |
| 820 | if (empty($format)) { |
| 821 | $format = self::getCurrentDateTimeFormatDB() . ':s'; |
| 822 | } |
| 823 | return gmdate($format, $dt); |
| 824 | } |
| 825 | public static function getFirstDateMonthDB( $dt = false ) { |
| 826 | $format = 'Y-m-01'; |
| 827 | if (false == $dt) { |
| 828 | $data = new DateTime('now', self::getTimeZone()); |
| 829 | return $data->format($format); |
| 830 | } |
| 831 | return gmdate($format, $dt); |
| 832 | } |
| 833 | public static function getConvertedDate( $dt = false, $format = '' ) { |
| 834 | if ('' === $format) { |
| 835 | $format = self::getCurrentDateFormat(); |
| 836 | } |
| 837 | if (false == $dt) { |
| 838 | $data = new DateTime('now', self::getTimeZone()); |
| 839 | return $data->format($format); |
| 840 | } |
| 841 | return gmdate($format, $dt); |
| 842 | } |
| 843 | |
| 844 | public static function addDays( $days, $format = '', $years = 0 ) { |
| 845 | if ('' === $format) { |
| 846 | $format = self::getCurrentDateTimeFormat(); |
| 847 | } |
| 848 | $data = new DateTime('now', self::getTimeZone()); |
| 849 | $days = (int) $days; |
| 850 | if (!empty($days)) { |
| 851 | if ($days > 0) { |
| 852 | $data->add(DateInterval::createFromDateString($days . ' days')); |
| 853 | } else { |
| 854 | $data->sub(DateInterval::createFromDateString(( $days * ( -1 ) ) . ' days')); |
| 855 | } |
| 856 | } |
| 857 | $years = (int) $years; |
| 858 | if (!empty($years)) { |
| 859 | if ($years > 0) { |
| 860 | $data->add(DateInterval::createFromDateString($years . ' years')); |
| 861 | } else { |
| 862 | $data->sub(DateInterval::createFromDateString(( $years * ( -1 ) ) . ' years')); |
| 863 | } |
| 864 | } |
| 865 | return $format ? $data->format($format) : $data->format('U') + $data->format('Z'); |
| 866 | } |
| 867 | public static function addInterval( $dt, $cnt, $units ) { |
| 868 | // Y-m-d H:i |
| 869 | // $units = minutes, hours, days |
| 870 | $date = new DateTime($dt); |
| 871 | $date->modify(( $cnt > 0 ? '+' : '-' ) . $cnt . ' ' . $units); |
| 872 | return $date->format('Y-m-d H:i'); |
| 873 | } |
| 874 | public static function getTimestamp() { |
| 875 | $data = new DateTime('now', self::getTimeZone()); |
| 876 | return $data->format('U') + $data->format('Z'); |
| 877 | } |
| 878 | public static function getTimestampDB() { |
| 879 | return self::getFormatedDateTime(self::getTimestamp(), 'Y-m-d H:i:s'); |
| 880 | } |
| 881 | public static function getTimestampFrom( $dt ) { |
| 882 | return self::checkDateTime($dt, self::getCurrentDateTimeFormatDB()); |
| 883 | } |
| 884 | public static function checkDateTime( $dt, $format = '' ) { |
| 885 | if (empty($format)) { |
| 886 | $format = self::getCurrentDateTimeFormat(); |
| 887 | } |
| 888 | $data = date_create_from_format($format, $dt, self::getTimeZone()); |
| 889 | return $data ? $data->format('U') + $data->format('Z') : false; |
| 890 | } |
| 891 | public static function checkDateTimeFormat( $dt, $format = '' ) { |
| 892 | $date = DateTime::createFromFormat($format, $dt); |
| 893 | return $date && $date->format($format) === $dt; |
| 894 | } |
| 895 | public static function convertDateFormat( $dt, $from = '', $to = 'Y-m-d' ) { |
| 896 | if (empty($dt)) { |
| 897 | return $dt; |
| 898 | } |
| 899 | if (empty($from)) { |
| 900 | $from = self::getCurrentDateFormat(); |
| 901 | } |
| 902 | if ($from == $to) { |
| 903 | return $dt; |
| 904 | } |
| 905 | $dt = self::checkDateTime($dt, $from); |
| 906 | return $dt ? self::getFormatedDateTime($dt, $to) : false; |
| 907 | } |
| 908 | public static function convertDateTimeFormat( $dt, $from = '', $to = '' ) { |
| 909 | if (empty($dt)) { |
| 910 | return $dt; |
| 911 | } |
| 912 | if (empty($from)) { |
| 913 | $from = self::getCurrentDateTimeFormat(); |
| 914 | } |
| 915 | if (empty($to)) { |
| 916 | $to = self::getCurrentDateTimeFormatDB(); |
| 917 | } |
| 918 | if ($from == $to) { |
| 919 | return $dt; |
| 920 | } |
| 921 | $dt = self::checkDateTime($dt, $from); |
| 922 | return $dt ? self::getFormatedDateTime($dt, $to) : false; |
| 923 | } |
| 924 | public static function convertDateTimeToFront( $dt, $full = false ) { |
| 925 | return self::convertDateTimeFormat($dt, self::getCurrentDateTimeFormatDB() . ( $full ? ':s' : '' ), self::getCurrentDateTimeFormat()); |
| 926 | } |
| 927 | public static function convertDateTimeToDB( $dt ) { |
| 928 | return self::convertDateTimeFormat($dt); |
| 929 | } |
| 930 | public static function convertDateTimeToISO8601( $dt, $tz ) { |
| 931 | $dt = DateTime::createFromFormat('Y-m-d H:i', $dt, $tz ? new DateTimeZone($tz) : self::getTimeZone()); |
| 932 | return $dt->format(DateTime::RFC3339); |
| 933 | } |
| 934 | |
| 935 | public static function colourBrightness( $hex, $percent ) { |
| 936 | // Work out if hash given |
| 937 | $hash = ''; |
| 938 | if (stristr($hex, '#')) { |
| 939 | $hex = str_replace('#', '', $hex); |
| 940 | $hash = '#'; |
| 941 | } |
| 942 | /// HEX TO RGB |
| 943 | $rgb = array(hexdec(substr($hex, 0, 2)), hexdec(substr($hex, 2, 2)), hexdec(substr($hex, 4, 2))); |
| 944 | //// CALCULATE |
| 945 | for ($i = 0; $i < 3; $i++) { |
| 946 | // See if brighter or darker |
| 947 | if ($percent > 0) { |
| 948 | // Lighter |
| 949 | $rgb[$i] = round($rgb[$i] * $percent) + round(255 * ( 1 - $percent )); |
| 950 | } else { |
| 951 | // Darker |
| 952 | $positivePercent = $percent - ( $percent * 2 ); |
| 953 | $rgb[$i] = round($rgb[$i] * ( 1 - $positivePercent )); // round($rgb[$i] * (1-$positivePercent)); |
| 954 | } |
| 955 | // In case rounding up causes us to go to 256 |
| 956 | if ($rgb[$i] > 255) { |
| 957 | $rgb[$i] = 255; |
| 958 | } |
| 959 | } |
| 960 | //// RBG to Hex |
| 961 | $hex = ''; |
| 962 | for ($i = 0; $i < 3; $i++) { |
| 963 | // Convert the decimal digit to hex |
| 964 | $hexDigit = dechex($rgb[$i]); |
| 965 | // Add a leading zero if necessary |
| 966 | if (strlen($hexDigit) == 1) { |
| 967 | $hexDigit = '0' . $hexDigit; |
| 968 | } |
| 969 | // Append to the hex string |
| 970 | $hex .= $hexDigit; |
| 971 | } |
| 972 | return $hash . $hex; |
| 973 | } |
| 974 | public static function isHPOS() { |
| 975 | if ( class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class ) ) { |
| 976 | return \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled(); |
| 977 | } |
| 978 | return false; |
| 979 | } |
| 980 | public static function isWooCommercePluginActivated() { |
| 981 | return class_exists( 'WooCommerce' ); |
| 982 | } |
| 983 | public static function isExistMB() { |
| 984 | return function_exists('mb_substr'); |
| 985 | } |
| 986 | public static function mbstrlen( $s ) { |
| 987 | return function_exists('mb_strlen') ? mb_strlen($s) : strlen($s); |
| 988 | } |
| 989 | public static function mbsubstr( $s, $i, $l = null ) { |
| 990 | return function_exists('mb_substr') ? mb_substr($s, $i, $l) : substr($s, $i, $l); |
| 991 | } |
| 992 | public static function mbstrrpos( $h, $n, $o = 0 ) { |
| 993 | return function_exists('mb_strrpos') ? mb_strrpos($h, $n, $o) : strrpos($h, $n, $o); |
| 994 | } |
| 995 | public static function mbstrpos( $h, $n, $o = 0 ) { |
| 996 | return function_exists('mb_strpos') ? mb_strpos($h, $n, $o) : strpos($h, $n, $o); |
| 997 | } |
| 998 | public static function mbstripos( $h, $n, $o = 0 ) { |
| 999 | return function_exists('mb_stripos') ? mb_stripos($h, $n, $o) : stripos($h, $n, $o); |
| 1000 | } |
| 1001 | public static function getRealUserIp() { |
| 1002 | if (!empty($_SERVER['HTTP_CLIENT_IP'])) { |
| 1003 | $ip = sanitize_text_field(wp_unslash($_SERVER['HTTP_CLIENT_IP'])); |
| 1004 | } elseif (!empty($_SERVER['HTTP_X_GT_VIEWER_IP'])) { |
| 1005 | $ip = sanitize_text_field(wp_unslash($_SERVER['HTTP_X_GT_VIEWER_IP'])); |
| 1006 | } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { |
| 1007 | $ip = sanitize_text_field(wp_unslash($_SERVER['HTTP_X_FORWARDED_FOR'])); |
| 1008 | } elseif (!empty($_SERVER['REMOTE_ADDR'])) { |
| 1009 | $ip = sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])); |
| 1010 | } else { |
| 1011 | $ip = '127.0.0.1'; |
| 1012 | } |
| 1013 | $part = explode(':', $ip); |
| 1014 | return $part[0]; |
| 1015 | } |
| 1016 | public static function insertKeyValuePair( $arr, $key, $val, $after ) { |
| 1017 | $start = $arr; |
| 1018 | $end = array(); |
| 1019 | $index = array_search($after, array_keys($arr)); |
| 1020 | if (false !== $index) { |
| 1021 | $end = array_splice($arr, $index + 1); |
| 1022 | $start = array_splice($arr, 0, $index + 1); |
| 1023 | } |
| 1024 | return array_merge($start, array($key => $val), $end); |
| 1025 | } |
| 1026 | public static function getCountWords( $text ) { |
| 1027 | $text = trim(wp_strip_all_tags(html_entity_decode($text, ENT_QUOTES))); |
| 1028 | $text = preg_replace('/[\n]+/', ' ', $text); |
| 1029 | $text = preg_replace('/[\s]+/', '@SEPARATOR@', $text); |
| 1030 | $text_array = explode('@SEPARATOR@', $text); |
| 1031 | $count = count($text_array); |
| 1032 | $last_key = end($text_array); |
| 1033 | if (empty($last_key)) { |
| 1034 | $count--; |
| 1035 | } |
| 1036 | return $count; |
| 1037 | } |
| 1038 | |
| 1039 | public static function checkEmptyApiKeys( $apiParams, &$error ) { |
| 1040 | switch ($apiParams['engine']) { |
| 1041 | case 'open-ai': |
| 1042 | if (empty($apiParams['api_key'])) { |
| 1043 | $error = __('API key for OpenAI is required', 'ai-copilot-content-generator'); |
| 1044 | return false; |
| 1045 | } |
| 1046 | break; |
| 1047 | case 'gemini': |
| 1048 | if (empty($apiParams['gemini_api_key'])) { |
| 1049 | $error = __('API key for Gemini is required', 'ai-copilot-content-generator'); |
| 1050 | return false; |
| 1051 | } |
| 1052 | break; |
| 1053 | case 'deep-seek': |
| 1054 | if (empty($apiParams['deep_seek_api_key'])) { |
| 1055 | $error = __('API key for DeepSeek is required', 'ai-copilot-content-generator'); |
| 1056 | return false; |
| 1057 | } |
| 1058 | break; |
| 1059 | default: |
| 1060 | break; |
| 1061 | } |
| 1062 | |
| 1063 | return true; |
| 1064 | } |
| 1065 | public static function controlUploatedFile( $file, $extensions = array() ) { |
| 1066 | $result = ''; |
| 1067 | if (isset($file['error']) && !empty($file['error']) && UPLOAD_ERR_OK !== $file['error']) { |
| 1068 | switch ($file['error']) { |
| 1069 | case UPLOAD_ERR_INI_SIZE: |
| 1070 | case UPLOAD_ERR_FORM_SIZE: |
| 1071 | $result = esc_html__('The uploaded file exceeds the max size of uploaded files.', 'ai-copilot-content-generator'); |
| 1072 | break; |
| 1073 | case UPLOAD_ERR_PARTIAL: |
| 1074 | $result = esc_html__('The uploaded file was only partially uploaded.', 'ai-copilot-content-generator'); |
| 1075 | break; |
| 1076 | case UPLOAD_ERR_NO_FILE: |
| 1077 | $result = esc_html__('No file was uploaded.', 'ai-copilot-content-generator'); |
| 1078 | break; |
| 1079 | case UPLOAD_ERR_NO_TMP_DIR: |
| 1080 | $result = esc_html__('Missing a temporary folder.', 'ai-copilot-content-generator'); |
| 1081 | break; |
| 1082 | case UPLOAD_ERR_CANT_WRITE: |
| 1083 | $result = esc_html__('Failed to write file to disk.', 'ai-copilot-content-generator'); |
| 1084 | break; |
| 1085 | default: |
| 1086 | $result = esc_html__('Unexpected error.', 'ai-copilot-content-generator'); |
| 1087 | } |
| 1088 | } else { |
| 1089 | $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); |
| 1090 | if (!in_array($extension, $extensions)) { |
| 1091 | $result = esc_html__('Unsupported file type', 'ai-copilot-content-generator'); |
| 1092 | } |
| 1093 | } |
| 1094 | return $result; |
| 1095 | } |
| 1096 | public static function calcTokensByModel( $model, $text ) { |
| 1097 | waicImportClass('WaicTokinizerFactory', WAIC_HELPERS_DIR . 'tokinizerFactory.php'); |
| 1098 | |
| 1099 | $enc = WaicTokinizerFactory::createByModelName($model); |
| 1100 | $tokens = $enc->encode($text); |
| 1101 | return count($tokens); |
| 1102 | } |
| 1103 | public static function calcTokensByEncoding( $encoding, $text ) { |
| 1104 | //https://platform.openai.com/tokenizer |
| 1105 | waicImportClass('WaicTokinizerFactory', WAIC_HELPERS_DIR . 'tokinizerFactory.php'); |
| 1106 | |
| 1107 | $enc = WaicTokinizerFactory::createByEncodingName($encoding); |
| 1108 | $tokens = $enc->encode($text); |
| 1109 | return count($tokens); |
| 1110 | } |
| 1111 | public static function getObjectTaxonomiesList( $obj ) { |
| 1112 | $list = array(); |
| 1113 | $taxonomies = get_object_taxonomies($obj, 'objects'); |
| 1114 | |
| 1115 | foreach ($taxonomies as $taxonomy) { |
| 1116 | $list[$taxonomy->name] = $taxonomy->label; |
| 1117 | } |
| 1118 | return $list; |
| 1119 | } |
| 1120 | public static function getTaxonomyTermsList( $postId, $taxonomy ) { |
| 1121 | $list = ''; |
| 1122 | $terms = get_the_terms( $postId, $taxonomy ); |
| 1123 | if ( ! empty( $terms ) ) { |
| 1124 | foreach ( $terms as $term ) { |
| 1125 | $list .= $term->name . ', '; |
| 1126 | } |
| 1127 | $list = substr($list, 0, -2); |
| 1128 | } |
| 1129 | return $list; |
| 1130 | } |
| 1131 | public static function markdownToHtml( $content ) { |
| 1132 | waicImportClass('WaicParsedown', WAIC_HELPERS_DIR . 'parsedown.php'); |
| 1133 | $Parsedown = new WaicParsedown(); |
| 1134 | $content = $Parsedown->text( $content ); |
| 1135 | return $content; |
| 1136 | } |
| 1137 | public static function flattenJson($data, $prefix = '') { |
| 1138 | $result = array(); |
| 1139 | |
| 1140 | foreach ($data as $key => $value) { |
| 1141 | $newKey = $prefix === '' ? $key : $prefix . '/' . $key; |
| 1142 | |
| 1143 | if (is_array($value) || is_object($value)) { |
| 1144 | $result += self::flattenJson((array) $value, $newKey); |
| 1145 | } else { |
| 1146 | $result[$newKey] = $value; |
| 1147 | } |
| 1148 | } |
| 1149 | return $result; |
| 1150 | } |
| 1151 | public static function arrayToXml($data, $root = 'request') { |
| 1152 | if (!class_exists('SimpleXMLElement')) { |
| 1153 | return ''; |
| 1154 | } |
| 1155 | $xml = new SimpleXMLElement("<{$root}></{$root}>"); |
| 1156 | |
| 1157 | $add = function($value, $key) use (&$xml) { |
| 1158 | if (is_array($value)) { |
| 1159 | $child = $xml->addChild($key); |
| 1160 | foreach ($value as $k => $v) { |
| 1161 | if (is_array($v)) { |
| 1162 | $subChild = $child->addChild(is_numeric($k) ? "item{$k}" : $k); |
| 1163 | foreach ($v as $subKey => $subVal) { |
| 1164 | $subChild->addChild(is_numeric($subKey) ? "item{$subKey}" : $subKey, htmlspecialchars((string)$subVal)); |
| 1165 | } |
| 1166 | } else { |
| 1167 | $child->addChild(is_numeric($k) ? "item{$k}" : $k, htmlspecialchars((string)$v)); |
| 1168 | } |
| 1169 | } |
| 1170 | } else { |
| 1171 | $xml->addChild($key, htmlspecialchars((string)$value)); |
| 1172 | } |
| 1173 | }; |
| 1174 | array_walk($data, $add); |
| 1175 | return $xml->asXML(); |
| 1176 | } |
| 1177 | public static function responseToArray( $response ) { |
| 1178 | $body = wp_remote_retrieve_body($response); |
| 1179 | $contentType = wp_remote_retrieve_header($response, 'content-type'); |
| 1180 | if (strpos($contentType, ';') !== false) { |
| 1181 | $contentType = explode(';', $contentType)[0]; |
| 1182 | } |
| 1183 | |
| 1184 | $vars = array(); |
| 1185 | |
| 1186 | switch (trim(strtolower($contentType))) { |
| 1187 | case 'application/json': |
| 1188 | case 'text/json': |
| 1189 | $vars = json_decode($body, true); |
| 1190 | break; |
| 1191 | case 'application/xml': |
| 1192 | case 'text/xml': |
| 1193 | libxml_use_internal_errors(true); |
| 1194 | $xml = simplexml_load_string($body); |
| 1195 | if ($xml !== false) { |
| 1196 | $vars = json_decode(json_encode($xml), true); |
| 1197 | } |
| 1198 | break; |
| 1199 | case 'application/x-www-form-urlencoded': |
| 1200 | parse_str($body, $vars); |
| 1201 | break; |
| 1202 | case 'text/plain': |
| 1203 | case 'text/html': |
| 1204 | $lines = explode("\n", $body); |
| 1205 | foreach ($lines as $line) { |
| 1206 | if (strpos($line, '=') !== false) { |
| 1207 | [$key, $value] = explode('=', $line, 2); |
| 1208 | $vars[trim($key)] = trim($value); |
| 1209 | } |
| 1210 | } |
| 1211 | break; |
| 1212 | default: |
| 1213 | $vars = ['raw' => $body]; |
| 1214 | break; |
| 1215 | } |
| 1216 | return $vars; |
| 1217 | } |
| 1218 | public static function getProductStockStatusesList() { |
| 1219 | $list = array(); |
| 1220 | if (function_exists('wc_get_product_stock_status_options')) { |
| 1221 | $list = wc_get_product_stock_status_options(); |
| 1222 | } |
| 1223 | return $list; |
| 1224 | } |
| 1225 | } |
| 1226 |