Help with emailing code


#1

I am using a web script that allows Users’ to internally message(chat) one another. I’m trying to add in some code so that a message is sent to the User, by email, notifying him that a message is waiting. I added an email notification at …/emails/message-alert and added some code to this php file (from line 54 to 69), but upon testing, by sending an internal message (chat) to another User, no email arrives to the ‘another’ User’s email address. Can you check what I’ve added and provide some suggestions or solution? Much thanks.

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

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
					))
);
if ($pt->config->validation == 'on') {
				$link = $email_code . '/' . $email;
				$data['EMAIL_CODE'] = $link;
				$data['USERNAME'] = $username;
				$send_email_data = array(
				'from_email' => $pt->config->email,
				'from_name' => $pt->config->name,
				'to_email' => $pt->config->user_two,
				'to_name' => $username,
				'subject' => 'Message Waiting',
				'charSet' => 'UTF-8',
				'message_body' => PT_LoadPage('emails/message-alert', $data),
				'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");
	}
}
?>

#2

Aside from whatever your problem is, you need to use Prepared Statements. Also,

if (IS_LOGGED == false)

is redundant and improperly written. The if already checks for true/false. It should be written as,

if (!IS_LOGGED)

All the code depends on the value of $first yet I do not see it defined anywhere. Where does this variable come from?


#3

HUH??? We have no idea what those line numbers mean…
AND, you show code for adding, deleting chats, nothing about your problem.
What do you mean by: I added an email notification at …/emails/message-alert
we can not see that file… We only see what you list here…

So, show the part where the process is failing and we might be able to help you!


#4

Thanks for your replies.
Regarding line 52, etc. that line is:
if ($pt->config->validation == 'on') {

Please disregard " I added an email notification at …/emails/message-alert", it’s probably irrelevant to my posting, at this point.

This part isn’t working:
if ($pt->config->validation == ‘on’) {
$link = $email_code . ‘/’ . $email;
$data[‘EMAIL_CODE’] = $link;
$data[‘USERNAME’] = $username;
$send_email_data = array(
‘from_email’ => $pt->config->email,
‘from_name’ => $pt->config->name,
‘to_email’ => $pt->config->user_two,
‘to_name’ => $username,
‘subject’ => ‘Message Waiting’,
‘charSet’ => ‘UTF-8’,
‘message_body’ => PT_LoadPage(‘emails/message-alert’, $data),
‘is_html’ => true
);
$send_message = PT_SendMessage($send_email_data);

Regarding “Where does this variable come from?”. This may help:

<div class="page-margin pt_shadow">
    <div class="row">
        <div class="col-md-4 mobilerightpane no-padding-right">
            {{SIDEBAR}}
        </div>
        <div class="col-md-8 mobileleftpane no-padding-left">
			<ul class="pt_msg_main">
				<div class="settings-header pt_msg_header">
					<h3 class="pull-left"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-chevron-left mobilemsgclose"><polyline points="15 18 9 12 15 6"></polyline></svg> <?php echo (!empty($pt->chat_user->name)) ? "<a style='color: #fff;' href='" . $pt->chat_user->url . "'>" . $pt->chat_user->name . "</a>" : "<a style='color: #fff;' class='user-link'></a>";?></h3>
					<?php echo (!empty($pt->chat_user->name)) ? '<div class="pull-right" id="delete-conversation"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-trash"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg></div>' : '';?>
					<div class="clear"></div>
				</div>
				<button id="load-more-messages" title="Load more messages"><i class="fa fa-angle-up"></i></button>
				<div class="pt_msg_joint">
					<div class="user-messages user-setting-panel pt_msg_area">
						{{HTML}}
					</div>
					<div class="user-send-message">
						<form action="#" method="POST" id="new-message-form">
							<textarea name="new-message" id="new-message" cols="30" rows="2" placeholder="{{LANG write_message}}"></textarea>
							<button type="submit" id="send-button"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-right"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg></button>
							<input type="hidden" id="user-id" name="id" value="<?php echo $pt->chat_id; ?>">
							<input type="hidden" id="user-avatar" value="<?php echo ($pt->chat_user->avatar) ? $pt->chat_user->avatar : "";?>">
						</form>
					</div>
				</div>
			</ul>
        </div>
        <div class="clear"></div>
	</div>
</div>
<br>
<script>
$('.mobilemsgclose').on('click',function (){
	$('.mobileleftpane').fadeOut(100);
	$('.mobilerightpane').fadeIn(100);
});

var messagesInterval = <?php echo (!empty($pt->extra_config->ajax_message_update_interval)) ? $pt->extra_config->ajax_message_update_interval : 3000 ?>;
function fetchMessages() {
    $.post('{{LINK aj/messages/fetch}}', {id: $('#user-id').val(), last_id: $('.message:last').attr('data-id')}, function(data, textStatus, xhr) {
        if (data.status == 200) {
            if (data.message.length > 0) {
                $('.messages').append(data.message);
                 $('.user-messages').scrollTop($('.user-messages')[0].scrollHeight);
            }
            if ($('#search-list').val() == 0) {
                $('.messages-sidebar .list-group').html(data.users);
            }
        }
        setTimeout(function () {
            fetchMessages();
        }, messagesInterval);
    });
}
$(document).on('click', '.messages-sidebar a', function(event) {
    clearTimeout(messagesInterval);
    /* Act on the event */
});
$(document).on('click', '#load-more-messages', function(event) {
  event.preventDefault();
  $('#load-more-messages i').removeClass('fa-angle-up');
  $('#load-more-messages i').addClass('fa-spinner fa-spin');
  $.post('{{LINK aj/messages/fetch}}', {id: $('#user-id').val(), first_id: $('.message:first').attr('data-id')}, function(data, textStatus, xhr) {
        $('#load-more-messages i').removeClass('fa-spinner fa-spin');
        $('#load-more-messages i').addClass('fa-angle-up');
        if (data.status == 200) {
            if (data.message.length > 0) {
                $('.messages').prepend(data.message);
            } else {
                $('#load-more-messages').animate({
                    top: "-50",
                }, 200, function() {
                    $('#load-more-messages').hide();
                    $('#load-more-messages').css('top', '60px');
                });
            }
            $('.user-messages').scrollTop(0);
        }
        $('#load-more-messages i').removeClass('fa-spinner fa-spin');
        $('#load-more-messages i').addClass('fa-angle-up');
    });
});

$(document).on('click', '#delete-conversation', function(event) {
    if (!confirm("{{LANG are_you_sure_you_want_delete_chat}}")) {
        return false;
    }
    $(this).find('i').toggleClass('fa-trash fa-spinner fa-spin');
    $.post('{{LINK aj/messages/delete_chat}}', {id: $('#user-id').val()}, function(data, textStatus, xhr) {
        $('#delete-conversation').find('i').removeClass('fa-spinner fa-spin');
        $('#delete-conversation').find('i').addClass('fa-trash');
        $('.messages').empty();
    });
});

$(function() {
        setTimeout(function () {
            fetchMessages();
        }, messagesInterval);
        $('.user-messages').scrollTop($('.user-messages')[0].scrollHeight);
        var $id = makeid();
    	var form = $('form#new-message-form');

        $('#search-list').on('keyup', function(event) {
            $('#search-icon').toggleClass('fa-search fa-spinner fa-spin');
            $.post('{{LINK aj/messages/search}}', {keyword: $(this).val()}, function(data, textStatus, xhr) {
                $('#search-icon').toggleClass('fa-spinner fa-spin fa-search ');
                if (data.status == 200) {
                    $('.messages-sidebar .list-group').html(data.users);
                }
            });
        });

    	$('#new-message').on('keyup', function(event) {
    		if (event.keyCode == 13 && !event.shiftKey) {
                $id = makeid();
                if ($(this).val().length > 1) {
                    form.submit();
                } else {
                    $('#new-message').val('');
                }
    		}
    	});

        form.ajaxForm({
            url: '{{LINK aj/messages/new}}?hash=' + $('.main_session').val(),
            data: {message_id: $('#message_id').val()},
            beforeSubmit: function(formData, jqForm, options) {
                if ($('.messages').length == 0) {
                    $('.user-messages').html('<div class="messages"></div>');
                }
                if ($('#new-message').val().length >= 1) {
                    formData.push({ name: 'message_id', value: $id });
                    $('.messages').append('<div class="data_message" data-id="' + $id + '"><div class="message to-user pull-right" data-id=""><div class="user-message">' + nl2br(escapeHTML($('#new-message').val())) + '</div><div class="clear"></div></div><div class="clear"></div></div>');
                    $('#new-message').val('');
                    $('.user-messages').scrollTop($('.user-messages')[0].scrollHeight);
                    $id = makeid();
                } else {
                    $('#new-message').val('');
                } 
            },
            success: function(data) {
                $('.data_message[data-id="' + data.message_id + '"]').html(data.message);
            }
        });
    });
</script>

Any help will be appreciated.


#5

Well, you check for a value.

if ($pt->config->validation == ‘on’) {
$link = $email_code . ‘/’ . $email;
… Load other varialbes…
);
$send_message = PT_SendMessage($send_email_data);

There is no ending bracket } on this code…
Also, have you debugged it to see if the value inside variable named $pt->config-validation is actually equal to “on”? You should display that value on the page somewhere and check if it is really on or something else.


#6

Thanks for your reply. Much appreciated. The code now looks like this:

if ($pt->config->validation == ‘on’) {
$link = $email_code . ‘/’ . $email;
$data[‘EMAIL_CODE’] = $link;
$data[‘USERNAME’] = $username;
$send_email_data = array(
‘from_email’ => $pt->config->email,
‘from_name’ => $pt->config->name,
‘to_email’ => $pt->config->user_two,
‘to_name’ => $username,
‘subject’ => ‘Message Waiting’,
‘charSet’ => ‘UTF-8’,
‘message_body’ => PT_LoadPage(‘emails/message-alert’, $data),
‘is_html’ => true
);
$send_message = PT_SendMessage($send_email_data);
}
}
}
}
}

I think that’s improved?
No, I have not “debugged it to see…”. Could you please tell me how/here to do that, please?
I look forward to any additional assistance. Thanks again.


#7

You only need one ending bracket. so, the first one on the IF (…) { and one at the end of the IF clause }

Well, you can either set up a conditional IF statement or just have it echo the value of the variable.
So, just before the IF statement have it echo $pt->config->validation; and it should display the value.
Or, change the IF statement to contain a second part. Loosely, like this:
IF ($pt->config->validation==“on”) {
…do all the rest you showed…
} else {
echo “Validation is not on…”;
}
this would email if the validation is on, but, display something if it is not on. My guess is that your condition in the if-clause is not being met. Therefore, the IF never does anything and no email is sent out…


#8

Thanks for your reply. Greatly appreciated.
I think you logic is sound: “your condition in the if-clause is not being met. Therefore, the IF never does anything and no email is sent out…” So, I added the echo, I think, correctly, (below). However no echoed statement appeared. Any additional suggestions/solutions will be welcomed.

			    if ($pt->config->validation == 'on') {
				$link = $email_code . '/' . $email;
				$data['EMAIL_CODE'] = $link;
				$data['USERNAME'] = $username;
				$send_email_data = array(
				'from_email' => $pt->config->email,
				'from_name' => $pt->config->name,
				'to_email' => $pt->config->user_two,
				'to_name' => $username,
				'subject' => 'Message Waiting',
				'charSet' => 'UTF-8',
				'message_body' => PT_LoadPage('emails/message-alert', $data),
				'is_html' => true
				);
				$send_message = PT_SendMessage($send_email_data);
				} else {
				echo "Validation is not on";
				}
			}
		}
	}
}

#9

Well, it is hard to guess at this. Perhaps the code before the snippet you showed us is failing to let the process get to this point. So, you need to test this code and debug it’s flow to see if it even gets down to the point where it checks the validation setting. You can place some DIE() functions along the code and see where it is failing to get to the email section. Just place a die(“got here…”); line above the validation==‘on’ line and see if the process dies and displays the got-here message. If it does not, then a previous line is causing it to fail. Then, move the die() line up higher until you locate where it shows up. Then, debug the lines from there down to see where you code fails. If you get no email and get no validation not on message, then it is failing higher up in your code. It could also be in your mail function you set up. (PT_SendMessage(); ) which might be not working correctly.


#10

Thanks so much again for your effort to help me. Much appreciated.
I tried what you suggested without success.
Maybe this file is where the emailing code needs to be?

<div class="page-margin pt_shadow">
    <div class="row">
        <div class="col-md-4 mobilerightpane no-padding-right">
            {{SIDEBAR}}
        </div>
        <div class="col-md-8 mobileleftpane no-padding-left">
			<ul class="pt_msg_main">
				<div class="settings-header pt_msg_header">
					<h3 class="pull-left"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-chevron-left mobilemsgclose"><polyline points="15 18 9 12 15 6"></polyline></svg> <?php echo (!empty($pt->chat_user->name)) ? "<a style='color: #fff;' href='" . $pt->chat_user->url . "'>" . $pt->chat_user->name . "</a>" : "<a style='color: #fff;' class='user-link'></a>";?></h3>
					<?php echo (!empty($pt->chat_user->name)) ? '<div class="pull-right" id="delete-conversation"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-trash"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg></div>' : '';?>
					<div class="clear"></div>
				</div>
				<button id="load-more-messages" title="Load more messages"><i class="fa fa-angle-up"></i></button>
				<div class="pt_msg_joint">
					<div class="user-messages user-setting-panel pt_msg_area">
						{{HTML}}
					</div>
					<div class="user-send-message">
						<form action="#" method="POST" id="new-message-form">
							<textarea name="new-message" id="new-message" cols="30" rows="2" placeholder="{{LANG write_message}}"></textarea>
							<button type="submit" id="send-button"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-right"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg></button>
							<input type="hidden" id="user-id" name="id" value="<?php echo $pt->chat_id; ?>">
							<input type="hidden" id="user-avatar" value="<?php echo ($pt->chat_user->avatar) ? $pt->chat_user->avatar : "";?>">
						</form>
					</div>
				</div>
			</ul>
        </div>
        <div class="clear"></div>
	</div>
</div>
<br>
<script>
$('.mobilemsgclose').on('click',function (){
	$('.mobileleftpane').fadeOut(100);
	$('.mobilerightpane').fadeIn(100);
});

var messagesInterval = <?php echo (!empty($pt->extra_config->ajax_message_update_interval)) ? $pt->extra_config->ajax_message_update_interval : 3000 ?>;
function fetchMessages() {
    $.post('{{LINK aj/messages/fetch}}', {id: $('#user-id').val(), last_id: $('.message:last').attr('data-id')}, function(data, textStatus, xhr) {
        if (data.status == 200) {
            if (data.message.length > 0) {
                $('.messages').append(data.message);
                 $('.user-messages').scrollTop($('.user-messages')[0].scrollHeight);
            }
            if ($('#search-list').val() == 0) {
                $('.messages-sidebar .list-group').html(data.users);
            }
        }
        setTimeout(function () {
            fetchMessages();
        }, messagesInterval);
    });
}
$(document).on('click', '.messages-sidebar a', function(event) {
    clearTimeout(messagesInterval);
    /* Act on the event */
});
$(document).on('click', '#load-more-messages', function(event) {
  event.preventDefault();
  $('#load-more-messages i').removeClass('fa-angle-up');
  $('#load-more-messages i').addClass('fa-spinner fa-spin');
  $.post('{{LINK aj/messages/fetch}}', {id: $('#user-id').val(), first_id: $('.message:first').attr('data-id')}, function(data, textStatus, xhr) {
        $('#load-more-messages i').removeClass('fa-spinner fa-spin');
        $('#load-more-messages i').addClass('fa-angle-up');
        if (data.status == 200) {
            if (data.message.length > 0) {
                $('.messages').prepend(data.message);
            } else {
                $('#load-more-messages').animate({
                    top: "-50",
                }, 200, function() {
                    $('#load-more-messages').hide();
                    $('#load-more-messages').css('top', '60px');
                });
            }
            $('.user-messages').scrollTop(0);
        }
        $('#load-more-messages i').removeClass('fa-spinner fa-spin');
        $('#load-more-messages i').addClass('fa-angle-up');
    });
});

$(document).on('click', '#delete-conversation', function(event) {
    if (!confirm("{{LANG are_you_sure_you_want_delete_chat}}")) {
        return false;
    }
    $(this).find('i').toggleClass('fa-trash fa-spinner fa-spin');
    $.post('{{LINK aj/messages/delete_chat}}', {id: $('#user-id').val()}, function(data, textStatus, xhr) {
        $('#delete-conversation').find('i').removeClass('fa-spinner fa-spin');
        $('#delete-conversation').find('i').addClass('fa-trash');
        $('.messages').empty();
    });
});

$(function() {
        setTimeout(function () {
            fetchMessages();
        }, messagesInterval);
        $('.user-messages').scrollTop($('.user-messages')[0].scrollHeight);
        var $id = makeid();
    	var form = $('form#new-message-form');

        $('#search-list').on('keyup', function(event) {
            $('#search-icon').toggleClass('fa-search fa-spinner fa-spin');
            $.post('{{LINK aj/messages/search}}', {keyword: $(this).val()}, function(data, textStatus, xhr) {
                $('#search-icon').toggleClass('fa-spinner fa-spin fa-search ');
                if (data.status == 200) {
                    $('.messages-sidebar .list-group').html('HAMZA');
                }
            });
        });

    	$('#new-message').on('keyup', function(event) {
    		if (event.keyCode == 13 && !event.shiftKey) {
                $id = makeid();
                if ($(this).val().length > 1) {
                    form.submit();
                } else {
                    $('#new-message').val('');
                }
    		}
    	});

        form.ajaxForm({
            url: '{{LINK aj/messages/new}}?hash=' + $('.main_session').val(),
            data: {message_id: $('#message_id').val()},
            beforeSubmit: function(formData, jqForm, options) {
                if ($('.messages').length == 0) {
                    $('.user-messages').html('<div class="messages"></div>');
                }
                if ($('#new-message').val().length >= 1) {
                    formData.push({ name: 'message_id', value: $id });
                    $('.messages').append('<div class="data_message" data-id="' + $id + '"><div class="message to-user pull-right" data-id=""><div class="user-message">' + nl2br(escapeHTML($('#new-message').val())) + '</div><div class="clear"></div></div><div class="clear"></div></div>');
                    $('#new-message').val('');
                    $('.user-messages').scrollTop($('.user-messages')[0].scrollHeight);
                    $id = makeid();
                } else {
                    $('#new-message').val('');
                } 
            },
            success: function(data) {
                $('.data_message[data-id="' + data.message_id + '"]').html(data.message);
            }
        });
    });
</script>

#11

The “emailing code” is the post before where you showed us the PHP code.
But, I see several places in this last post like {{HTML}} which means you are using a template of some sort.
In the above code, the section starting with <div class="user-send-message"> is where the message is posted. Then, the PHP takes over. You showed us part of the PHP code where it builds the email to send.
In that section, you need to figure out why it is not getting down to the validation section. If you are not getting the email, one of two things are happening. Either you are building an invalid email and it is not being sent because the code fails, or the code is never getting to the part where it builds and sends the email.

To really debug this, we would need to see more of the PHP code. In other words, you posted that code before this current post. But, it starts at if ($pt->config->validation == 'on') { and something before that is most likely causing your code NOT to get to that point. You need to debug step by step the sections above that to see where it is failing. Post more code Or zip it all up and send it to me in a private message so I can see more of the code. (I am heading out on a fishing trip for a few days and will not get back to this again until Monday…


#12

Thanks again SO much for your message. I had copied (from the registration file) the
if ($pt->config->validation == 'on')
from this file (line 111), and added it to the messages.php file, that I showed in my initial posting. Maybe I should have copied more from registration file (below) to add before if ($pt…etc ?

<?php
if (IS_LOGGED == true || $pt->config->user_registration != 'on') {
    header("Location: " . PT_Link(''));
    exit();
}

$color1      = '2ec0bc';
$color2      = '8ef9f6';
$errors      = array();
$erros_final = '';
$username    = '';
$email       = '';
$success     = '';
$recaptcha   = '<div class="g-recaptcha" data-sitekey="' . $pt->config->recaptcha_key . '"></div>';
$pt->custom_fields = $db->where('registration_page','1')->get(T_FIELDS);
$field_data        = array();
if ($pt->config->recaptcha != 'on') {
    $recaptcha = '';
}
if (!empty($_POST)) {
    if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['email']) || empty($_POST['c_password']) || empty($_POST['gender'])) {
        $errors[] = $lang->please_check_details;
    } else {
        $username        = PT_Secure($_POST['username']);
        $password        = PT_Secure($_POST['password']);
        $c_password      = PT_Secure($_POST['c_password']);
        $password_hashed = sha1($password);
        $email           = PT_Secure($_POST['email']);
        $gender          = PT_Secure($_POST['gender']);
        if ($gender != 'female' && $gender != 'male') {
            $errors[] = $lang->gender_is_invalid;
        }
        if (PT_UsernameExists($_POST['username'])) {
            $errors[] = $lang->username_is_taken;
        }
        if (strlen($_POST['username']) < 4 || strlen($_POST['username']) > 32) {
            $errors[] = $lang->username_characters_length;
        }
        if (!preg_match('/^[\w]+$/', $_POST['username'])) {
            $errors[] = $lang->username_invalid_characters;
        }
        if (PT_UserEmailExists($_POST['email'])) {
            $errors[] = $lang->email_exists;
        }
        if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            $errors[] = $lang->email_invalid_characters;
        }
        if ($password != $c_password) {
            $errors[] = $lang->password_not_match;
        }
        if (strlen($password) < 4) {
            $errors[] = $lang->password_is_short;
        }
        if ($pt->config->recaptcha == 'on') {
            if (!isset($_POST['g-recaptcha-response']) || empty($_POST['g-recaptcha-response'])) {
                $errors[] = $lang->reCaptcha_error;
            }
        }

        if (empty($_POST['terms'])) {
            $errors[] = $lang->terms_accept;
        } elseif ($_POST['terms'] != 'on') {
            $errors[] = $lang->terms_accept;
        }
        

        if (!empty($pt->custom_fields) && count($pt->custom_fields) > 0) {
            foreach ($pt->custom_fields as $field) {
                $field_id   = $field->id;
                $field->fid = "fid_$field_id";

                if (!empty($_POST[$field->fid])) {
                    $name = $field->fid;
                    if (!empty($_POST[$name])) {
                        $field_data[] = array(
                            $name => $_POST[$name]
                        );
                    }
                }
            }
        }


        $active = ($pt->config->validation == 'on') ? 0 : 1;
        if (empty($errors)) {
            $email_code = sha1(time() + rand(111,999));
            $insert_data = array(
                'username' => $username,
                'password' => $password_hashed,
                'email' => $email,
                'ip_address' => get_ip_address(),
                'gender' => $gender,
                'active' => $active,
                'email_code' => $email_code,
                'last_active' => time(),
                'registered' => date('Y') . '/' . intval(date('m'))
            );
            $insert_data['language'] = $pt->config->language;
            if (!empty($_SESSION['lang'])) {
                if (in_array($_SESSION['lang'], $langs)) {
                    $insert_data['language'] = $_SESSION['lang'];
                }
            }
            $user_id             = $db->insert(T_USERS, $insert_data);
            if (!empty($user_id)) {
                if (!empty($field_data)) {
                    PT_UpdateUserCustomData($user_id,$field_data,false);
                }


                if ($pt->config->validation == 'on') {
                     $link = $email_code . '/' . $email; 
                     $data['EMAIL_CODE'] = $link;
                     $data['USERNAME']   = $username;
                     $send_email_data = array(
                        'from_email' => $pt->config->email,
                        'from_name' => $pt->config->name,
                        'to_email' => $email,
                        'to_name' => $username,
                        'subject' => 'Confirm your account',
                        'charSet' => 'UTF-8',
                        'message_body' => PT_LoadPage('emails/confirm-account', $data),
                        'is_html' => true
                    );
                    $send_message = PT_SendMessage($send_email_data);
                    $success = $success_icon . $lang->successfully_joined_desc;
                } 

                else {
                    $session_id          = sha1(rand(11111, 99999)) . time() . md5(microtime());
                    $insert_data         = array(
                        'user_id' => $user_id,
                        'session_id' => $session_id,
                        'time' => time()
                    );
                    $insert              = $db->insert(T_SESSIONS, $insert_data);
                    $_SESSION['user_id'] = $session_id;
                    setcookie("user_id", $session_id, time() + (10 * 365 * 24 * 60 * 60), "/");
                    $pt->loggedin = true;
                    header("Location: $site_url");
                    exit();
                }
            }
        }
    }
}
$pt->page          = 'login';
$pt->title         = $lang->register . ' | ' . $pt->config->title;
$pt->description   = $pt->config->description;
$pt->keyword       = $pt->config->keyword;
$custom_fields     = "";
if (!empty($errors)) {
    foreach ($errors as $key => $error) {
        $erros_final .= $error_icon . $error . "<br>";
    }
}
if (!empty($pt->custom_fields)) {
    foreach ($pt->custom_fields as $field) {
        $field_id       = $field->id;
        $fid            = "fid_$field_id";
        $pt->filed      = $field;
        $custom_fields .= PT_LoadPage('auth/register/custom-fields',array(
            'NAME'      => $field->name,
            'FID'       => $fid
        ));
    }
}

$pt->content     = PT_LoadPage('auth/register/content', array(
    'COLOR1' => $color1,
    'COLOR2' => $color2,
    'ERRORS' => $erros_final,
    'USERNAME' => $username,
    'EMAIL' => $email,
    'SUCCESS' => $success,
    'RECAPTCHA' => $recaptcha,
    'CUSTOM_FIELDS' => $custom_fields
));

#13

Well, the code: if(!empty($_POST)) { is the part where the code starts once the user presses the button.
Your button has the type=‘submit’ which forces it to restart the page and in that process handle the PHP code.

Therefore, you can test each part step by step from there down. Place a die(“some-message”) right after this line. Then test it and see if it shows that message. If it does not, something is wrong in how you created the button or the form set up. If it shows the message, then move the line down further and test the next section. In this, well tedious, method, you should be able to trace down thru the code and figure out where it is failing. Give it a try and see if you can figure out where it is in error.

Also, I put the code into my editor (Netbeans) and it did not throw out any errors, so it must be a logic problem.


#14

Thanks for your reply. I greatly appreciate your reply, but I may be confusing things. The code above is from a working registration file, that doesn’t need to be de-bugged


#15

Running out of time as I am packing for a trip early in the morning.

I must not understand what you are asking for. If you want to add another email to notify someone once an email is sent, just create a second version and place it right after the first one is sent out. Is that what you are talking about? Guess we are both confused… Sorry for that!


#16

I have gotten additional help and have solved this issue. Thanks for your kind help, have a great trip


#17

Glad you have solved it!