STOP !
I found a problem It s not ok. In this case simple user can't see staff response for his notes.
The big select with union must be like this with new column 'row_type':
$sql=
'(SELECT 1 as row_type, msg.msg_id, msg.created, msg.message, count(attach_id) as attachments, concat("Customer (",source,")") as source, "M" as msgtype '.
' FROM '.TICKET_MESSAGE_TABLE.' msg '.
' LEFT JOIN '.TICKET_ATTACHMENT_TABLE.' attach ON msg.ticket_id=attach.ticket_id AND msg.msg_id=attach.ref_id AND ref_type="M" '.
' WHERE msg.ticket_id='.db_input($id).
' GROUP BY msg.msg_id) '.
' UNION '.
' (SELECT 2 as row_type, resp.response_id, resp.created, resp.response, count(attach_id) as attachments, resp.staff_name, "R" FROM '.TICKET_RESPONSE_TABLE.' resp '.
' LEFT JOIN '.TICKET_ATTACHMENT_TABLE.' attach ON resp.ticket_id=attach.ticket_id AND resp.response_id=attach.ref_id AND ref_type="R" '.
' WHERE resp.ticket_id='.db_input($id).
' GROUP BY resp.response_id) '.
' UNION '.
' (SELECT 3 as row_type, note.note_id, note.created, note.note, 0, concat(note.source, " - ", note.title), "N" '.
' FROM '.TICKET_NOTE_TABLE.' note WHERE note.ticket_id='.db_input($id).
' AND note.title NOT IN ("Ticket Updated", "Ticket Marked Overdue") AND note.title NOT LIKE "%Transfer%" ) '.
' ORDER BY created ASC ';
and in while have to check row_type
while ($msg_row = db_fetch_array($msgres)) {
if ($msg_row == 1) {
$msgid = $msg_row;
}