Only sending one email notification

This code (below) sends an email notification to a User, when he’s received a web site chat/message. However, sending an email with each chat/message will probably be too many emails received. I’d like help to modify it, so that when a chat/message is received, and an email is sent, to that User, no more email notifications get sent until the User visits the site again. Any help/guidance will be appreciated.

<?php
if (IS_LOGGED == false) {
    $data = array(
        'status' => 400,
        'error' => 'Not logged in'
    );
    echo json_encode($data);

   exit();

}
$username    = '';

function sendNotif($a)
{
try
{
$db = new PDO('mysql:host=localhost;dbname=realm1', 'real1', 'pass');
}

catch (Exception $e)
{
        die('Erreur : ' . $e->getMessage());
}

$query=$db->prepare("SELECT * FROM users WHERE id = :val1  ");

$query->bindValue(':val1', $a, PDO::PARAM_STR);

$query->execute();

$data = $query->fetch(PDO::FETCH_ASSOC);

return $data['email'];

}

function sendNotifuser($a)
{
try
{
$db = new PDO('mysql:host=localhost;dbname=realml1', 'real1', 'pass');
}
catch (Exception $e)
{
     die('Erreur : ' . $e->getMessage());
}

$query=$db->prepare("SELECT * FROM users WHERE id = :val1  ");

$query->bindValue(':val1', $a, PDO::PARAM_STR);

$query->execute();

$data = $query->fetch(PDO::FETCH_ASSOC);

 return $data['username'];

}


if ($first == 'new') {

	if (!empty($_POST['id']) && !empty($_POST['new-message'])) {

		$link_regex = '/(http\:\/\/|https\:\/\/|www\.)([^\ ]+)/i';

	    $i          = 0;

	    preg_match_all($link_regex, PT_Secure($_POST['new-message']), $matches);

	    foreach ($matches[0] as $match) {

	        $match_url           = strip_tags($match);

	        $syntax              = '[a]' . urlencode($match_url) . '[/a]';

	        $_POST['new-message'] = str_replace($match, $syntax, $_POST['new-message']);

	    }

		$new_message = PT_Secure($_POST['new-message']);

		$id = PT_Secure($_POST['id']);

		if ($id != $pt->user->id) {

			$chat_exits = $db->where("user_one", $pt->user->id)->where("user_two", $id)->getValue(T_CHATS, 'count(*)');

			if (!empty($chat_exits)) {

				$db->where("user_two", $pt->user->id)->where("user_one", $id)->update(T_CHATS, array('time' => time()));

				$db->where("user_one", $pt->user->id)->where("user_two", $id)->update(T_CHATS, array('time' => time()));

				if ($db->where("user_two", $pt->user->id)->where("user_one", $id)->getValue(T_CHATS, 'count(*)') == 0) {

					$db->insert(T_CHATS, array('user_two' => $pt->user->id, 'user_one' => $id,'time' => time()));

				}

			} else {

				$db->insert(T_CHATS, array('user_one' => $pt->user->id, 'user_two' => $id,'time' => time()));

				if (empty($db->where("user_two", $pt->user->id)->where("user_one", $id)->getValue(T_CHATS, 'count(*)'))) {

					$db->insert(T_CHATS, array('user_two' => $pt->user->id, 'user_one' => $id,'time' => time()));
				}
			}

			$insert_message = array(

				'from_id' => $pt->user->id,

				'to_id' => $id,

				'text' => $new_message,

				'time' => time()

			);

			$insert = $db->insert(T_MESSAGES, $insert_message);

			if ($insert) {

				$pt->message = PT_GetMessageData($insert);

				$data = array(

					'status' => 200,

					'message_id' => $_POST['message_id'],

					'message' => PT_LoadPage('messages/ajax/outgoing', array(

						'ID' => $pt->message->id,

					'TEXT' => $pt->message->text
					))
				);



				$link = $email_code . '/' . $email;
				$send_email_data = array(
				'from_email' => $pt->config->email,
				'from_name' => $pt->config->name,
				'to_email' => sendNotif($id),
				'to_name' => sendNotifuser($id),
				'subject' => 'Message Waiting',
				'charSet' => 'UTF-8',
				'message_body' => PT_LoadPage('emails/message-alert', array(
						'USERNAME' => sendNotifuser($id)
					)),

				'is_html' => true
				);
				$send_message = PT_SendMessage($send_email_data);
		}

	}

}

}



if ($first == 'fetch') {

    if (empty($_POST['last_id'])) {

		$_POST['last_id'] = 0;

	}

	if (empty($_POST['id'])) {

		$_POST['id'] = 0;

	}

	if (empty($_POST['first_id'])) {

		$_POST['first_id'] = 0;

	}

	$messages_html = PT_GetMessages($_POST['id'], array('last_id' => $_POST['last_id'], 'first_id' => $_POST['first_id'], 'return_method' => 'html'));

	if (!empty($messages_html)) {

		$html = PT_LoadPage("messages/{$pt->config->server}/messages", array('MESSAGES' => $messages_html));

	} else {

		$html = PT_LoadPage("messages/ajax/no-messages");

	}



	$users_html = PT_GetMessagesUserList(array('return_method' => 'html'));



	if (!empty($messages_html) || !empty($users_html)) {

		$data = array('status' => 200, 'message' => $messages_html, 'users' => $users_html);

	}

}



if ($first == 'search') {

	$keyword = '';

	$users_html = '<p class="text-center">' . $lang->no_match_found . '</p>';

	if (isset($_POST['keyword'])) {

		$users_html = PT_GetMessagesUserList(array('return_method' => 'html', 'keyword' => $_POST['keyword']));

	}

	$data = array('status' => 200, 'users' => $users_html);

}



if ($first == 'delete_chat') {

	if (!empty($_POST['id'])) {

		$id = PT_Secure($_POST['id']);

		$messages = $db->where("(from_id = {$pt->user->id} AND to_id = {$id}) OR (from_id = {$id} AND to_id = {$pt->user->id})")->get(T_MESSAGES);

		$update1 = array();

		$update2 = array();

		$erase = array();

		foreach ($messages as $key => $message) {

			if ($message->from_deleted == 1 || $message->to_deleted == 1) {

				$erase[] = $message->id;

			} else {

				if ($message->to_id == $pt->user->id) {

					$update2[] = $message->id;

				} else {

					$update1[] = $message->id;

				}

			}

		}

		if (!empty($erase)) {

			$erase = implode(',', $erase);

			$final_query = "DELETE FROM " . T_MESSAGES . " WHERE id IN ($erase)";

			$db->rawQuery($final_query);

		}

		if (!empty($update1)) {

			$update1 = implode(',', $update1);

			$final_query = "UPDATE " . T_MESSAGES . " set `from_deleted` = '1' WHERE `id` IN({$update1}) ";

			$db->rawQuery($final_query);

		}

		if (!empty($update2)) {

			$update2 = implode(',', $update2);

			$final_query = "UPDATE " . T_MESSAGES . " set `to_deleted` = '1' WHERE `id` IN({$update2}) ";

			$db->rawQuery($final_query);

		}

		$delete_chats = $db->rawQuery("DELETE FROM " . T_CHATS . " WHERE user_one = {$pt->user->id} AND user_two = $id");

	}

}

?>

Well, not looking at your code, but, logically here is how I would work it out.

First, you have a user ID of some sort. They receive a chat-message. They receive a notice saying they have some sort of messages and should log in to review them.

Next, you have in your database a “last-accessed” date when they logged in the last time. If not, you need to add that into your user database to track when each member has logged in.

Then, you need an extra field that notes they have notifications either chats or messages and when they occurred. That way, when a notice has been sent, you can mark this field it was sent. If the last log-in date is after the notice was sent, you do not send another one. Once the log-in date is updated when the user logs in again, the notice flag or notification field gets set to the log in date and they do not get another email.

So, think out your logic and create the correct fields needed. Then, in the website code add sections if a new chat or message is sent to one user, set the notification field as needed. Should work…

Just logic ideas, not any code ideas… Figure out the logic of the process flow first and then figure out the code. Hope this info helps…

Thanks for your reply.
The ‘users’ table currently has a ‘last_active’ column that has, for example “1533326208” in it.
I had help adding a column, that I thought could be used for this, named 'alerts" in the ‘users’ table, that holds a 0 or 1 (maybe not needed). So, how can I pull all of this together? Any additional guidance will be appreciated.

Well, that last_active column is most likely not formatted correctly as a date or date-time field. I will guess it is a date stored in milliseconds. Hard to deal with it in that format. No easy way. Normally, I would set that field to be a “DATETIME” formatted column. Then, when a user logs in, it saves the date and time in the format of YYYY-MM-DD:HH-SS so that you know the exact date and time of when the login has occurred.

Depending on how complicated the site is, you might want to look for all accesses to the last_active column in all your site and perhaps you can change the formatting of it. You would then have to alter how the date and time is stored in that column and save it correctly.

If your site only uses the last_active field in one place, then we are in luck and can alter the field column to “datetime” format and get this sorted out for you. Look around your files and let us know how that last_active is used currently in your site. Make sense?

Thanks again, I will check into that

Sponsor our Newsletter | Privacy Policy | Terms of Service