File size: 11,830 Bytes
5f32fbd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 | <?php
namespace App\Helpers\Classes;
use App\Models\RateLimit;
use App\Models\Setting;
use App\Models\SettingTwo;
use App\Repositories\Contracts\ExtensionRepositoryInterface;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Route;
class Helper
{
public static function showIntercomForBuyer(array $extensions = []): bool
{
if (self::showIntercomForVipMembership()) {
return false;
}
$extensionsCollection = collect(
$extensions ?: app(ExtensionRepositoryInterface::class)->extensions()
)
->where('is_theme', request()->routeIs('dashboard.admin.themes.*'))
->where('licensed', true)
->where('price', '>', 0);
return $extensionsCollection->isNotEmpty();
}
public static function showIntercomForVipMembership(): bool
{
if (! Auth::user()?->isAdmin()) {
return false;
}
$marketSubscription = app(ExtensionRepositoryInterface::class)->subscription()->json();
if (data_get($marketSubscription, 'data.stripe_status') === 'active') {
return true;
}
return false;
}
public static function marketplacePaymentMessage(string $status): string
{
return match ($status) {
'paid' => __('Your payment has been received successfully.'),
'pending' => __('Your payment is pending. Please check back later for confirmation. Once processed, you\'ll be able to download the extension.'),
default => __('Your payment was unsuccessful. Please try again'),
};
}
public static function hasRoute($route = null): bool
{
if ($route && Route::has($route)) {
return true;
}
return false;
}
public static function arrayMerge($merge = true, array $array = [], array ...$mergeArray): array
{
if ($merge) {
return array_merge($array, ...$mergeArray);
}
return $array;
}
public static function routeWithoutTranslate($route = null)
{
if (is_null($route)) {
return '/';
}
// URL'yi ayrıştır ve path bölümünü al
$parsedUrl = parse_url($route);
$path = isset($parsedUrl['path']) ? $parsedUrl['path'] : '';
// Path'i "/" ile böl
$pathParts = explode('/', $path);
// Belirli bir alt dizinden sonra gelen kısmı bul
$start = array_search('dashboard', $pathParts);
if ($start !== false) {
// İstenen kısmı dizi olarak al
$specificPathParts = array_slice($pathParts, $start);
// Dizi elemanlarını birleştirerek string haline getir
return '/' . implode('/', $specificPathParts);
}
return '/'; // Aranan kısım bulunamazsa boş döndür
}
public static function decodePaymentToken(string $token): array
{
$base64 = base64_decode($token);
$data = explode(':', $base64);
[$domain, $slug, $license] = $data;
return compact('domain', 'slug', 'license');
}
public static function setEnv(array $data = []): void
{
$envPath = base_path('.env');
$content = file_get_contents($envPath);
foreach ($data as $key => $value) {
$keyPattern = preg_quote($key, '/');
$pattern = "/^{$keyPattern}=[^\r\n]*/m";
if (preg_match($pattern, $content)) {
$content = preg_replace($pattern, "{$key}=" . '"' . "{$value}" . '"', $content);
} else {
$content .= "\n{$key}=" . '"' . "{$value}" . '"';
}
}
file_put_contents($envPath, $content);
}
public static function dbConnectionStatus(): bool
{
try {
DB::connection()->getPdo();
return true;
} catch (Exception $e) {
return false;
}
}
public static function sortingOpenAiSelected($data, $selected = null)
{
$data = $data->map(function ($item) use ($selected) {
$item->selected = 0;
if ($selected) {
if (in_array($item->slug, $selected)) {
$item->selected = 1;
}
}
return $item;
});
return $data->sortByDesc('selected');
}
public static function setFalAIKey(): string
{
// $settings = Setting::query()->first();
// $apiKeys = [];
// if ($settings?->getAttribute('user_api_option')) {
// $apiKeys = explode(',', auth()->user()?->getAttribute('anthropic_api_keys'));
// } else {
// $apiKeys = explode(',', setting('fal_ai'));
// }
$apiKeys = explode(',', setting('fal_ai_api_secret'));
return Arr::random($apiKeys);
}
public static function setAnthropicKey(): string
{
$settings = Setting::query()->first();
$apiKeys = [];
if ($settings?->getAttribute('user_api_option')) {
$apiKeys = explode(',', auth()->user()?->getAttribute('anthropic_api_keys'));
} else {
$apiKeys = explode(',', setting('anthropic_api_secret'));
}
return Arr::random($apiKeys);
}
public static function setOpenAiKey(): string
{
$settings = Setting::query()->first();
if ($settings?->getAttribute('user_api_option')) {
$apiKeys = explode(',', auth()->user()?->getAttribute('api_keys'));
} else {
$apiKeys = explode(',', $settings?->getAttribute('openai_api_secret'));
}
config(['openai.api_key' => $apiKeys[array_rand($apiKeys)]]);
return config('openai.api_key');
}
public static function setGeminiKey(): string
{
$settings = Setting::query()->first();
if ($settings?->getAttribute('user_api_option')) {
$apiKeys = explode(',', auth()->user()?->getAttribute('gemini_api_keys'));
} else {
$apiKeys = explode(',', setting('gemini_api_secret', ''));
}
config(['gemini.api_key' => $apiKeys[array_rand($apiKeys)]]);
config(['gemini.request_timeout' => 120]);
return config('gemini.api_key');
}
public static function strip_all_tags($text, $remove_breaks = false)
{
if (is_null($text)) {
return '';
}
if (! is_scalar($text)) {
/*
* To maintain consistency with pre-PHP 8 error levels,
* trigger_error() is used to trigger an E_USER_WARNING,
* rather than _doing_it_wrong(), which triggers an E_USER_NOTICE.
*/
trigger_error(
sprintf(
/* translators: 1: The function name, 2: The argument number, 3: The argument name, 4: The expected type, 5: The provided type. */
__('Warning: %1$s expects parameter %2$s (%3$s) to be a %4$s, %5$s given.'),
__FUNCTION__,
'#1',
'$text',
'string',
gettype($text)
),
E_USER_WARNING
);
return '';
}
$text = preg_replace('@<(script|style)[^>]*?>.*?</\\1>@si', '', $text);
$text = strip_tags($text);
if ($remove_breaks) {
$text = preg_replace('/[\r\n\t ]+/', ' ', $text);
}
return trim($text);
}
public static function multi_explode($delimiters, $string): array
{
$ready = str_replace($delimiters, $delimiters[0], $string);
$ready = str_replace([',,'], ',', $ready);
$ready = str_replace('-', '', $ready);
return explode($delimiters[0], $ready);
}
public static function settingTwo(string $key, $default = null)
{
$setting = SettingTwo::query()->first();
return $setting?->getAttribute($key) ?? $default;
}
public static function setting(string $key, $default = null, $setting = null)
{
$setting = $setting ?: Setting::query()->first();
return $setting?->getAttribute($key) ?? $default;
}
public static function appIsDemo(): bool
{
return config('app.status') == 'Demo';
}
public static function appIsNotDemo(): bool
{
return config('app.status') != 'Demo';
}
public static function checkImageDailyLimit()
{
$settings_two = SettingTwo::first();
if ($settings_two->daily_limit_enabled) {
if (Helper::appIsDemo()) {
$msg = __('You have reached the maximum number of image generation allowed on the demo.');
} else {
$msg = __('You have reached the maximum number of image generation allowed.');
}
$ipAddress = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : request()->ip();
$db_ip_address = RateLimit::where('ip_address', $ipAddress)->where('type', 'image')->first();
if ($db_ip_address) {
if (now()->diffInDays(Carbon::parse($db_ip_address->last_attempt_at)->format('Y-m-d')) > 0) {
$db_ip_address->attempts = 0;
}
} else {
$db_ip_address = new RateLimit(['ip_address' => $ipAddress]);
}
if ($db_ip_address->attempts >= $settings_two->allowed_images_count) {
$data = [
'errors' => [$msg],
];
return response()->json($data, 429);
} else {
$db_ip_address->attempts++;
$db_ip_address->last_attempt_at = now();
$db_ip_address->save();
}
}
return response()->json([], 200);
}
public static function checkRemainingImages($usr = null)
{
$user = $usr ?? auth()->user();
if ($user->getAttribute('team')) {
$teamManager = $user->teamManager;
if ($teamManager) {
if ($teamManager->remaining_images <= 0 and $teamManager->remaining_images != -1) {
$data = [
'errors' => ['You have no credits left. Please consider upgrading your plan.'],
];
return response()->json($data, 429);
}
}
$member = $user->teamMember;
if ($member) {
if (! $member->allow_unlimited_credits) {
if ($member->remaining_images <= 0 and $member->remaining_images != -1) {
$data = [
'errors' => ['You have no credits left. Please consider upgrading your plan.'],
];
return response()->json($data, 429);
}
}
}
} else {
if ($user->remaining_images <= 0 and $user->remaining_images != -1) {
$data = [
'errors' => ['You have no credits left. Please consider upgrading your plan.'],
];
return response()->json($data, 429);
}
}
return response()->json([], 200);
}
public static function sorting(array $data, $column, $direction)
{
if ($column) {
$data = collect($data)->sortBy($column, SORT_REGULAR, $direction == 'asc');
}
return $data;
}
public static function parseUrl(string ...$urls): string
{
return collect($urls)->map(fn ($url) => trim($url, '/'))->implode('/');
}
}
|