[ 'class' => AccessControl::class, 'rules' => [ [ 'actions' => ['login', 'signup', 'createuser', 'loginuser', 'forgotpassword', 'resetpassword', 'error', 'forgotpasswordsendlink', 'saveresetpassword', 'confirmaccount', 'smtpfirebasesync', 'mailresponsehandler', 'testpostsmtp', 'robots','getresendlink'], 'allow' => true, ], [ 'actions' => ['logout', 'index', 'smtp101', 'smtp2023', 'dashboard', 'smtp', 'createsmtp', 'timings', 'addworkinghours', 'profile', 'updateprofile', 'changepass', 'deletetimings', 'deletesmtp', 'changesmtpstatus', 'smtpdashboard', 'updatesmtpsettings', 'updatesmtpemailsignature', 'updatesmtpwarmuptopic', 'pricing', 'updatesmtpwarmuplanguage', 'getdashboarddata', 'getchartdata', 'smtprunspftest', 'emailwarmupconfig', 'storecsv', 'emailsignature', 'deleteaccount', 'filterdata', 'searchemail', 'checksmtp', 'checkimap', 'addemailblacklist', 'storeblacklistcsv', 'emailblacklist', 'domainblacklist', 'deleteblacklist', 'searchblacklist', 'getactivitychartdata', 'customtemplate', 'template', 'deleteblacklistemailbulk', 'deletesmtpemailbulk', 'deleteblacklistdomainbulk', 'storecustomtemplate', 'deletecustomtemplate', 'fetchcustomtemplate', 'updatetemplate', 'assigntag', 'addbulk','generatetemplate','aitemplate','bulkchangesmtpstatus','uploadprofileimage'], 'allow' => true, 'roles' => ['@'], ], ], ], 'verbs' => [ 'class' => VerbFilter::class, 'actions' => [ 'logout' => ['post'], ], ], ]; } /** * {@inheritdoc} */ public function actions() { return [ 'error' => [ 'class' => \yii\web\ErrorAction::class, ], ]; } /** * Displays homepage. * * @return string */ public function actionIndex() { //echo Yii::$app->user->identity->username;exit; //return $this->render('smtp'); $url = \Yii::$app->request->baseUrl . "/site/smtp"; return $this->redirect($url); } public function actionTemplate() { $templates = Yii::$app->getDb()->createCommand("SELECT t.templateId,u.userId,t.counter from `templates` t,`users` u WHERE u.userId = t.userId AND t.templateOrder = 0 AND u.status = 1")->queryAll(); $array = array(); if ($templates) { foreach ($templates as $template) { echo $template['templateId'] . "\r\n"; echo $template['userId'] . "\r\n"; echo $template['counter'] . "\r\n"; } } exit; } // public function getsmtpdetails($smtpid) // { // $smtplist_query = new Query; // $smtplist = $smtplist_query->select(['emailAddress','smtp','port','encryption','smtpId','status','senderName','warm_up_topic','selected_language','perDayLimit','provider','sends','receives','replies','signature']) // ->from('smtp') // ->where(['smtpId' => $smtpid]) // ->all(); // return $smtplist; // } public function actionPricing() { return $this->render('pricing'); } public function actionBlacklist() { return $this->render('blacklist'); } public function actionEmailblacklist() { $blacklist_query = new Query; $blacklist = $blacklist_query->select(['userId', 'type', 'blacklisted', 'csv_file_id']) ->from('blacklist') ->where(['userId' => Yii::$app->user->identity->userId]) ->andWhere(['type' => '0']); // ->all(); $emailFilter = Yii::$app->request->get('emailFilter'); if (!empty($emailFilter)) { $blacklist->andFilterWhere(['like', 'blacklisted', $emailFilter]); } $countQuery = $blacklist->count(); $pages = new Pagination(['totalCount' => $countQuery, 'pageSize' => 10]); $models = $blacklist->offset($pages->offset) ->limit($pages->limit) ->orderBy(['id' => SORT_DESC]) ->all(); return $this->render('emailblacklist', array('blacklist' => $models, 'pages' => $pages)); } public function actionDomainblacklist() { $blacklist_query = new Query; $blacklist = $blacklist_query->select(['userId', 'type', 'blacklisted', 'csv_file_id']) ->from('blacklist') ->where(['userId' => Yii::$app->user->identity->userId]) ->andWhere(['type' => '1']); // ->all(); $domainFilter = Yii::$app->request->get('domainFilter'); if (!empty($domainFilter)) { $blacklist->andFilterWhere(['like', 'blacklisted', $domainFilter]); } $countQuery = $blacklist->count(); $pages = new Pagination(['totalCount' => $countQuery, 'pageSize' => 10]); $models = $blacklist->offset($pages->offset) ->limit($pages->limit) ->orderBy(['id' => SORT_DESC]) ->all(); return $this->render('domainblacklist', array('blacklist' => $models, 'pages' => $pages)); } public function actionSmtpdashboard() { $smtplist_query = new Query; $smtplist = $smtplist_query->select(['emailAddress', 'smtpId', 'senderName', 'status', 'sends', 'receives', 'perDayLimit', 'signature']) ->from('smtp') ->where(['userId' => Yii::$app->user->identity->userId]) ->all(); return $this->render('dashboard101', array('smtplist' => $smtplist)); } // Profile settings public function actionProfile() { return $this->render('profile'); } public function actionRobots() { $this->layout = 'empty.php'; return $this->render('robots'); } public function actionUpdatesmtpwarmuplanguage() { $warmuplanguage = $_POST['warmuplanguage']; $smtp_id = $_POST['smtp_id']; Yii::$app->db->createCommand("update smtp set selected_language = '" . $warmuplanguage . "' where smtpId = " . $smtp_id)->execute(); } public function actionUpdatesmtpwarmuptopic() { $warmuptopic = $_POST['warmuptopic']; $smtp_id = $_POST['smtp_id']; Yii::$app->db->createCommand("update smtp set warm_up_topic = '" . $warmuptopic . "' where smtpId = " . $smtp_id)->execute(); } public function actionUpdatesmtpsettings() { $fromname_smtp = $_POST['fromname_smtp']; $perdaysmtpdetails = $_POST['perdaysmtpdetails']; $smtp_id = $_POST['smtp_id']; $templateId = $_POST['templatetopicId']; Yii::$app->db->createCommand("update smtp set senderName = '" . $fromname_smtp . "', perDayLimit = '" . $perdaysmtpdetails . "',nextRunTime='" . time() . "',templateId='".$templateId."' where smtpId = " . $smtp_id)->execute(); } //khushi public function actionUpdatesmtpemailsignature() { $signature1 = $_POST['signature1']; $smtp_id = $_POST['smtpId']; $result = Yii::$app->db->createCommand("update smtp set signature = '" . $signature1 . "' where smtpId = " . $smtp_id)->execute(); echo json_encode($result); } public function actionAddemailblacklist() { $response_arr = [ 'http_status' => 405, 'data' => [], 'message' => 'Method Not Allowed' ]; $userID = Yii::$app->user->identity->userId; $emailblacklist = $_POST['emailblacklist']; if (isset($_POST['blacklist_type'])) { $blacklist_type = $_POST['blacklist_type']; } else { $response_arr['message'] = 'Blacklist type not idenetified'; echo json_encode($response_arr); exit(); } $pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^"; if (!empty($emailblacklist)) { if (!preg_match($pattern, $emailblacklist) && $blacklist_type == '0') { $response_arr['message'] = 'Invalid Email address'; $response_arr['http_status'] = 400; echo json_encode($response_arr); exit(); } if (!$this->isValidDomain($emailblacklist) && $blacklist_type == '1') { $response_arr['http_status'] = 406; $response_arr['message'] = "Invalid Domain name.Please enter a valid domain name"; echo json_encode($response_arr); exit(); } // c that blacklist_email is present in blacklist table $existing_blacklist = Yii::$app->db->createCommand("Select blacklisted from blacklist where userId = '" . Yii::$app->user->identity->userId . "' AND type='" . $blacklist_type . "' AND blacklisted = '" . $emailblacklist . "'")->queryOne(); if ($existing_blacklist && $blacklist_type == '0') { $response_arr['message'] = 'Email address already exists in blacklist'; $response_arr['http_status'] = 400; echo json_encode($response_arr); exit(); } if ($existing_blacklist && $blacklist_type == '1') { $response_arr['message'] = 'Domain already exists in blacklist'; $response_arr['http_status'] = 400; echo json_encode($response_arr); exit(); } // $existing_email_id = Yii::$app->db->createCommand("Select emailAddress,smtpId from smtp where userId = '".Yii::$app->user->identity->userId."' AND emailAddress = '".$emailblacklist."'")->queryOne(); // if($existing_email_id){ Yii::$app->db->createCommand("INSERT INTO `blacklist`(`userId`,`type`,`blacklisted`) VALUES ('" . $userID . "','" . $blacklist_type . "','" . $emailblacklist . "')")->execute(); $lastcreatedblacklistId = Yii::$app->db->getLastInsertID(); // Yii::$app->db->createCommand("update smtp set isBlacklisted = '1' where smtpId = '".$existing_email_id['smtpId']."' AND emailAddress='".$existing_email_id['emailAddress']."'")->execute(); if ($lastcreatedblacklistId) { $response_arr['http_status'] = 200; $response_arr['message'] = "Blacklisted Successfully."; } else { $response_arr['http_status'] = 400; $response_arr['message'] = "Something went wrong!"; } } else { $response_arr['message'] = 'Empty field'; $response_arr['http_status'] = 400; } // } echo json_encode($response_arr); // exit(); // } } //khushi start public function actionDeleteblacklistemailbulk() { $selectedlist = $_POST['selectedlist']; if (is_array($selectedlist)) { $selectedlist = implode("', '", $selectedlist); } Yii::$app->db->createCommand("DELETE FROM blacklist WHERE blacklisted IN ('" . $selectedlist . "')")->execute(); echo json_encode(['status' => 'success', 'message' => 'Blacklist emails deleted successfully']); } public function actionDeleteblacklistdomainbulk() { $selectedlist = $_POST['selectedlist']; if (is_array($selectedlist)) { $selectedlist = implode("', '", $selectedlist); } Yii::$app->db->createCommand("DELETE FROM blacklist WHERE blacklisted IN ('" . $selectedlist . "')")->execute(); echo json_encode(['status' => 'success', 'message' => 'Blacklist domains deleted successfully']); } public function actionDeletesmtpemailbulk() { $selectedlist = $_POST['selectedlist']; if (is_array($selectedlist)) { $selectedlist = implode(",", $selectedlist); } //Yii::$app->db->createCommand("DELETE FROM smtp WHERE emailAddress IN ('".$selectedlist."') AND status=0")->execute(); Yii::$app->db->createCommand("UPDATE smtp SET deletedAt='" . date('Y-m-d h:i:s') . "',status=0 WHERE smtpId IN (" . $selectedlist . ") and userId=" . Yii::$app->user->identity->userId)->execute(); Yii::$app->db->createCommand("UPDATE tasks SET status=5 WHERE senderSmtpId IN (" . $selectedlist . ") OR receiverSmtpId IN (" . $selectedlist . ") AND userId=" . Yii::$app->user->identity->userId)->execute(); echo json_encode(['status' => 'success', 'message' => 'Smtp deleted successfully']); } //khushi end public function actionDeleteblacklist() { if (isset($_POST['blacklist_value'])) { $blacklist_value = $_POST['blacklist_value']; $blacklist_type = $_POST['blacklist_type']; Yii::$app->db->createCommand("DELETE FROM blacklist WHERE blacklisted='" . $blacklist_value . "' AND userId = '" . Yii::$app->user->identity->userId . "' AND type='" . $blacklist_type . "' ")->execute(); echo json_encode(['status' => 'success', 'message' => 'Blacklist deleted successfully']); exit; } else { echo json_encode(['status' => 'error', 'message' => 'Somethig went wrong']); exit; } } function isValidDomain($domain) { // Regular expression pattern to match domain name format $pattern = '/^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,}$/i'; // Perform the validation return preg_match($pattern, $domain); } public function actionAdddomainblacklist() { $response_arr = [ 'http_status' => 405, 'data' => [], 'message' => 'Method Not Allowed' ]; $userID = Yii::$app->user->identity->userId; $domainblacklist = $_POST['domainblacklist']; $blacklist_type = $_POST['blacklist_type']; if (!empty($domainblacklist)) { $validate = $this->isValidDomain($domainblacklist); if ($validate) { // // check that blacklist_domain is present in blacklist table $existing_blacklist = Yii::$app->db->createCommand("Select blacklisted from blacklist where userId = '" . Yii::$app->user->identity->userId . "' AND type='" . $blacklist_type . "' AND blacklisted = '" . $domainblacklist . "'")->queryOne(); if ($existing_blacklist) { $response_arr['message'] = 'Domain already exists in database'; $response_arr['http_status'] = 400; } else { $existing_domain = Yii::$app->db->createCommand("Select emailAddress,smtpId from smtp where userId = '" . Yii::$app->user->identity->userId . "' AND SUBSTRING_INDEX(emailAddress,'@',-1) = '" . $domainblacklist . "'")->queryAll(); if ($existing_domain) { Yii::$app->db->createCommand("INSERT INTO `blacklist`(`userId`,`isEmail`,`isDomain`,`blacklisted`) VALUES ('" . $userID . "','0','1','" . $domainblacklist . "')")->execute(); $lastcreatedblacklistId = Yii::$app->db->getLastInsertID(); for ($i = 0; $i < count($existing_domain); $i++) { Yii::$app->db->createCommand("update smtp set isBlacklisted = '1' where smtpId = '" . $existing_domain[$i]['smtpId'] . "' AND SUBSTRING_INDEX(emailAddress,'@',-1)='" . $domainblacklist . "'")->execute(); } if ($lastcreatedblacklistId) { $response_arr['http_status'] = 200; $response_arr['message'] = "Blacklisted Successfully."; } else { $response_arr['http_status'] = 400; $response_arr['message'] = "Error."; } } else { $response_arr['http_status'] = 404; $response_arr['message'] = "Domain is not present in SMTP list."; } } } else { $response_arr['http_status'] = 406; $response_arr['message'] = "Invalid Domain name.Please enter a valid domain name"; } } else { $response_arr['http_status'] = 404; $response_arr['message'] = "Domain Field is empty.Please enter domain name."; } echo json_encode($response_arr); exit(); } //khushi end public function actionUpdateprofile() { $firstName = $_POST['firstName']; $lastName = $_POST['lastName']; Yii::$app->db->createCommand("update users set firstname = '" . $firstName . "', lastname = '" . $lastName . "' where userId = " . Yii::$app->user->identity->userId)->execute(); } public function actionChangepass() { $mypasskey = Yii::$app->request->post('newpass'); if (preg_match('/^(?=.*[!@#$%^&*-])(?=.*[0-9])(?=.*[A-Z]).{6,20}$/', $mypasskey)) { $password = password_hash($mypasskey, PASSWORD_DEFAULT); $sql = "UPDATE `users` SET `password`='" . $password . "' where `userId`='" . Yii::$app->user->identity->userId . "'"; Yii::$app->db->createCommand($sql)->execute(); return 3; } else { return 1; } } public function getsmtpdetails($smtpid) { $smtplist_query = new Query; $smtplist = $smtplist_query->select(['emailAddress', 'smtp', 'port', 'encryption', 'smtpId', 'status', 'senderName', 'warm_up_topic', 'selected_language', 'perDayLimit', 'provider', 'sends', 'receives', 'replies', 'signature']) ->from('smtp') ->where(['smtpId' => $smtpid]) ->all(); return $smtplist; } public function getsmtpinboxvsspam($smtpid) { $getinboxtoday = Yii::$app->db->createCommand("Select taskId from completedtasks where senderSmtpId = '" . $smtpid . "' AND userId = '" . Yii::$app->user->identity->userId . "' AND stepOrder = '0' AND mailStatus = '1' AND completedOn >= now() - INTERVAL 1 DAY")->queryAll(); $getcntinbox = count($getinboxtoday); $getspamtoday = Yii::$app->db->createCommand("Select taskId from completedtasks where senderSmtpId = '" . $smtpid . "' AND userId = '" . Yii::$app->user->identity->userId . "' AND stepOrder = '0' AND mailStatus = '2' AND completedOn >= now() - INTERVAL 1 DAY")->queryAll(); $getcntspam = count($getspamtoday); return $getcntinbox . ':' . $getcntspam; } public function gettotalactivity($smtpid) { $getinboxtoday = Yii::$app->db->createCommand("Select taskId,completedOn,senderSmtpId,userId,status,receiverId from completedtasks where senderSmtpId = '" . $smtpid . "' AND userId = '" . Yii::$app->user->identity->userId . "' AND mailStatus = '1' AND completedOn >= now() - INTERVAL 1 DAY")->queryAll(); $getcntinbox = count($getinboxtoday); $getspamtoday = Yii::$app->db->createCommand("Select taskId from completedtasks where senderSmtpId = '" . $smtpid . "' AND userId = '" . Yii::$app->user->identity->userId . "' AND stepOrder = '0' AND mailStatus = '2' AND completedOn >= now() - INTERVAL 1 DAY")->queryAll(); $getcntspam = count($getspamtoday); return $getcntinbox . ':' . $getcntspam; } // create user public function actionCreateuser() { // msg for status code // 0 = something went wrong contact support // 1 = user alredy availabel // 2 = Please confirm email we have sent you //echo '
'; print_r($_POST);

		if (isset($_POST['email']) && !empty($_POST['email']) && isset($_POST['password']) && !empty($_POST['password'])) {
			//echo "SELECT userId FROM users where email = '".$_POST['email']."'"; exit;
			$checkemail = Yii::$app->db->createCommand("SELECT userId,email FROM users where email = '" . $_POST['email'] . "'")->queryOne();
			//echo '
'; print_r($checkemail); exit;
			if (isset($checkemail['userId']) && $checkemail['userId'] != '') {

				//echo '1'; exit;  

				$url = \Yii::$app->request->baseUrl . "/site/signup?status=1";
				return $this->redirect($url);
			} else {

				$timezone_offset_minutes = 330;
				$timezone_name = timezone_name_from_abbr("", $timezone_offset_minutes * 60, false);
				echo $timezone_name;

				//echo '2'; exit;
				$hash = Yii::$app->getSecurity()->generatePasswordHash($_POST['password']);
				//echo "INSERT INTO `users`(`email`,`password`) VALUES ('".$_POST['email']."','".$hash."')"; exit;
				Yii::$app->db->createCommand("INSERT INTO `users`(`username`,`email`,`password`,`firstname`,`lastname`,`contactPhone`,`timezone`) VALUES ('" . $_POST['email'] . "','" . $_POST['email'] . "','" . $hash . "','".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['contactphone']."','" . $timezone_name . "')")->execute();
				$userId = Yii::$app->db->getLastInsertID();
				$userId = base64_encode($userId);
				
				try {

					$mail = new \PHPMailer(); // create a new object
					$mail->IsSMTP(); // enable SMTP
					$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
					$mail->SMTPAuth = true; // authentication enabled
					$mail->Host = Yii::$app->params['smtpHost'];
					$mail->Username = Yii::$app->params['smtpUsername'];
					$mail->Password = Yii::$app->params['smtpPassword'];
					$mail->SMTPSecure = strtolower(Yii::$app->params['smtpEncryption']); // only lowercase enc will work 
					$mail->Port = Yii::$app->params['smtpPort'];

					$mail->SetFrom(Yii::$app->params['fromEmail'], Yii::$app->params['fromName']);
					$mail->Subject = "Inbox Igniter - Confirmation link";
					$mail->IsHTML(true);

					// $message = '

Click on below link to confirm your account.

'; // $message .= '

https://app.inboxigniter.com/site/confirmaccount?key=' . $userId . '

'; $message = $message = '

Please Confirm Your InboxIgnitor Email.

Hi

Please click on the confirm email button to confirm your email.

Confirm Email

If you did not request this email you can safely ignore it.

'; $mail->Body = $message; $mail->AddAddress($_POST['email']); $mailstatus = $mail->Send(); if ($mailstatus) { echo 'Email sent to confirm password.'; Yii::$app->session->set('userEmail', $_POST['email']); Yii::$app->session->set('userId', $userId ); } else { echo 'Something went wrong!'; } } catch (Exception $e) { if (!$e->getCode()) { } else { } } $url = \Yii::$app->request->baseUrl . "/site/login?status=2"; return $this->redirect($url); } } else { $url = \Yii::$app->request->baseUrl . "/site/login?status=0"; return $this->redirect($url); } } public function actionConfirmaccount() { if (isset($_REQUEST['key'])) { $userId = base64_decode($_REQUEST['key']); $cdate = date('Y-m-d h:i:s'); $sql = "UPDATE `users` SET `emailVerifiedAt`='" . $cdate . "' where `userId`='" . $userId . "'"; Yii::$app->db->createCommand($sql)->execute(); $url = \Yii::$app->request->baseUrl . "/site/login?status=6"; return $this->redirect($url); } else { $url = \Yii::$app->request->baseUrl . "/site?status=0"; return $this->redirect($url); } } public function actionLoginuser() { // msg for status code // 0 = something went wrong contact support // 3 = user not found // 4 = wrong password if (isset($_POST['email']) && !empty($_POST['email']) && isset($_POST['password']) && !empty($_POST['password'])) { //echo "SELECT userId FROM users where email = '".$_POST['email']."'"; exit; $checkemail = Yii::$app->db->createCommand("SELECT userId,email,password,emailVerifiedAt FROM users where email = '" . $_POST['email'] . "'")->queryOne(); //echo '
'; print_r($checkemail); exit;

			if (isset($checkemail['userId']) && $checkemail['userId'] != '') {
				if ($checkemail['emailVerifiedAt']  != 'NULL') {
					if (Yii::$app->getSecurity()->validatePassword($_POST['password'], $checkemail['password'])) {


						$session = Yii::$app->session;
						$session->set('userId', $checkemail['userId']);
						$session->set('email', $_POST['email']);

						$url = \Yii::$app->request->baseUrl . "/site/smtp101";
						return $this->redirect($url);
					} else {
						$url = \Yii::$app->request->baseUrl . "/site/login?status=4";
						return $this->redirect($url);
					}
				} else {
					$url = \Yii::$app->request->baseUrl . "/site/login?status=2";
					return $this->redirect($url);
				}
			} else {
				$url = \Yii::$app->request->baseUrl . "/site/login?status=3";
				return $this->redirect($url);
			}
		} else {
			$url = \Yii::$app->request->baseUrl . "/site/login?status=0";
			return $this->redirect($url);
		}
	}

	/**
	 * Login action.
	 *
	 * @return string|Response
	 */
	public function actionLogin()
	{

		if (!Yii::$app->user->isGuest) {
			return $this->goHome();
		}
		$model = new LoginForm();
		$showResendLink = false;
		if ($model->load(Yii::$app->request->post())) {
			//echo $passwordHash = Yii::$app->getSecurity()->generatePasswordHash($model->password);exit;
			//if (Yii::$app->getSecurity()->validatePassword($_POST['password'],$checkemail['password'])) {
			$user = Yii::$app->db->createCommand("SELECT * FROM users where email ='" . $model->username . "'")->queryOne();
			
			if (empty($user)) {
				$model->password = '';
				$this->layout = 'blank';
				return $this->render('login', ['model' => $model, 'error' => 'User not found.']);
			}
			if (empty($user['emailVerifiedAt'])) {
				$showResendLink = true;
				$error = 'You need to confirm your Email Address.';
				$this->layout = 'blank';
				return $this->render('login', ['model' => $model, 'error' => $error , 'showResendLink' => $showResendLink]);
				// $url = \Yii::$app->request->baseUrl . "/site/login?status=2";
				// return $this->redirect($url);
			}
			if ($model->login()) {
				$showResendLink = false;
				return $this->redirect(['site/smtp']);
			}
			$showResendLink = false;
			$model->password = '';
			$this->layout = 'blank';
			return $this->render('login', ['model' => $model , 'showResendLink' => $showResendLink ]);
		} else {
			$showResendLink = false;
			$model->password = '';
			$this->layout = 'blank';
			return $this->render('login', ['model' => $model , 'showResendLink' => $showResendLink]);
		}
	}
	public function actionGetresendlink(){

		$userEmail = Yii::$app->session->get('userEmail');
		$userId = Yii::$app->session->get('userId' );

		if($userEmail && $userId && Yii::$app->request->isAjax){

				try {
					$mail = new \PHPMailer(); // create a new object
					$mail->IsSMTP(); // enable SMTP
					$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
					$mail->SMTPAuth = true; // authentication enabled
					$mail->Host = Yii::$app->params['smtpHost'];
					$mail->Username = Yii::$app->params['smtpUsername'];
					$mail->Password = Yii::$app->params['smtpPassword'];
					$mail->SMTPSecure = strtolower(Yii::$app->params['smtpEncryption']); // only lowercase enc will work 
					$mail->Port = Yii::$app->params['smtpPort'];
					$mail->SetFrom(Yii::$app->params['fromEmail'], Yii::$app->params['fromName']);
					$mail->Subject = "Inbox Igniter - Confirmation link";
					$mail->IsHTML(true);
		
					// $message = '

Click on below link to confirm your account.

'; // $message .= '

https://app.inboxigniter.com/site/confirmaccount?key=' . $userId . '

'; $message = '

Please Confirm Your InboxIgnitor Email.

Hi

Please click on the confirm email button to confirm your email.

Confirm Email

If you did not request this email you can safely ignore it.

'; $mail->Body = $message; $mail->AddAddress($userEmail); $mailstatus = $mail->Send(); if ($mailstatus) { Yii::$app->session->set('userEmail', $userEmail); Yii::$app->session->set('userId', $userId ); echo json_encode(['message' => 'Confirmation link resent successfully']); } else { echo 'Something went wrong!'; } } catch (Exception $e) { if (!$e->getCode()) { } else { } } }else{ echo json_encode(['message' => 'nope']); } } /** * Signup action. * * @return string|Response */ public function actionSignup() { if (!Yii::$app->user->isGuest) { return $this->goHome(); } $this->layout = 'blank'; return $this->render('signup'); } /** * Forgot password action. * * @return string|Response */ public function actionForgotpassword() { $this->layout = 'blank'; return $this->render('forgotpassword'); } /** * Forgot password Send Email action. * * @return string|Response */ public function actionForgotpasswordsendlink() { // email send code here $response_arr = [ "status" => 405, "message" => "Access Denied" ]; $checkemail = Yii::$app->db->createCommand("SELECT userId,firstname,email,password FROM users where email = '" . $_POST['email'] . "'")->queryOne(); if (!empty($checkemail) && isset($checkemail['email']) && $checkemail['email'] != '') { $userId = base64_encode($checkemail['userId']); $userName = base64_encode($checkemail['firstname']); try { $mail = new \PHPMailer(); // create a new object $mail->IsSMTP(); // enable SMTP $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only $mail->SMTPAuth = true; // authentication enabled $mail->Host = Yii::$app->params['smtpHost']; $mail->Username = Yii::$app->params['smtpUsername']; $mail->Password = Yii::$app->params['smtpPassword']; $mail->SMTPSecure = strtolower(Yii::$app->params['smtpEncryption']); // only lowercase enc will work $mail->Port = Yii::$app->params['smtpPort']; $mail->SetFrom(Yii::$app->params['fromEmail'], Yii::$app->params['fromName']); $mail->Subject = "Password reset link"; $mail->IsHTML(true); $message = '

Reset your InboxIgnitor account Password.

Hi '.$userName.'

Please click on the Reset Password button to reset password.

https://app.inboxigniter.com/site/resetpassword?key=' . $userId . '

If you did not request this email you can safely ignore it.

'; $mail->Body = $message; $mail->AddAddress($_POST['email']); $mailstatus = $mail->Send(); if ($mailstatus) { $response_arr['status'] = 200; $response_arr['message'] = "An Email has been sent with instructions for reseting your password."; echo json_encode($response_arr); exit; } else { $response_arr['status'] = 404; $response_arr['message'] = "Something went wrong!"; echo json_encode($response_arr); exit; } } catch (Exception $e) { if (!$e->getCode()) { } else { } } } else { $response_arr['status'] = 404; $response_arr['message'] = "Email not found!"; echo json_encode($response_arr); exit; } } /** * Forgot password action. * * @return string|Response */ public function actionResetpassword() { $this->layout = 'blank'; $email = $_GET['key']; $email = Yii::$app->db->createCommand("SELECT email FROM users WHERE userId ='" . base64_decode($email) . "'")->queryOne(); return $this->render('resetpassword', array('email' => $email)); } public function actionSaveresetpassword() { $userid = base64_decode($_POST['Keyid']); $password_val = $_POST['password_val']; $password = password_hash($password_val, PASSWORD_DEFAULT); $sql = "UPDATE `users` SET `password`='" . $password . "' where `userId`='" . $userid . "'"; Yii::$app->db->createCommand($sql)->execute(); return 1; } /** * Logout action. * * @return Response */ public function actionLogout() { Yii::$app->user->logout(); // return $this->goHome(); return $this->redirect('login'); } /** * Signup SMTP. * * @return string|Response */ public function actionSmtp101() { $smtplist_query = new Query; $smtplist = $smtplist_query->select(['emailAddress', 'smtp', 'port', 'encryption', 'smtpId', 'status', 'sends', 'receives', 'provider']) ->from('smtp') ->where(['userId' => Yii::$app->user->identity->userId]); // ->all(); $countQuery = $smtplist->count(); $pages = new Pagination(['totalCount' => $countQuery, 'pageSize' => 10]); $models = $smtplist->offset($pages->offset) ->limit($pages->limit) ->orderBy(['smtpId' => SORT_DESC]) ->all(); // $pages->setPageSize(3); $timinglist_query = new Query; $timinglist = $timinglist_query->select(['workingHourId', 'name']) ->from('workinghours') ->where(['userId' => Yii::$app->user->identity->userId]) ->all(); $userId = Yii::$app->user->identity->userId; // fetching providers using userID $filterdata1 = Yii::$app->db->createCommand("SELECT DISTINCT provider FROM `smtp` where userId = " . $userId)->queryAll(); // fetching domains using userID $filterdata2 = Yii::$app->db->createCommand("SELECT SUBSTRING_INDEX(emailAddress,'@',-1) as domainName FROM `smtp` where userId = " . $userId . " GROUP by domainName")->queryAll(); return $this->render('smtp101', array('smtplist' => $models, 'pages' => $pages, 'timinglist' => $timinglist, 'filterdata2' => $filterdata2, 'filterdata1' => $filterdata1, 'userId' => $userId)); } /** * Signup SMTP. * * @return string|Response */ public function actionSmtp2023() { $smtplist_query = new Query; $smtplist = $smtplist_query->select(['emailAddress', 'smtpId', 'senderName', 'status', 'sends', 'receives', 'perDayLimit', 'signature']) ->from('smtp') ->where(['userId' => Yii::$app->user->identity->userId]) ->all(); $timinglist_query = new Query; $timinglist = $timinglist_query->select(['workingHourId', 'name']) ->from('workinghours') ->where(['userId' => Yii::$app->user->identity->userId]) ->all(); // $this->layout = 'main'; return $this->render('smtp2023', array('smtplist' => $smtplist, 'timinglist' => $timinglist)); } public function actionDashboard() { //echo '
'; print_r($_SESSION); exit;          
		$smtplist_query = new Query;
		$smtplist = $smtplist_query->select(['emailAddress', 'smtpId', 'senderName', 'status', 'sends', 'receives', 'perDayLimit', 'signature'])
			->from('smtp')
			->where(['userId' => Yii::$app->user->identity->userId])
			->all();

		$timinglist_query = new Query;
		$timinglist = $timinglist_query->select(['workingHourId', 'name'])
			->from('workinghours')
			->where(['userId' => Yii::$app->user->identity->userId])
			->all();
        // dop
		return $this->render('dashboard', array('smtplist' => $smtplist, 'timinglist' => $timinglist));
	}

    public function providerData($smtp_id){
 
		$response_arr = [];
		$provider_inbox = Yii::$app->db->createCommand("SELECT c.senderSmtpId, c.receiverSmtpId, c.mailstatus, COUNT(c.receiverSmtpId) as count, s.provider FROM `completedtasks` c, `smtp` s WHERE c.senderSmtpId='".$smtp_id."' AND c.stepOrder='0' AND c.status='7' AND c.mailstatus='1' AND completedOn >= now() - INTERVAL 1 DAY AND c.receiverSmtpId = s.smtpId GROUP BY s.provider")->queryAll();

		$provider_spam = Yii::$app->db->createCommand("SELECT c.senderSmtpId, c.receiverSmtpId, c.mailstatus, COUNT(c.receiverSmtpId) as count, s.provider FROM `completedtasks` c, `smtp` s WHERE c.senderSmtpId='".$smtp_id."' AND c.stepOrder='0' AND c.status='7' AND c.mailstatus='2' AND completedOn >= now() - INTERVAL 1 DAY AND c.receiverSmtpId = s.smtpId GROUP BY s.provider")->queryAll();
		
		$mailstatus_count = [];
		
		if (is_array($provider_inbox)) {
			foreach ($provider_inbox as $inbox) {
				$provider = $inbox['provider'];
				$count = $inbox['count'];
				$mailstatus_count[$provider]['inbox'] = $count;
			}
		} else {
			// Handle the case of a single object
			$provider = $provider_inbox['provider'];
			$count = $provider_inbox['count'];
			$mailstatus_count[$provider]['inbox'] = $count;

		}
	  
		if (is_array($provider_spam)) {
			foreach ($provider_spam as $inbox) {
				$provider = $inbox['provider'];
				$count = $inbox['count'];
				$mailstatus_count[$provider]['spam'] = $count;
			}
		} else {
			// Handle the case of a single object
			$provider = $provider_spam['provider'];
			$count = $provider_spam['count'];
			$mailstatus_count[$provider]['spam'] = $count;
		}
        
		$total_inbox_count =0;
		$total_spam_count =0;
		foreach ($mailstatus_count as $provider => $count) {
			if (isset($count['inbox']) && $count['inbox'] != '0'){
				$total_inbox_count += $count['inbox']; 
			}
			if(isset($count['spam']) && $count['spam'] != '0'){
                $total_spam_count += $count['spam']; 
			}
		}
        
		// Calculate percentages for each provider
		$provider_percentages = [];    
		$inbox_percentage=0;
		$spam_percentage=0;
        
		foreach ($mailstatus_count as $provider => $counts) {
			$inbox_count = isset($counts['inbox']) ? $counts['inbox'] : 0;
			$spam_count = isset($counts['spam']) ? $counts['spam'] : 0;
		
			$total_count = $inbox_count + $spam_count;
			

		    if($total_count != 0)
			{
				if($inbox_count != 0){
                    $inbox_percentage = ($inbox_count / $total_count) * 100;
				}else{
					$inbox_percentage = 0;
				}

				if($spam_count != 0){
                    $spam_percentage = ($spam_count / $total_count) * 100;
				}else{
					$spam_percentage = 0;
				}
		     }else{
				$inbox_percentage = '0';
				$spam_percentage ='0';
			 }
			$provider_percentages[$provider] = [
				'inbox' => $inbox_percentage,
				'spam' => $spam_percentage,
			];	

			 
		}
		$provider_percentages['total_inbox_count'] = $total_inbox_count;
		$provider_percentages['total_spam_count'] = $total_spam_count;
		
		
		return $provider_percentages;
		
	}

	public function getDeliverabilityPercentage($smtp_id)
	{


		$smtplist_query = new Query;
		$smtplist = $smtplist_query->select(['emailAddress'])
			->from('smtp')
			->where(['smtpId' => $smtp_id])
			->one();


		$emailAddress = $smtplist['emailAddress'];
		$response_arr = [];
		$userGmailRow['user_email'] = $emailAddress;
		$spf = '';
		$dmarc = '';
		$dkim = '';
		$bimi = '';
		$mail_arr = explode('@', $userGmailRow['user_email']);


		$results = dns_get_record($mail_arr[1], DNS_NS);
		$result_txt = dns_get_record($mail_arr[1], DNS_TXT);
		$result_DMARC = dns_get_record("_dmarc." . $mail_arr[1], DNS_TXT);
		$result_Dkim = dns_get_record("google._domainkey." . $mail_arr[1], DNS_TXT);
		$result_Bimi = dns_get_record("_bimi." . $mail_arr[1], DNS_TXT); // BIMI record

		if (!empty($result_txt)) {
			foreach ($result_txt as $txt) {
				if (strpos($txt['txt'], "v=spf1") !== false) {
					$spf = $txt['txt'];
				}
			}
		}
		if (!empty($result_Dkim)) {
			foreach ($result_Dkim as $Dkim) {
				if (strpos($Dkim['txt'], "v=DKIM1") !== false) {
					$dkim = $Dkim['txt'];
				}
			}
		}
		if (!empty($result_DMARC)) {
			foreach ($result_DMARC as $txt) {
				if (strpos($txt['txt'], "v=DMARC1") !== false) {
					$dmarc = $txt['txt'];
				}
			}
		}
		if (!empty($result_Bimi)) {
			foreach ($result_Bimi as $txt) {
				if (strpos($txt['txt'], "v=BIMI1") !== false) {
					$bimi = $txt['txt'];
				}
			}
		}



		$spfScore = ($spf !== '') ? 3 : 0;

		$dkimScore = ($dkim !== '') ? 3 : 0;

		$dmarcScore = ($dmarc !== '') ? 3 : 0;

		$bimiScore = ($bimi !== '') ? 1 : 0;

		$deliverabilityScore = $spfScore + $dkimScore + $dmarcScore + $bimiScore;


		$deliverabilityScoreScaled = ($deliverabilityScore / 10) * 100;

		$response_arr['spf'] = $spfScore;
		$response_arr['dkim'] = $dkimScore;
		$response_arr['dmarc'] = $dmarcScore;
		$response_arr['bimi'] = $bimiScore;
		$response_arr['deliverabilityScore'] = $deliverabilityScore;
		$response_arr['deliverabilirty'] = $deliverabilityScoreScaled;

		return $response_arr;
	}


	public function actionSmtp()
	{
		$totalInbox = 0;
		$totalspam = 0;
		$smtplist_query = new Query;
		$smtplist = $smtplist_query->select(['emailAddress', 'smtp', 'port', 'encryption', 'smtpId', 'status', 'sends', 'receives', 'provider', 'perDayLimit', 'senderName', 'isCsvProcessed','templateId'])
			->from('smtp')
			->where(['userId' => Yii::$app->user->identity->userId, 'deletedAt' => NULL]);

		$emailFilter = Yii::$app->request->get('emailFilter');
		if (!empty($emailFilter)) {
			$smtplist->andFilterWhere(['like', 'emailAddress', $emailFilter]);
		}
		$provider = Yii::$app->request->get('provider');

		if (!empty($provider)) {
			$smtplist->andFilterWhere(['like', 'provider', $provider]);
		}
		// ->all(); 
		$countQuery = $smtplist->count();
		$pages = new Pagination(['totalCount' => $countQuery, 'pageSize' => 10]);
		$models = $smtplist->offset($pages->offset)
			->limit($pages->limit)
			->orderBy(['smtpId' => SORT_DESC])
			->all();

		// total sends,receives and spams unrecieved       
		$totalsends = Yii::$app->db->createCommand("SELECT COUNT(taskId) AS totalSends FROM completedtasks WHERE completedOn >= DATE_SUB(NOW(), INTERVAL 7 DAY)  AND userId = '" . Yii::$app->user->identity->userId . "' AND `mailStatus` IN (0, 1, 2) AND (status='7') AND stepOrder='0'")->queryScalar();  

		// // mailstatus = 1 Inbox abd status ='7' (finished task)
		$totalDelivered = Yii::$app->db->createCommand("SELECT COUNT(taskId) AS totalDelivered FROM completedtasks WHERE completedOn >= DATE_SUB(NOW(), INTERVAL 7 DAY) AND status='7' AND stepOrder='0' AND mailstatus='1' AND userId = '" . Yii::$app->user->identity->userId . "'")->queryScalar();

		// // mailstatus = 2 Spam
		$totalSpam = Yii::$app->db->createCommand("SELECT COUNT(taskId) AS totalSpam FROM completedtasks WHERE completedOn >= DATE_SUB(NOW(), INTERVAL 7 DAY) AND status='7' AND stepOrder='0' AND mailstatus='2' AND userId = '" . Yii::$app->user->identity->userId . "'")->queryScalar();

		// // mailstatus = 0 Undelivered      
		$totalUndelivered = Yii::$app->db->createCommand("SELECT COUNT(taskId) AS totalUndelivered FROM completedtasks WHERE completedOn >= DATE_SUB(NOW(), INTERVAL 7 DAY) AND status='4' AND stepOrder='0' AND mailstatus='3' AND userId = '" . Yii::$app->user->identity->userId . "'")->queryScalar();

		$tottask1 = Yii::$app->db->createCommand("SELECT COUNT(taskId) as totalsent FROM completedtasks WHERE userId = '" . Yii::$app->user->identity->userId . "' AND completedOn >= ( CURDATE() - INTERVAL 14 DAY ) AND stepOrder='0' AND `mailStatus` IN (0, 1, 2) AND (status='7')")->queryScalar();

		$tottask2 = Yii::$app->db->createCommand("SELECT COUNT(taskId) as totalsent FROM completedtasks WHERE userId = '" . Yii::$app->user->identity->userId . "' AND completedOn >= ( CURDATE() - INTERVAL 7 DAY ) AND stepOrder='0' AND `mailStatus` IN (0, 1, 2) AND (status='7')")->queryScalar();

		$percentageSent1 = $tottask1 - $tottask2;
		// $percentageSent =   $tottask2 - $percentageSent1;
		if ($percentageSent1 != 0) {
			$percentageSent = (100 * $tottask2) / (2 * $percentageSent1);
		} else {
			$percentageSent = 0;
		}
		if ($percentageSent >= 0) {
			$ptype = 1;
		} else {
			$ptype = 0;
		}

		$todelivered1 = Yii::$app->db->createCommand("SELECT COUNT(taskId) as totaldelivered FROM completedtasks WHERE userId = '" . Yii::$app->user->identity->userId . "' AND status='7' AND mailstatus='1' AND stepOrder='0' AND completedOn >= ( CURDATE() - INTERVAL 14 DAY )")->queryScalar();

		$todelivered2 = Yii::$app->db->createCommand("SELECT COUNT(taskId) as totaldelivered FROM completedtasks WHERE userId = '" . Yii::$app->user->identity->userId . "' AND status='7' AND mailstatus='1' AND stepOrder='0' AND completedOn >= ( CURDATE() - INTERVAL 7 DAY )")->queryScalar();

		$percentageDelivered1 = $todelivered1 - $todelivered2;
		$percentageDelivered = 0;
		$ptype2 = 0;
		if ($percentageDelivered1 != 0) {
			$percentageDelivered = (100 * $todelivered2) / (2 * $percentageDelivered1);
		}
		if ($percentageDelivered >= 0) {
			$ptype2 = 1;
		}
		$toundelivered1 = Yii::$app->db->createCommand("SELECT COUNT(taskId) as totalundelivered FROM completedtasks WHERE userId = '" . Yii::$app->user->identity->userId . "' AND status='4' AND mailstatus='3' AND stepOrder='0' AND completedOn >= ( CURDATE() - INTERVAL 14 DAY )")->queryScalar();

		$toundelivered2 = Yii::$app->db->createCommand("SELECT COUNT(taskId) as totalundelivered FROM completedtasks  WHERE userId = '" . Yii::$app->user->identity->userId . "' AND status='4' AND mailstatus='3' AND stepOrder='0' AND completedOn >= ( CURDATE() - INTERVAL 7 DAY )")->queryScalar();

		$percentageUndelivered1 = $toundelivered1 - $toundelivered2;
		$percentageUndelivered = 0;
		if ($percentageUndelivered1 != 0) {
			$percentageUndelivered = (100 * $toundelivered2) / (2 * $percentageUndelivered1);
		}

		$ptype3 = 0;
		if ($percentageUndelivered >= 0) {
			$ptype3 = 1;
		}


		$totalspam1 = Yii::$app->db->createCommand("SELECT COUNT(taskId) as totalspam FROM completedtasks WHERE userId = '" . Yii::$app->user->identity->userId . "' AND status='7' AND mailstatus='2' AND stepOrder='0' AND completedOn >= ( CURDATE() - INTERVAL 14 DAY )")->queryScalar();


		$totalspam2 = Yii::$app->db->createCommand("SELECT COUNT(taskId) as totalspam FROM completedtasks WHERE userId = '" . Yii::$app->user->identity->userId . "' AND status='7' AND mailstatus='2' AND stepOrder='0' AND completedOn >= ( CURDATE() - INTERVAL 7 DAY )")->queryScalar();

		$percentageSpam1 = $totalspam1 - $totalspam2;
		// $percentageSpam = $totalspam2 - $percentageSpam1;
		$percentageSpam = 122;
		$percentageSpam = 0;
		$ptype4 = 0;
		if ($percentageSpam1 != 0) {
			$percentageSpam = (100 * $totalspam2) / (2 * $percentageSpam1);
		}
		if ($percentageSpam >= 0) {
			$ptype4 = 1;
		}
		// deliverability

		// Assuming you have the specific user's userId
		$userId = Yii::$app->user->identity->userId; // Replace with the actual userId

		// Fetch unique senderSmtpIds for this user
		$senderSmtpIdsQuery = "SELECT DISTINCT senderSmtpId FROM completedtasks WHERE userId = :userId";
		$senderSmtpIds = Yii::$app->db->createCommand($senderSmtpIdsQuery, [':userId' => $userId])->queryColumn();

		// Initialize variables to store total delivered and total sends

		// $currentDate = date('Y-m-d');
		// 	$endOfWeek = date('Y-m-d');
		// 	$startOfWeek = date('Y-m-d', strtotime('- days', strtotime($endOfWeek)));

		// 	$data = Yii::$app->db->createCommand("
		// 			SELECT DAYNAME(completedOn) as maintime,
		// 				SUM(IF(mailstatus = 1, 1, 0)) as inbox_value,
		// 				SUM(IF(mailstatus != 1, 1, 0)) as spam_value        
		// 			FROM `completedtasks`
		// 			WHERE 
		// 			userId = '" . Yii::$app->user->identity->userId . "'
		// 				AND senderSmtpId = '" . $smtp_id . "'    
		// 				AND status = '7'
		// 				AND DATE(completedOn) BETWEEN '" . $startOfWeek . "' AND '" . $endOfWeek . "'
		// 				AND mailstatus IN (1, 2) 
		// 			GROUP BY 
		// 				DAYNAME(completedOn);                     
		// 		")->queryAll();
		// }

		$endOfWeek = date('Y-m-d');
		$startOfWeek = date('Y-m-d', strtotime('-7 days', strtotime($endOfWeek)));
		$i = 0;
		for ($i = 0; $i < count($models); $i++) {
			$totalSends = Yii::$app->db->createCommand("SELECT COUNT(taskId) AS totalSends FROM completedtasks WHERE senderSmtpId = '" . $models[$i]['smtpId'] . "' AND userId = '" . Yii::$app->user->identity->userId . "' AND stepOrder = '0' AND mailStatus = '1' AND DATE(completedOn) BETWEEN '" . $startOfWeek . "' AND '" . $endOfWeek . "'")->queryScalar();

			$spam = Yii::$app->db->createCommand("SELECT COUNT(taskId) AS spam FROM completedtasks WHERE senderSmtpId = '" . $models[$i]['smtpId'] . "' AND userId = '" . Yii::$app->user->identity->userId . "' AND stepOrder = '0' AND mailStatus = '2' AND DATE(completedOn) BETWEEN '" . $startOfWeek . "' AND '" . $endOfWeek . "'")->queryScalar();
			$overallDeliverabilityPercentage = 0;
			$total = $totalSends + $spam;
			$totalInbox  = $totalSends;
			$totalspam   = $spam;
			if ($totalSends != 0) {
				$overallDeliverabilityPercentage = ($totalSends / $total) * 100;
				$overallDeliverabilityPercentage = round($overallDeliverabilityPercentage);
				$models[$i]['overallDeliverabilityPercentage'] = $overallDeliverabilityPercentage;
				$models[$i]['totalSends'] = $totalInbox;
				$models[$i]['spam'] = $totalspam;
			}
		}

		// $overallDeliverabilityPercentage = $models['overallDeliverabilityPercentage'];
		$timinglist_query = new Query;
		$timinglist = $timinglist_query->select(['workingHourId', 'name'])
			->from('workinghours')
			->where(['userId' => Yii::$app->user->identity->userId])
			->all();

		$userId = Yii::$app->user->identity->userId;
		// fetching providers using userID  
		$filterdata1 = Yii::$app->db->createCommand("SELECT DISTINCT provider FROM `smtp` where userId = " . $userId)->queryAll();
		// fetching domains using userID  
		$filterdata2 = Yii::$app->db->createCommand("SELECT SUBSTRING_INDEX(emailAddress,'@',-1) as domainName FROM `smtp` where userId = " . $userId . " GROUP by domainName")->queryAll();

		return $this->render('smtp', array('smtplist' => $models, 'pages' => $pages, 'timinglist' => $timinglist, 'filterdata2' => $filterdata2, 'filterdata1' => $filterdata1, 'totalsends' => $totalsends, 'totalDelivered' => $totalDelivered, 'totalSpam' => $totalSpam, 'totalUndelivered' => $totalUndelivered, 'percentageSent' => abs($percentageSent), 'percentageDelivered' => abs($percentageDelivered), 'percentageUndelivered' => abs($percentageUndelivered), 'percentageSpam' => abs($percentageSpam), 'ptype4' => $ptype4, 'ptype3' => $ptype3, 'ptype2' => $ptype2, 'ptype' => $ptype, 'totalInbox' => $totalInbox, 'totalspam' => $totalspam));
	}
	/**
	 * Timings.
	 *
	 * @return string|Response  
	 */
	public function actionTimings()
	{
		$timinglist_query = new Query;
		$timinglist = $timinglist_query->select(['workingHourId', 'name', 'day', 'starttime', 'endtime'])
			->from('workinghours')
			->where(['userId' => Yii::$app->user->identity->userId])
			->all();

		$this->layout = 'main';
		return $this->render('timings', array('timinglist' => $timinglist));
	}

	public function actionDeletetimings()
	{
		$timing_id = $_POST['timing_id'];
		$deteleTimnigs = Yii::$app->db->createCommand("Delete from workinghours where workingHourId = " . $timing_id)->execute();
	}
	public function actionDeletesmtp()
	{

		$smtp_id = $_POST['smtp_id'];
		$deteleTimnigs = Yii::$app->db->createCommand("Delete from smtp where smtpId = " . $smtp_id)->execute();
	}

	public function actionChangesmtpstatus()
	{
		$smtp_id = $_POST['smtp_id'];
		$status = $_POST['status'];
		$updtesmtp = Yii::$app->db->createCommand("update smtp set status = " . $status . "  where smtpId = " . $smtp_id)->execute();
	}
	// create SMTP
	public function actionCreatesmtp()
	{

		/* design return array structure */
		$response_arr = [
			'http_status' => 405,
			'data' => [],
			'message' => 'Method Not Allowed'
		];

		$smtparray = json_decode($_POST['smtpdetails']);
		// if (isset($_POST["provider"])) {
		// 	$provider = $_POST["provider"];        
		// }   
		
		$dataArry = array();

		foreach ($smtparray as $key => $val) {

			$dataArry[$val->name] = $val->value;
		}
		$userID = Yii::$app->user->identity->userId;
		$nextRunTime = time();
		//$currentTimezoneval = $dataArry['currentTimezoneval'];
		$currentTimezoneval = 'Asia/Kolkata';
		//$workingHours = $dataArry['workingHours'];
		$workingHours = 1;
		// devang change
		// $dataArry['email_provider'] = $provider;    
		// devang change end
		// $email_provider = $dataArry['email_provider'];
		$email_address = $dataArry['email_address'];
		$sender_name = $dataArry['sender_name'];
		$email_password = $dataArry['email_password'];
		$outgoing_mail_server = $dataArry['outgoing_mail_server'];
		$smtp_port = $dataArry['smtp_port'];
		$smtp_encryption = $dataArry['smtp_encryption'];
		$imap_email_address = $dataArry['imap_email_address'];
		$imap_password = $dataArry['imap_password'];
		$incoming_mail_server = $dataArry['incoming_mail_server'];
		$imap_port = $dataArry['imap_port'];
		$imap_encryption = $dataArry['imap_encryption'];

		$lastDotPosition = strrpos($outgoing_mail_server, '.');
		$secondLastDotPosition = strrpos($outgoing_mail_server, '.', $lastDotPosition - strlen($outgoing_mail_server) - 1);
		if ($lastDotPosition !== false && $secondLastDotPosition !== false) {
			$email_provider = substr($outgoing_mail_server, $secondLastDotPosition + 1, $lastDotPosition - $secondLastDotPosition - 1);
		} else {
			$email_provider = '';
		}
		// $email_provider = $dataArry['email_provider'];  
		// echo $email_provider;exit;                    


		//echo '
'; print_r($dataArry); exit;

		/* check for request method */
		if ($_SERVER['REQUEST_METHOD'] === 'POST') {
			$data = $dataArry;
			if (!empty($data)) {
				// devang code start
				/* checking that email address already exist or not. */
				$existing_email_id = new Query;
				$existing_email_id = $existing_email_id->select(['emailAddress'])
					->from('smtp')
					->where(['emailAddress' => $email_address, 'userId' => $userID])
					->all();

				if ($existing_email_id) {
					$response_arr['message'] = 'Email address already exists in your account.';   
					$response_arr['http_status'] = 400;
				} else {
					/* initiate process by calling "send_email_to_user" function. */
					// $process = $this->send_email_to_user($data);
					// if ($process['status']) {
					/* check if value is true / success set success response. */

					// $response_arr['data'] = $process['data'];

					// $response_arr['status'] = $process['status'];

					Yii::$app->db->createCommand("INSERT INTO `smtp`(`userId`,`workingHourId`,`timezone`,`nextRunTime`,`provider`,`emailAddress`,`emailPassword`,`username`,`senderName`,`smtp`,`port`,`encryption`,`imapEmailAddress`,`imapEmailPassword`,`imapSmtp`,`imapPort`,`imapEncryption`) VALUES ('" . $userID . "','" . $workingHours . "','" . $currentTimezoneval . "','" . $nextRunTime . "','" . $email_provider . "','" . $email_address . "','" . $email_password . "','" . $email_address . "','" . $sender_name . "','" . $outgoing_mail_server . "','" . $smtp_port . "','" . $smtp_encryption . "','" . $imap_email_address . "','" . $imap_password . "','" . $incoming_mail_server . "','" . $imap_port . "','" . $imap_encryption . "')")->execute();

					$lastcreatedsmtpId = Yii::$app->db->getLastInsertID();

					$uniqueId = $this->generateRandomString(20);
					$uniqueId = $uniqueId . $lastcreatedsmtpId;
					$updtesmtp = Yii::$app->db->createCommand("update smtp set smtpCode = '" . $uniqueId . "'  where smtpId = " . $lastcreatedsmtpId)->execute();

					$response_arr['message'] = "SMTP & IMAP Details saved succecssfully.";
					$response_arr['http_status'] = 200;

					// } else {/* if value is false / failure set response. */	
					// 	$response_arr['message'] = $process['message']; 
					// 	$response_arr['http_status'] = 404;
					// }
				}
				// devang code end
			} else {
				$response_arr['message'] = 'Empty request';
				$response_arr['http_status'] = 406;
			}
		}
		/* process response deliver by below line. */
		echo json_encode($response_arr);
		exit();
	}

	public function actionAddbulk()
	{
		$response_arr = [
			'http_status' => 405,
			'data' => [],
			'message' => 'Method Not Allowed'
		];

		$selectedLanguage = $_POST['selected_language'];
		$selectedTopic = $_POST['warm_up_topic']; 
		$selectedbulk = $_POST['selectedbulk'];
		       
		foreach ($selectedbulk as $bulkId) {                
			$result = Yii::$app->db->createCommand("update smtp set selected_language = '" . $selectedLanguage . "', warm_up_topic = '" . $selectedTopic . "' where smtpId = " . $bulkId)->execute();           
		}       
		     
		echo json_encode($response_arr);
		exit();  
	}

	// devang code start
	public function actionStorecsv()
	{
		$response_arr = [
			'http_status' => 405,
			'data' => [],
			'message' => 'Method Not Allowed'
		];


		// $formData = json_decode($_POST['formData']);


		if ($_FILES["csv_file1"]["error"] > 0) {
			// var_dump($_FILES['csv_file1']);
			$response_arr['http_status'] = 400;
			$response_arr['message'] = "Error uploading the file.";
			echo json_encode($response_arr);
			exit;
		}

		// neccessary column data

		$filename = $_FILES["csv_file1"]["name"];
		$fileExt = pathinfo($filename, PATHINFO_EXTENSION);

		$userID = Yii::$app->user->identity->userId;
		$workingHours = 1;
		$nextRunTime = time();
		$currentTimezoneval = 'Asia/Kolkata';
		$dataArray = array();
		// for storing csv file columns
		$csvArray = array();

		// neccessary column data end

		// check the file format
		if (strcasecmp($fileExt, "csv") !== 0) {
			$response_arr['http_status'] = 400;
			$response_arr['message'] = "Invalid file format. Please upload a CSV file.";
			echo json_encode($response_arr);
			exit;
		}

		$expectedHeader = array("provider", "emailaddress", "app_password", "sender_name", "outgoing_mail_server(SMTP)", "smtp_port", "smtp_encryption", "emailaddress", "app_password", "incoming_mail_server(IMAP)", "imap_port", "imap_encryption");

		// Read the uploaded CSV file and check the header.
		$file = fopen($_FILES["csv_file1"]["tmp_name"], "r");
		$uploadedHeader = fgetcsv($file);
		fclose($file);

		if ($uploadedHeader !== $expectedHeader) {
			$response_arr['http_status'] = 400;
			$response_arr['message'] = "Header is not proper, Please set the header same as the sample CSV file.";
			echo json_encode($response_arr);
			exit;
		}

		if ($_SERVER['REQUEST_METHOD'] === 'POST') {
			Yii::$app->db->createCommand("INSERT INTO `csv_file`(`userId`,`csv_file_name`) VALUES ('" . $userID . "','" . $filename . "')")->execute();
			$lastcreatedfileId = Yii::$app->db->getLastInsertID();

			$file = fopen($_FILES["csv_file1"]["tmp_name"], "r");
			//remove csv header
			fgetcsv($file);
			$flag = 0;

			while (($data = fgetcsv($file)) !== false) {
				if (count($data) > 2) {
					if (!empty($data[0]) && !empty($data[1]) && !empty($data[2]) && !empty($data[3]) && !empty($data[4]) && !empty($data[5]) && !empty($data[6]) && !empty($data[7]) && !empty($data[8]) && !empty($data[9]) && !empty($data[10]) && !empty($data[11])) {
						$existing_email_id = Yii::$app->db->createCommand("Select emailAddress from smtp where userId = '" . Yii::$app->user->identity->userId . "' AND emailAddress = '" . $data[1] . "'")->queryOne();
						if ($existing_email_id) {
							array_push($dataArray, $existing_email_id['emailAddress']);
							$flag = 1;
						} else {
							Yii::$app->db->createCommand("INSERT INTO `smtp`(`userId`,`workingHourId`,`timezone`,`nextRunTime`,`provider`,`emailAddress`,`emailPassword`,`username`,`senderName`,`smtp`,`port`,`encryption`,`imapEmailAddress`,`imapEmailPassword`,`imapSmtp`,`imapPort`,`imapEncryption`,`csv_file_id`) VALUES ('" . $userID . "','" . $workingHours . "','" . $currentTimezoneval . "','" . $nextRunTime . "','" . $data[0] . "','" . $data[1] . "','" . $data[2] . "','" . $data[1] . "','" . $data[3] . "','" . $data[4] . "','" . $data[5] . "','" . $data[6] . "','" . $data[7] . "','" . $data[8] . "','" . $data[9] . "','" . $data[10] . "','" . $data[11] . "','" . $lastcreatedfileId . "')")->execute();
							$lastcreatedsmtpId = Yii::$app->db->getLastInsertID();
							$uniqueId = $this->generateRandomString(20);
							$uniqueId = $uniqueId . $lastcreatedsmtpId;
							$updtesmtp = Yii::$app->db->createCommand("update smtp set smtpCode = '" . $uniqueId . "',isCsvProcessed = '0',status = '0' where smtpId = " . $lastcreatedsmtpId)->execute();
							$flag = 1;
						}
					}
				}
			}
			fclose($file);
			if ($flag == 1) {
				if (empty($dataArray)) {
					$response_arr['message'] = 'Filename and data stored successfully in database';
					$response_arr['http_status'] = 200;
				} else {
					$response_arr['message'] = 'Filename and data stored successfully in database,but there are some duplicate emails exist in database';
					$response_arr['http_status'] = 200;
				}
			}
		}

		return json_encode($response_arr);
	}

	public function generateblacklistCsvContent($data)
	{
		$outputBuffer = fopen('php://memory', 'w'); // Open an in-memory buffer in write mode

		// Write each email as a single cell in a row
		foreach ($data as $email) {
			$rowdata = array($email);
			fputcsv($outputBuffer, $rowdata);
		}

		rewind($outputBuffer); // Move the file pointer to the beginning of the buffer
		$csvContent = stream_get_contents($outputBuffer); // Get the buffer contents

		fclose($outputBuffer); // Close the buffer

		return $csvContent;
	}
	public function actionStoreblacklistcsv()
	{
		$response_arr = [
			'http_status' => 405,
			'data' => [],
			'message' => 'Method Not Allowed'
		];


		// $formData = json_decode($_POST['formData']);

		if ($_FILES["csv_file2"]["error"] > 0) {
			if ($_FILES["csv_file2"]["error"] > 0) {
				var_dump($_FILES['csv_file2']);
				$response_arr['http_status'] = 400;
				$response_arr['message'] = "Error uploading the file.";
				echo json_encode($response_arr);
				exit;
			}
			exit;
		}
		// neccessary column data

		$filename = $_FILES["csv_file2"]["name"];
		$fileExt = pathinfo($filename, PATHINFO_EXTENSION);
		// check the file format
		if (strcasecmp($fileExt, "csv") !== 0) {
			$response_arr['http_status'] = 400;
			$response_arr['message'] = "Invalid file format. Please upload a CSV file.";
			echo json_encode($response_arr);
			exit;
		}

		$userID = Yii::$app->user->identity->userId;
		$dataArray = array();
		// for storing csv file columns
		$csvArray = array();
		// validate emails
		$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";
		// neccessary column data end
		$expectedHeader_email = array("email");
		$expectedHeader_domain = array("domain");

		$blacklist_type = $_POST['blacklist_type'];
		// Read the uploaded CSV file and check the header.
		$file = fopen($_FILES["csv_file2"]["tmp_name"], "r");
		$uploadedHeader = fgetcsv($file);
		fclose($file);
		// for email blacklist    
		if ($uploadedHeader === $expectedHeader_email) {
			if ($_SERVER['REQUEST_METHOD'] === 'POST') {
				$isBlacklist = '1';
				Yii::$app->db->createCommand("INSERT INTO `csv_file`(`userId`,`csv_file_name`,`isBlacklist`) VALUES ('" . $userID . "','" . $filename . "','" . $isBlacklist . "')")->execute();

				$lastcreatedfileId = Yii::$app->db->getLastInsertID();
				$response_arr['message'] = 'filename stored successfully in database';
				$response_arr['http_status'] = 200;

				$file = fopen($_FILES["csv_file2"]["tmp_name"], "r");
				//remove csv header
				fgetcsv($file);
				$sum = 0;
				while (($data = fgetcsv($file)) !== false) {

					if (count($data) == 1) {
						$blacklistEmail = $data[0];

						if (preg_match($pattern, $blacklistEmail)) {  //validate emails
							//   check that email is present in blacklist table
							$existing_blacklist = Yii::$app->db->createCommand("Select blacklisted from blacklist where userId = '" . Yii::$app->user->identity->userId . "' AND type='" . $blacklist_type . "' AND blacklisted = '" . $data[0] . "'")->queryOne();

							if ($existing_blacklist) {

								array_push($dataArray, $data[0]);
							} else {
								//  check that email is present in smtp table


								// if($existing_email){
								Yii::$app->db->createCommand("INSERT INTO `blacklist`(`userId`,`type`,`blacklisted`,`csv_file_id`) VALUES ('" . $userID . "','$blacklist_type','" . $data[0] . "','" . $lastcreatedfileId . "')")->execute();
								//    Yii::$app->db->createCommand("update smtp set isBlacklisted = '1'  where smtpId = '".$existing_email['smtpId']."' AND  emailAddress='".$existing_email['emailAddress']."'")->execute();
								$sum = 1;
								// }else{
								// 	array_push($dataArray,$data[0]);
								// }
							}
						} else {
							array_push($dataArray, $data[0]);
						}
					}
				}
				fclose($file);

				if ($sum == 1) {
					$response_arr['message'] = 'Filename and data stored successfully in database';
					$response_arr['http_status'] = 200;
				} else {
					$response_arr['message'] = 'Emails are already exists in database';
					$response_arr['http_status'] = 400;
				}
			} else {
				echo json_encode($response_arr);
				exit();
			}
			// for domain blacklist 
		} elseif ($uploadedHeader === $expectedHeader_domain) {
			if ($_SERVER['REQUEST_METHOD'] === 'POST') {
				$isBlacklist = '1';
				Yii::$app->db->createCommand("INSERT INTO `csv_file`(`userId`,`csv_file_name`,`isBlacklist`) VALUES ('" . $userID . "','" . $filename . "','" . $isBlacklist . "')")->execute();

				$lastcreatedfileId = Yii::$app->db->getLastInsertID();
				$response_arr['message'] = 'filename stored successfully in database';
				$response_arr['http_status'] = 200;

				$file = fopen($_FILES["csv_file2"]["tmp_name"], "r");
				//remove csv header
				fgetcsv($file);
				$sum = 0;
				while (($data = fgetcsv($file)) !== false) {

					if (count($data) == 1) {
						$blacklistDomain = $data[0];

						$validate = $this->isValidDomain($blacklistDomain);
						if ($validate) {
							$existing_blacklist = Yii::$app->db->createCommand("Select blacklisted from blacklist where userId = '" . Yii::$app->user->identity->userId . "' AND type='" . $blacklist_type . "' AND blacklisted = '" . $blacklistDomain . "'")->queryOne();


							if ($existing_blacklist) {

								array_push($dataArray, $data[0]);
							} else {
								// $existing_domain = Yii::$app->db->createCommand("SELECT emailAddress,smtpId FROM `smtp` where SUBSTRING_INDEX(emailAddress,'@',-1) = '".$blacklistDomain."' AND userId = '".Yii::$app->user->identity->userId."'")->queryAll();

								// if($existing_domain){
								Yii::$app->db->createCommand("INSERT INTO `blacklist`(`userId`,`type`,`blacklisted`,`csv_file_id`) VALUES ('" . $userID . "','" . $blacklist_type . "','" . $blacklistDomain . "','" . $lastcreatedfileId . "')")->execute();
								// $count = count($existing_domain);
								// if($count > 0){
								// 	$i = '';
								// for($i=0;$idb->createCommand("update smtp set isBlacklisted = '1' where smtpId = '".$existing_domain[$i]['smtpId']."' AND  SUBSTRING_INDEX(emailAddress,'@',-1)='".$blacklistDomain."'")->execute();  
								// 	}
								// 	$sum = 1;
								// }
								$sum = 1;
								//    }else{
								// 	array_push($dataArray,$data[0]);
								//    }
							}
						} else {
							array_push($dataArray, $data[0]);
						}
					}
				}
				fclose($file);

				if ($sum == 1) {
					$response_arr['message'] = 'Filename and data stored successfully in database';
					$response_arr['http_status'] = 200;
				} else {
					$response_arr['message'] = 'All domains are already exists in database';
					$response_arr['http_status'] = 400;
				}
			} else {
				echo json_encode($response_arr);
				exit();
			}
		} else {
			$response_arr['http_status'] = 400;
			$response_arr['message'] = "Header is not proper, Please set the header same as the sample CSV file.";
			echo json_encode($response_arr);
			exit;
		}


		$csvContent = $this->generateblacklistCsvContent($dataArray);

		Yii::$app->response->headers->set('Content-Type', 'text/csv');
		Yii::$app->response->headers->set('Content-Disposition', 'attachment; filename="data.csv"');

		$response_arr['data'] = $csvContent;
		return json_encode($response_arr);
	}
	//    devang code end

	// devang code start
	public function actionChecksmtp()
	{
		/* design return array structure */
		$response_arr = [
			'http_status' => 405,
			'data' => [],
			'message' => 'Method Not Allowed'
		];


		$smtparray = json_decode($_POST['smtpdetails']);

		$dataArry = array();

		foreach ($smtparray as $key => $val) {

			$dataArry[$val->name] = $val->value;
		}

		if ($_SERVER['REQUEST_METHOD'] === 'POST') {
			$data = $dataArry;
			$data['check_imap_conn'] = false;
			if (!empty($data)) {
				$process = $this->send_email_to_user($data);

				if ($process['status']) {/* check if value is true / success set success response. */
					$response_arr['message'] = $process['message'];
					$response_arr['data'] = $process['data'];
					$response_arr['http_status'] = 200;
					$response_arr['status'] = $process['status'];
				} else {
					$response_arr['message'] = $process['message'];
					$response_arr['data'] = $process['data'];
					$response_arr['http_status'] = 400;
				}
			} else {
				$response_arr['message'] = "Bad Request";
				$response_arr['http_status'] = 404;
			}
		}
		echo json_encode($response_arr);
		exit();
	}


	public function actionCheckimap()
	{
		/* design return array structure */
		$response_arr = [
			'http_status' => 405,
			'data' => [],
			'message' => 'Method Not Allowed'
		];


		$smtparray = json_decode($_POST['smtpdetails']);

		$dataArry = array();

		foreach ($smtparray as $key => $val) {

			$dataArry[$val->name] = $val->value;
		}

		if ($_SERVER['REQUEST_METHOD'] === 'POST') {
			$data = $dataArry;
			if (!empty($data)) {
				$process = $this->checkIMAP1($data);
				if ($process['status'] == '1') {/* check if value is true / success set success response. */
					$response_arr['message'] = $process['msg'];
					$response_arr['data'] = $process['data'];
					$response_arr['http_status'] = 200;
					$response_arr['status'] = $process['status'];
				} else {
					$response_arr['message'] = $process['msg'];
					$response_arr['http_status'] = 404;
				}
			} else {
				$response_arr['message'] = "Empty Request";
				$response_arr['http_status'] = 404;
			}
		}
		echo json_encode($response_arr);
		exit();
	}

	public function checkIMAP1($process_data)
	{
		$return_data = ['status' => 0, 'msg' => 'Something went wrong, try later.', 'data' => []];
		$string_imap = $process_data['incoming_mail_server'] . ':' . $process_data['imap_port'];
		$date = date('j M Y', time());
		error_reporting(E_ERROR);
		try {
			// $connection = imap_open('{' . $string_imap . '/imap/ssl}INBOX', $process_data['imap_email_address'], $process_data['imap_email_password']) or die();
			$connection = imap_open('{' . $string_imap . '/imap/ssl}INBOX', $process_data['imap_email_address'], $process_data['imap_password']);
			if ($connection) {
				$emailData = imap_search($connection, 'FROM "' . $process_data['imap_email_address'] . '" SUBJECT "[IGNORE] SMTP connection validation by Inboxigniter" SINCE "' . $date . '"', SE_UID);
				imap_close($connection);

				// return ['status' => 1,'message'=>'IMAP Connection authenticated Successfully'];
				$return_data['status'] = 1;
				$return_data['msg'] = 'IMAP details authenticated successfully.';
			} else {
				$return_data['msg'] = 'IMAP could not authenticate.';
			}
		} catch (Exception $e) {
			$return_data['data'] = $e;
			$return_data['msg'] = $e->getMessage();
		}
		return $return_data;
	}

	// devang code end
	public function generateRandomString($length)
	{
		$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		$randomString = '';

		$characterllength = strlen($characters);
		for ($i = 0; $i < $length; $i++) {
			$randomString .= $characters[rand(0, $characterllength - 1)];
		}

		return $randomString;
	}


	public function send_email_to_user($request_data)
	{
		$process_result = ['status' => 0, 'message' => "Unable to process", 'data' => []];
		$process_result = $this->sentViaSMTP($request_data);
		return $process_result;
	}


	public function sentViaSMTP($mail_request)
	{

		try {
			ob_start();

			$mail = new \PHPMailer(); // create a new object
			$mail->IsSMTP(); // enable SMTP
			$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
			$mail->SMTPAuth = true; // authentication enabled
			$mail->Host = $mail_request['outgoing_mail_server'];
			$mail->Username = $mail_request['email_address'];
			$mail->Password = $mail_request['email_password'];
			$mail->SMTPSecure = strtolower($mail_request['smtp_encryption']); // only lowercase enc will work 
			$mail->Port = $mail_request['smtp_port']; // 465

			$mail->SetFrom($mail_request['email_address'], $mail_request['sender_name']);
			$mail->Subject = "[IGNORE] SMTP connection validation by Inboxigniter";
			$mail->IsHTML(true);

			$message = 'We are verifying your SMTP connection, please ignore this email.';
			$mail->Body = $message;
			$mail->AddAddress($mail_request['email_address'], $mail_request['sender_name']);

			// for debuging


			$mailstatus = $mail->Send();

			$debugOutput = ob_get_clean();
			$responseData = array(
				'debug_output' => $debugOutput
			);

			if ($mail_request['check_imap_conn'] == false) {
				if ($mailstatus) {
					return ['status' => 1, "message" => "Mail sent.", 'data' => []];
				} else {
					return ['status' => 0, "message" => "Could not authenticate", 'data' => [$responseData]];
				}
			}

			if ($mail_request['check_imap_conn'] == true) {
				if ($mailstatus) {
					$check_imap = $this->checkIMAP1($mail_request);
					if (isset($check_imap['status'])) {
						if (empty($check_imap['status'])) {
							return ['status' => 0, "message" => "Please check your settings for IMAP."];
						}
						return ['status' => 1, "message" => "Mail sent.", 'data' => []];
					}
					return ['status' => 0, "message" => "Please check your settings for IMAP."];
				} else {
					return ['status' => false, "message" => "Email Sent failed"];
				}
			}
		} catch (Exception $e) {

			if (!$e->getCode()) {
				return ['status' => 0, 'message' => 'Please check your Gmail settings for smtp.'];
			} else {
				return ['status' => 0, 'message' => $e->getMessage(), 'data' => $e];
			}
		}
	}

	public function warning_handler($errno, $errstr)
	{
		return [
			'status' => 0,
			'message' => $errno . " " . $errstr
		];
		exit();
	}

	public function actionSmtpfirebasesync()
	{
		$smtpId = $_POST['smtpId'];
		$action = $_POST['action']; //ADD
		echo "Hii";
		exit;
	}
	public function actionMailresponsehandler()
	{
		echo "Hii";
		exit;
	}
	public function actionTestpostsmtp()
	{
		$smtpId = $_POST['smtpId'];
		$subject = $_POST['subject'];
		echo "Hii";
		exit;
	}

	public function checkIMAP($mail_request)
	{
		$string_imap = $mail_request['incoming_mail_server'] . ':' . $mail_request['imap_port'];
		$date = date('j M Y', time());
		error_reporting(E_ERROR);
		try {
			$connection = imap_open('{' . $string_imap . '/imap/sll}INBOX', $mail_request['imap_email_address'], $mail_request['imap_password']) or die();
			if ($connection) {
				$emailData = imap_search($connection, 'FROM "' . $mail_request['imap_email_address'] . '" SUBJECT "[IGNORE] SMTP connection validation by Inboxigniter" SINCE "' . $date . '"', SE_UID);
				imap_close($connection);
				return ['status' => 1, 'message' => 'IMAP Connection authenticated Successfully'];
			} else {
				// $lastError = imap_last_error();
				return [
					'status' => 0,
					'message' => 'check your IMAP details.'
				];
			}
		} catch (Exception $e) {
			//        echo json_encode( $e->getMessage());
			//    exit();
			return [
				'status' => 0,
				'message' => $e->getMessage() //imap_last_error()
			];
		}
	}


	public function actionAddworkinghours()
	{


		$whtitle = $_POST['whtitle'];
		$whtitle = addllashes($whtitle);
		$whtitle = htmlspecialchars($whtitle);
		$whstarttime = $_POST['whstarttime'] . ':00';
		$whendtime = $_POST['whendtime'] . ':00';
		//echo "
"; print_r($_POST); exit; 
		// Get user timezone
		$user_timezone = 'Asia/Kolkata';
		$getTimezone = Yii::$app->db->createCommand("SELECT timezone FROM users where userId =" . Yii::$app->user->identity->userId)->queryOne();
		if (isset($getTimezone['timezone']) && $getTimezone['timezone'] != '') {
			$user_timezone = $getTimezone['timezone'];
		}
		// End
		//$server_start_time = '00:00:00';
		//$server_end_time = '00:00:00';
		//echo $whstarttime.'===='.$whendtime.'
'; exit; if (isset($whstarttime)) { $ist_date = \DateTime::createFromFormat('H:i:s', $whstarttime, new \DateTimeZone($user_timezone)); //print_r($ist_date);die; $gmt_date = clone $ist_date; // we don't want PHP's default pass object by reference here $gmt_date->setTimeZone(new \DateTimeZone('UTC')); //echo 'IST: ' . $ist_date->format('H:i:s').'

'; // IST: 2011-04-27 2:45 AM $server_start_time = $gmt_date->format('H:i:s'); // GMT: 2011-04-27 12:15 PM } if (isset($whendtime)) { $ist_date1 = \DateTime::createFromFormat('H:i:s', $whendtime, new \DateTimeZone($user_timezone)); $gmt_date1 = clone $ist_date1; // we don't want PHP's default pass object by reference here $gmt_date1->setTimeZone(new \DateTimeZone('UTC')); //echo 'IST: ' . $ist_date->format('H:i:s').'

'; // IST: 2011-04-27 2:45 AM $server_end_time = $gmt_date1->format('H:i:s'); // GMT: 2011-04-27 12:15 PM } //echo 'Start Time: '.$server_start_time.' - End Time: '.$server_end_time; exit; $sql = Yii::$app->db->createCommand("INSERT INTO workinghours(name,starttime,endtime,starttimeIso,endtimeIso,serverStarttime,serverEndtime,userId,day) VALUES ('" . $whtitle . "', '" . $_POST['whstarttime_usr'] . "', '" . $_POST['whendtime_usr'] . "', '" . $whstarttime . "', '" . $whendtime . "', '" . $server_start_time . "', '" . $server_end_time . "', '" . Yii::$app->user->identity->userId . "', '" . $_POST['chkDayStr'] . "' ) ")->execute(); } public function actionGetdashboarddata() { $smtpId = $_POST['smtp_id']; $today = date('Y-m-d'); $yesterday = date('Y-m-d', strtotime('-1 day')); $getsenttoday = Yii::$app->db->createCommand("Select taskId from completedtasks where senderSmtpId = '" . $smtpId . "' AND userId = '" . Yii::$app->user->identity->userId . "' AND stepOrder = '0' AND completedOn >= now() - INTERVAL 1 DAY")->queryAll(); $getcntsent = count($getsenttoday); $getinboxtoday = Yii::$app->db->createCommand("Select taskId from completedtasks where senderSmtpId = '" . $smtpId . "' AND userId = '" . Yii::$app->user->identity->userId . "' AND stepOrder = '0' AND mailStatus = '1' AND completedOn >= now() - INTERVAL 1 DAY")->queryAll(); $getcntinbox = count($getinboxtoday); $getspamtoday = Yii::$app->db->createCommand("Select taskId from completedtasks where senderSmtpId = '" . $smtpId . "' AND userId = '" . Yii::$app->user->identity->userId . "' AND stepOrder = '0' AND mailStatus = '2' AND completedOn >= now() - INTERVAL 1 DAY")->queryAll(); $getcntspam = count($getspamtoday); $getrecivedtoday = Yii::$app->db->createCommand("Select taskId from completedtasks where receiverSmtpId = '" . $smtpId . "' AND stepOrder = '0' AND receiverId = '" . Yii::$app->user->identity->userId . "' AND completedOn >= now() - INTERVAL 1 DAY")->queryAll(); $getcntrecived = count($getrecivedtoday); // $getsentyesterday = Yii::$app->db->createCommand("SELECT taskId FROM completedtasks WHERE senderSmtpId = :smtpId AND userId = :userId AND stepOrder = '0' AND completedOn >= :yesterday AND completedOn < :today")->queryAll(); // $getcntsentyesterday = count($getsentyesterday); // $getreceivedyesterday = Yii::$app->db->createCommand("SELECT taskId FROM completedtasks WHERE receiverSmtpId = :smtpId AND stepOrder = '0' AND receiverId = :userId AND completedOn >= :yesterday AND completedOn < :today")->queryAll(); // $getcntreceivedyesterday = count($getreceivedyesterday); echo $getcntsent . ':' . $getcntinbox . ':' . $getcntspam . ':' . $getcntrecived; } public function getTodaydata($smtpId) { $response_arr = [ 'getsenttoday' => 0, 'getinboxtoday' => 0, 'getspamtoday' => 0, 'getrecivedtoday' => 0, // 'getsentyesterday' => 0, // 'getreceivedyesterday' => 0 ]; $getcntinbox = 0; $getcntspam = 0; $getcntrecived = 0; $getcntsent = 0; // $getcntsentyesterday = 0; // $getcntreceivedyesterday = 0; $today = date('Y-m-d'); $yesterday = date('Y-m-d', strtotime('-1 day')); // echo "Select taskId from completedtasks where senderSmtpId = '".$smtpId."' AND userId = '".Yii::$app->user->identity->userId."' AND stepOrder = '0' AND completedOn >= now() - INTERVAL 1 DAY";exit; $getsenttoday = Yii::$app->db->createCommand("Select taskId from completedtasks where senderSmtpId = '" . $smtpId . "' AND userId = '" . Yii::$app->user->identity->userId . "' AND stepOrder = '0' AND status=7 AND completedOn >= now() - INTERVAL 1 DAY")->queryAll(); $getcntsent = count($getsenttoday); $getinboxtoday = Yii::$app->db->createCommand("Select taskId from completedtasks where senderSmtpId = '" . $smtpId . "' AND userId = '" . Yii::$app->user->identity->userId . "' AND stepOrder = '0' AND mailStatus = '1' AND completedOn >= now() - INTERVAL 1 DAY")->queryAll(); $getcntinbox = count($getinboxtoday); $getspamtoday = Yii::$app->db->createCommand("Select taskId from completedtasks where senderSmtpId = '" . $smtpId . "' AND userId = '" . Yii::$app->user->identity->userId . "' AND stepOrder = '0' AND mailStatus = '2' AND completedOn >= now() - INTERVAL 1 DAY")->queryAll(); $getcntspam = count($getspamtoday); $getrecivedtoday = Yii::$app->db->createCommand("Select taskId from completedtasks where receiverSmtpId = '" . $smtpId . "' AND stepOrder = '0' AND receiverId = '" . Yii::$app->user->identity->userId . "' AND completedOn >= now() - INTERVAL 1 DAY")->queryAll(); $getcntrecived = count($getrecivedtoday); // $getsentyesterday = Yii::$app->db->createCommand("SELECT taskId FROM completedtasks WHERE senderSmtpId = :smtpId AND userId = :userId AND stepOrder = '0' AND completedOn >= :yesterday AND completedOn < :today")->queryAll(); // $getcntsentyesterday = count($getsentyesterday); // $getreceivedyesterday = Yii::$app->db->createCommand("SELECT taskId FROM completedtasks WHERE receiverSmtpId = :smtpId AND stepOrder = '0' AND receiverId = :userId AND completedOn >= :yesterday AND completedOn < :today")->queryAll(); // $getcntreceivedyesterday = count($getreceivedyesterday); if ($getcntsent !== 0) { $response_arr['getsenttoday'] = $getcntsent; } if ($getcntinbox !== 0) { $response_arr['getinboxtoday'] = $getcntinbox; } if ($getcntspam !== 0) { $response_arr['getspamtoday'] = $getcntspam; } if ($getcntrecived !== 0) { $response_arr['getrecivedtoday'] = $getcntrecived; } // if ($getcntsentyesterday !== 0) { // $response_arr['getspamtoday'] = $getcntsentyesterday; // } // if ($getcntreceivedyesterday !== 0) { // $response_arr['getrecivedtoday'] = $getcntreceivedyesterday; // } return $response_arr; } public function actionGetchartdata() { //echo '
'; print_r($_GET); exit;

		$s_date = implode('-', array_reverse(explode('/', $_GET['s_date'])));
		$e_date = implode('-', array_reverse(explode('/', $_GET['e_date'])));
		$userid = Yii::$app->user->identity->userId;
		$smtpId = $_GET['smtp_id'];

		$res_arr = array();
		$rep_acc_data = Yii::$app->db->createCommand("SELECT COUNT(taskId) as sent, DATE_FORMAT(completedOn, '%Y-%m-%d') as sent_at FROM completedtasks WHERE completedOn BETWEEN '" . $s_date . "' AND '" . $e_date . "' AND senderSmtpId = '" . $smtpId . "' AND userId = '" . Yii::$app->user->identity->userId . "' AND stepOrder = '0' GROUP BY sent_at")->queryAll();


		$rep_res_data = Yii::$app->db->createCommand("SELECT COUNT(taskId) as Received, DATE_FORMAT(completedOn, '%Y-%m-%d') AS created_at FROM `completedtasks` WHERE userId = '" . Yii::$app->user->identity->userId . "' and receiverSmtpId = '" . $smtpId . "' and completedOn BETWEEN '" . $s_date . "' AND '" . $e_date . "' AND stepOrder = '0' AND receiverId = '" . Yii::$app->user->identity->userId . "' GROUP BY created_at")->queryAll();

		//echo "SELECT COUNT(taskId) as Received, DATE_FORMAT(completedOn, '%Y-%m-%d') AS created_at FROM `completedtasks` WHERE userId = '" . Yii::$app->user->identity->userId . "' and receiverSmtpId = '".$smtpId."' and completedOn BETWEEN '" . $s_date . "' AND '" . $e_date . "' AND stepOrder = '0' AND receiverId = '".Yii::$app->user->identity->userId."' GROUP BY created_at"; exit;


		$dates = $this->getallDates($s_date, $e_date);

		//echo '
'; print_r($dates); exit;

		$k = 0;
		foreach ($dates as $date_v) {
			$arr = [];
			$rkey = '';
			$akey = '';
			//echo $date_v; exit;
			$rkey = array_search($date_v, array_column($rep_res_data, 'created_at'));
			$akey = array_search($date_v, array_column($rep_acc_data, 'sent_at'));

			//echo '
'; print_r($rkey); exit;

			if ($rkey !== false && $akey !== false) {
				$arr['b'] = $rep_res_data[$rkey]['Received'];
				$arr['a'] = $rep_acc_data[$akey]['sent'];
				$arr['y'] = date('d/m', strtotime($date_v));
				$res_arr[$k] = $arr;
				//echo '
'; print_r($arr);

				$k++;
			} elseif ($rkey !== false && $akey === false) {
				$arr['b'] = $rep_res_data[$rkey]['Received'];
				$arr['y'] = date('d/m', strtotime($date_v));
				$arr['a'] = 0;
				$res_arr[$k] = $arr;
				$k++;
			} elseif ($akey !== false && $rkey === false) {
				$arr['a'] = $rep_acc_data[$akey]['sent'];
				$arr['y'] = date('d/m', strtotime($date_v));
				$arr['b'] = 0;
				$res_arr[$k] = $arr;
				$k++;
			}/* else{
              $arr['a'] = 0;
              $arr['b'] = 0;
              $arr['y'] = $date_v;
              } */
		}

		echo json_encode($res_arr);
	}

	public function getallDates($s_date, $e_date)
	{
		$dates = array();

		$d1 = strtotime($s_date);
		$d2 = strtotime($e_date);

		//echo $d1."==".$d2; exit;

		for ($currentDate = $d1; $currentDate <= $d2; $currentDate += (86400)) {
			$date = date('Y-m-d', $currentDate);
			$dates[] = $date;
		}
		//echo '
'; print_r($dates); exit;
		return $dates;
	}


	public function actionSmtprunspftest()
	{

		$provider = $_GET['provider'];

		if (isset($_GET['provider']) && $_GET['provider'] != '') {
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, "https://rf6ot22nli.execute-api.us-east-2.amazonaws.com/default/domain_check?domain=" . $provider);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");


			$headers = array();
			$headers[] = "Accept: application/json";
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

			$result = curl_exec($ch);
			if (curl_errno($ch)) {
				echo 'Error:' . curl_error($ch);
			}
			curl_close($ch);

			//echo $result;
			$spfdata = json_decode($result, true);
			echo '
    '; // echo 'KeyValue'; if (!empty($spfdata)) { foreach ($spfdata as $key => $val) { //echo ''; echo '
  • ' . $key . ': ' . $val . '
  • '; } } else { echo '
  • No data!
  • '; } echo '
'; } else { echo 0; } } public function actionEmailwarmupconfig() { if (isset($_POST["skipwarmupphase"])) { $sql = Yii::$app->db->createCommand("INSERT INTO workinghours(name,userId,day,starttime,endtime,starttimeIso,endtimeIso,serverStarttime,serverEndtime,skipwarmupphase) VALUES ('demo', '4', '1,2,3,4,5,6,7', '" . $_POST['starttime'] . "','" . $_POST['endtime'] . "', '09:30:00','20:30:00', '04:00:00', '15:00:00','" . $_POST["skipwarmupphase"] . "') ")->execute(); echo "inserted"; } // else{ // $sql = Yii::$app->db->createCommand("INSERT INTO workinghours(name,userId,day,starttime,endtime,starttimeIso,endtimeIso,serverStarttime,serverEndtime,skipwarmupphase) // VALUES ('demo', '4', '1,2,3,4,5,6,7', '" . $_POST['starttime'] . "','" . $_POST['endtime'] . "', '09:30:00','20:30:00', '04:00:00', '15:00:00','".$_POST["skipwarmupphase"]."') ")->execute(); // } } public function actionEmailsignature() { if (isset($_POST['smtpId']) && isset($_POST['isEmailSignature'])) { $smtpId = $_POST['smtpId']; $isEmailSignature = $_POST['isEmailSignature']; $smtpAccount = Yii::$app->db->createCommand('SELECT * FROM smtp WHERE smtpId =' . $smtpId)->queryOne(); if ($smtpAccount) { Yii::$app->db->createCommand() ->update('smtp', ['isemailSignature' => $isEmailSignature], ['smtpId' => $smtpId]) ->execute(); echo json_encode(['status' => 'success', 'message' => 'Email Signature enabled successfully']); } else { echo json_encode(['status' => 'success', 'message' => 'Account not found']); } } else { echo json_encode(['status' => 'error', 'message' => 'Email Signature not provided']); } } // public function actionCustomtemplate(){ // } public function actionDeleteaccount() { if (isset($_POST['smtpId'])) { $smtpId = $_POST['smtpId']; Yii::$app->db->createCommand()->delete('smtp', ['smtpId' => $smtpId])->execute(); echo json_encode(['status' => 'success', 'message' => 'Account deleted successfully']); exit; // header("Location:https://app.inboxigniter.com/site/smtpdashboard"); } else { echo json_encode(['status' => 'error', 'message' => 'Somethig went wrong']); exit; } } public function actionFilterdata() { if (isset($_POST['provider']) && isset($_POST['domains'])) { $provider = $_POST['provider']; $domains = $_POST['domains']; $filteredData = Yii::$app->db->createCommand("SELECT * FROM `smtp` where provider = '" . $provider . "' AND SUBSTRING_INDEX(emailAddress,'@',-1) = '" . $domains . "' AND userId = '" . Yii::$app->user->identity->userId . "' ")->queryAll(); if ($filteredData) { echo json_encode(['status' => 'success', 'message' => 'Data filtered successfully.', 'filteredData' => $filteredData]); exit; } else { echo json_encode(['status' => '404', 'message' => 'Data not found.', 'filteredData' => []]); exit; } } else { echo json_encode(['status' => 'error', 'message' => 'Somethig went wrong']); exit; } } public function actionSearchemail() { // $smtplist_query = new Query; // $smtplist = $smtplist_query->select(['emailAddress','smtp','port','encryption','smtpId','status','sends','receives','provider','perDayLimit','senderName']) // ->from('smtp') // ->where(['userId' => Yii::$app->user->identity->userId,'deletedAt'=>NULL]); // // ->all(); // $countQuery = $smtplist->count(); // $pages = new Pagination(['totalCount' => $countQuery,'pageSize' => 20]); // $models = $smtplist->offset($pages->offset) // ->limit($pages->limit) // ->orderBy(['smtpId' => SORT_DESC]) // ->all(); if (isset($_POST['vals'])) { $keyword = $_POST['vals']; $filteredData = Yii::$app->db->createCommand("SELECT * FROM `smtp` where emailAddress LIKE '%" . $keyword . "%' AND userId = '" . Yii::$app->user->identity->userId . "'")->queryAll(); if ($filteredData) { echo json_encode(['status' => 'success', 'message' => 'Data filtered successfully.', 'data' => $filteredData]); exit; } else { echo json_encode(['status' => '404', 'message' => 'Data Not found', 'data' => []]); exit; } } else { echo json_encode(['status' => 'error', 'message' => 'Somethig went wrong']); exit; } } public function actionSearchblacklist() { // type = 0 for emailblacklist // type = 1 for domainblacklist if (isset($_POST['type']) && $_POST['type'] == '0') { if (isset($_POST['vals'])) { $keyword = $_POST['vals']; $filteredData = Yii::$app->db->createCommand("SELECT * FROM `blacklist` where blacklisted LIKE '%" . $keyword . "%' AND type = '0' AND userId = '" . Yii::$app->user->identity->userId . "' ")->queryAll(); if ($filteredData) { echo json_encode(['status' => 'success', 'message' => 'Emails found successfully.', 'data' => $filteredData]); exit; } else { echo json_encode(['status' => '404', 'message' => 'Data Not found', 'data' => []]); exit; } } else { echo json_encode(['status' => 'error', 'message' => 'Somethig went wrong']); exit; } } elseif (isset($_POST['type']) && $_POST['type'] == '1') { if (isset($_POST['vals'])) { $keyword = $_POST['vals']; $filteredData = Yii::$app->db->createCommand("SELECT * FROM `blacklist` where blacklisted LIKE '%" . $keyword . "%' AND type = '1' AND userId = '" . Yii::$app->user->identity->userId . "' ")->queryAll(); if ($filteredData) { echo json_encode(['status' => 'success', 'message' => 'Emails found successfully.', 'data' => $filteredData]); exit; } else { echo json_encode(['status' => '404', 'message' => 'Data Not found', 'data' => []]); exit; } } else { echo json_encode(['status' => 'error', 'message' => 'Somethig went wrong']); exit; } } else { echo json_encode(['status' => 'error', 'message' => 'Somethig went wrong']); exit; } } public function actionGetactivitychartdata() { $smtp_id = Yii::$app->request->post('smtp_id'); $duration = Yii::$app->request->post('duration'); // echo $smtp_id; $smtp_id = base64_decode($smtp_id); // Fetch data based on $smtp_id and $duration $data = $this->getactivitychartdata($smtp_id, $duration); return json_encode($data); } public function getactivitychartdata($smtp_id, $duration) { $response_arr = [ 'data' => 0, 'message' => 'Invalid Method', 'status' => 500 ]; // $smtp_id = base64_decode($smtp_id); //today's logic start (final) if ($duration == "today") { $current_time = date('H:i:s'); $today_date = date('Y-m-d'); $data = Yii::$app->db->createCommand("SELECT TIME(completedOn) as maintime,SUM(IF(mailstatus = 1, 1, 0)) as inbox_value,SUM(IF(mailstatus != 1, 1, 0)) as spam_value FROM `completedtasks` WHERE userId = '" . Yii::$app->user->identity->userId . "' AND senderSmtpId = '" . $smtp_id . "' AND status = '7' AND completedOn >= NOW() - INTERVAL 1 DAY -- This condition starts from yesterday AND mailstatus IN (1, 2) AND stepOrder='0' GROUP BY TIME(completedOn);")->queryAll(); } //today's logic end (final) //yesterday logic start (final) if ($duration == "yesterday") { $yesterday_date = date('Y-m-d', strtotime('-1 day')); $data = Yii::$app->db->createCommand("SELECT HOUR(completedOn) as maintime,SUM(IF(mailstatus = 1, 1, 0)) as inbox_value,SUM(IF(mailstatus != 1, 1, 0)) as spam_value FROM `completedtasks` WHERE userId = '" . Yii::$app->user->identity->userId . "' AND senderSmtpId = '" . $smtp_id . "' AND status = '7' AND stepOrder='0' AND DATE(completedOn) = '" . $yesterday_date . "' AND mailstatus IN (1, 2) AND stepOrder='0' GROUP BY HOUR(completedOn);")->queryAll(); } //yesterday Logic end (final) //week logic start (final) if ($duration == "week") { $currentDate = date('Y-m-d'); $endOfWeek = date('Y-m-d'); $startOfWeek = date('Y-m-d', strtotime('-7 days', strtotime($endOfWeek))); $data = Yii::$app->db->createCommand("SELECT DAYNAME(completedOn) as maintime,SUM(IF(mailstatus = 1, 1, 0)) as inbox_value,SUM(IF(mailstatus != 1, 1, 0)) as spam_value FROM `completedtasks` WHERE userId = '" . Yii::$app->user->identity->userId . "'AND senderSmtpId = '" . $smtp_id . "' AND status = '7' AND DATE(completedOn) BETWEEN '" . $startOfWeek . "' AND '" . $endOfWeek . "' AND mailstatus IN (1, 2) AND stepOrder='0' GROUP BY DAYNAME(completedOn);")->queryAll(); } //week logic end (final) //month logic start (final) if ($duration == "month") { $firstDayOfCurrentMonth = date('Y-m-01'); $lastDayOfCurrentMonth = date('Y-m-t'); $startOfLastMonth = date('Y-m-d', strtotime('-1 month', strtotime($firstDayOfCurrentMonth))); $endOfLastMonth = date('Y-m-t', strtotime('-1 month', strtotime($firstDayOfCurrentMonth))); $data = Yii::$app->db->createCommand("SELECT MONTHNAME(completedOn) as maintime,SUM(IF(mailstatus = 1, 1, 0)) as inbox_value,SUM(IF(mailstatus != 1, 1, 0)) as spam_value FROM `completedtasks` WHERE userId = '" . Yii::$app->user->identity->userId . "' AND senderSmtpId = '" . $smtp_id . "' AND status = '7' AND DATE(completedOn) BETWEEN '" . $firstDayOfCurrentMonth . "' AND '" . $lastDayOfCurrentMonth . "' AND mailstatus IN (1, 2) AND stepOrder='0' GROUP BY MONTHNAME(completedOn);")->queryAll(); } //month logic end (final) //Quarter logic start (final) if ($duration == "quarter") { $currentDate = date('Y-m-d'); $startOfCurrentQuarter = date('Y-m-01', strtotime('first day of this quarter', strtotime($currentDate))); $endOfCurrentQuarter = date('Y-m-t', strtotime('last day of this quarter', strtotime($currentDate))); $year = date('Y', strtotime($currentDate)); $month = date('n', strtotime($currentDate)); if ($month >= 1 && $month <= 3) { $firstDayOfQuarter = $year . '-01-01'; $lastDayOfQuarter = $year . '-03-31'; } elseif ($month >= 4 && $month <= 6) { $firstDayOfQuarter = $year . '-04-01'; $lastDayOfQuarter = $year . '-06-30'; } elseif ($month >= 7 && $month <= 9) { $firstDayOfQuarter = $year . '-07-01'; $lastDayOfQuarter = $year . '-09-30'; } else { $firstDayOfQuarter = $year . '-10-01'; $lastDayOfQuarter = $year . '-12-31'; } $date_str = strval($firstDayOfQuarter); $data = Yii::$app->db->createCommand("SELECT MONTHNAME(completedOn) as maintime,SUM(IF(mailstatus = 1, 1, 0)) as inbox_value,SUM(IF(mailstatus != 1, 1, 0)) as spam_value FROM `completedtasks` WHERE `senderSmtpId` = '" . $smtp_id . "' AND `userId` = '" . Yii::$app->user->identity->userId . "' AND `completedOn` BETWEEN '" . $date_str . "' AND '" . $lastDayOfQuarter . "' AND mailstatus IN (1, 2) AND stepOrder='0' GROUP BY MONTHNAME(completedOn);")->queryAll(); } //Quarter Logic end (final) //year logic start (final) if ($duration == "year") { $currentDate = date('Y-m-d'); $startOfLastYear = date('Y-m-d', strtotime('-1 year', strtotime($currentDate))); $endOfLastYear = date('Y-m-d', strtotime('-1 day', strtotime($currentDate))); $data = Yii::$app->db->createCommand("SELECT MONTHNAME(completedOn) as maintime,SUM(IF(mailstatus = 1, 1, 0)) as inbox_value,SUM(IF(mailstatus != 1, 1, 0)) as spam_value FROM `completedtasks` WHERE userId = '" . Yii::$app->user->identity->userId . "' AND senderSmtpId = '" . $smtp_id . "' AND status = '7' AND DATE(completedOn) BETWEEN '" . $startOfLastYear . "' AND '" . $endOfLastYear . "' AND mailstatus IN (1, 2) AND stepOrder='0' GROUP BY MONTHNAME(completedOn);")->queryAll(); } if (empty($data)) { $response_arr['status'] = 404; $response_arr['data'] = ''; $response_arr['message'] = 'Data not found'; } else { $response_arr['status'] = 200; $response_arr['data'] = $data; $response_arr['message'] = 'Data found successfully'; } return $response_arr; exit; } public function actionFetchcustomtemplate() { $response_arr = [ 'http_status' => 405, 'data' => [], 'message' => 'Method Not Allowed' ]; $parentId = $_POST['parentId']; $templateId = $_POST['templateId']; if (isset($_POST['templateId']) && isset($_POST['parentId'])) { $result = Yii::$app->db->createCommand("SELECT * FROM templates1 WHERE parentId = '" . $parentId . "' ORDER BY templateId")->queryAll(); if (!empty($result)) { $response_arr['http_status'] = 200; $response_arr['data'] = $result; $response_arr['message'] = "Data Found"; echo json_encode($response_arr); exit; } else { $response_arr['http_status'] = 404; $response_arr['message'] = "Data Not Found"; echo json_encode($response_arr); exit; } } } // update tempplate public function actionUpdatetemplate() { $response_arr = [ 'http_status' => 405, 'data' => [], 'message' => 'Method Not Allowed' ]; if (isset($_POST['update1']) && $_POST['update1'] == '1') { if (isset($_POST['parentId'])) { $step3 = ''; if (isset($_POST['templateName_edit'])) { $userId = Yii::$app->user->identity->userId; $templateName = $_POST['templateName_edit']; $subject1 = $_POST['subject1_edit']; $template1 = $_POST['template1_edit']; $templateId = $_POST['templateId']; // first template update smtp set selected_language = '".$warmuplanguage."' where smtpId = ".$smtp_id $step3 = Yii::$app->db->createCommand("Update `templates` set templateName= '" . $templateName . "',subject='" . $subject1 . "',template='" . $template1 . "' where templateId= '" . $templateId . "' AND parentId= '" . $_POST['parentId'] . "' AND userId = '" . $userId . "' ")->execute(); if ($step3 == 1) { $response_arr['http_status'] = 200; $response_arr['message'] = "Template Updated successfully."; } else { $response_arr['http_status'] = 404; $response_arr['message'] = "Something went wrong,please try again later."; } } } echo json_encode($response_arr); exit(); } if (isset($_POST['update2']) && $_POST['update2'] == '1') { if (isset($_POST['parentId'])) { $step3 = ''; $userId = Yii::$app->user->identity->userId; $subject2 = $_POST['subject2_edit']; $template2 = $_POST['template2_edit']; $templateId = $_POST['templateId']; // first template update smtp set selected_language = '".$warmuplanguage."' where smtpId = ".$smtp_id $step3 = Yii::$app->db->createCommand("Update `templates1` set subject='" . $subject2 . "',template='" . $template2 . "' where templateId= '" . $templateId . "' AND parentId= '" . $_POST['parentId'] . "' AND userId = '" . $userId . "' ")->execute(); if ($step3 == 1) { $response_arr['http_status'] = 200; $response_arr['message'] = "Template Updated successfully."; } else { $response_arr['http_status'] = 404; $response_arr['message'] = "Something went wrong,please try again later."; } } echo json_encode($response_arr); exit(); } if (isset($_POST['update3']) && $_POST['update3'] == '1') { if (isset($_POST['parentId'])) { $step3 = ''; $userId = Yii::$app->user->identity->userId; $subject3 = $_POST['subject3_edit']; $template3 = $_POST['template3_edit']; $templateId = $_POST['templateId']; // first template update smtp set selected_language = '".$warmuplanguage."' where smtpId = ".$smtp_id $step3 = Yii::$app->db->createCommand("Update `templates1` set subject='" . $subject3 . "',template='" . $template3 . "' where templateId= '" . $templateId . "' AND parentId= '" . $_POST['parentId'] . "' AND userId = '" . $userId . "' ")->execute(); if ($step3 == 1) { $response_arr['http_status'] = 200; $response_arr['message'] = "Template Updated successfully."; } else { $response_arr['http_status'] = 404; $response_arr['message'] = "Something went wrong,please try again later."; } } echo json_encode($response_arr); exit(); } } // insert a new template public function actionStorecustomtemplate() { $response_arr = [ 'http_status' => 405, 'data' => [], 'message' => 'Method Not Allowed' ]; $step3 = ''; if (isset($_POST['templateName']) && isset($_POST['subject1']) && isset($_POST['template1']) && isset($_POST['subject2']) && isset($_POST['template2']) && isset($_POST['subject3']) && isset($_POST['template3'])) { $userId = Yii::$app->user->identity->userId; $templateName = $_POST['templateName']; $subject1 = $_POST['subject1']; $template1 = $_POST['template1']; $subject2 = $_POST['subject2']; $template2 = $_POST['template2']; $subject3 = $_POST['subject3']; $template3 = $_POST['template3']; // first template $step1 = Yii::$app->db->createCommand("INSERT INTO `templates`(`userId`,`templateOrder`,`templateName`,`subject`,`template`,`counter`) VALUES ('" . $userId . "','0','" . $templateName . "','" . $subject1 . "','" . $template1 . "','0')")->execute(); $parentId = Yii::$app->db->getLastInsertID(); $result = Yii::$app->db->createCommand("update templates set parentId = '" . $parentId . "' where templateId = " . $parentId)->execute(); $step2 = Yii::$app->db->createCommand("INSERT INTO `templates`(`parentId`,`userId`,`templateOrder`,`subject`,`template`) VALUES ('" . $parentId . "','" . $userId . "','1','" . $subject2 . "','" . $template2 . "')")->execute(); $step3 = Yii::$app->db->createCommand("INSERT INTO `templates`(`parentId`,`userId`,`templateOrder`,`subject`,`template`) VALUES ('" . $parentId . "','" . $userId . "','2','" . $subject3 . "','" . $template3 . "')")->execute(); if ($step3 == 1) { $response_arr['http_status'] = 200; $response_arr['message'] = "Template stored successfully."; } else { $response_arr['http_status'] = 404; $response_arr['message'] = "Something went wrong,please try again later."; } } echo json_encode($response_arr); exit(); } public function actionDeletecustomtemplate() { if (isset($_POST['delete_template'])) { $delete_template = $_POST['delete_template']; // echo $delete_template; exit; // $parent_id = $_POST['parent_id']; Yii::$app->db->createCommand("DELETE FROM templates1 WHERE parentId='" . $delete_template . "' ")->execute(); echo json_encode(['status' => 'success', 'message' => 'Templates deleted successfully']); exit; } else { echo json_encode(['status' => 'error', 'message' => 'Something went wrong']); exit; } } public function actionAssigntag() { if (isset($_POST['tagName']) && isset($_POST['templateIds'])) { $templateIds = $_POST['templateIds']; $tagName = $_POST['tagName']; if (is_array($templateIds)) { $templateIds = implode(", ", $templateIds); } $step1 = Yii::$app->db->createCommand("INSERT INTO `tags`(`tagName`,`templateId`) VALUES ('" . $tagName . "','" . $templateIds . "')")->execute(); $lastcreatedtagId = Yii::$app->db->getLastInsertID(); $existingTagsQuery = Yii::$app->db->createCommand("SELECT tagIds FROM templates1 WHERE templateId IN (" . $templateIds . ")")->queryAll(); $existingTagIds = []; foreach ($existingTagsQuery as $row) { $tagIds = explode(", ", $row['tagIds']); $existingTagIds = array_merge($existingTagIds, $tagIds); } $existingTagIds = array_unique($existingTagIds); $existingTagIds[] = $lastcreatedtagId; $result = Yii::$app->db->createCommand("UPDATE templates1 SET tagIds = '" . implode(", ", $existingTagIds) . "' WHERE templateId IN (" . $templateIds . ")")->execute(); if ($result) { $response_arr['status'] = 'success'; $response_arr['message'] = 'Tag assigned successfully'; } else { $response_arr['status'] = 'error'; $response_arr['message'] = 'Something went wrong, Tag not assigned'; } } return json_encode($response_arr); } public function getYesterdayData($smtpId) { $response_arr = [ 'getsentyesterday' => 0, 'getrecivedyesterday' => 0 ]; $getcntrecived = 0; $getcntsent = 0; // Define the date for yesterday // $yesterday = date('Y-m-d', strtotime('-2 day')); $getsentyesterday = Yii::$app->db->createCommand(" SELECT taskId FROM completedtasks WHERE senderSmtpId = :smtpId AND userId = :userId AND stepOrder = '0' AND completedOn >= NOW() - INTERVAL 48 HOUR AND completedOn < NOW() - INTERVAL 24 HOUR; ") ->bindValues([ ':smtpId' => $smtpId, ':userId' => Yii::$app->user->identity->userId, ]) ->queryAll(); $getreceivedyesterday = Yii::$app->db->createCommand(" SELECT taskId FROM completedtasks WHERE receiverSmtpId = :smtpId AND receiverId = :userId AND stepOrder = '0' AND completedOn >= NOW() - INTERVAL 48 HOUR AND completedOn < NOW() - INTERVAL 24 HOUR; ") ->bindValues([ ':smtpId' => $smtpId, ':userId' => Yii::$app->user->identity->userId, ]) ->queryAll(); $getcntsent = count($getsentyesterday); $getcntrecived = count($getreceivedyesterday); // Repeat similar modifications for other queries (getinboxyesterday, getspamyesterday, getrecivedyesterday) using the $yesterday date. // Set the counts in the response array if ($getcntsent !== 0) { $response_arr['getsentyesterday'] = $getcntsent; } if ($getcntrecived !== 0) { $response_arr['getrecivedyesterday'] = $getcntrecived; } // Repeat for other counts (inbox, spam, received) return $response_arr; } public function actionAitemplate() { $subject = ''; if(isset($_POST['subject'])){ $subject = $_POST['subject']; $api_key = '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'; // Create a prompt for OpenA $prompt = "Generate 5 example emails with 2 example response with the following format of email template for \"$subject\" End each section with '*7#-034@@!' except for the last template. : 1: Title: [Title] Subject: $subject Email Template Body: [Email Template Body] Response 1: [Response 1] Response 2: [Response 2] *7#-034@@! 2: Title: [Title] Subject: $subject Email Template Body: [Email Template Body] Response 1: [Response1] Response 2: [Response 2] *7#-034@@! 3: Title: [Title] Subject: $subject Email Template Body: [Email Template Body] Response 1: [Response 1] Response 2: [Response 2] *7#-034@@! 4: Title: [Title] Subject: $subject Email Template Body: [Email Template Body] Response 1: [Response 1] Response 2: [Response 2] *7#-034@@! 5: Title: [Title] Subject: $subject Email Template Body: [Email Template Body] Response 1: [Response 1] Response 2: [Response 2] *7#-034@@! "; // Set the OpenAI API endpoint URLs $url = 'https://api.openai.com/v1/engines/text-davinci-003/completions'; // Create a cURL handle $ch = curl_init($url); // Set cURL options curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([ 'prompt' => $prompt, 'max_tokens' => 1500, // Adjust this based on your requirements ])); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key, ]); // Execute the cURL request $response = curl_exec($ch); // Check for cURL errors if ($response === false) { echo 'cURL Error: ' . curl_error($ch); } else { // Decode the JSON response $response = json_decode($response); // Check if the 'choices' property exists in the response if (isset($response->choices)) { $generatedTemplate = $response->choices[0]->text; $templates = explode('*7#-034@@!', $generatedTemplate); $titles = []; $subjects = []; $emailBodies = []; $responses1 = []; $responses2 = []; $templatearr = []; foreach ($templates as $template) { // Extract title if (preg_match('/Title: (.+)$/m', $template, $matches)) { $titles[] =str_replace("'","\'",trim($matches[1])); } if (preg_match('/Subject: (.+)$/m', $template, $matches)) { $subjects[] = str_replace("'","\'",trim($matches[1])); } if (preg_match('/Email Template Body:(.+)/s', $template, $matches)) { $emailBodies[] = str_replace("'","\'",trim($matches[1])); } if (preg_match('/Response 1: (.+)$/m', $template, $matches)) { $responses1[] = str_replace("'","\'",trim($matches[1])); } if (preg_match('/Response 2: (.+)$/m', $template, $matches)) { $responses2[] = str_replace("'","\'",trim($matches[1])); } $templatearr[] = $template; // Extract email template body // if (preg_match('/Email Template Body:(.+)(Response 1 : .+)(Response 2 : .+)/s', $template, $matches)) { // $emailBodies[] = trim($matches[1]); // // Extract response 1 // $response1 = trim($matches[2]); // // Extract response 2 // $response2 = trim($matches[3]); // // echo $response1; // // echo $response2; // // die(); // // Store responses in an array // $responses1[] = $response1; // $responses2[] = $response2; // } } // echo count($titles); // echo count($subjects); // echo count($emailBodies); // echo count($responses1); // echo count($responses2); if(count($titles) == 5 && count($subjects) == 5 && count($emailBodies) == 5 && count($responses1) == 5 && count($responses2) == 5){ $userId = Yii::$app->user->identity->userId; foreach ($titles as $key => $title) { $subject = (string)$subjects[$key]; $emailBody = strval($emailBodies[$key]); $response1 = $responses1[$key]; $response2 = $responses2[$key]; $step1 = Yii::$app->db->createCommand("INSERT INTO `templates`(`userId`,`templateOrder`,`templateName`,`subject`,`template`,`counter`) VALUES ('" . $userId . "','0','" . (string)$title . "','" . $subject . "','" . (string)$emailBody . "','0')")->execute(); $parentId = Yii::$app->db->getLastInsertID(); $result = Yii::$app->db->createCommand("update templates set parentId = '" . $parentId . "' where templateId = " . $parentId)->execute(); $step2 = Yii::$app->db->createCommand("INSERT INTO `templates`(`userId`,`parentId`,`templateOrder`,`subject`,`template`) VALUES ('" . $userId . "','" . $parentId . "','1','Reply Follow up 1','" . (string)$response1 . "')")->execute(); $step3 = Yii::$app->db->createCommand("INSERT INTO `templates`(`userId`,`parentId`,`templateOrder`,`subject`,`template`) VALUES ('" . $userId . "','" . $parentId . "','2','Reply Follow up 2','" . (string)$response2 . "')")->execute(); if ($step1 == 1 ) { echo "ok"; } else { echo 'nope'; } } } else{ $generatedTemplate = 'Template1 generation failed'; } } else { // Handle the case where 'choices' is not found in the response $generatedTemplate = 'Template generation failed'; } // Pass the generated template to the view return $this->render('aitemplate', ['generatedTemplate' => $generatedTemplate]); } } return $this->render('aitemplate', ['generatedTemplate' =>'']); } public function actionBulkchangesmtpstatus() { if(!empty($_POST['selectedlist'])){ $selectedlist = $_POST['selectedlist']; if (is_array($selectedlist)) { $selectedlist = implode("', '", $selectedlist); } $sql = "UPDATE smtp SET status = CASE WHEN status = 0 THEN 1 ELSE 0 END WHERE smtpId IN ('" . $selectedlist . "')"; Yii::$app->db->createCommand($sql)->execute(); echo json_encode(['status' => 'success', 'message' => 'Smtp status changed successfully']); } } public function getTemplatetopics(){ // SELECT templateName FROM templates WHERE userId='0' AND templateOrder='0' $templateTopics = Yii::$app->db->createCommand("SELECT templateName,templateId FROM templates WHERE userId='0' AND templateOrder='0'")->queryAll(); if(!empty($templateTopics)){ return $templateTopics; } } }