Added Setting.php, [Logs, Messages] Model

This commit is contained in:
Gitea
2025-04-23 17:52:22 +05:30
parent 20ebb7e4a4
commit b799ac3f9a
20 changed files with 1704 additions and 10 deletions

21
app/Models/Log.php Normal file
View File

@@ -0,0 +1,21 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Log extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'ip',
'email',
];
}

108
app/Models/Message.php Normal file
View File

@@ -0,0 +1,108 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class Message extends Model
{
use HasFactory;
public static function store(Request $request): void
{
$message = new Message;
$message->subject = $request->subject;
$message->from = $request->from;
$message->to = $request->to;
if ($request->has('html')) {
$message->body = $request->html;
} else {
$message->body = $request->text;
}
$message->save();
if ($request->has('content-ids')) {
$message->attachments = $request->get('attachment-info');
$message->save();
$directory = './attachments/' . $message->id;
is_dir($directory) || mkdir($directory, 0777, true);
$attachment_ids = json_decode($request->get('attachment-info'));
foreach ($attachment_ids as $attachment_id => $attachment_info) {
$allowed = explode(',', 'csv,doc,docx,xls,xlsx,ppt,pptx,xps,pdf,dxf,ai,psd,eps,ps,svg,ttf,zip,rar,tar,gzip,mp3,mpeg,wav,ogg,jpeg,jpg,png,gif,bmp,tif,webm,mpeg4,3gpp,mov,avi,mpegs,wmv,flx,txt');
$file = explode('.', $attachment_info->filename);
if (in_array($file[count($file) - 1], $allowed)) {
Storage::disk('tmp')->putFileAs($directory, $request->file($attachment_id), $attachment_info->filename);
}
}
}
}
public static function getMessages($email): array
{
$limit = json_decode(config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15;
$messages = Message::where('to', $email)->orWhere('to', 'like', '%<' . $email . '>%')->limit($limit)->get();
$response = [
'data' => [],
'notifications' => []
];
foreach ($messages as $message) {
$content = str_replace('<a', '<a target="blank"', $message->body);
if (json_decode(config('app.settings.configuration_settings'))->enable_masking_external_link) {
$content = str_replace('href="', 'href="https://href.li/?', $content);
}
$obj = [];
$obj['subject'] = $message->subject;
$sender = explode('<', $message->from);
$obj['sender_name'] = $sender[0];
if (isset($sender[1])) {
$obj['sender_email'] = str_replace('>', '', $sender[1]);
} else {
$obj['sender_email'] = $obj['sender_name'];
}
$obj['timestamp'] = $message->created_at;
$obj['date'] = $message->created_at->format(json_decode(config('app.settings.configuration_settings'))->date_format, 'd M Y h:i A');
$obj['datediff'] = $message->created_at->diffForHumans();
$obj['id'] = $message->id;
$obj['content'] = $content;
$obj['attachments'] = [];
$domain = explode('@', $obj['sender_email'])[1];
$blocked = in_array($domain, json_decode(config('app.settings.configuration_settings'))->blocked_domains);
if ($blocked) {
$obj['subject'] = __('Blocked');
$obj['content'] = __('Emails from') . ' ' . $domain . ' ' . __('are blocked by Admin');
}
if ($message->attachments && !$blocked) {
$attachments = json_decode($message->attachments);
foreach ($attachments as $id => $attachment) {
$url = config('app.settings.app_base_url') . '/tmp/attachments/' . $message->id . '/' . $attachment->filename;
if (str_contains($obj['content'], $id)) {
$obj['content'] = str_replace('cid:' . $id, $url, $obj['content']);
} else {
if (Storage::disk('tmp')->exists('attachments/' . $message->id . '/' . $attachment->filename)) {
$obj['attachments'][] = [
'file' => $attachment->filename,
'url' => $url
];
}
}
}
}
$response['data'][] = $obj;
if (!$message->is_seen) {
$response['notifications'][] = [
'subject' => $obj['subject'],
'sender_name' => $obj['sender_name'],
'sender_email' => $obj['sender_email']
];
if (config('app.zemail_log')) {
file_put_contents(storage_path('logs/zemail.csv'), request()->ip() . "," . date("Y-m-d h:i:s a") . "," . $obj['sender_email'] . "," . $email . PHP_EOL, FILE_APPEND);
}
$message->is_seen = true;
$message->save();
}
}
return $response;
}
}

52
app/Models/Meta.php Normal file
View File

@@ -0,0 +1,52 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Meta extends Model {
use HasFactory;
public function incrementMeta($value = 1) {
$this->value = $this->value + $value;
$this->save();
return true;
}
public static function incrementEmailIdsCreated($value = 1): bool
{
$meta = Meta::where('key', 'email_ids_created')->first();
if ($meta) {
$meta->incrementMeta($value);
return true;
}
return false;
}
public static function incrementMessagesReceived($value = 1): bool
{
$meta = Meta::where('key', 'messages_received')->first();
if ($meta) {
$meta->incrementMeta($value);
return true;
}
return false;
}
public static function getEmailIdsCreated() {
$meta = Meta::where('key', 'email_ids_created')->first();
if ($meta) {
return $meta->value;
}
return "NaN";
}
public static function getMessagesReceived() {
$meta = Meta::where('key', 'messages_received')->first();
if ($meta) {
return $meta->value;
}
return "NaN";
}
}

View File

@@ -25,11 +25,15 @@ class Setting extends Model
'app_header',
'app_footer',
'imap_settings',
'configuration_settings',
'ads_settings',
];
protected $casts = [
'app_meta' => 'json',
'app_social' => 'json',
'imap_settings' => 'json',
'configuration_settings' => 'json',
'ads_settings' => 'json',
];
}

516
app/Models/ZEmail.php Normal file
View File

@@ -0,0 +1,516 @@
<?php
namespace App\Models;
use Carbon\Carbon;
use Ddeboer\Imap\Search\Email\Cc;
use Ddeboer\Imap\Search\Email\To;
use Ddeboer\Imap\SearchExpression;
use Ddeboer\Imap\Server;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cookie;
use function str_replace;
class ZEmail extends Model
{
public static function check()
{
return ZEmail::createCustomEmail(username: 'sdcs', domain: 'e-pool.uk');
}
public static function connectMailBox($imap = null): \Ddeboer\Imap\ConnectionInterface
{
if ($imap === null) {
$imap = json_decode(config('app.settings.imap_settings'), true);
}
$flags = $imap['protocol'] . '/' . $imap['encryption'];
if ($imap['validate_cert']) {
$flags = $flags . '/validate-cert';
} else {
$flags = $flags . '/novalidate-cert';
}
$server = new Server($imap['host'], $imap['port'], $flags);
return $server->authenticate($imap['username'], $imap['password']);
}
public static function getMessages($email, $type = 'to', $deleted = []): array
{
if (config('app.beta_feature')) {
return Message::getMessages($email);
}
$allowed = explode(',', 'doc,docx,xls,xlsx,ppt,pptx,xps,pdf,dxf,ai,psd,eps,ps,svg,ttf,zip,rar,tar,gzip,mp3,mpeg,wav,ogg,jpeg,jpg,png,gif,bmp,tif,webm,mpeg4,3gpp,mov,avi,mpegs,wmv,flx,txt');
$connection = ZEmail::connectMailBox();
$mailbox = $connection->getMailbox('INBOX');
$search = new SearchExpression();
if ($type == 'cc') {
$search->addCondition(new Cc($email));
} else {
$search->addCondition(new To($email));
}
$messages = $mailbox->getMessages($search, \SORTDATE, true);
$limit = json_decode(config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15;
$count = 1;
$response = [
'data' => [],
'notifications' => []
];
foreach ($messages as $message) {
if (in_array($message->getNumber(), $deleted)) {
$message->delete();
continue;
}
$blocked = false;
$sender = $message->getFrom();
$date = $message->getDate();
if (!$date) {
$date = new \DateTime();
if ($message->getHeaders()->get('udate')) {
$date->setTimestamp($message->getHeaders()->get('udate'));
}
}
$datediff = new Carbon($date);
$content = '';
$html = $message->getBodyHtml();
if ($html) {
$content = str_replace('<a', '<a target="blank"', $html);
} else {
$text = $message->getBodyText();
$content = str_replace('<a', '<a target="blank"', str_replace(array("\r\n", "\n"), '<br/>', $text));
}
if (json_decode(config('app.settings.configuration_settings'))->enable_masking_external_link) {
$content = str_replace('href="', 'href="http://href.li/?', $content);
}
$obj = [];
$obj['subject'] = $message->getSubject();
$obj['sender_name'] = $sender->getName();
$obj['sender_email'] = $sender->getAddress();
$obj['timestamp'] = $message->getDate();
$obj['date'] = $date->format(json_decode(config('app.settings.configuration_settings'))->date_format, 'd M Y h:i A');
$obj['datediff'] = $datediff->diffForHumans();
$obj['id'] = $message->getNumber();
$obj['content'] = $content;
$obj['attachments'] = [];
//Checking if Sender is Blocked
$domain = explode('@', $obj['sender_email'])[1];
$blocked = in_array($domain, json_decode(config('app.settings.configuration_settings'))->blocked_domains);
if ($blocked) {
$obj['subject'] = __('Blocked');
$obj['content'] = __('Emails from') . ' ' . $domain . ' ' . __('are blocked by Admin');
}
if ($message->hasAttachments() && !$blocked) {
$attachments = $message->getAttachments();
$directory = './tmp/attachments/' . $obj['id'] . '/';
is_dir($directory) || mkdir($directory, 0777, true);
foreach ($attachments as $attachment) {
$filenameArray = explode('.', $attachment->getFilename());
$extension = $filenameArray[count($filenameArray) - 1];
if (in_array($extension, $allowed)) {
if (!file_exists($directory . $attachment->getFilename())) {
file_put_contents(
$directory . $attachment->getFilename(),
$attachment->getDecodedContent()
);
}
if ($attachment->getFilename() !== 'undefined') {
$url = config('app.settings.app_base_url') . str_replace('./', '/', $directory . $attachment->getFilename());
$structure = $attachment->getStructure();
if (isset($structure->id) && str_contains($obj['content'], trim($structure->id, '<>'))) {
$obj['content'] = str_replace('cid:' . trim($structure->id, '<>'), $url, $obj['content']);
}
$obj['attachments'][] = [
'file' => $attachment->getFilename(),
'url' => $url
];
}
}
}
}
$response['data'][] = $obj;
if (!$message->isSeen()) {
$response['notifications'][] = [
'subject' => $obj['subject'],
'sender_name' => $obj['sender_name'],
'sender_email' => $obj['sender_email']
];
if (config('app.zemail_log')) {
file_put_contents(storage_path('logs/zemail.csv'), request()->ip() . "," . date("Y-m-d h:i:s a") . "," . $obj['sender_email'] . "," . $email . PHP_EOL, FILE_APPEND);
}
}
$message->markAsSeen();
if (++$count > $limit) {
break;
}
}
$response['data'] = array_reverse($response['data']);
$connection->expunge();
return $response;
}
public static function deleteMessage($id): void
{
$connection = ZEmail::connectMailBox();
$mailbox = $connection->getMailbox('INBOX');
$mailbox->getMessage($id)->delete();
$connection->expunge();
}
public static function getEmail($generate = false) {
if (Cookie::has('email')) {
return Cookie::get('email');
} else {
return $generate ? ZEmail::generateRandomEmail() : null;
}
}
public static function getEmails() {
if (Cookie::has('emails')) {
return unserialize(Cookie::get('emails'));
} else {
return [];
}
}
public static function setEmail($email): void
{
$emails = unserialize(Cookie::get('emails'));
if (is_array($emails) && in_array($email, $emails)) {
Cookie::queue('email', $email, 43800);
}
}
public static function removeEmail($email): void
{
$emails = ZEmail::getEmails();
$key = array_search($email, $emails);
if ($key !== false) {
array_splice($emails, $key, 1);
}
if (count($emails) > 0) {
ZEmail::setEmail($emails[0]);
Cookie::queue('emails', serialize($emails), 43800);
} else {
Cookie::queue('email', '', -1);
Cookie::queue('emails', serialize([]), -1);
}
}
public static function createCustomEmailFull($email): string
{
$data = explode('@', $email);
$username = $data[0];
if (strlen($username) < json_decode(config('app.settings.configuration_settings'))->custom_username_length_min || strlen($username) > json_decode(config('app.settings.configuration_settings'))->custom_username_length_max) {
$zemail = new ZEmail();
$username = $zemail->generateRandomUsername();
}
$domain = $data[1];
return ZEmail::createCustomEmail($username, $domain);
}
public static function createCustomEmail($username, $domain): string
{
$username = preg_replace('/[^a-zA-Z0-9+.]/', '', strtolower($username));
$settings = json_decode(config('app.settings.configuration_settings'), true);
$forbidden_ids = $settings['forbidden_ids'] ?? [];
$gmail_usernames = $settings['gmailUsernames'] ?? [];
$domains = $settings['domains'] ?? [];
if (in_array($username, $forbidden_ids)) {
return ZEmail::generateRandomEmail(true);
}
if ($username === '' && in_array($domain, ['gmail.com', 'googlemail.com'])) {
return ZEmail::generateRandomGmail(true);
}
$zemail = new ZEmail();
if ($username === '' && in_array($domain, $domains)) {
return $zemail->generateRandomUsername().'@'.$domain;
}
if (in_array($domain, ['gmail.com', 'googlemail.com'])) {
if (str_contains($username, '+')) {
[$check_username, $post_username] = explode('+', $username, 2);
if (in_array($check_username, $gmail_usernames)) {
$email = $username . '@' . $domain;
} else {
$email = $zemail->getRandomGmailUser() . '+' . $post_username . '@' . $domain;
}
} elseif (str_contains($username, '.')) {
$check_username = str_replace('.', '', $username);
if (in_array($check_username, $gmail_usernames)) {
$email = $username . '@' . $domain;
} else {
$email = $zemail->generateRandomGmail() . '@' . $domain;
}
} else {
$email = $zemail->getRandomGmailUser() . '+' . $username . '@' . $domain;
}
ZEmail::storeEmail($email);
return $email;
}
// Handle other custom domains
if (!in_array($domain, $domains)) {
return ZEmail::generateRandomEmail(true);
}
$finalDomain = in_array($domain, $domains) ? $domain : ($domains[0] ?? 'example.com');
$email = $username . '@' . $finalDomain;
ZEmail::storeEmail($email);
return $email;
}
public static function generateRandomEmail($store = true): string
{
$zemail = new ZEmail();
$domain = $zemail->getRandomDomain();
if ($domain == "gmail.com") {
$rd = mt_rand(0,1);
if ($rd == 0) {
$email = $zemail->generateRandomGmail();
} else {
$email = $zemail->getRandomGmailUser().'+'.$zemail->generateRandomUsername().'@gmail.com';
}
} elseif ($domain == "googlemail.com") {
$rd = mt_rand(0,1);
if ($rd == 0) {
$email = $zemail->generateRandomGmail();
} else {
$email = $zemail->getRandomGmailUser().'+'.$zemail->generateRandomUsername().'@googlemail.com';
}
} else {
$email = $zemail->generateRandomUsername() . '@' . $domain;
}
if ($store) {
ZEmail::storeEmail($email);
}
return $email;
}
public static function generateRandomGmail($store = true): string
{
$zemail = new ZEmail();
$uname = $zemail->getRandomGmailUser();
$uname_len = strlen($uname);
$len_power = $uname_len - 1;
$combination = pow(2,$len_power);
$rand_comb = mt_rand(1,$combination);
$formatted = implode(' ',str_split($uname));
$uname_exp = explode(' ', $formatted);
$bin = intval("");
for($i=0; $i<$len_power; $i++) {
$bin .= mt_rand(0,1);
}
$bin = explode(' ', implode(' ',str_split(strval($bin))));
$email = "";
for($i=0; $i<$len_power; $i++) {
$email .= $uname_exp[$i];
if($bin[$i]) {
$email .= ".";
}
}
$email .= $uname_exp[$i];
$gmail_rand = mt_rand(1,10);
if($gmail_rand > 5) {
$email .= "@gmail.com";
} else {
$email .= "@googlemail.com";
}
if ($store) {
ZEmail::storeEmail($email);
}
return $email;
}
private static function storeEmail($email): void
{
Log::create([
'ip' => request()->ip(),
'email' => $email
]);
Cookie::queue('email', $email, 43800);
$emails = Cookie::has('emails') ? unserialize(Cookie::get('emails')) : [];
if (!in_array($email, $emails)) {
ZEmail::incrementEmailStats();
$emails[] = $email;
Cookie::queue('emails', serialize($emails), 43800);
}
}
/**
* Stats Handling Functions
*/
public static function incrementEmailStats($count = 1): void
{
Meta::incrementEmailIdsCreated($count);
}
public static function incrementMessagesStats($count = 1): void
{
Meta::incrementMessagesReceived($count);
}
private function generateRandomUsername(): string
{
$start = json_decode(config('app.settings.configuration_settings'))->random_username_length_min ?? 0;
$end = json_decode(config('app.settings.configuration_settings'))->random_username_length_max ?? 0;
if ($start == 0 && $end == 0) {
return $this->generatePronounceableWord();
}
return $this->generatedRandomBetweenLength($start, $end);
}
protected function generatedRandomBetweenLength($start, $end): string
{
$length = rand($start, $end);
return $this->generateRandomString($length);
}
private function getRandomDomain() {
$domains = json_decode(config('app.settings.configuration_settings'))->domains ?? [];
$count = count($domains);
return $count > 0 ? $domains[rand(1, $count) - 1] : '';
}
private function getRandomGmailUser() {
$gmailusername = json_decode(config('app.settings.configuration_settings'))->gmailUsernames ?? [];
$count = count($gmailusername);
return $count > 0 ? $gmailusername[rand(1, $count) - 1] : '';
}
private function generatePronounceableWord(): string
{
$c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
$v = 'aeiou'; //vowels
$a = $c . $v; //both
$random = '';
for ($j = 0; $j < 2; $j++) {
$random .= $c[rand(0, strlen($c) - 1)];
$random .= $v[rand(0, strlen($v) - 1)];
$random .= $a[rand(0, strlen($a) - 1)];
}
return $random;
}
private function generateRandomString($length = 10): string
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
}
// public static function createCustomEmail($username, $domain): string
// {
// $username = str_replace('[^a-zA-Z0-9]', '', strtolower($username));
// $forbidden_ids = json_decode(config('app.settings.configuration_settings'))->forbidden_ids ?? [];
// $gmail_usernames = json_decode(config('app.settings.configuration_settings'))->gmailUsernames ?? [];
// if (in_array($username, $forbidden_ids)) {
// return ZEmail::generateRandomEmail(true);
// }
// $zemail = new ZEmail();
// if($domain == "gmail.com") {
//
// if(str_contains($username, "+")){
// $check_username = explode("+", $username)[0];
// $post_username = explode("+", $username)[1];
// if (in_array($check_username, $gmail_usernames)) {
// $email = $username . '@gmail.com';
// ZEmail::storeEmail($email);
// return $email;
// } else {
//
// $email = $zemail->getRandomGmailUser().'+'.$post_username.'@gmail.com';
// ZEmail::storeEmail($email);
// return $email;
// }
// }
// elseif(str_contains($username, ".")){
// $check_username = str_replace(".","",$username);
//
// if (in_array($check_username, $gmail_usernames)) {
// $email = $username . '@gmail.com';
// ZEmail::storeEmail($email);
// return $email;
// } else {
//
// $email = $zemail->generateRandomGmail();
// ZEmail::storeEmail($email);
// return $email;
// }
//
// }
// else {
//
// $email = $zemail->getRandomGmailUser().'+'.$username.'@gmail.com';
// ZEmail::storeEmail($email);
// return $email;
// }
// } elseif($domain == "googlemail.com") {
// if(str_contains($username, "+")){
// $check_username = explode("+", $username)[0];
// $post_username = explode("+", $username)[1];
//
// if (in_array($check_username, $gmail_usernames)) {
// $email = $username . '@googlemail.com';
// ZEmail::storeEmail($email);
// return $email;
// } else {
//
// $email = $zemail->getRandomGmailUser().'+'.$post_username.'@googlemail.com';
// ZEmail::storeEmail($email);
// return $email;
// }
// }
// elseif(str_contains($username, ".")){
// $check_username = str_replace(".","",$username);
//
// if (in_array($check_username, $gmail_usernames)) {
// $email = $username . '@googlemail.com';
// ZEmail::storeEmail($email);
// return $email;
// } else {
//
// $email = $zemail->generateRandomGmail();
// ZEmail::storeEmail($email);
// return $email;
// }
// }
// else {
// $email = $zemail->getRandomGmailUser().'+'.$username.'@googlemail.com';
// ZEmail::storeEmail($email);
// return $email;
// }
// } else {
// $domains = json_decode(config('app.settings.configuration_settings'))->domains ?? [];
// if (in_array($domain, $domains)) {
// $email = $username . '@' . $domain;
// ZEmail::storeEmail($email);
// return $email;
// } else {
// $email = $username . '@' . $domains[0];
// ZEmail::storeEmail($email);
// return $email;
// }
//
// }
// }