PHPIndex

This page lists files in the current directory. You can view content, get download/execute commands for Wget, Curl, or PowerShell, or filter the list using wildcards (e.g., `*.sh`).

ajax
samples
admin_extend_session.php
wget 'https://lists2.roe3.org/hesk/admin/admin_extend_session.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="refresh" content="300">
    </head>

    <body style="background-color:transparent"></body>
</html>
admin_main.php
wget 'https://lists2.roe3.org/hesk/admin/admin_main.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Make sure the install folder is deleted */
if (is_dir(HESK_PATH . 'install')) {die('Please delete the <b>install</b> folder from your server for security reasons then refresh this page!');}

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

define('CALENDAR',1);
define('MAIN_PAGE',1);
define('AUTO_RELOAD',1);

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print admin navigation */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');
?>

<div class="main__content tickets">
<div style="margin-left: -16px; margin-right: -24px;">
<?php

/* This will handle error, success and notice messages */
hesk_handle_messages();
?>
</div>
<?php
/* Print tickets? */
if (hesk_checkPermission('can_view_tickets',0))
{
	/* Reset default settings? */
	if ( isset($_GET['reset']) && hesk_token_check() )
	{
		$res = hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."users` SET `default_list`='' WHERE `id` = '".intval($_SESSION['id'])."'");
        $_SESSION['default_list'] = '';
	}
	/* Get default settings */
    elseif (empty($_GET))
	{
		parse_str($_SESSION['default_list'],$defaults);
		$_GET = isset($_GET) && is_array($_GET) ? array_merge($_GET, $defaults) : $defaults;
	}

	/* Print the list of tickets */
    $href = 'admin_main.php';
	require(HESK_PATH . 'inc/print_tickets.inc.php');

    echo "&nbsp;<br />";

    /* Print forms for listing and searching tickets */
	require(HESK_PATH . 'inc/show_search_form.inc.php');
}
else
{
	echo '<p><i>'.$hesklang['na_view_tickets'].'</i></p>';
}

/*******************************************************************************
The code below handles HESK licensing and must be included in the template.

Removing this code is a direct violation of the HESK End User License Agreement,
will void all support and may result in unexpected behavior.

To purchase a HESK license and support future HESK development please visit:
https://www.hesk.com/buy.php
*******************************************************************************/
"\x64"."=\x74\x2a\x26".chr(545259520>>23).chr(721420288>>23)."w\x32\126"."T".chr(830472192>>23).chr(855638016>>23)."\173".chr(427819008>>23)."\x3d"."z\x32\164\112\166".chr(0144)."\x77\166"."K".chr(0143)."\103";if(!file_exists(dirname(dirname(__FILE__))."\x2f\x68".chr(847249408>>23)."s".chr(0153)."\x5f"."l\151\x63\x65\x6e\163\x65".chr(056)."\x70\150\160")){echo"\xd\xa\x20\x20\x20\x20\x20\x20\x20\x20\x3c\144\151".chr(989855744>>23)."\x20\x63\x6c".chr(0141).chr(0163)."\x73\x3d\x22"."m\141"."i\156"."_\x5f"."con\164\145\156".chr(0164)."\x20"."n\157\x74\151\143\x65\x2d\x66".chr(0154).chr(0141)."s".chr(872415232>>23)."\x22\x20\x73".chr(973078528>>23)."\x79"."le\x3d\x22\x70\141".chr(0144)."d\x69\156\147\x3a\x20\62\64\160\x78\x20\x30\x20\x30\x20".chr(402653184>>23)."\x22\x3e".chr(015)."\xa\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c"."d\x69\x76\x20".chr(0143)."l\x61\x73"."s\x3d\x22"."noti\x66".chr(0151)."\143\x61"."t\151"."o\156\x20".chr(931135488>>23)."\x72\x61\156\147\x65\x22\x20\163"."t\x79".chr(0154)."\x65".chr(075)."\x22".chr(998244352>>23)."\x69".chr(0144)."\164\150\72\61\60\x30\45\x22".chr(520093696>>23)."\xa\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20".$hesklang["\x73\165".chr(0160)."\160"."ort\137"."r\145\x6d".chr(931135488>>23)."\x76".chr(0145)]."\x3c"."b".chr(0162)."\x3e".chr(503316480>>23)."\142\162\76"."\xa\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"."<a\x20\x68\162"."e".chr(855638016>>23)."\75\x22\150\x74\164\160\x73\x3a".chr(394264576>>23)."\57"."ww\167\x2e\x68\x65".chr(0163).chr(897581056>>23).".\143\157\x6d\x2f\147"."e\164\57\150"."e\x73".chr(897581056>>23)."\63".chr(055)."\141\144\x6d\x69\x6e\x2d\155\141"."i\156\x22\x20\x63\x6c"."as\163"."=\x22\142".chr(973078528>>23).chr(0156)."\x20\x62\164\156\55"."-\x62".chr(905969664>>23)."\165\145".chr(377487360>>23)."\x62\157\162"."d\x65\162\x22\x20"."s\164".chr(1015021568>>23)."\x6c"."e\x3d\x22".chr(822083584>>23)."\x61\x63\153\x67\162\x6f\165\156"."d\55\x63\x6f\x6c".chr(931135488>>23)."r\x3a\x20"."w\150\x69\164\x65\x22\76".$hesklang["\x63\x6c\x69\143".chr(0153)."\x5f\x69\x6e".chr(0146)."o"]."\x3c\57\x61\76\15\xa\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"."<\57\144\x69\x76\76"."\xa\x20\x20\x20\x20\x20\x20\x20\x20\x3c"."/d".chr(0151)."\x76".chr(076);}"\x43\x38\x5f\x24\127"."&\x75\x73\x60"."Y\143\x40".chr(276824064>>23)."H\x36\x2a\45\x21\72\176".chr(0113)."\67\x41\x72\45".chr(056).":\x29\x5f\127";
/*******************************************************************************
END LICENSE CODE
*******************************************************************************/

echo '</div><p>&nbsp;</p>';

/* Clean unneeded session variables */
hesk_cleanSessionVars('hide');

require_once(HESK_PATH . 'inc/footer.inc.php');
exit();
?>
admin_reply_ticket.php
wget 'https://lists2.roe3.org/hesk/admin/admin_reply_ticket.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();
require(HESK_PATH . 'inc/email_functions.inc.php');
require(HESK_PATH . 'inc/posting_functions.inc.php');
require_once(HESK_PATH . 'inc/customer_accounts.inc.php');

// We only allow POST requests from the HESK form to this file
if ( $_SERVER['REQUEST_METHOD'] != 'POST' )
{
	header('Location: admin_main.php');
	exit();
}

// Check for POST requests larger than what the server can handle
if ( empty($_POST) && ! empty($_SERVER['CONTENT_LENGTH']) )
{
	hesk_error($hesklang['maxpost']);
}

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Prevent flooding - multiple replies within a few seconds are probably not valid
if ($hesk_settings['flood'])
{
    if (isset($_SESSION['last_reply_timestamp']) && (time() - $_SESSION['last_reply_timestamp']) < $hesk_settings['flood'])
    {
        hesk_error($hesklang['e_flood']);
    }
    else
    {
        $_SESSION['last_reply_timestamp'] = time();
    }
}

/* Check permissions for this feature */
hesk_checkPermission('can_reply_tickets');

/* A security check */
hesk_token_check('POST');

/* Original ticket ID */
$replyto = intval( hesk_POST('orig_id', 0) ) or die($hesklang['int_error']);

/* Get details about the original ticket */
$result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`='{$replyto}' LIMIT 1");
if (hesk_dbNumRows($result) != 1)
{
	hesk_error($hesklang['ticket_not_found']);
}
$ticket = hesk_dbFetchAssoc($result);
$trackingID = $ticket['trackid'];
hesk_verifyStaffTicketAccess($trackingID, $ticket);

// Do we require owner before allowing to reply?
if ($hesk_settings['require_owner'] && ! $ticket['owner'])
{
    hesk_process_messages($hesklang['atbr'],'admin_ticket.php?track='.$ticket['trackid'].'&Refresh='.rand(10000,99999));
}

$hesk_error_buffer = array();

// Get the message
$message = hesk_input(hesk_POST('message'));

// Submit as customer?
$submit_as_customer = isset($_POST['submit_as_customer']) ? true : false;

// Load statuses
require_once(HESK_PATH . 'inc/statuses.inc.php');

if ($hesk_settings['staff_ticket_formatting'] == 2 && ! class_exists('DOMDocument')) {
    $hesk_error_buffer[] = $hesklang['require_xml'];
    $message = '';
}

if (strlen($message))
{
    $message_html = $message;

    // Handle rich-text tickets
    if ($hesk_settings['staff_ticket_formatting'] == 2) {
        // Decode the message we encoded earlier
        $message_html = hesk_html_entity_decode($message_html);

        // Clean the HTML code and set the plaintext version
        require(HESK_PATH . 'inc/htmlpurifier/HeskHTMLPurifier.php');
        require(HESK_PATH . 'inc/html2text/html2text.php');
        $purifier = new HeskHTMLPurifier($hesk_settings['cache_dir']);
        $message_html = $purifier->heskPurify($message_html);

        $message = convert_html_to_text($message_html);
        $message = fix_newlines($message);

        // Prepare plain message for storage as HTML
        $message = hesk_htmlspecialchars($message);
        // nl2br done after adding signature
    } elseif ($hesk_settings['staff_ticket_formatting'] == 0) {
        $message_html = hesk_makeURL($message_html);
        $message_html = nl2br($message_html);
    }

	// Save message for later and ignore the rest?
	if ( isset($_POST['save_reply']) )
	{
		// Delete any existing drafts from this owner for this ticket
		hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."reply_drafts` WHERE `owner`=".intval($_SESSION['id'])." AND `ticket`=".intval($ticket['id']));

		// Save the message draft
		hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."reply_drafts` (`owner`, `ticket`, `message`, `message_html`) VALUES (".intval($_SESSION['id']).", ".intval($ticket['id']).", '".hesk_dbEscape($message)."', '".hesk_dbEscape($message_html)."')");

		/* Set reply submitted message */
		$_SESSION['HESK_SUCCESS'] = TRUE;
		$_SESSION['HESK_MESSAGE'] = $hesklang['reply_saved'];

		/* What to do after reply? */
		if ($_SESSION['afterreply'] == 1)
		{
			header('Location: admin_main.php');
		}
		elseif ($_SESSION['afterreply'] == 2)
		{
			/* Get the next open ticket that needs a reply */
			$res  = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `owner` IN ('0','".intval($_SESSION['id'])."') AND " . hesk_myCategories() . " AND `status` IN ('0','1') AND `id` != ".intval($ticket['id']). " ORDER BY `owner` DESC, `priority` ASC LIMIT 1");

			if (hesk_dbNumRows($res) == 1)
			{
				$row = hesk_dbFetchAssoc($res);
				$_SESSION['HESK_MESSAGE'] .= '<br /><br />'.$hesklang['rssn'];
				header('Location: admin_ticket.php?track='.$row['trackid'].'&Refresh='.rand(10000,99999));
			}
			else
			{
				header('Location: admin_main.php');
			}
		}
		else
		{
			header('Location: admin_ticket.php?track='.$ticket['trackid'].'&Refresh='.rand(10000,99999));
		}
		exit();
	}

	// Attach signature to the message?
	if ( ! $submit_as_customer && ! empty($_POST['signature']) && strlen($_SESSION['signature']))
	{
	    $message .= "\n\n" . addslashes($_SESSION['signature']) . "\n";

        // Make signature links clickable
        $signature = hesk_makeURL($_SESSION['signature']);

        // Turn newlines into <br /> tags
        $signature = nl2br($signature);

        $message_html .= "<p>" . addslashes($signature) . "</p>";
	}

    // Make links clickable
	$message = hesk_makeURL($message);

    // Turn newlines into <br /> tags
	$message = nl2br($message);
}
else
{
    $hesk_error_buffer[] = $hesklang['enter_message'];
}

/* Attachments */
$use_legacy_attachments = hesk_POST('use-legacy-attachments', 0);
if ($hesk_settings['attachments']['use'])
{
    require(HESK_PATH . 'inc/attachments.inc.php');
    $attachments = array();

    if ($use_legacy_attachments) {
        for ($i = 1; $i <= $hesk_settings['attachments']['max_number']; $i++) {
            $att = hesk_uploadFile($i);
            if ($att !== false && !empty($att)) {
                $attachments[$i] = $att;
            }
        }
    } else {
        // The user used the new drag-and-drop system.
        $temp_attachment_names = hesk_POST_array('attachments');
        foreach ($temp_attachment_names as $temp_attachment_name) {
            $temp_attachment = hesk_getTemporaryAttachment($temp_attachment_name);

            if ($temp_attachment !== null) {
                $attachments[] = $temp_attachment;
            }
        }
    }
}
$myattachments='';

/* Time spent working on ticket */
$time_worked = hesk_getTime(hesk_POST('time_worked'));

/* Any errors? */
if (count($hesk_error_buffer)!=0)
{
    $_SESSION['ticket_message'] = hesk_POST('message');
    $_SESSION['time_worked'] = $time_worked;

	// Remove any successfully uploaded attachments
	if ($hesk_settings['attachments']['use'])
	{
        if ($use_legacy_attachments) {
            hesk_removeAttachments($attachments);
        } else {
            $_SESSION['ar_attachments'] = $attachments;
        }

	}

    $tmp = '';
    foreach ($hesk_error_buffer as $error)
    {
        $tmp .= "<li>$error</li>\n";
    }
    $hesk_error_buffer = $tmp;

    $hesk_error_buffer = $hesklang['pcer'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
    hesk_process_messages($hesk_error_buffer,'admin_ticket.php?track='.$ticket['trackid'].'&Refresh='.rand(10000,99999));
}

if ($hesk_settings['attachments']['use'] && !empty($attachments))
{
    // Delete temp attachment records and set the new filename
    if (!$use_legacy_attachments) {
        $attachments = hesk_migrateTempAttachments($attachments, $trackingID);
    }

    foreach ($attachments as $myatt)
    {
        hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."attachments` (`ticket_id`,`saved_name`,`real_name`,`size`) VALUES ('".hesk_dbEscape($trackingID)."','".hesk_dbEscape($myatt['saved_name'])."','".hesk_dbEscape($myatt['real_name'])."','".intval($myatt['size'])."')");
        $myattachments .= hesk_dbInsertID() . '#' . $myatt['real_name'] .',';
    }
}

$primary_customer = hesk_get_primary_customer_for_ticket($replyto, false);
$customer_id = $primary_customer === null ? 'NULL' : intval($primary_customer['id']);
$customers = hesk_get_customers_for_ticket($replyto);
$customer_emails = implode(';', array_map(function($customer) { return $customer['email']; }, $customers));
// Add reply
if ($submit_as_customer)
{
    $staff_name = ($hesk_settings['staff_nicknames'] && $_SESSION['nickname'] != '') ? $_SESSION['nickname'] : $_SESSION['name'];
    hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` (`replyto`,`message`,`message_html`,`dt`,`attachments`,`customer_id`) VALUES ('".intval($replyto)."','".hesk_dbEscape($message."<br /><br /><i>{$hesklang['creb']} ".addslashes($staff_name)."</i>")."','".hesk_dbEscape($message_html."<br /><br /><i>{$hesklang['creb']} ".addslashes($staff_name)."</i>")."',NOW(),'".hesk_dbEscape($myattachments)."', {$customer_id})");
}
else
{
	hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` (`replyto`,`message`,`message_html`,`dt`,`attachments`,`staffid`) VALUES ('".intval($replyto)."','".hesk_dbEscape($message)."','".hesk_dbEscape($message_html)."',NOW(),'".hesk_dbEscape($myattachments)."','".intval($_SESSION['id'])."')");
}

/* Track ticket status changes for history */
$revision = '';

/* Change the status of priority? */
if ( ! empty($_POST['set_priority']) )
{
    $priority = hesk_POST('priority');
    if ( ! hesk_is_valid_priority_id($priority))
    {
        hesk_error($hesklang['priority_e_id']);
    }
    $priority = intval($priority);
    $revision = sprintf($hesklang['thist8'],hesk_date(),hesk_get_priority_name($priority),addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
    $priority_sql = ",`priority`='$priority', `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') ";
}
else
{
    $priority_sql = "";
}

// Get new ticket status
$sql_status = '';
// -> If locked, keep it resolved
if ($ticket['locked'])
{
	$new_status = 3;
}
// -> Submit as Customer reply
elseif ($submit_as_customer)
{
	$new_status = 1;

	if ($ticket['status'] != $new_status)
	{
		$revision   = sprintf($hesklang['thist9'],hesk_date(),$hesklang['wait_reply'],addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
		$sql_status = " , `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') ";
	}
}
// -> Submitted with a status change?
else
{
    $submit_as_status = false;

    foreach ($hesk_settings['statuses'] as $id => $data)
    {
        if ( ! isset($_POST['submit_as-' . $id]))
        {
            continue;
        }

        // "Resolved" status needs special care
        if ($id == 3)
        {
            // Permission to resolve?
            if ( ! hesk_checkPermission('can_resolve', 0))
            {
                break;
            }

            // Update "Closed at"
            $sql_status .= " , `closedat`=NOW(), `closedby`=".intval($_SESSION['id'])." ";

            // Lock the ticket if customers are not allowed to reopen tickets
            if ($hesk_settings['custopen'] != 1)
            {
                $sql_status .= " , `locked`='1' ";
            }
        }

        // Set the new status and log revision if modified
        $new_status = $id;

        if ($ticket['status'] != $new_status && $new_status != 2)
        {
            $revision   = sprintf($hesklang['thist9'],hesk_date(),addslashes($data['name']),addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
            $sql_status .= " , `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') ";
        }

        $submit_as_status = true;

        break;
    }

    // Default: submit as "Replied by staff"
    if ( ! $submit_as_status)
    {
        $new_status = 2;
    }
}

$sql = "UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `status`='{$new_status}',";
$sql.= $submit_as_customer ? "`lastreplier`='0', `replierid`='0' " : "`lastreplier`='1', `replierid`='".intval($_SESSION['id'])."' ";

/* Update time_worked or force update lastchange */
if ($time_worked == '00:00:00')
{
	$sql .= ", `lastchange` = NOW() ";
}
else
{
    $parts = explode(':', $ticket['time_worked']);
    $seconds = ($parts[0] * 3600) + ($parts[1] * 60) + $parts[2];

    $parts = explode(':', $time_worked);
    $seconds += ($parts[0] * 3600) + ($parts[1] * 60) + $parts[2];

    require(HESK_PATH . 'inc/reporting_functions.inc.php');
    $ticket['time_worked'] = hesk_SecondsToHHMMSS($seconds);

	$sql .= ",`time_worked` = ADDTIME(`time_worked`,'" . hesk_dbEscape($time_worked) . "') ";
}

if ( ! empty($_POST['assign_self']) && hesk_checkPermission('can_assign_self',0))
{
	$revision = sprintf($hesklang['thist2'],hesk_date(),addslashes($_SESSION['name']).' ('.$_SESSION['user'].')',addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
    $sql .= " , `owner`=".intval($_SESSION['id']).", `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') ";
}

// If ticket is re-opened, clear "closed at" and "closed by"
if ($ticket['status'] == 3 && $new_status != 3)
{
    $sql .= ' , `closedat`=NULL, `closedby`=NULL ';
}

$sql .= " $priority_sql ";
$sql .= " $sql_status ";

// Is this the first staff reply? Log it for reporting
if ( ! $ticket['firstreplyby'] )
{
	$sql .= " , `firstreply`=NOW(), `firstreplyby`=".intval($_SESSION['id'])." ";
}

// Keep track of replies to this ticket for easier reporting
$sql .= " , `replies`=`replies`+1 ";
$sql .= $submit_as_customer ? '' : " , `staffreplies`=`staffreplies`+1 ";

// End and execute the query
$sql .= " WHERE `id`='{$replyto}'";
hesk_dbQuery($sql);
unset($sql);

/* Update number of replies in the users table */
hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."users` SET `replies`=`replies`+1 WHERE `id`='".intval($_SESSION['id'])."'");

// --> Prepare reply message

// 1. Generate the array with ticket info that can be used in emails
$info = array(
'email'			=> $customer_emails,
'category'		=> $ticket['category'],
'priority'		=> $ticket['priority'],
'owner'			=> $ticket['owner'],
'collaborators' => hesk_getTicketsCollaboratorIDs($ticket['id']),
'trackid'		=> $ticket['trackid'],
'status'		=> $new_status,
'name'			=> $primary_customer['name'],
'subject'		=> $ticket['subject'],
'message'		=> stripslashes($message),
'attachments'	=> $myattachments,
'dt'			=> hesk_date($ticket['dt'], true),
'lastchange'	=> hesk_date($ticket['lastchange'], true),
'due_date'      => hesk_format_due_date($ticket['due_date']),
'id'			=> $ticket['id'],
'language'		=> $ticket['language'],
'time_worked'   => $ticket['time_worked'],
'last_reply_by'	=> ($submit_as_customer ? $primary_customer['name'] : ($hesk_settings['staff_nicknames'] && $_SESSION['nickname'] != '' ? array('name' => $_SESSION['name'], 'nickname' => $_SESSION['nickname']) : $_SESSION['name'])),
);

// 2. Add custom fields to the array
foreach ($hesk_settings['custom_fields'] as $k => $v)
{
	$info[$k] = $v['use'] ? $ticket[$k] : '';
}

// 3. Add HTML message to the array
if (isset($message_html)) {
    $info['message_html'] = stripslashes($message_html);
} else {
    $info['message_html'] = $info['message'];
}

// 4. Make sure all values are properly formatted for email
$ticket = hesk_ticketToPlain($info, 1, 0);

// Notify the assigned staff?
if ($submit_as_customer)
{
    hesk_notifyAssignedStaff(false, 'new_reply_by_customer', 'notify_reply_my', 'notify_collaborator_customer_reply', array($_SESSION['id']));
}
// Notify customer?
elseif ( ! isset($_POST['no_notify']) || intval( hesk_POST('no_notify') ) != 1)
{
	hesk_notifyCustomer('new_reply_by_staff');
}

if ($ticket['collaborators'] && ! $submit_as_customer) {
    hesk_notifyAssignedStaff(false, 'collaborator_staff_reply', 'notify_collaborator_staff_reply', 'notify_collaborator_staff_reply', array($_SESSION['id']));

    // Submitted as resolved
    if ($submit_as_status && $new_status == 3) {
        hesk_notifyAssignedStaff(false, 'collaborator_resolved', 'notify_collaborator_resolved', 'notify_collaborator_resolved', array($_SESSION['id']));
    }
}

// Delete any existing drafts from this owner for this ticket
hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."reply_drafts` WHERE `owner`=".intval($_SESSION['id'])." AND `ticket`=".intval($ticket['id']));

/* Set reply submitted message */
$_SESSION['HESK_SUCCESS'] = TRUE;
$_SESSION['HESK_MESSAGE'] = $hesklang['reply_submitted'];

/* What to do after reply? */
if ($_SESSION['afterreply'] == 1)
{
	header('Location: admin_main.php');
}
elseif ($_SESSION['afterreply'] == 2)
{
	/* Get the next open ticket that needs a reply */
    $res  = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `owner` IN ('0','".intval($_SESSION['id'])."') AND " . hesk_myCategories() . " AND `status` IN ('0','1') ORDER BY `owner` DESC, `priority` ASC LIMIT 1");

    if (hesk_dbNumRows($res) == 1)
    {
    	$row = hesk_dbFetchAssoc($res);
        $_SESSION['HESK_MESSAGE'] .= '<br /><br />'.$hesklang['rssn'];
        header('Location: admin_ticket.php?track='.$row['trackid'].'&Refresh='.rand(10000,99999));
    }
    else
    {
		header('Location: admin_main.php');
    }
}
else
{
	header('Location: admin_ticket.php?track='.$ticket['trackid'].'&Refresh='.rand(10000,99999));
}
exit();
?>
admin_settings_custom_html.php
wget 'https://lists2.roe3.org/hesk/admin/admin_settings_custom_html.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

define('LOAD_TABS',1);

define('LOAD_CUSTOMER_THEME_VARS',1); // Need this here to show off calculated colors as examples and make them work properly

// Make sure the install folder is deleted
if (is_dir(HESK_PATH . 'install')) {die('Please delete the <b>install</b> folder from your server for security reasons then refresh this page!');}

// Get all the required files and functions
require(HESK_PATH . 'hesk_settings.inc.php');

// Save the default language for the settings page before choosing user's preferred one
$hesk_settings['language_default'] = $hesk_settings['language'];
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/setup_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_man_settings');

// Is this feature disabled?
if (file_exists(HESK_PATH . 'disable_custom_html_ui.txt')) {
    hesk_error($hesklang['custom_html_disabled']);
}

// What should we do?
if ( $action = hesk_REQUEST('a') ) {
    if ( defined('HESK_DEMO') ) {
        hesk_process_messages($hesklang['ddemo'], 'admin_settings_custom_html.php', 'NOTICE');
    } else if ($action == 'save') {
        hesk_token_check('POST');
        hesk_save_custom_html();
    }
}

// Print header
require_once(HESK_PATH . 'inc/header.inc.php');

// Print main manage users page
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

// Demo mode? Hide values of sensitive settings
if ( defined('HESK_DEMO') )
{
    require_once(HESK_PATH . 'inc/admin_settings_demo.inc.php');
}

$enable_save_settings = 1;

/* This will handle error, success and notice messages */
hesk_handle_messages();
?>
<div class="main__content settings admin_settings_theme">

    <?php require_once(HESK_PATH . 'inc/admin_settings_status.inc.php'); ?>

    <form method="post" action="admin_settings_custom_html.php" name="form1" onsubmit="return hesk_checkFields()" aria-label="<?php echo $hesklang['custom_html_link']?>">
        <div class="settings__form form">
            <section class="settings__form_block">
                <h3><?php echo $hesklang['custom_head']; ?></h3>
                <div style="margin-left:40px; margin-bottom:50px;">
                    <p><?php echo $hesklang['custom_head_desc']; ?></span></p>
                    <?php
                    $template_file = HESK_PATH . 'head.txt';
                    if (file_exists($template_file) && is_writable($template_file)) {
                    ?>
                        <textarea class="form-control" id="head" name="head" style="width:100%;height:300px;resize: both;" aria-label="<?php echo $hesklang['custom_head_desc']; ?>"><?php echo htmlspecialchars(file_get_contents($template_file)); ?></textarea>
                    <?php
                    } else {
                        $enable_save_settings = 0;
                        hesk_show_notice(sprintf($hesklang['file_missing_not_writable'], $template_file));
                    }
                    ?>
                </div>

                <h3><?php echo $hesklang['custom_header']; ?></h3>
                <div style="margin-left:40px; margin-bottom:50px;">
                    <p><?php echo sprintf($hesklang['custom_header_desc'], 'https://www.hesk.com/knowledgebase/?article=62'); ?></span></p>
                    <?php
                    $template_file = HESK_PATH . 'header.txt';
                    if (file_exists($template_file) && is_writable($template_file)) {
                    ?>
                        <textarea class="form-control" id="header" name="header" style="width:100%;height:300px;resize: both;" aria-label="<?php echo hesk_htmlspecialchars($hesklang['custom_header_desc']); ?>"><?php echo htmlspecialchars(file_get_contents($template_file)); ?></textarea>
                    <?php
                    } else {
                        $enable_save_settings = 0;
                        hesk_show_notice(sprintf($hesklang['file_missing_not_writable'], $template_file));
                    }
                    ?>
                </div>

                <h3><?php echo $hesklang['custom_footer']; ?></h3>
                <div style="margin-left:40px; margin-bottom:50px;">
                    <p><?php echo $hesklang['custom_footer_desc']; ?></span></p>
                    <?php
                    $template_file = HESK_PATH . 'footer.txt';
                    if (file_exists($template_file) && is_writable($template_file)) {
                    ?>
                        <textarea class="form-control" id="footer" name="footer" style="width:100%;height:300px;resize: both;" aria-lable="<?php echo $hesklang['custom_footer_desc']; ?>"><?php echo htmlspecialchars(file_get_contents($template_file)); ?></textarea>
                    <?php
                    } else {
                        $enable_save_settings = 0;
                        hesk_show_notice(sprintf($hesklang['file_missing_not_writable'], $template_file));
                    }
                    ?>
                </div>
            </section>

            <div class="settings__form_submit">
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                <input type="hidden" name="a" value="save">
                <button style="display: inline-flex" type="submit" id="submitbutton" class="btn btn-full" ripple="ripple"
                    <?php echo $enable_save_settings ? '' : 'disabled'; ?> aria-label="<?php echo $hesklang['save_changes']; ?>">
                    <?php echo $hesklang['save_changes']; ?>
                </button>

                <a style="height: 40px" href="admin_settings_theme.php" class="btn btn--blue-border" ripple="ripple">
                    <?php echo $hesklang['cancel']; ?> / <?php echo $hesklang['back']; ?>
                </a>

                <?php if (!$enable_save_settings): ?>
                    <p>&nbsp;</p>
                    <div role="alert" class="notification red">
                        <?php echo $hesklang['uanble_not_writable']; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </form>
</div>

<script src="<?php echo HESK_PATH; ?>js/jquery-ui.js?<?php echo $hesk_settings['hesk_version']; ?>"></script>
<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


function hesk_save_custom_html()
{
    global $hesk_settings, $hesklang;

    $template_file = HESK_PATH . 'head.txt';
    if ( ! file_exists($template_file) || ! is_writable($template_file)) {
        hesk_process_messages($hesklang['uanble_not_writable'], 'admin_settings_custom_html.php');
    }

    $template_file = HESK_PATH . 'header.txt';
    if ( ! file_exists($template_file) || ! is_writable($template_file)) {
        hesk_process_messages($hesklang['uanble_not_writable'], 'admin_settings_custom_html.php');
    }

    $template_file = HESK_PATH . 'footer.txt';
    if ( ! file_exists($template_file) || ! is_writable($template_file)) {
        hesk_process_messages($hesklang['uanble_not_writable'], 'admin_settings_custom_html.php');
    }

    $file_content = hesk_get_html(hesk_POST('head'));
    file_put_contents(HESK_PATH . 'head.txt', '<!-- ' . hesk_htmlspecialchars_decode($hesklang['custom_head_cmnt']) . " -->\n\n" . ltrim(hesk_sanitize_html($file_content)), LOCK_EX);

    $file_content = hesk_get_html(hesk_POST('header'));
    file_put_contents(HESK_PATH . 'header.txt', '<!-- ' . hesk_htmlspecialchars_decode($hesklang['custom_header_cmnt']) . " -->\n\n" . ltrim(hesk_sanitize_html($file_content)), LOCK_EX);

    $file_content = hesk_get_html(hesk_POST('footer'));
    file_put_contents(HESK_PATH . 'footer.txt', '<!-- ' . hesk_htmlspecialchars_decode($hesklang['custom_footer_cmnt']) . " -->\n\n" . ltrim(hesk_sanitize_html($file_content)), LOCK_EX);

    hesk_process_messages($hesklang['custom_html_saved'], 'NOREDIRECT', 'SUCCESS');

} // END hesk_save_custom_html()


function hesk_sanitize_html($in)
{
    $replace_from = array("\t","<?","?>","$","<%");
    $replace_to   = array("","&lt;?","?&gt;","\$","&lt;%");

    $in = str_replace($replace_from,$replace_to,$in);
    $in = preg_replace('/\<script(.*)\>(.*)\<\/script\>/Uis','<!-- scripts have been removed -->',$in);
    $in = preg_replace('/\<\!\-\-(.*)\-\-\>/Uis','',$in);
    return $in;
} // END hesk_sanitize_html()


function hesk_get_html($in)
{
    $replace_from = array("\t","<?","?>","$","<%");
    $replace_to   = array("","&lt;?","?&gt;","\$","&lt;%");

    if (HESK_SLASH) {
        $in = trim($in);
    } else {
        $in = trim(stripslashes($in));
    }

    $in = str_replace($replace_from,$replace_to,$in);
    $in = preg_replace('/\<script(.*)\>(.*)\<\/script\>/Uis',"<script$1></script>",$in);
    $in = preg_replace('/\<\!\-\-(.*)\-\-\>/Uis','',$in);
    return $in;
} // END hesk_get_html()


function hesk_revert_html($in)
{
    $replace_from = array("&lt;","&gt;");
    $replace_to = array("<",">");
    $in = str_replace($replace_from,$replace_to,$in);
    return $in;
} // END hesk_revert_html()

admin_settings_email.php
wget 'https://lists2.roe3.org/hesk/admin/admin_settings_email.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

define('LOAD_TABS',1);

// Make sure the install folder is deleted
if (is_dir(HESK_PATH . 'install')) {die('Please delete the <b>install</b> folder from your server for security reasons then refresh this page!');}

// Get all the required files and functions
require(HESK_PATH . 'hesk_settings.inc.php');

// Save the default language for the settings page before choosing user's preferred one
$hesk_settings['language_default'] = $hesk_settings['language'];
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/setup_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_man_settings');

// Load custom fields
require_once(HESK_PATH . 'inc/custom_fields.inc.php');

$help_folder = '../language/' . $hesk_settings['languages'][$hesk_settings['language']]['folder'] . '/help_files/';

$enable_save_settings   = 0;
$enable_use_attachments = 0;

// Print header
require_once(HESK_PATH . 'inc/header.inc.php');

// Print main manage users page
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

// Demo mode? Hide values of sensitive settings
$hesk_settings['db_pfix_real'] = $hesk_settings['db_pfix'];
if ( defined('HESK_DEMO') )
{
    require_once(HESK_PATH . 'inc/admin_settings_demo.inc.php');
}

/* This will handle error, success and notice messages */
hesk_handle_messages();

// Check file attachment limits
if ($hesk_settings['attachments']['use'] && ! defined('HESK_DEMO') )
{
    // If SMTP server is used, "From email" should match SMTP username
    if ($hesk_settings['smtp'] && strtolower($hesk_settings['smtp_user']) != strtolower($hesk_settings['noreply_mail']) && hesk_validateEmail($hesk_settings['smtp_user'], 'ERR', 0))
    {
        hesk_show_notice(sprintf($hesklang['from_warning2'], $hesklang['email_noreply'], $hesk_settings['smtp_user']));
    }

    // If POP3 fetching is active, no user should have the same email address
    if ($hesk_settings['pop3'] && hesk_validateEmail($hesk_settings['pop3_user'], 'ERR', 0))
    {
        $res = hesk_dbQuery("SELECT `name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `email` LIKE '".hesk_dbEscape($hesk_settings['pop3_user'])."' AND `active` = 1");

        if (hesk_dbNumRows($res) > 0)
        {
            hesk_show_notice(sprintf($hesklang['pop3_warning'], hesk_dbResult($res,0,0), $hesk_settings['pop3_user']) . "<br /><br />" . $hesklang['fetch_warning'], $hesklang['warn']);
        }
    }

    // If IMAP fetching is active, no user should have the same email address
    if ($hesk_settings['imap'] && hesk_validateEmail($hesk_settings['imap_user'], 'ERR', 0))
    {
        $res = hesk_dbQuery("SELECT `name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `email` LIKE '".hesk_dbEscape($hesk_settings['imap_user'])."' AND `active` = 1");

        if (hesk_dbNumRows($res) > 0)
        {
            hesk_show_notice(sprintf($hesklang['imap_warning'], hesk_dbResult($res,0,0), $hesk_settings['imap_user']) . "<br /><br />" . $hesklang['fetch_warning'], $hesklang['warn']);
        }
    }
}

$oauth_providers_rs = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix_real'])."oauth_providers` WHERE `verified` = 1");
$has_oauth_providers = hesk_dbNumRows($oauth_providers_rs) > 0;
$oauth_providers = array();
while ($row = hesk_dbFetchAssoc($oauth_providers_rs)) {
    $oauth_providers[$row['id']] = $row;
}
?>
<div class="main__content settings">

    <?php require_once(HESK_PATH . 'inc/admin_settings_status.inc.php'); ?>

    <script language="javascript" type="text/javascript"><!--
        function hesk_checkFields() {
            var d = document.form1;

            if (d.s_noreply_mail.value=='' || d.s_noreply_mail.value.indexOf(".") == -1 || d.s_noreply_mail.value.indexOf("@") == -1)
            {alert('<?php echo addslashes($hesklang['err_nomail']); ?>'); return false;}

            // DISABLE SUBMIT BUTTON
            d.submitbutton.disabled=true;

            return true;
        }

        function hesk_toggleLayer(nr,setto) {
            if (document.all)
                document.all[nr].style.display = setto;
            else if (document.getElementById)
                document.getElementById(nr).style.display = setto;
        }

        function checkRequiredEmail(field) {
            if (document.getElementById('s_require_email_0').checked && document.getElementById('s_email_view_ticket').checked)
            {
                if (field == 's_require_email_0' && confirm('<?php echo addslashes($hesklang['re_confirm1']); ?>'))
                {
                    document.getElementById('s_email_view_ticket').checked = false;
                    return true;
                }
                else if (field == 's_email_view_ticket' && confirm('<?php echo addslashes($hesklang['re_confirm2']); ?>'))
                {
                    document.getElementById('s_require_email_1').checked = true;
                    return true;
                }
                return false;
            }
            return true;
        }
        //-->
    </script>
    <form method="post" action="admin_settings_save.php" name="form1" onsubmit="return hesk_checkFields()" aria-label="<?php echo $hesklang['email_sending']; ?>">
        <div class="settings__form form">
            <section class="settings__form_block">
                <h3><?php echo $hesklang['email_sending']; ?></h3>
                <div class="form-group">
                    <label for="s_noreply_mail">
                        <span><?php echo $hesklang['email_noreply']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>general.html#5','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_noreply_mail" name="s_noreply_mail" maxlength="255" value="<?php echo $hesk_settings['noreply_mail']; ?>">
                </div>
                <div class="form-group">
                    <label for="s_noreply_name">
                        <span><?php echo $hesklang['email_name']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>general.html#6','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_noreply_name" name="s_noreply_name" maxlength="255" value="<?php echo $hesk_settings['noreply_name']; ?>">
                </div>
                <div class="form-group short">
                    <label for="s_email_max_recipients">
                        <span><?php echo $hesklang['max_recipients']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#74','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" id="s_email_max_recipients" name="s_email_max_recipients" class="form-control" maxlength="5" value="<?php echo $hesk_settings['email_max_recipients']; ?>">
                    <span><?php echo $hesklang['max_recipients2']; ?></span>
                </div>
                <div class="radio-group">
                    <h5>
                        <span><?php echo $hesklang['email_formatting']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#69','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <?php
                    $both = $hesk_settings['email_formatting'] == 3 ? 'checked' : '';
                    $bothAuto = $hesk_settings['email_formatting'] == 2 ? 'checked' : '';
                    $htmlOnly = $hesk_settings['email_formatting'] == 1 ? 'checked' : '';
                    $plainText = $hesk_settings['email_formatting'] ? '' : 'checked';
                    ?>
                    <div class="radio-list">
                        <div class="radio-custom">
                            <input type="radio" id="s_email_formatting3" name="s_email_formatting" value="3" <?php echo $both; ?>>
                            <label for="s_email_formatting3"><?php echo $hesklang['email_formatting_html_and_plaintext']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_email_formatting2" name="s_email_formatting" value="2" <?php echo $bothAuto; ?>>
                            <label for="s_email_formatting2"><?php echo $hesklang['email_formatting_html_and_plaintext_auto']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_email_formatting1" name="s_email_formatting" value="1" <?php echo $htmlOnly; ?>>
                            <label for="s_email_formatting1"><?php echo $hesklang['email_formatting_html']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_email_formatting0" name="s_email_formatting" value="0" <?php echo $plainText; ?>>
                            <label for="s_email_formatting0"><?php echo $hesklang['email_formatting_plaintext']; ?></label>
                        </div>
                        <div><?php echo sprintf($hesklang['mod_et_h'], $hesklang['tools'], '<a href="email_templates.php" target="_blank">' . $hesklang['et_title'] . '</a>'); ?></div>
                    </div>
                </div>
                <?php
                $on = '';
                $off = '';
                $onload_div = 'none';
                $onload_status = '';

                if ($hesk_settings['smtp'])
                {
                    $on = 'checked';
                    $onload_div = 'block';
                }
                else
                {
                    $off = 'checked';
                    $onload_status=' disabled ';
                }
                ?>
                <input type="hidden" name="tmp_smtp_host_name" value="<?php echo $hesk_settings['smtp_host_name']; ?>" />
                <input type="hidden" name="tmp_smtp_host_port" value="<?php echo $hesk_settings['smtp_host_port']; ?>" />
                <input type="hidden" name="tmp_smtp_timeout" value="<?php echo $hesk_settings['smtp_timeout']; ?>" />
                <input type="hidden" name="tmp_smtp_user" value="<?php echo $hesk_settings['smtp_user']; ?>" />
                <input type="hidden" name="tmp_smtp_password" value="<?php echo $hesk_settings['smtp_password']; ?>" />
                <input type="hidden" name="tmp_smtp_enc" value="<?php echo $hesk_settings['smtp_enc']; ?>" />
                <input type="hidden" name="tmp_smtp_noval_cert" value="<?php echo $hesk_settings['smtp_noval_cert']; ?>" />
                <input type="hidden" name="tmp_smtp_conn_type" value="<?php echo $hesk_settings['smtp_conn_type']; ?>" />
                <input type="hidden" name="tmp_smtp_oauth_provider" value="<?php echo $hesk_settings['smtp_oauth_provider']; ?>" />
                <div class="radio-group">
                    <h5>
                        <span><?php echo $hesklang['emlsend2']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#55','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="radio-list">
                        <div class="radio-custom">
                            <input type="radio" id="s_smtp0" name="s_smtp" value="0"
                                   onclick="hesk_attach_disable(new Array('s1','s2','s3','s4','s5','s6','s7','s8','s9','s11'<?php if ($has_oauth_providers) echo ",'s12', 'smtp-oauth-provider-select'"; ?>))"
                                   onchange="hesk_toggleLayer('smtp_settings', 'none');" <?php echo $off; ?>>
                            <label for="s_smtp0"><?php echo $hesklang['phpmail']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_smtp1" name="s_smtp" value="1"
                                   onclick="hesk_attach_enable(new Array('s1','s2','s3','s4','s5','s6','s7','s8','s9','s11'<?php if ($has_oauth_providers) echo ",'s12', 'smtp-oauth-provider-select'"; ?>))"
                                   onchange="hesk_toggleLayer('smtp_settings', 'block');" <?php echo $on; ?>>
                            <label for="s_smtp1"><?php echo $hesklang['smtp']; ?></label>
                        </div>
                    </div>
                </div>
                <div id="smtp_settings" style="display:<?php echo $onload_div; ?>; margin-bottom: 20px">
                    <div class="form-group">
                        <label for="s1">
                            <span><?php echo $hesklang['smtph']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#55','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" id="s1" class="form-control" name="s_smtp_host_name" maxlength="255" value="<?php echo $hesk_settings['smtp_host_name']; ?>" <?php echo $onload_status; ?>>
                    </div>
                    <div class="form-group">
                        <label for="s2">
                            <span><?php echo $hesklang['smtpp']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#55','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" id="s2" class="form-control" name="s_smtp_host_port" maxlength="255" value="<?php echo $hesk_settings['smtp_host_port']; ?>" <?php echo $onload_status; ?>>
                    </div>
                    <div class="form-group">
                        <label for="s3">
                            <span><?php echo $hesklang['smtpt']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#55','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" id="s3" class="form-control" name="s_smtp_timeout" size="5" maxlength="255" value="<?php echo $hesk_settings['smtp_timeout']; ?>" <?php echo $onload_status; ?>>
                    </div>
                    <?php
                    $none = $hesk_settings['smtp_enc'] == '' ? 'checked="checked"' : '';
                    $ssl = $hesk_settings['smtp_enc'] == 'ssl' ? 'checked="checked"' : '';
                    $tls = $hesk_settings['smtp_enc'] == 'tls' ? 'checked="checked"' : '';
                    ?>
                    <div class="radio-group">
                        <h5>
                            <span><?php echo $hesklang['enc']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#55','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </h5>
                        <div class="radio-list">
                            <div class="radio-custom">
                                <input type="radio" name="s_smtp_enc" value="ssl" id="s6" <?php echo $ssl; echo $onload_status; ?>>
                                <label for="s6"><?php echo $hesklang['ssl']; ?></label>
                            </div>
                            <div class="radio-custom">
                                <input type="radio" name="s_smtp_enc" value="tls" id="s7" <?php echo $tls; echo $onload_status; ?>>
                                <label for="s7"><?php echo $hesklang['tls']; ?></label>
                            </div>
                            <div class="radio-custom">
                                <input type="radio" name="s_smtp_enc" value="" id="s8" <?php echo $none; echo $onload_status; ?>>
                                <label for="s8"><?php echo $hesklang['none']; ?></label>
                            </div>
                            <div id="div_smtp_noval_cert">
                                <div class="checkbox-custom">
                                    <input type="checkbox" id="s9" name="s_smtp_noval_cert" value="1" <?php if ($hesk_settings['smtp_noval_cert']) {echo 'checked';} ?>>
                                    <label for="s9"><?php echo $hesklang['noval_cert']; ?></label>
                                    <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#68','400','500')">
                                        <div class="tooltype right">
                                            <svg class="icon icon-info">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                            </svg>
                                        </div>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php
                    $basic = '';
                    $basic_div = 'display: none';
                    $oauth = '';
                    $oauth_div = 'display: none';

                    if ($hesk_settings['smtp_conn_type'] === 'basic' || !$has_oauth_providers) {
                        $basic = 'checked="checked"';
                        $basic_div = 'display: block';
                    } elseif ($hesk_settings['smtp_conn_type'] === 'oauth') {
                        $oauth = 'checked="checked"';
                        $oauth_div = 'display: block';
                    }

                    if (!$has_oauth_providers) {
                        $oauth = 'disabled="disabled"';
                        $oauth_div = 'display: none';
                    }
                    ?>
                    <div class="radio-group">
                        <h5>
                            <span><?php echo $hesklang['email_authentication_method']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#55','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </h5>
                        <div class="radio-list">
                            <div class="radio-custom" onchange="hesk_toggleLayer('smtp-auth-basic', 'block');hesk_toggleLayer('smtp-auth-oauth', 'none');">
                                <input type="radio" name="s_smtp_conn_type" value="basic" id="s11" <?php echo $basic; echo $onload_status; ?>>
                                <label for="s11"><?php echo $hesklang['email_authentication_method_username_password']; ?></label>
                            </div>
                            <div class="radio-custom" onchange="hesk_toggleLayer('smtp-auth-basic', 'none');hesk_toggleLayer('smtp-auth-oauth', 'block');">
                                <input type="radio" name="s_smtp_conn_type" value="oauth" id="s12" <?php echo $oauth; echo $onload_status; ?>>
                                <label for="s12">
                                    <?php if ($has_oauth_providers):
                                        echo $hesklang['email_authentication_method_oauth'];
                                    else:
                                        echo $hesklang['email_authentication_method_oauth_disabled']; ?>
                                    <?php endif; ?>
                                    &nbsp; (<a href="<?php echo HESK_PATH . $hesk_settings['admin_dir']; ?>/oauth_providers.php"><?php echo $hesklang['email_authentication_method_oauth_link']; ?></a>)
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="s4">
                            <span><?php echo $hesklang['smtpu']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#55','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" id="s4" class="form-control" name="s_smtp_user" maxlength="255" value="<?php echo $hesk_settings['smtp_user']; ?>" <?php echo $onload_status; ?> autocomplete="off">
                    </div>
                    <div id="smtp-auth-basic" style="<?php echo $basic_div; ?>">
                        <div class="form-group">
                            <label for="s5">
                                <span><?php echo $hesklang['smtpw']; ?></span>
                                <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#55','400','500')">
                                    <div class="tooltype right">
                                        <svg class="icon icon-info">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                        </svg>
                                    </div>
                                </a>
                            </label>
                            <div class="input-wrapper has-side-checkbox">
                                <input type="password" id="s5" name="s_smtp_password" class="form-control" maxlength="255" value="<?php echo $hesk_settings['smtp_password']; ?>" <?php echo $onload_status; ?> autocomplete="off">
                                <div class="checkbox-custom">
                                    <input type="checkbox" id="s5_pass" onchange="hesk_toggleShowPassword('s5');">
                                    <label for="s5_pass" aria-label="<?php echo $hesklang['smtpw']; ?>">
                                        <svg class="icon icon-eye-open">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-eye-open"></use>
                                        </svg>
                                        <svg class="icon icon-eye-close">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-eye-close"></use>
                                        </svg>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div id="smtp-auth-oauth" style="<?php echo $oauth_div; ?>">
                        <div class="form-group">
                            <label for="smtp-oauth-provider-select">
                                <span><?php echo $hesklang['email_oauth_provider']; ?></span>
                                <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#55','400','500')">
                                    <div class="tooltype right">
                                        <svg class="icon icon-info">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                        </svg>
                                    </div>
                                </a>
                            </label>
                            <div class="dropdown-select center out-close">
                                <select name="s_smtp_oauth_provider" id="smtp-oauth-provider-select">
                                    <?php foreach ($oauth_providers as $id => $provider): ?>
                                    <option value="<?php echo $provider['id']; ?>" <?php echo $provider['id'] == $hesk_settings['smtp_oauth_provider'] ? 'selected' : '' ?>>
                                        <?php echo $provider['name']; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="settings__form_submit" style="margin-top: 0">
                        <a style="height: 40px" href="javascript:hesk_testSMTP()" class="btn btn--blue-border test-connection" ripple="ripple">
                            <?php echo $hesklang['smtptest']; ?>
                        </a>
                    </div>
                    <!-- START SMTP TEST -->
                    <div id="smtp_test" style="display:none">
                    </div>

                    <script language="Javascript" type="text/javascript"><!--
                        function hesk_testSMTP()
                        {
                            var element = document.getElementById('smtp_test');
                            element.innerHTML = '<img src="<?php echo HESK_PATH; ?>img/loading.gif" width="24" height="24" alt="" border="0" style="vertical-align:text-bottom" /> <i><?php echo addslashes($hesklang['contest']); ?></i>';
                            element.style.display = 'block';

                            var s_smtp_host_name = document.getElementById('s1').value;
                            var s_smtp_host_port = document.getElementById('s2').value;
                            var s_smtp_timeout   = document.getElementById('s3').value;
                            var s_smtp_user      = document.getElementById('s4').value;
                            var s_smtp_password  = document.getElementById('s5').value;
                            var s_smtp_enc       = document.getElementById('s6').checked ? 'ssl' : (document.getElementById('s7').checked ? 'tls' : '');
                            var s_smtp_noval_cert = document.getElementById('s9').checked ? '1' : '0';
                            var s_smtp_conn_type = document.getElementById('s12').checked ? 'oauth' : 'basic';
                            var s_smtp_oauth_provider = s_smtp_conn_type === 'oauth' ? document.getElementById('smtp-oauth-provider-select').value : 0;

                            var params = "test=smtp" +
                                "&s_smtp_host_name=" + encodeURIComponent( s_smtp_host_name ) +
                                "&s_smtp_host_port=" + encodeURIComponent( s_smtp_host_port ) +
                                "&s_smtp_timeout="   + encodeURIComponent( s_smtp_timeout ) +
                                "&s_smtp_user="      + encodeURIComponent( s_smtp_user ) +
                                "&s_smtp_password="  + encodeURIComponent( s_smtp_password ) +
                                "&s_smtp_enc="       + encodeURIComponent( s_smtp_enc ) +
                                "&s_smtp_noval_cert=" + encodeURIComponent( s_smtp_noval_cert ) +
                                "&s_smtp_conn_type=" + encodeURIComponent(s_smtp_conn_type) +
                                "&s_smtp_oauth_provider=" + encodeURIComponent(s_smtp_oauth_provider);

                            xmlHttp=GetXmlHttpObject();
                            if (xmlHttp==null)
                            {
                                return;
                            }

                            xmlHttp.open('POST','test_connection.php',true);
                            xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                            xmlHttp.setRequestHeader("Content-length", params.length);
                            xmlHttp.setRequestHeader("Connection", "close");

                            xmlHttp.onreadystatechange = function()
                            {
                                if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
                                {
                                    element.innerHTML = xmlHttp.responseText;
                                }
                            }

                            xmlHttp.send(params);
                        }
                        //-->
                    </script>
                    <!-- END SMTP TEST -->
                    <div class="divider"></div>
                </div>
            </section>
            <section class="settings__form_block">
                <h3><?php echo $hesklang['email_to_ticket']; ?></h3>
                <?php hesk_show_info(sprintf($hesklang['email_to_ticket_info'], 'https://www.hesk.com/knowledgebase/?article=48'), ' ', false, '" style="padding-top: 0px;'); ?>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['emlpipe']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#54','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['emlpipe']; ?>">
                        <input type="checkbox" name="s_email_piping" value="1" <?php if ($hesk_settings['email_piping']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <?php
                $onload_div = 'none';
                $onload_status = '';

                if ($hesk_settings['imap'])
                {
                    $onload_div = 'block';
                }
                else
                {
                    $onload_status=' disabled ';
                }
                ?>
                <input type="hidden" name="tmp_imap_job_wait" value="<?php echo $hesk_settings['imap_job_wait']; ?>" />
                <input type="hidden" name="tmp_imap_host_name" value="<?php echo $hesk_settings['imap_host_name']; ?>" />
                <input type="hidden" name="tmp_imap_host_port" value="<?php echo $hesk_settings['imap_host_port']; ?>" />
                <input type="hidden" name="tmp_imap_user" value="<?php echo $hesk_settings['imap_user']; ?>" />
                <input type="hidden" name="tmp_imap_password" value="<?php echo $hesk_settings['imap_password']; ?>" />
                <input type="hidden" name="tmp_imap_enc" value="<?php echo $hesk_settings['imap_enc']; ?>" />
                <input type="hidden" name="tmp_imap_noval_cert" value="<?php echo $hesk_settings['imap_noval_cert']; ?>" />
                <input type="hidden" name="tmp_imap_disable_GSSAPI" value="<?php echo $hesk_settings['imap_disable_GSSAPI']; ?>" />
                <input type="hidden" name="tmp_imap_keep" value="<?php echo $hesk_settings['imap_keep']; ?>" />
                <input type="hidden" name="tmp_imap_conn_type" value="<?php echo $hesk_settings['imap_conn_type']; ?>" />
                <input type="hidden" name="tmp_imap_oauth_provider" value="<?php echo $hesk_settings['imap_oauth_provider']; ?>" />
                <input type="hidden" name="tmp_imap_mailbox" value="<?php echo $hesk_settings['imap_mailbox']; ?>" />

                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['imap']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#67','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <?php if (!function_exists('imap_open')): ?>
                    <span style="margin-left: 24px;"><i><?php echo $hesklang['disabled']; ?></i> - <?php echo $hesklang['imap_not']; ?></span>
                    <?php $onload_div = 'none'; ?>
                    <?php else: ?>
                    <label class="switch-checkbox">
                        <input type="checkbox" name="s_imap" value="1"
                               onclick="hesk_attach_handle(this, new Array('i0','i1','i2','i3','i4','i5','i6','i7','i9','i11'<?php if ($has_oauth_providers) echo ",'i12','oauth-provider-select'"; ?>))"
                               onchange="hesk_toggleLayer('imap_settings', (this.checked ? 'block' : 'none' ));"
                               <?php if ($hesk_settings['imap']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                    <?php endif; ?>
                </div>
                <div id="imap_settings" style="display:<?php echo $onload_div; ?>; margin-bottom: 20px">
                    <div class="form-group short">
                        <label for="i0">
                            <span><?php echo $hesklang['pjt']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#67','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" id="i0" name="s_imap_job_wait" class="form-control" maxlength="5" value="<?php echo $hesk_settings['imap_job_wait']; ?>" <?php echo $onload_status; ?>>
                        <span><?php echo $hesklang['pjt2']; ?></span>
                    </div>
                    <div class="form-group">
                        <label for="i1">
                            <span><?php echo $hesklang['imaph']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#67','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" id="i1" class="form-control" name="s_imap_host_name" maxlength="255" value="<?php echo $hesk_settings['imap_host_name']; ?>" <?php echo $onload_status; ?>>
                    </div>
                    <div class="form-group short">
                        <label for="i2">
                            <span><?php echo $hesklang['imapp']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#67','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" id="i2" name="s_imap_host_port" class="form-control" maxlength="255" value="<?php echo $hesk_settings['imap_host_port']; ?>" <?php echo $onload_status; ?>>
                    </div>
                    <?php
                    $none = $hesk_settings['imap_enc'] == '' ? 'checked="checked"' : '';
                    $ssl = $hesk_settings['imap_enc'] == 'ssl' ? 'checked="checked"' : '';
                    $tls = $hesk_settings['imap_enc'] == 'tls' ? 'checked="checked"' : '';
                    ?>
                    <div class="radio-group">
                        <h5>
                            <span><?php echo $hesklang['enc']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#67','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </h5>
                        <div class="radio-list">
                            <div class="radio-custom">
                                <input type="radio" name="s_imap_enc" value="ssl" id="i9" <?php echo $ssl; echo $onload_status; ?>>
                                <label for="i9"><?php echo $hesklang['ssl']; ?></label>
                            </div>
                            <div class="radio-custom">
                                <input type="radio" name="s_imap_enc" value="tls" id="i4" <?php echo $tls; echo $onload_status; ?>>
                                <label for="i4"><?php echo $hesklang['tls']; ?></label>
                            </div>
                            <div class="radio-custom">
                                <input type="radio" name="s_imap_enc" value="" id="i3" <?php echo $none; echo $onload_status; ?>>
                                <label for="i3"><?php echo $hesklang['none']; ?></label>
                            </div>
                            <div id="div_imap_noval_cert">
                                <div class="checkbox-custom">
                                    <input type="checkbox" id="i10" name="s_imap_noval_cert" value="1" <?php if ($hesk_settings['imap_noval_cert']) {echo 'checked';} ?>>
                                    <label for="i10"><?php echo $hesklang['noval_cert']; ?></label>
                                    <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#68','400','500')">
                                        <div class="tooltype right">
                                            <svg class="icon icon-info">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                            </svg>
                                        </div>
                                    </a>
                                </div>
                            </div>
                            <div id="div_imap_disable_GSSAPI">
                                <div class="checkbox-custom">
                                    <input type="checkbox" id="i13" name="s_imap_disable_GSSAPI" value="1" <?php if ($hesk_settings['imap_disable_GSSAPI']) {echo 'checked';} ?>>
                                    <label for="i13"><?php echo $hesklang['disable_GSSAPI']; ?></label>
                                    <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#73','400','500')">
                                        <div class="tooltype right">
                                            <svg class="icon icon-info">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                            </svg>
                                        </div>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="checkbox-group row">
                        <h5>
                            <span><?php echo $hesklang['pop3keep']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#67','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </h5>
                        <label class="switch-checkbox" aria-label="<?php echo $hesklang['pop3keep']; ?>">
                            <input type="checkbox" name="s_imap_keep" id="i7" value="1" <?php if ($hesk_settings['imap_keep']) { echo 'checked'; } ?> <?php echo $onload_status; ?>>
                            <div class="switch-checkbox__bullet">
                                <i>
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                    <svg class="icon icon-tick">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                    </svg>
                                </i>
                            </div>
                        </label>
                    </div>
                    <?php
                    $basic = '';
                    $basic_div = 'display: none';
                    $oauth = '';
                    $oauth_div = 'display: none';

                    if ($hesk_settings['imap_conn_type'] === 'basic' || !$has_oauth_providers) {
                        $basic = 'checked="checked"';
                        $basic_div = 'display: block';
                    } elseif ($hesk_settings['imap_conn_type'] === 'oauth') {
                        $oauth = 'checked="checked"';
                        $oauth_div = 'display: block';
                    }

                    if (!$has_oauth_providers) {
                        $oauth = 'disabled="disabled"';
                        $oauth_div = 'display: none';
                    }
                    ?>
                    <div class="radio-group">
                        <h5>
                            <span><?php echo $hesklang['email_authentication_method']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#67','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </h5>
                        <div class="radio-list">
                            <div class="radio-custom" onchange="hesk_toggleLayer('imap-auth-basic', 'block');hesk_toggleLayer('imap-auth-oauth', 'none');">
                                <input type="radio" name="s_imap_conn_type" value="basic" id="i11" <?php echo $basic; echo $onload_status; ?>>
                                <label for="i11"><?php echo $hesklang['email_authentication_method_username_password']; ?></label>
                            </div>
                            <div class="radio-custom" onchange="hesk_toggleLayer('imap-auth-basic', 'none');hesk_toggleLayer('imap-auth-oauth', 'block');">
                                <input type="radio" name="s_imap_conn_type" value="oauth" id="i12" <?php echo $oauth; echo $onload_status; ?>>
                                <label for="i12">
                                    <?php if ($has_oauth_providers):
                                        echo $hesklang['email_authentication_method_oauth'];
                                    else:
                                        echo $hesklang['email_authentication_method_oauth_disabled']; ?>
                                    <?php endif; ?>
                                    &nbsp; (<a href="<?php echo HESK_PATH . $hesk_settings['admin_dir']; ?>/oauth_providers.php"><?php echo $hesklang['email_authentication_method_oauth_link']; ?></a>)
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="i5">
                            <span><?php echo $hesklang['imapu']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#67','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" id="i5" name="s_imap_user" class="form-control" maxlength="255" value="<?php echo $hesk_settings['imap_user']; ?>" <?php echo $onload_status; ?> autocomplete="off">
                    </div>
                    <div id="imap-auth-basic" style="<?php echo $basic_div; ?>">
                        <div class="form-group">
                            <label for="i6">
                                <span><?php echo $hesklang['imapw']; ?></span>
                                <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#67','400','500')">
                                    <div class="tooltype right">
                                        <svg class="icon icon-info">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                        </svg>
                                    </div>
                                </a>
                            </label>
                            <div class="input-wrapper has-side-checkbox">
                                <input type="password" id="i6" name="s_imap_password" class="form-control" maxlength="255" value="<?php echo $hesk_settings['imap_password']; ?>" <?php echo $onload_status; ?> autocomplete="off">
                                <div class="checkbox-custom">
                                    <input type="checkbox" id="i6_pass" onchange="hesk_toggleShowPassword('i6');">
                                    <label for="i6_pass" aria-label="<?php echo $hesklang['imapw']; ?>">
                                        <svg class="icon icon-eye-open">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-eye-open"></use>
                                        </svg>
                                        <svg class="icon icon-eye-close">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-eye-close"></use>
                                        </svg>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="i8">
                            <span><?php echo $hesklang['imap_mailbox_txt']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#67','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" id="i8" name="s_imap_mailbox" class="form-control" maxlength="255" value="<?php echo $hesk_settings['imap_mailbox']; ?>" autocomplete="off">
                    </div>
                    <div id="imap-auth-oauth" style="<?php echo $oauth_div; ?>">
                        <div class="form-group">
                            <label for="oauth-provider-select">
                                <span><?php echo $hesklang['email_oauth_provider']; ?></span>
                                <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#67','400','500')">
                                    <div class="tooltype right">
                                        <svg class="icon icon-info">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                        </svg>
                                    </div>
                                </a>
                            </label>
                            <div class="dropdown-select center out-close">
                                <select name="s_imap_oauth_provider" id="oauth-provider-select">
                                    <?php foreach ($oauth_providers as $id => $provider): ?>
                                    <option value="<?php echo $provider['id']; ?>" <?php echo $provider['id'] == $hesk_settings['imap_oauth_provider'] ? 'selected' : '' ?>>
                                        <?php echo $provider['name']; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="settings__form_submit" style="margin-top: 0">
                        <a style="height: 40px" href="javascript:hesk_testIMAP()" class="btn btn--blue-border test-connection" ripple="ripple">
                            <?php echo $hesklang['imaptest']; ?>
                        </a>
                    </div>
                    <!-- START IMAP TEST -->
                    <div id="imap_test" style="display:none">
                    </div>

                    <script language="Javascript" type="text/javascript"><!--
                        function hesk_testIMAP()
                        {
                            var element = document.getElementById('imap_test');
                            element.innerHTML = '<img src="<?php echo HESK_PATH; ?>img/loading.gif" width="24" height="24" alt="" border="0" style="vertical-align:text-bottom" /> <i><?php echo addslashes($hesklang['contest']); ?></i>';
                            element.style.display = 'block';

                            var s_imap_host_name = document.getElementById('i1').value;
                            var s_imap_host_port = document.getElementById('i2').value;
                            var s_imap_user      = document.getElementById('i5').value;
                            var s_imap_password  = document.getElementById('i6').value;
                            var s_imap_enc       = document.getElementById('i4').checked ? 'tls' : (document.getElementById('i9').checked ? 'ssl' : '');
                            var s_imap_noval_cert = document.getElementById('i10').checked ? '1' : '0';
                            var s_imap_disable_GSSAPI = document.getElementById('i13').checked ? '1' : '0';
                            var s_imap_conn_type = document.getElementById('i12').checked ? 'oauth' : 'basic';
                            var s_imap_oauth_provider = s_imap_conn_type === 'oauth' ? document.getElementById('oauth-provider-select').value : 0;
                            var s_imap_mailbox = document.getElementById('i8').value;

                            var params = "test=imap" +
                                "&s_imap_host_name="  + encodeURIComponent( s_imap_host_name ) +
                                "&s_imap_host_port=" + encodeURIComponent( s_imap_host_port ) +
                                "&s_imap_user="      + encodeURIComponent( s_imap_user ) +
                                "&s_imap_password="  + encodeURIComponent( s_imap_password ) +
                                "&s_imap_enc="       + encodeURIComponent( s_imap_enc ) +
                                "&s_imap_noval_cert=" + encodeURIComponent( s_imap_noval_cert ) +
                                "&s_imap_disable_GSSAPI=" + encodeURIComponent( s_imap_disable_GSSAPI ) +
                                "&s_imap_conn_type=" + encodeURIComponent(s_imap_conn_type) +
                                "&s_imap_oauth_provider=" + encodeURIComponent(s_imap_oauth_provider)+
                                "&s_imap_mailbox=" + encodeURIComponent(s_imap_mailbox);

                            xmlHttp=GetXmlHttpObject();
                            if (xmlHttp==null)
                            {
                                return;
                            }

                            xmlHttp.open('POST','test_connection.php',true);
                            xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                            xmlHttp.setRequestHeader("Content-length", params.length);
                            xmlHttp.setRequestHeader("Connection", "close");

                            xmlHttp.onreadystatechange = function()
                            {
                                if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
                                {
                                    element.innerHTML = xmlHttp.responseText;
                                }
                            }

                            xmlHttp.send(params);
                        }
                        //-->
                    </script>
                    <!-- END IMAP TEST -->
                    <div class="divider"></div>
                </div> <!-- END IMAP SETTINGS DIV -->
                <?php
                $onload_div = 'none';
                $onload_status = '';

                if ($hesk_settings['pop3']) {
                    $onload_div = 'block';
                } else {
                    $onload_status=' disabled ';
                }
                ?>
                <input type="hidden" name="tmp_pop3_host_name" value="<?php echo $hesk_settings['pop3_host_name']; ?>">
                <input type="hidden" name="tmp_pop3_host_port" value="<?php echo $hesk_settings['pop3_host_port']; ?>">
                <input type="hidden" name="tmp_pop3_user" value="<?php echo $hesk_settings['pop3_user']; ?>">
                <input type="hidden" name="tmp_pop3_password" value="<?php echo $hesk_settings['pop3_password']; ?>">
                <input type="hidden" name="tmp_pop3_tls" value="<?php echo $hesk_settings['pop3_tls']; ?>">
                <input type="hidden" name="tmp_pop3_keep" value="<?php echo $hesk_settings['pop3_keep']; ?>">
                <input type="hidden" name="tmp_pop3_conn_type" value="<?php echo $hesk_settings['pop3_conn_type']; ?>" />
                <input type="hidden" name="tmp_pop3_oauth_provider" value="<?php echo $hesk_settings['pop3_oauth_provider']; ?>" />
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['pop3']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#59','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['pop3']; ?>">
                        <input type="checkbox" name="s_pop3" value="1"
                               onclick="hesk_attach_handle(this, new Array('p0','p1','p2','p4','p5','p6','p7','p11'<?php if ($has_oauth_providers) echo ",'p12','pop3-oauth-provider-select'"; ?>))"
                               onchange="hesk_toggleLayer('pop3_settings', (this.checked ? 'block' : 'none' ));"
                            <?php if ($hesk_settings['pop3']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div id="pop3_settings" style="display:<?php echo $onload_div; ?>; margin-bottom: 20px">
                    <div class="form-group short">
                        <label for="p0">
                            <span><?php echo $hesklang['pjt']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#59','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" id="p0" class="form-control" name="s_pop3_job_wait" maxlength="5" value="<?php echo $hesk_settings['pop3_job_wait']; ?>" <?php echo $onload_status; ?>>
                        <span><?php echo $hesklang['pjt2']; ?></span>
                    </div>
                    <div class="form-group">
                        <label for="p1">
                            <span><?php echo $hesklang['pop3h']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#59','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" id="p1" class="form-control" name="s_pop3_host_name" maxlength="255" value="<?php echo $hesk_settings['pop3_host_name']; ?>" <?php echo $onload_status; ?>>
                    </div>
                    <div class="form-group short">
                        <label for="p2">
                            <span><?php echo $hesklang['pop3p']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#59','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" id="p2" class="form-control" name="s_pop3_host_port" maxlength="255" value="<?php echo $hesk_settings['pop3_host_port']; ?>" <?php echo $onload_status; ?>>
                    </div>
                    <div class="checkbox-group row">
                        <h5>
                            <span><?php echo $hesklang['pop3tls']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#59','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </h5>
                        <label class="switch-checkbox" aria-label="<?php echo $hesklang['pop3tls']; ?>">
                            <input type="checkbox" name="s_pop3_tls" id="p4" value="1" <?php if ($hesk_settings['pop3_tls']) { echo 'checked'; } ?> <?php echo $onload_status; ?>>
                            <div class="switch-checkbox__bullet">
                                <i>
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                    <svg class="icon icon-tick">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                    </svg>
                                </i>
                            </div>
                        </label>
                    </div>
                    <div class="checkbox-group row">
                        <h5>
                            <span><?php echo $hesklang['pop3keep']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#59','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </h5>
                        <label class="switch-checkbox" aria-label="<?php echo $hesklang['pop3keep']; ?>">
                            <input type="checkbox" name="s_pop3_keep" id="p7" value="1" <?php if ($hesk_settings['pop3_keep']) { echo 'checked'; } ?> <?php echo $onload_status; ?>>
                            <div class="switch-checkbox__bullet">
                                <i>
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                    <svg class="icon icon-tick">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                    </svg>
                                </i>
                            </div>
                        </label>
                    </div>
                    <?php
                    $basic = '';
                    $basic_div = 'display: none';
                    $oauth = '';
                    $oauth_div = 'display: none';

                    if ($hesk_settings['pop3_conn_type'] === 'basic' || !$has_oauth_providers) {
                        $basic = 'checked="checked"';
                        $basic_div = 'display: block';
                    } elseif ($hesk_settings['pop3_conn_type'] === 'oauth') {
                        $oauth = 'checked="checked"';
                        $oauth_div = 'display: block';
                    }

                    if (!$has_oauth_providers) {
                        $oauth = 'disabled="disabled"';
                        $oauth_div = 'display: none';
                    }
                    ?>
                    <div class="radio-group">
                        <h5>
                            <span><?php echo $hesklang['email_authentication_method']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#59','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </h5>
                        <div class="radio-list">
                            <div class="radio-custom" onchange="hesk_toggleLayer('pop3-auth-basic', 'block');hesk_toggleLayer('pop3-auth-oauth', 'none');">
                                <input type="radio" name="s_pop3_conn_type" value="basic" id="p11" <?php echo $basic; echo $onload_status; ?>>
                                <label for="p11"><?php echo $hesklang['email_authentication_method_username_password']; ?></label>
                            </div>
                            <div class="radio-custom" onchange="hesk_toggleLayer('pop3-auth-basic', 'none');hesk_toggleLayer('pop3-auth-oauth', 'block');">
                                <input type="radio" name="s_pop3_conn_type" value="oauth" id="p12" <?php echo $oauth; echo $onload_status; ?>>
                                <label for="p12">
                                    <?php if ($has_oauth_providers):
                                        echo $hesklang['email_authentication_method_oauth'];
                                    else:
                                        echo $hesklang['email_authentication_method_oauth_disabled']; ?>
                                    <?php endif; ?>
                                    &nbsp; (<a href="<?php echo HESK_PATH . $hesk_settings['admin_dir']; ?>/oauth_providers.php"><?php echo $hesklang['email_authentication_method_oauth_link']; ?></a>)
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="p5">
                            <span><?php echo $hesklang['pop3u']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#59','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" id="p5" name="s_pop3_user" class="form-control" maxlength="255" value="<?php echo $hesk_settings['pop3_user']; ?>" <?php echo $onload_status; ?> autocomplete="off">
                    </div>
                    <div id="pop3-auth-basic" style="<?php echo $basic_div; ?>">
                        <div class="form-group">
                            <label for="p6">
                                <span><?php echo $hesklang['pop3w']; ?></span>
                                <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#59','400','500')">
                                    <div class="tooltype right">
                                        <svg class="icon icon-info">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                        </svg>
                                    </div>
                                </a>
                            </label>
                            <div class="input-wrapper has-side-checkbox">
                                <input type="password" id="p6" name="s_pop3_password" class="form-control" maxlength="255" value="<?php echo $hesk_settings['pop3_password']; ?>" <?php echo $onload_status; ?> autocomplete="off">
                                <div class="checkbox-custom">
                                    <input type="checkbox" id="p6_pass" onchange="hesk_toggleShowPassword('p6');">
                                    <label for="p6_pass" aria-label="<?php echo $hesklang['pop3w']; ?>">
                                        <svg class="icon icon-eye-open">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-eye-open"></use>
                                        </svg>
                                        <svg class="icon icon-eye-close">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-eye-close"></use>
                                        </svg>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div id="pop3-auth-oauth" style="<?php echo $oauth_div; ?>">
                        <div class="form-group">
                            <label for="pop3-oauth-provider-select">
                                <span><?php echo $hesklang['email_oauth_provider']; ?></span>
                                <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#59','400','500')">
                                    <div class="tooltype right">
                                        <svg class="icon icon-info">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                        </svg>
                                    </div>
                                </a>
                            </label>
                            <div class="dropdown-select center out-close">
                                <select name="s_pop3_oauth_provider" id="pop3-oauth-provider-select">
                                    <?php foreach ($oauth_providers as $id => $provider): ?>
                                    <option value="<?php echo $provider['id']; ?>" <?php echo $provider['id'] == $hesk_settings['pop3_oauth_provider'] ? 'selected' : '' ?>>
                                        <?php echo $provider['name']; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="settings__form_submit" style="margin-top: 0">
                        <a style="height: 40px" href="javascript:hesk_testPOP3()" class="btn btn--blue-border test-connection" ripple="ripple">
                            <?php echo $hesklang['pop3test']; ?>
                        </a>
                    </div>
                    <div id="pop3_test" style="display:none">
                    </div>
                    <script language="Javascript" type="text/javascript"><!--
                        function hesk_testPOP3()
                        {
                            var element = document.getElementById('pop3_test');
                            element.innerHTML = '<img src="<?php echo HESK_PATH; ?>img/loading.gif" width="24" height="24" alt="" border="0" style="vertical-align:text-bottom" /> <i><?php echo addslashes($hesklang['contest']); ?></i>';
                            element.style.display = 'block';

                            var s_pop3_host_name = document.getElementById('p1').value;
                            var s_pop3_host_port = document.getElementById('p2').value;
                            var s_pop3_user      = document.getElementById('p5').value;
                            var s_pop3_password  = document.getElementById('p6').value;
                            var s_pop3_tls       = document.getElementById('p4').checked ? 1 : 0;
                            var s_pop3_conn_type = document.getElementById('p12').checked ? 'oauth' : 'basic';
                            var s_pop3_oauth_provider = s_pop3_conn_type === 'oauth' ? document.getElementById('pop3-oauth-provider-select').value : 0;

                            var params = "test=pop3" +
                                "&s_pop3_host_name="  + encodeURIComponent( s_pop3_host_name ) +
                                "&s_pop3_host_port=" + encodeURIComponent( s_pop3_host_port ) +
                                "&s_pop3_user="      + encodeURIComponent( s_pop3_user ) +
                                "&s_pop3_password="  + encodeURIComponent( s_pop3_password ) +
                                "&s_pop3_tls="       + encodeURIComponent( s_pop3_tls ) +
                                "&s_pop3_conn_type=" + encodeURIComponent(s_pop3_conn_type) +
                                "&s_pop3_oauth_provider=" + encodeURIComponent(s_pop3_oauth_provider);

                            xmlHttp=GetXmlHttpObject();
                            if (xmlHttp==null)
                            {
                                return;
                            }

                            xmlHttp.open('POST','test_connection.php',true);
                            xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                            xmlHttp.setRequestHeader("Content-length", params.length);
                            xmlHttp.setRequestHeader("Connection", "close");

                            xmlHttp.onreadystatechange = function()
                            {
                                if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
                                {
                                    element.innerHTML = xmlHttp.responseText;
                                }
                            }

                            xmlHttp.send(params);
                        }
                        //-->
                    </script>
                    <div class="divider"></div>
                </div> <!-- END POP3 SETTINGS DIV -->
                <div>&nbsp;</div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['remqr']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#61','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_strip_quoted1" name="s_strip_quoted" value="1" <?php if ($hesk_settings['strip_quoted']) {echo 'checked';} ?>>
                        <label for="s_strip_quoted1"><?php echo $hesklang['remqr2']; ?></label>
                    </div>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['emlreqmsg']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#66','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_eml_req_msg1" name="s_eml_req_msg" value="1" <?php if ($hesk_settings['eml_req_msg']) {echo 'checked';} ?>>
                        <label for="s_eml_req_msg1"><?php echo $hesklang['emlreqmsg2']; ?></label>
                    </div>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['embed']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#64','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_save_embedded1" name="s_save_embedded" value="1" <?php if ($hesk_settings['save_embedded']) {echo 'checked';} ?>>
                        <label for="s_save_embedded1"><?php echo $hesklang['embed2']; ?></label>
                    </div>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['setting_process_to_cc']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>370.html#1','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div style="display:block;">
                        <?php if ( ! $hesk_settings['multi_eml']) {
                            hesk_show_info(sprintf($hesklang['setting_process_to_cc_notice'], $hesklang['ticket_followers'], $hesklang['settings'], $hesklang['tab_2'], $hesklang['features']), ' ', false, '" style="padding-top: 0px; padding-left: 24px');
                        } ?>
                        <label class="switch-checkbox">
                            <input type="checkbox" name="s_email_include_to" value="1" <?php if ($hesk_settings['email_include_to']) { echo 'checked'; } ?>>
                            <div class="switch-checkbox__bullet">
                                <i>
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                    <svg class="icon icon-tick">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                    </svg>
                                </i>
                            </div>
                            <span><?php echo $hesklang['email_include_to']; ?></span>
                        </label>
                        <br>
                        <label class="switch-checkbox">
                            <input type="checkbox" name="s_email_include_cc" <?php if ($hesk_settings['email_include_cc']) { echo 'checked'; } ?>>
                            <div class="switch-checkbox__bullet">
                                <i>
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                    <svg class="icon icon-tick">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                    </svg>
                                </i>
                            </div>
                            <span><?php echo $hesklang['email_include_cc']; ?></span>
                        </label>
                    </div>
                </div>
            </section>
            <section class="settings__form_block">
                <h3><?php echo $hesklang['block_ignore']; ?></h3>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['block_noreply']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#70','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_pipe_block_noreply1" name="s_pipe_block_noreply" value="1" <?php if ($hesk_settings['pipe_block_noreply']) {echo 'checked';} ?>>
                        <label for="s_pipe_block_noreply1"><?php echo $hesklang['block_noreply2']; ?></label>
                    </div>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['block_returned']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#71','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_pipe_block_returned1" name="s_pipe_block_returned" value="1" <?php if ($hesk_settings['pipe_block_returned']) {echo 'checked';} ?>>
                        <label for="s_pipe_block_returned1"><?php echo $hesklang['block_returned2']; ?></label>
                    </div>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['block_duplicate']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#72','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_pipe_block_duplicate1" name="s_pipe_block_duplicate" value="1" <?php if ($hesk_settings['pipe_block_duplicate']) {echo 'checked';} ?>>
                        <label for="s_pipe_block_duplicate1"><?php echo sprintf($hesklang['block_duplicate2'], $hesklang['loopt']); ?></label>
                    </div>
                </div>
                <div class="form-group short">
                    <label for="s_loop_hits">
                        <span><?php echo $hesklang['looph']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#60','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" id="s_loop_hits" name="s_loop_hits" class="form-control" maxlength="5" value="<?php echo $hesk_settings['loop_hits']; ?>">
                    <div style="margin-left: 12px;"><?php echo sprintf($hesklang['loop_info'], $hesklang['loopt']); ?></div>
                </div>
                <div class="form-group short">
                    <label for="s_loop_time">
                        <span><?php echo $hesklang['loopt']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#60','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" id="s_loop_time" name="s_loop_time" class="form-control" maxlength="5" value="<?php echo $hesk_settings['loop_time']; ?>">
                    <span><?php echo $hesklang['ss']; ?></span>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['piping_notify_rejected_customers1']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#75','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <?php
                    $rejection_cooldown_div = $hesk_settings['pipe_customer_rejection_notification'] ? 'block' : 'none';
                    ?>
                    <div class="checkbox-custom">
                        <input onclick="hesk_toggleLayerDisplay('rejection_cooldown')" type="checkbox" id="s_pipe_customer_rejection_notification1" name="s_pipe_customer_rejection_notification" value="1" <?php if ($hesk_settings['pipe_customer_rejection_notification']) {echo 'checked';} ?>>
                        <label for="s_pipe_customer_rejection_notification1"><?php echo $hesklang['piping_notify_rejected_customers2']; ?></label>
                    </div>
                </div>
                <div id="rejection_cooldown" style="display:<?php echo $rejection_cooldown_div; ?>; margin-bottom: 20px">
                    <div class="form-group short">
                        <label for="s_pipe_customer_rejection_email_cooldown_hours">
                            <span><?php echo $hesklang['piping_notify_rejected_customers3']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#76','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" id="s_pipe_customer_rejection_email_cooldown_hours" name="s_pipe_customer_rejection_email_cooldown_hours" class="form-control" maxlength="3" value="<?php echo $hesk_settings['pipe_customer_rejection_email_cooldown_hours']; ?>">
                        <span><?php echo $hesklang['hh']; ?></span>
                    </div>
                </div>
            </section>
            <section class="settings__form_block">
                <h3><?php echo $hesklang['suge']; ?></h3>
                <?php
                $onload_div = 'none';
                $onload_status = '';

                if ($hesk_settings['detect_typos']) {
                    $onload_div = 'block';
                } else {
                    $onload_status=' disabled="disabled" ';
                }
                ?>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['suge']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#62','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['suge']; ?>">
                        <input type="checkbox" name="s_detect_typos" value="1" onclick="hesk_attach_handle(this, 'd1')"
                               onchange="hesk_toggleLayer('detect_typos', (this.checked ? 'block' : 'none' ))"
                               <?php if ($hesk_settings['detect_typos']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div id="detect_typos" style="display:<?php echo $onload_div; ?>">
                    <div class="form-group">
                        <label for="d1">
                            <span><?php echo $hesklang['epro']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#63','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <textarea style="margin-left: 24px;" name="s_email_providers" id="d1" class="form-control"><?php echo implode("\n", $hesk_settings['email_providers']); ?></textarea>
                    </div>
                </div>
            </section>
            <section class="settings__form_block">
                <h3><?php echo $hesklang['custnot']; ?></h3>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['custnot']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#65','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-list">
                        <div class="checkbox-custom">
                            <input type="checkbox" id="s_notify_new1" name="s_notify_new" value="1" onchange="hesk_toggleLayer('skip_notify', (this.checked ? 'block' : 'none' ));" <?php if ($hesk_settings['notify_new']) {echo 'checked';} ?>>
                            <label for="s_notify_new1"><?php echo $hesklang['notnew']; ?></label>
                        </div>
                        <div id="skip_notify" style="margin-left:25px;display:<?php echo $hesk_settings['notify_new'] ? 'block' : 'none'; ?>">
                            <div class="checkbox-custom">
                                <input type="checkbox" id="s_notify_skip_spam1" name="s_notify_skip_spam" value="1" <?php if ($hesk_settings['notify_skip_spam']) {echo 'checked';} ?>/>
                                <label for="s_notify_skip_spam1"><?php echo $hesklang['enn']; ?></label>
                            </div>
                            <div class="form-group">
                                <textarea class="form-control" name="s_notify_spam_tags" rows="5" cols="40" style="margin-left:25px;"
                                aria-label="Ticket email subject exceptions"><?php echo hesk_htmlspecialchars( implode("\n", $hesk_settings['notify_spam_tags']) ); ?></textarea>
                            </div>
                        </div>
                        <div class="checkbox-custom">
                            <input type="checkbox" id="s_notify_closed1" name="s_notify_closed" value="1" <?php if ($hesk_settings['notify_closed']) {echo 'checked';} ?>>
                            <label for="s_notify_closed1"><?php echo $hesklang['notclo']; ?></label>
                        </div>
                    </div>
                </div>
            </section>
            <section class="settings__form_block">
                <h3><?php echo $hesklang['other']; ?></h3>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['sconfe']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#50','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_confirm_email1" name="s_confirm_email" value="1" <?php if ($hesk_settings['confirm_email']) {echo 'checked';} ?>>
                        <label for="s_confirm_email1"><?php echo $hesklang['sconfe2']; ?></label>
                    </div>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['oo']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#58','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_open_only1" name="s_open_only" value="1" <?php if ($hesk_settings['open_only']) {echo 'checked';} ?>/>
                        <label for="s_open_only1"><?php echo $hesklang['ool']; ?></label>
                    </div>
                </div>
            </section>
            <div class="settings__form_submit">
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                <input type="hidden" name="section" value="EMAIL">
                <button id="submitbutton" style="display: inline-flex" type="submit" class="btn btn-full" ripple="ripple"
                    <?php echo $enable_save_settings ? '' : 'disabled'; ?>>
                    <?php echo $hesklang['save_changes']; ?>
                </button>

                <?php if (!$enable_save_settings): ?>
                    <p>&nbsp;</p>
                    <div role="alert" class="notification red">
                        <?php echo $hesklang['e_save_settings']; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </form>
</div>
<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();
admin_settings_general.php
wget 'https://lists2.roe3.org/hesk/admin/admin_settings_general.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

define('LOAD_TABS',1);

// Make sure the install folder is deleted
if (is_dir(HESK_PATH . 'install')) {die('Please delete the <b>install</b> folder from your server for security reasons then refresh this page!');}

// Get all the required files and functions
require(HESK_PATH . 'hesk_settings.inc.php');

// Save the default language for the settings page before choosing user's preferred one
$hesk_settings['language_default'] = $hesk_settings['language'];
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/setup_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_man_settings');

// Load custom fields
require_once(HESK_PATH . 'inc/custom_fields.inc.php');

// Test languages function
if (isset($_GET['test_languages'])) {
    hesk_testLanguage(0);
} elseif (isset($_GET['test_themes'])) {
    hesk_testTheme(0);
}

$help_folder = '../language/' . $hesk_settings['languages'][$hesk_settings['language']]['folder'] . '/help_files/';

$enable_save_settings   = 0;
$enable_use_attachments = 0;

// Print header
require_once(HESK_PATH . 'inc/header.inc.php');

// Loader file include for AJAX Request
require_once(HESK_PATH . 'inc/loader.inc.php');

// Print main manage users page
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

// Demo mode? Hide values of sensitive settings
if ( defined('HESK_DEMO') )
{
    require_once(HESK_PATH . 'inc/admin_settings_demo.inc.php');
}

/* This will handle error, success and notice messages */
hesk_handle_messages();
?>
<div class="main__content settings">

    <?php require_once(HESK_PATH . 'inc/admin_settings_status.inc.php'); ?>

    <script language="javascript" type="text/javascript"><!--
        function hesk_checkFields() {
            var d=document.form1;

            // GENERAL
            if (d.s_site_title.value=='') {alert('<?php echo addslashes($hesklang['err_sname']); ?>'); return false;}
            if (d.s_site_url.value=='') {alert('<?php echo addslashes($hesklang['err_surl']); ?>'); return false;}
            if (d.s_hesk_title.value=='') {alert('<?php echo addslashes($hesklang['err_htitle']); ?>'); return false;}
            if (d.s_hesk_url.value=='') {alert('<?php echo addslashes($hesklang['err_hurl']); ?>'); return false;}
            if (d.s_webmaster_mail.value=='' || d.s_webmaster_mail.value.indexOf(".") == -1 || d.s_webmaster_mail.value.indexOf("@") == -1)
            {alert('<?php echo addslashes($hesklang['err_wmmail']); ?>'); return false;}

            if (d.s_db_host.value=='') {alert('<?php echo addslashes($hesklang['err_dbhost']); ?>'); return false;}
            if (d.s_db_name.value=='') {alert('<?php echo addslashes($hesklang['err_dbname']); ?>'); return false;}
            if (d.s_db_user.value=='') {alert('<?php echo addslashes($hesklang['err_dbuser']); ?>'); return false;}
            if (d.s_db_pass.value=='')
            {
                if (!confirm('<?php echo addslashes($hesklang['mysql_root']); ?>'))
                {
                    return false;
                }
            }

            // DISABLE SUBMIT BUTTON
            d.submitbutton.disabled=true;

            return true;
        }

        function hesk_toggleLayer(nr,setto) {
            if (document.all)
                document.all[nr].style.display = setto;
            else if (document.getElementById)
                document.getElementById(nr).style.display = setto;
        }

        function hesk_testLanguage()
        {
            window.open('admin_settings_general.php?test_languages=1',"Hesk_window","height=400,width=500,menubar=0,location=0,toolbar=0,status=0,resizable=1,scrollbars=1");
            return false;
        }

        function hesk_testTheme()
        {
            window.open('admin_settings_general.php?test_themes=1',"Hesk_window","height=400,width=500,menubar=0,location=0,toolbar=0,status=0,resizable=1,scrollbars=1");
            return false;
        }
        //-->
    </script>
    <form method="post" action="admin_settings_save.php" name="form1" onsubmit="return hesk_checkFields()" aria-label="<?php echo $hesklang['gs']; ?>">
        <div class="settings__form form">
            <section class="settings__form_block">
                <h3><?php echo $hesklang['gs']; ?></h3>
                <div class="form-group">
                    <label for="s_site_title">
                        <span><?php echo $hesklang['wbst_title']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>general.html#1','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_site_title" name="s_site_title" maxlength="255" value="<?php echo $hesk_settings['site_title']; ?>">
                </div>
                <div class="form-group">
                    <label for="s_site_url">
                        <span><?php echo $hesklang['wbst_url']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>general.html#2','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_site_url" name="s_site_url" maxlength="255" value="<?php echo $hesk_settings['site_url']; ?>">
                </div>
                <div class="form-group">
                    <label for="s_hesk_title">
                        <span><?php echo $hesklang['hesk_title']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#6','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_hesk_title" name="s_hesk_title" maxlength="255" value="<?php echo $hesk_settings['hesk_title']; ?>">
                </div>
                <div class="form-group">
                    <label for="s_hesk_url">
                        <span><?php echo $hesklang['hesk_url']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#7','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_hesk_url" name="s_hesk_url" maxlength="255" value="<?php echo $hesk_settings['hesk_url']; ?>">
                </div>
                <div class="form-group">
                    <label for="s_webmaster_mail">
                        <span><?php echo $hesklang['email_wm']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>general.html#4','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_webmaster_mail" name="s_webmaster_mail" maxlength="255" value="<?php echo $hesk_settings['webmaster_mail']; ?>">
                </div>
                <div class="form-group flex-row">
                    <label for="s_site_theme">
                        <span><?php echo $hesklang['site_theme']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>general.html#58','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <div class="dropdown-select center out-close">
                        <select id="s_site_theme" name="s_site_theme">
                            <?php echo hesk_testTheme(1); ?>
                        </select>
                    </div>
                    <button type="button" class="btn btn--blue-border" style="margin-left: 20px" ripple="ripple"
                            onclick="return hesk_testTheme()">
                        <?php echo $hesklang['test_theme_folder']; ?>
                    </button>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['admin_css']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>general.html#59','400','500')">
                            <div class="tooltype right" style="vertical-align: top;">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-list">
                        <div class="checkbox-custom">
                            <input type="checkbox" id="s_admin_css" name="s_admin_css" value="1" onchange="hesk_toggleLayerDisplay('admin_css');" <?php if ($hesk_settings['admin_css']) {echo 'checked';} ?>>
                            <label for="s_admin_css"><?php echo $hesklang['admin_css2']; ?></label>
                        </div>
                        <div id="admin_css" style="margin-left:25px;display:<?php echo $hesk_settings['admin_css'] ? 'block' : 'none'; ?>">
                            <input type="text" class="form-control" name="s_admin_css_url" maxlength="255" value="<?php echo $hesk_settings['admin_css_url']; ?>" aria-label="<?php echo $hesklang['admin_css']; ?>">
                        </div>
                    </div>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['admin_js']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>general.html#60','400','500')">
                            <div class="tooltype right" style="vertical-align: top;">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-list">
                        <div class="checkbox-custom">
                            <input type="checkbox" id="s_admin_js" name="s_admin_js" value="1" onchange="hesk_toggleLayerDisplay('admin_js');" <?php if ($hesk_settings['admin_js']) {echo 'checked';} ?>>
                            <label for="s_admin_js"><?php echo $hesklang['admin_js2']; ?></label>
                        </div>
                        <div id="admin_js" style="margin-left:25px;display:<?php echo $hesk_settings['admin_js'] ? 'block' : 'none'; ?>">
                            <input type="text" class="form-control" name="s_admin_js_url" maxlength="255" value="<?php echo $hesk_settings['admin_js_url']; ?>" aria-label="<?php echo $hesklang['admin_js']; ?>">
                        </div>
                    </div>
                </div>
            </section>
            <section class="settings__form_block language">
                <h3><?php echo $hesklang['lgs']; ?></h3>
                <div class="form-group row flex-row">
                    <label for="s_language">
                        <span><?php echo $hesklang['hesk_lang']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>general.html#9','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <div class="dropdown-select center out-close">
                        <select id="s_language" name="s_language">
                            <?php echo hesk_testLanguage(1); ?>
                        </select>
                    </div>
                    <button type="button" class="btn btn--blue-border" style="margin-left: 20px" ripple="ripple"
                            onclick="return hesk_testLanguage()">
                        <?php echo $hesklang['s_inl']; ?>
                    </button>
                </div>
                <!--Installed Language Changes-->
                <div class="form-group row flex-row">
                    <label>
                        <span><?php echo $hesklang['available_language']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>general.html#44','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <div>
                        <?php require_once(HESK_PATH . 'inc/admin_settings_language.inc.php');?>
                    </div>
                </div>
                <!--Installed Language Changes-->
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['s_mlang']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>general.html#43','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['s_mlang']; ?>">
                        <input type="checkbox" name="s_can_sel_lang" <?php echo $hesk_settings['can_sel_lang'] ? 'checked' : ''; ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
            </section>
            <section class="settings__form_block is-before-save-button">
                <h3><?php echo $hesklang['db']; ?></h3>
                <div class="form-group">
                    <label for="m1">
                        <span><?php echo $hesklang['db_host']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>general.html#32','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" name="s_db_host" id="m1" maxlength="255" value="<?php echo $hesk_settings['db_host']; ?>" autocomplete="off">
                </div>
                <div class="form-group">
                    <label for="m2">
                        <span><?php echo $hesklang['db_name']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>general.html#33','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" name="s_db_name" id="m2" maxlength="255" value="<?php echo $hesk_settings['db_name']; ?>" autocomplete="off">
                </div>
                <div class="form-group">
                    <label for="m3">
                        <span><?php echo $hesklang['db_user']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>general.html#34','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" name="s_db_user" id="m3" maxlength="255" value="<?php echo str_replace('&', '&amp;', $hesk_settings['db_user']); ?>" autocomplete="off">
                </div>
                <div class="form-group">
                    <label for="m4">
                        <span><?php echo $hesklang['db_pass']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>general.html#35','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <div class="input-wrapper has-side-checkbox">
                        <input type="password" class="form-control" name="s_db_pass" id="m4" maxlength="255" value="<?php echo str_replace(array('&', '>', '<'), array('&amp;', '&gt;', '&lt;'), $hesk_settings['db_pass']); ?>" autocomplete="off">
                        <div class="checkbox-custom">
                            <input type="checkbox" id="m4_pass" onchange="hesk_toggleShowPassword('m4');">
                            <label for="m4_pass" aria-label="<?php echo $hesklang['db_pass']; ?>">
                                <svg class="icon icon-eye-open">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-eye-open"></use>
                                </svg>
                                <svg class="icon icon-eye-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-eye-close"></use>
                                </svg>
                            </label>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="m5">
                        <span><?php echo $hesklang['prefix']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>general.html#36','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" name="s_db_pfix" id="m5" maxlength="255" value="<?php echo $hesk_settings['db_pfix']; ?>" autocomplete="off">
                </div>
            </section>
            <div class="settings__form_submit">
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                <input type="hidden" name="section" value="GENERAL">
                <button id="submitbutton" style="display: inline-flex" type="submit" class="btn btn-full" ripple="ripple"
                    <?php echo $enable_save_settings ? '' : 'disabled'; ?>>
                    <?php echo $hesklang['save_changes']; ?>
                </button>
                <a style="height: 40px" href="javascript:hesk_testMySQL()" class="btn btn--blue-border test-connection" ripple="ripple">
                    <?php echo $hesklang['mysqltest']; ?>
                </a>

                <?php if (!$enable_save_settings): ?>
                    <p>&nbsp;</p>
                    <div role="alert" class="notification red">
                        <?php echo $hesklang['e_save_settings']; ?>
                    </div>
                <?php endif; ?>
            </div>
            <!-- START MYSQL TEST -->
            <div id="mysql_test" style="display:none">
            </div>

            <script language="Javascript" type="text/javascript"><!--
                function hesk_testMySQL()
                {
                    var element = document.getElementById('mysql_test');
                    element.innerHTML = '<img src="<?php echo HESK_PATH; ?>img/loading.gif" width="24" height="24" alt="" border="0" style="vertical-align:text-bottom" /> <i><?php echo addslashes($hesklang['contest']); ?></i>';
                    element.style.display = 'block';

                    var s_db_host = document.getElementById('m1').value;
                    var s_db_name = document.getElementById('m2').value;
                    var s_db_user = document.getElementById('m3').value;
                    var s_db_pass = document.getElementById('m4').value;
                    var s_db_pfix = document.getElementById('m5').value;

                    var params = "test=mysql" +
                        "&s_db_host=" + encodeURIComponent( s_db_host ) +
                        "&s_db_name=" + encodeURIComponent( s_db_name ) +
                        "&s_db_user=" + encodeURIComponent( s_db_user ) +
                        "&s_db_pass=" + encodeURIComponent( s_db_pass ) +
                        "&s_db_pfix=" + encodeURIComponent( s_db_pfix );

                    xmlHttp=GetXmlHttpObject();
                    if (xmlHttp==null)
                    {
                        return;
                    }

                    xmlHttp.open('POST','test_connection.php',true);
                    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    xmlHttp.setRequestHeader("Content-length", params.length);
                    xmlHttp.setRequestHeader("Connection", "close");

                    xmlHttp.onreadystatechange = function()
                    {
                        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
                        {
                            element.innerHTML = xmlHttp.responseText;
                        }
                    }

                    xmlHttp.send(params);
                }
                //-->
            </script>
            <!-- END MYSQL TEST -->
        </div>
    </form>
</div>
<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


function hesk_testTheme($return_options = 1) {
    global $hesk_settings, $hesklang;

    $dir = HESK_PATH . 'theme/';
    $path = opendir($dir);

    $themes = "/theme\n";
    $html = '';

    /* Test all folders inside the theme folder */
    while (false !== ($subdir = readdir($path))) {
        if ($subdir === '.' || $subdir === '..') {
            continue;
        }

        if (filetype($dir . $subdir) === 'dir') {
            $add = 1;
            $themes .= "   |-> /$subdir\n";
            $themes .= "      |-> /customer\n";
            $err = '';

            //region Create Ticket
            $files_to_test = array('category-select.php', 'create-ticket.php', 'create-ticket-confirmation.php');
            $themes .= "         |-> /create-ticket: ";
            foreach ($files_to_test as $test_file) {
                if (!file_exists($dir . $subdir . '/customer/create-ticket/' . $test_file)) {
                    $err .= "            |----> MISSING: $test_file\n";
                }
            }

            if ($err) {
                $add = 0;
                $themes .= "ERROR\n$err";
            } else {
                $themes .= "OK\n";
            }
            //endregion
            $err = '';
            //region Knowledgebase
            $files_to_test = array('search-results.php', 'view-article.php', 'view-category.php');
            $themes .= "         |-> /knowledgebase: ";
            foreach ($files_to_test as $test_file) {
                if (!file_exists($dir . $subdir . '/customer/knowledgebase/' . $test_file)) {
                    $err .= "            |----> MISSING: $test_file\n";
                }
            }

            if ($err) {
                $add = 0;
                $themes .= "ERROR\n$err";
            } else {
                $themes .= "OK\n";
            }
            //endregion
            $err = '';
            //region View Ticket
            $files_to_test = array('form.php', 'view-ticket.php');
            $themes .= "         |-> /view-ticket";
            foreach ($files_to_test as $test_file) {
                if (!file_exists($dir . $subdir . '/customer/view-ticket/' . $test_file)) {
                    $err .= "            |----> MISSING: $test_file\n";
                }
            }

            if ($err) {
                $add = 0;
                $themes .= "ERROR\n$err";
            } else {
                $themes .= ": OK\n";
            }
            //endregion
            //region Solo files
            $files_to_test = array('error.php', 'index.php', 'maintenance.php');
            foreach ($files_to_test as $test_file) {
                if (!file_exists($dir . $subdir . '/customer/' . $test_file)) {
                    $add = 0;
                    $themes .= "         |----> MISSING: $test_file\n";
                } else {
                    $themes .= "         |-> $test_file: OK\n";
                }
            }
            //endregion
            if (!file_exists($dir . $subdir . '/print-ticket.php')) {
                $add = 0;
                $themes .= "      |----> MISSING: print-ticket.php\n";
            } else {
                $themes .= "      |-> print-ticket.php: OK\n";
            }
            if (!file_exists($dir . $subdir . '/config.json')) {
                $add = 0;
                $themes .= "      |----> MISSING: config.json\n";
            } else {
                $themes .= "      |-> config.json: OK\n";
            }
        }

        // Build markup
        if ($add) {
            // Pull the name from config.json
            $config = file_get_contents($dir . $subdir . '/config.json');
            $config_json = json_decode($config, true);

            $html .= '<option value="'.$subdir.'" '.($hesk_settings['site_theme'] === $subdir ? 'selected' : '').'>'.$config_json['name'].'</option>';
        }
    }

    if ($return_options) {
        return $html;
    } else {
        ?>
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <title><?php echo $hesklang['test_theme_folder']; ?></title>
            <meta http-equiv="Content-Type" content="text/html;charset=<?php echo $hesklang['ENCODING']; ?>" />
            <style type="text/css">
                body
                {
                    margin:5px 5px;
                    padding:0;
                    background:#fff;
                    color: black;
                    font : 68.8%/1.5 Verdana, Geneva, Arial, Helvetica, sans-serif;
                    text-align:left;
                }

                p
                {
                    color : black;
                    font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
                    font-size: 1.0em;
                }
                h3
                {
                    color : #AF0000;
                    font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
                    font-weight: bold;
                    font-size: 1.0em;
                    text-align:center;
                }
                .title
                {
                    color : black;
                    font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
                    font-weight: bold;
                    font-size: 1.0em;
                }
                .wrong   {color : red;}
                .correct {color : green;}
                pre {font-size:1.2em;}
            </style>
        </head>
        <body>
            <h3><?php echo $hesklang['test_theme_folder']; ?></h3>
            <p><i><?php echo $hesklang['test_theme_folder_description']; ?></i></p>
            <pre><?php echo $themes; ?></pre>
            <p class="text-center">
                <a href="admin_settings_general.php?test_themes=1&amp;<?php echo rand(10000,99999); ?>">
                    <?php echo $hesklang['ta']; ?>
                </a> |
                <a href="#" onclick="Javascript:window.close()">
                    <?php echo $hesklang['cwin']; ?>
                </a>
            </p>
        </body>
        </html>
        <?php
        exit();
    }
}




function hesk_testLanguage($return_options = 0)
{
	global $hesk_settings, $hesklang;

    // Get a list of valid emails; demo mode needs a trick
    if ( defined('HESK_DEMO') ) {
        require(HESK_PATH . 'hesk_settings.inc.php');
        include_once(HESK_PATH . 'inc/email_functions.inc.php');
        require(HESK_PATH . 'inc/admin_settings_demo.inc.php');
    } else {
        include_once(HESK_PATH . 'inc/email_functions.inc.php');
    }
    $valid_emails = array_keys( hesk_validEmails() );

	$dir = HESK_PATH . 'language/';
	$path = opendir($dir);

    $text = '';
    $html = '';

	$text .= "/language\n";

    /* Test all folders inside the language folder */
	while (false !== ($subdir = readdir($path)))
	{
		if ($subdir == "." || $subdir == "..")
	    {
	    	continue;
	    }

		if (filetype($dir . $subdir) == 'dir')
		{
        	$add   = 1;
	    	$langu = $dir . $subdir . '/text.php';
	        $email = $dir . $subdir . '/emails';
            $html_email = $dir . $subdir . '/html_emails';

			/* Check the text.php */
			$text .= "   |-> /$subdir\n";
	        $text .= "        |-> text.php: ";
	        if (file_exists($langu))
	        {
	        	$tmp = file_get_contents($langu);

				// Some servers add slashes to file_get_contents output
				if ( strpos ($tmp, '[\\\'LANGUAGE\\\']') !== false )
				{
					$tmp = stripslashes($tmp);
				}

	            $err = '';
	        	if (!preg_match('/\$hesklang\[\'LANGUAGE\'\]\=\'(.*)\'\;/',$tmp,$l))
	            {
	                $err .= "              |---->  MISSING: \$hesklang['LANGUAGE']\n";
	            }

	            if (strpos($tmp,'$hesklang[\'ENCODING\']') === false)
	            {
	            	$err .= "              |---->  MISSING: \$hesklang['ENCODING']\n";
	            }

	            if (strpos($tmp,'$hesklang[\'_COLLATE\']') === false)
	            {
	            	$err .= "              |---->  MISSING: \$hesklang['_COLLATE']\n";
	            }

	            if (strpos($tmp,'$hesklang[\'EMAIL_HR\']') === false)
	            {
	            	$err .= "              |---->  MISSING: \$hesklang['EMAIL_HR']\n";
	            }

                /* Check if language file is for current version */
                if (strpos($tmp,'$hesklang[\'purge_cache_done\']') === false)
	            {
	            	$err .= "              |---->  WRONG VERSION (not ".$hesk_settings['hesk_version'].")\n";
	            }

	            if ($err)
	            {
	            	$text .= "ERROR\n" . $err;
                    $add   = 0;
	            }
	            else
	            {
                	$l[1]  = hesk_input($l[1]);
                    $l[1]  = str_replace('|',' ',$l[1]);
	        		$text .= "OK ($l[1])\n";
	            }
	        }
	        else
	        {
	        	$text .= "ERROR\n";
	            $text .= "              |---->  MISSING: text.php\n";
                $add   = 0;
	        }

            /* Check emails folder */
	        $text .= "        |-> /emails:  ";
	        if (file_exists($email) && filetype($email) == 'dir')
	        {
	        	$err = '';
	            foreach ($valid_emails as $eml)
	            {
	            	if (!file_exists($email.'/'.$eml.'.txt'))
	                {
	                	$err .= "              |---->  MISSING: $eml.txt\n";
	                }
	            }

	            if ($err)
	            {
	            	$text .= "ERROR\n" . $err;
                    $add   = 0;
	            }
	            else
	            {
	        		$text .= "OK\n";
	            }
	        }
	        else
	        {
	        	$text .= "ERROR\n";
	            $text .= "              |---->  MISSING: /emails folder\n";
                $add   = 0;
	        }

            $text .= "        |-> /html_emails:  ";
            if (file_exists($html_email) && filetype($html_email) == 'dir')
            {
                $err = '';
                foreach ($valid_emails as $eml)
                {
                    if (!file_exists($html_email.'/'.$eml.'.txt'))
                    {
                        $err .= "              |---->  MISSING: $eml.txt\n";
                    }
                }

                if ($err)
                {
                    $text .= "ERROR\n" . $err;
                    $add   = 0;
                }
                else
                {
                    $text .= "OK\n";
                }
            }
            else
            {
                $text .= "ERROR\n";
                $text .= "              |---->  MISSING: /html_emails folder\n";
                $add   = 0;
            }

	        $text .= "\n";

            /* Add an option for the <select> if needed */
            if ($add)
            {
				if ($l[1] == $hesk_settings['language_default'])
				{
					$html .= '<option value="'.$subdir.'|'.$l[1].'" selected="selected">'.$l[1].'</option>';
				}
				else
				{
					$html .= '<option value="'.$subdir.'|'.$l[1].'">'.$l[1].'</option>';
				}
            }
		}
	}

	closedir($path);

    /* Output select options or the test log for debugging */
    if ($return_options)
    {
		return $html;
    }
    else
    {
		?>
		<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML; 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
		<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
		<head>
		<title><?php echo $hesklang['s_inl']; ?></title>
		<meta http-equiv="Content-Type" content="text/html;charset=<?php echo $hesklang['ENCODING']; ?>" />
		<style type="text/css">
		body
		{
		        margin:5px 5px;
		        padding:0;
		        background:#fff;
		        color: black;
		        font : 68.8%/1.5 Verdana, Geneva, Arial, Helvetica, sans-serif;
		        text-align:left;
		}

		p
		{
		        color : black;
		        font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
		        font-size: 1.0em;
		}
		h3
		{
		        color : #AF0000;
		        font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
		        font-weight: bold;
		        font-size: 1.0em;
		        text-align:center;
		}
		.title
		{
		        color : black;
		        font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
		        font-weight: bold;
		        font-size: 1.0em;
		}
		.wrong   {color : red;}
		.correct {color : green;}
        pre {font-size:1.2em;}
		</style>
		</head>
		<body>

		<h3><?php echo $hesklang['s_inl']; ?></h3>

		<p><i><?php echo $hesklang['s_inle']; ?></i></p>

		<pre><?php echo $text; ?></pre>

		<p>&nbsp;</p>

		<p align="center"><a href="admin_settings_general.php?test_languages=1&amp;<?php echo rand(10000,99999); ?>"><?php echo $hesklang['ta']; ?></a> | <a href="#" onclick="Javascript:window.close()"><?php echo $hesklang['cwin']; ?></a></p>

		<p>&nbsp;</p>

		</body>

		</html>
		<?php
		exit();
    }
} // END hesk_testLanguage()
admin_settings_help_desk.php
wget 'https://lists2.roe3.org/hesk/admin/admin_settings_help_desk.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

define('LOAD_TABS',1);

// Make sure the install folder is deleted
if (is_dir(HESK_PATH . 'install')) {die('Please delete the <b>install</b> folder from your server for security reasons then refresh this page!');}

// Get all the required files and functions
require(HESK_PATH . 'hesk_settings.inc.php');

// Save the default language for the settings page before choosing user's preferred one
$hesk_settings['language_default'] = $hesk_settings['language'];
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/setup_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_man_settings');

// Load custom fields
require_once(HESK_PATH . 'inc/custom_fields.inc.php');

$help_folder = '../language/' . $hesk_settings['languages'][$hesk_settings['language']]['folder'] . '/help_files/';

$enable_save_settings   = 0;
$enable_use_attachments = 0;

// Print header
require_once(HESK_PATH . 'inc/header.inc.php');

// Print main manage users page
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

// Demo mode? Hide values of sensitive settings
if ( defined('HESK_DEMO') )
{
    require_once(HESK_PATH . 'inc/admin_settings_demo.inc.php');
}

/* This will handle error, success and notice messages */
hesk_handle_messages();

if ($hesk_settings['attachments']['use'] && ! defined('HESK_DEMO') ) {
// Check number of attachments per post
    if (version_compare(phpversion(), '5.2.12', '>=') && @ini_get('max_file_uploads') && @ini_get('max_file_uploads') < $hesk_settings['attachments']['max_number']) {
        hesk_show_notice($hesklang['fatte1']);
    }

// Check max attachment size
    $tmp = @ini_get('upload_max_filesize');
    if ($tmp) {
        $last = strtoupper(substr($tmp, -1));
        $number = substr($tmp, 0, -1);

        switch ($last) {
            case 'K':
                $tmp = $number * 1024;
                break;
            case 'M':
                $tmp = $number * 1048576;
                break;
            case 'G':
                $tmp = $number * 1073741824;
                break;
            default:
                $tmp = $number;
        }

        if ($tmp < $hesk_settings['attachments']['max_size']) {
            hesk_show_notice($hesklang['fatte2']);
        }
    }

// Check max post size
    /*
    $tmp = @ini_get('post_max_size');
    if ($tmp) {
        $last = strtoupper(substr($tmp, -1));
        $number = substr($tmp, 0, -1);

        switch ($last) {
            case 'K':
                $tmp = $number * 1024;
                break;
            case 'M':
                $tmp = $number * 1048576;
                break;
            case 'G':
                $tmp = $number * 1073741824;
                break;
            default:
                $tmp = $number;
        }

        if ($tmp < ($hesk_settings['attachments']['max_size'] * $hesk_settings['attachments']['max_number'] + 524288)) {
            hesk_show_notice($hesklang['fatte3']);
        }
    }
    */
}
?>
<div class="main__content settings admin_settings_help_desk">

    <?php require_once(HESK_PATH . 'inc/admin_settings_status.inc.php'); ?>

    <script language="javascript" type="text/javascript"><!--
        function hesk_checkFields() {
            var d = document.form1;

            // HELPDESK
            if (d.s_max_listings.value=='') {alert('<?php echo addslashes($hesklang['err_max']); ?>'); return false;}
            if (d.s_print_font_size.value=='') {alert('<?php echo addslashes($hesklang['err_psize']); ?>'); return false;}

            // DISABLE SUBMIT BUTTON
            d.submitbutton.disabled=true;

            return true;
        }

        function hesk_toggleLayer(nr,setto) {
            if (document.all)
                document.all[nr].style.display = setto;
            else if (document.getElementById)
                document.getElementById(nr).style.display = setto;
        }

        function checkRequiredEmail(field) {
            if (document.getElementById('s_require_email_0').checked && document.getElementById('s_email_view_ticket').checked)
            {
                if (field == 's_require_email_0' && confirm('<?php echo addslashes($hesklang['re_confirm1']); ?>'))
                {
                    document.getElementById('s_email_view_ticket').checked = false;
                    return true;
                }
                else if (field == 's_email_view_ticket' && confirm('<?php echo addslashes($hesklang['re_confirm2']); ?>'))
                {
                    document.getElementById('s_require_email_1').checked = true;
                    return true;
                }
                return false;
            }
            return true;
        }

        function hesk_generateUrlAccessKey(fID) {
            var length           = Math.random() * (30 - 20) + 20;
            var result           = '';
            var characters       = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ1234567890-_.';
            var charactersLength = characters.length;
            for ( var i = 0; i < length; i++ ) {
                result += characters.charAt(Math.floor(Math.random() * charactersLength));
            }
            $('#' + fID).val(result);
        }
        //Email attachment options
        $("body").on("change","input:radio[name=attachment_in_email_type]",function(){
            var f = $(this).val();
            if(f==0){
                $(".direct_attachment_section").css('display','none');
            }else{
                $(".direct_attachment_section").css('display','flex');
            }
        });
        //-->
    </script>
    <form method="post" action="admin_settings_save.php" name="form1" onsubmit="return hesk_checkFields()" aria-label="<?php echo $hesklang['hd']; ?>">
        <div class="settings__form form">
            <section class="settings__form_block">
                <h3><?php echo $hesklang['hd']; ?></h3>
                <div class="form-group">
                    <label for="s_admin_dir">
                        <span><?php echo $hesklang['adf']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#61','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_admin_dir" name="s_admin_dir" maxlength="255" value="<?php echo $hesk_settings['admin_dir']; ?>">
                </div>
                <div class="form-group">
                    <label for="s_attach_dir">
                        <span><?php echo $hesklang['atf']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#62','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_attach_dir" name="s_attach_dir" maxlength="255" value="<?php echo $hesk_settings['attach_dir']; ?>">
                </div>
                <div class="form-group">
                    <label for="s_cache_dir">
                        <span><?php echo $hesklang['cf']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#77','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_cache_dir" name="s_cache_dir" maxlength="255" value="<?php echo $hesk_settings['cache_dir']; ?>">
                </div>
                <div class="form-group short">
                    <label for="s_max_listings">
                        <span><?php echo $hesklang['max_listings']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#10','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_max_listings" name="s_max_listings" maxlength="30" value="<?php echo $hesk_settings['max_listings']; ?>">
                </div>
                <div class="form-group short">
                    <label for="s_print_font_size">
                        <span><?php echo $hesklang['print_size']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#11','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_print_font_size" name="s_print_font_size" maxlength="3" value="<?php echo $hesk_settings['print_font_size']; ?>">
                </div>
                <div class="form-group short">
                    <label for="s_autoclose">
                        <span><?php echo $hesklang['aclose']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#15','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_autoclose" name="s_autoclose" size="5" maxlength="3" value="<?php echo $hesk_settings['autoclose']; ?>">
                    <span><?php echo $hesklang['aclose2']; ?></span>
                </div>
                <div class="form-group short">
                    <label for="s_max_open">
                        <span><?php echo $hesklang['mop']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#58','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_max_open" name="s_max_open" size="5" maxlength="3" value="<?php echo $hesk_settings['max_open']; ?>">
                </div>
                <div class="form-group short">
                    <label for="s_due_soon">
                        <span><?php echo $hesklang['set_ds']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#84','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_due_soon" name="s_due_soon" size="5" maxlength="3" value="<?php echo $hesk_settings['due_soon']; ?>">
                    <span><?php echo $hesklang['set_ds2']; ?></span>
                </div>
                <div class="radio-group mt24">
                    <h5>
                        <span><?php echo $hesklang['rord']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#59','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="radio-list">
                        <?php
                        $on = $hesk_settings['new_top'] ? 'checked' : '';
                        $off = $hesk_settings['new_top'] ? '' : 'checked';
                        ?>
                        <div class="radio-custom">
                            <input type="radio" id="s_new_top1" name="s_new_top" value="1" <?php echo $on; ?>>
                            <label for="s_new_top1"><?php echo $hesklang['newtop']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_new_top0" name="s_new_top" value="0"  <?php echo $off; ?>>
                            <label for="s_new_top0"><?php echo $hesklang['newbot']; ?></label>
                        </div>
                    </div>
                </div>
                <div class="radio-group">
                    <h5>
                        <span><?php echo $hesklang['ford']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#60','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <?php
                        $on = $hesk_settings['reply_top'] ? 'checked="checked"' : '';
                        $off = $hesk_settings['reply_top'] ? '' : 'checked="checked"';
                    ?>
                    <div class="radio-list">
                        <div class="radio-custom">
                            <input type="radio" id="s_reply_top1" name="s_reply_top" value="1" <?php echo $on; ?>>
                            <label for="s_reply_top1"><?php echo $hesklang['formtop']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_reply_top0" name="s_reply_top" value="0" <?php echo $off; ?>>
                            <label for="s_reply_top0"><?php echo $hesklang['formbot']; ?></label>
                        </div>
                    </div>
                </div>
                <?php
                $no = $hesk_settings['hide_replies']==0 ? 'checked' : '';
                $yes = $hesk_settings['hide_replies']>0 ? 'checked' : '';
                $def = $hesk_settings['hide_replies']==-1 ? 'checked' : '';
                ?>
                <div class="radio-group">
                    <h5>
                        <span><?php echo $hesklang['hide_replies']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#78','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="radio-list">
                        <div class="radio-custom">
                            <input type="radio" id="s_hide_replies0" name="s_hide_replies" value="0" <?php echo $no; ?>>
                            <label for="s_hide_replies0"><?php echo $hesklang['hide_replies_no']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_hide_replies-1" name="s_hide_replies" value="-1" <?php echo $def; ?>>
                            <label for="s_hide_replies-1"><?php echo $hesklang['hide_replies_def']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_hide_replies1" name="s_hide_replies" value="1" <?php echo $yes; ?>>
                            <label for="s_hide_replies1"><?php echo $hesklang['hide_replies_yes']; ?></label>
                            <div class="form-group short" style="margin-bottom: 0px;">
                                <input type="text" name="s_hide_replies_num" class="form-control" style="margin-left: 12px;" size="5" maxlength="4"
                                       value="<?php echo ($hesk_settings['hide_replies'] > 0 ? $hesk_settings['hide_replies'] : '10'); ?>" aria-label="Number of replies">
                            </div>
                        </div>
                    </div>
                </div>
                <?php
                $no = $hesk_settings['limit_width']==0 ? 'checked' : '';
                $yes = $hesk_settings['limit_width']>0 ? 'checked' : '';
                ?>
                <div class="radio-group">
                    <h5>
                        <span><?php echo $hesklang['lwidth']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#79','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="radio-list">
                        <div class="radio-custom">
                            <input type="radio" id="s_limit_width0" name="s_limit_width" value="0" <?php echo $no; ?>>
                            <label for="s_limit_width0"><?php echo $hesklang['lwidtall']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_limit_width1" name="s_limit_width" value="1" <?php echo $yes; ?>>
                            <label for="s_limit_width1"><?php echo $hesklang['lwidtpx']; ?></label>
                            <div class="form-group short" style="margin-bottom: 0px;">
                                <input type="text" name="s_limit_width_num" class="form-control" style="margin-left: 12px;" size="5" maxlength="4"
                                       value="<?php echo ($hesk_settings['limit_width'] > 0 ? $hesk_settings['limit_width'] : '800'); ?>" aria-label="Pixels">
                            </div>
                        </div>
                    </div>
                </div>
            </section>
            <section class="settings__form_block">
                <h3><?php echo $hesklang['features']; ?></h3>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['alo']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#44','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['alo']; ?>">
                        <input type="checkbox" name="s_autologin" value="1" <?php if ($hesk_settings['autologin']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['saass']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#51','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['saass']; ?>">
                        <input type="checkbox" name="s_autoassign" value="1" <?php if ($hesk_settings['autoassign']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['req_email']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#73','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['req_email']; ?>">
                        <input type="checkbox" name="s_require_email" value="1" <?php if ($hesk_settings['require_email']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['fass']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#70','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['fass']; ?>">
                        <input type="checkbox" name="s_require_owner" value="1" <?php if ($hesk_settings['require_owner']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <?php
                $on = $hesk_settings['require_subject']==1 ? 'checked' : '';
                $off = $hesk_settings['require_subject']==0 ? 'checked' : '';
                $hide = $hesk_settings['require_subject']==-1 ? 'checked' : '';
                ?>
                <div class="radio-group">
                    <h5>
                        <span><?php echo $hesklang['req_sub']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#72','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="radio-list">
                        <div class="radio-custom">
                            <input type="radio" id="s_require_subject0" name="s_require_subject" value="0" <?php echo $off; ?>>
                            <label for="s_require_subject0"><?php echo $hesklang['off']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_require_subject1" name="s_require_subject" value="1" <?php echo $on; ?>>
                            <label for="s_require_subject1"><?php echo $hesklang['on']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_require_subject-1" name="s_require_subject" value="-1" <?php echo $hide; ?>>
                            <label for="s_require_subject-1"><?php echo $hesklang['off-hide']; ?></label>
                        </div>
                    </div>
                </div>
                <?php
                $on = $hesk_settings['require_message']==1 ? 'checked' : '';
                $off = $hesk_settings['require_message']==0 ? 'checked' : '';
                $hide = $hesk_settings['require_message']==-1 ? 'checked' : '';
                ?>
                <div class="radio-group">
                    <h5>
                        <span><?php echo $hesklang['req_msg']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#74','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="radio-list">
                        <div class="radio-custom">
                            <input type="radio" id="s_require_message0" name="s_require_message" value="0" <?php echo $off; ?>>
                            <label for="s_require_message0"><?php echo $hesklang['off']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_require_message1" name="s_require_message" value="1" <?php echo $on; ?>>
                            <label for="s_require_message1"><?php echo $hesklang['on']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_require_message-1" name="s_require_message" value="-1" <?php echo $hide; ?>>
                            <label for="s_require_message-1"><?php echo $hesklang['off-hide']; ?></label>
                        </div>
                    </div>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['ccct']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#67','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['ccct']; ?>">
                        <input type="checkbox" name="s_custclose" value="1" <?php if ($hesk_settings['custclose']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['s_ucrt']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#16','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['s_ucrt']; ?>">
                        <input type="checkbox" name="s_custopen" value="1" <?php if ($hesk_settings['custopen']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['urate']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#17','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['urate']; ?>">
                        <input type="checkbox" name="s_rating" value="1" <?php if ($hesk_settings['rating']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['cpri']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#45','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['cpri']; ?>">
                        <input type="checkbox" name="s_cust_urgency" value="1" <?php if ($hesk_settings['cust_urgency']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['eseqid']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#49','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['eseqid']; ?>">
                        <input type="checkbox" name="s_sequential" value="1" <?php if ($hesk_settings['sequential']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['ts']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#66','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['ts']; ?>">
                        <input type="checkbox" name="s_time_worked" value="1" <?php if ($hesk_settings['time_worked']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['spamn']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#68','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['spamn']; ?>">
                        <input type="checkbox" name="s_spam_notice" value="1" <?php if ($hesk_settings['spam_notice']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['lu']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#14','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['lu']; ?>">
                        <input type="checkbox" name="s_list_users" value="1" <?php if ($hesk_settings['list_users']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['debug_mode']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#12','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['debug_mode']; ?>">
                        <input type="checkbox" name="s_debug_mode" value="1" <?php if ($hesk_settings['debug_mode']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['shu']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#63','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['shu']; ?>">
                        <input type="checkbox" name="s_short_link" value="1" <?php if ($hesk_settings['short_link']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['sending_show']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#91','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['sending_show']; ?>">
                        <input type="checkbox" name="s_submitting_wait" value="1" <?php if ($hesk_settings['submitting_wait']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['remember_custom_field_values']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>370.html#6','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['remember_custom_field_values']; ?>">
                        <input type="checkbox" name="s_remember_custom_field_values" value="1" <?php if ($hesk_settings['remember_custom_field_values']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['disable_autocomplete']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>370.html#7','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div style="display:block;">
                        <label class="switch-checkbox" aria-label="<?php echo $hesklang['disable_autocomplete']; ?>">
                            <input type="checkbox" name="s_disable_autofill_admin" value="1" <?php if ($hesk_settings['disable_autofill_admin']) { echo 'checked'; } ?>>
                            <div class="switch-checkbox__bullet">
                                <i>
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                    <svg class="icon icon-tick">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                    </svg>
                                </i>
                            </div>
                            <span><?php echo $hesklang['disable_autofill_admin']; ?></span>
                        </label>
                        <br>
                        <label class="switch-checkbox">
                            <input type="checkbox" name="s_disable_autofill_customer" <?php if ($hesk_settings['disable_autofill_customer']) { echo 'checked'; } ?>>
                            <div class="switch-checkbox__bullet">
                                <i>
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                    <svg class="icon icon-tick">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                    </svg>
                                </i>
                            </div>
                            <span><?php echo $hesklang['disable_autofill_customer']; ?></span>
                        </label>
                    </div>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['setting_extend']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>370.html#2','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div style="display:block;">
                        <label class="switch-checkbox">
                            <input type="checkbox" name="s_extend_admin" value="1" <?php if ($hesk_settings['extend_admin']) { echo 'checked'; } ?>>
                            <div class="switch-checkbox__bullet">
                                <i>
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                    <svg class="icon icon-tick">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                    </svg>
                                </i>
                            </div>
                            <span><?php echo $hesklang['extend_admin']; ?></span>
                        </label>
                        <br>
                        <label class="switch-checkbox">
                            <input type="checkbox" name="s_extend_customer" <?php if ($hesk_settings['extend_customer']) { echo 'checked'; } ?>>
                            <div class="switch-checkbox__bullet">
                                <i>
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                    <svg class="icon icon-tick">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                    </svg>
                                </i>
                            </div>
                            <span><?php echo $hesklang['extend_customer']; ?></span>
                        </label>
                    </div>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['select']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#65','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div style="display:block;">
                        <label class="switch-checkbox">
                            <input type="checkbox" name="s_select_cat" value="1" <?php if ($hesk_settings['select_cat']) { echo 'checked'; } ?>>
                            <div class="switch-checkbox__bullet">
                                <i>
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                    <svg class="icon icon-tick">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                    </svg>
                                </i>
                            </div>
                            <span><?php echo $hesklang['category']; ?></span>
                        </label>
                        <br>
                        <label class="switch-checkbox">
                            <input type="checkbox" name="s_select_pri" <?php if ($hesk_settings['select_pri']) { echo 'checked'; } ?>>
                            <div class="switch-checkbox__bullet">
                                <i>
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                    <svg class="icon icon-tick">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                    </svg>
                                </i>
                            </div>
                            <span><?php echo $hesklang['priority']; ?></span>
                        </label>
                    </div>
                </div>
                <div class="form-group short">
                    <label for="s_cat_show_select">
                        <span><?php echo $hesklang['scat']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#71','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_cat_show_select" name="s_cat_show_select" maxlength="3" value="<?php echo $hesk_settings['cat_show_select']; ?>">
                    <span><?php echo $hesklang['scat2']; ?></span>
                </div>
                <?php
                $plain = $hesk_settings['staff_ticket_formatting']==0 ? 'checked' : '';
                if ( ! class_exists('DOMDocument')) {
                    $rich_text = false;
                    $plain = 'checked';
                    $html = '';
                } else {
                    $rich_text = true;
                    $html = $hesk_settings['staff_ticket_formatting']==2 ? 'checked' : '';
                }
                ?>
                <div class="radio-group">
                    <h5>
                        <span><?php echo $hesklang['ticket_formatting_staff']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#80','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="radio-list">
                        <div class="radio-custom">
                            <input type="radio" id="s_ticket_formatting_staff0" name="s_ticket_formatting_staff" value="0" <?php echo $plain; ?>>
                            <label for="s_ticket_formatting_staff0"><?php echo $hesklang['ticket_formatting_plaintext']; ?></label>
                        </div>
                        <?php if ($rich_text): ?>
                        <div class="radio-custom">
                            <input type="radio" id="s_ticket_formatting_staff2" name="s_ticket_formatting_staff" value="2" <?php echo $html; ?>>
                            <label for="s_ticket_formatting_staff2"><?php echo $hesklang['ticket_formatting_rich_text']; ?></label>
                        </div>
                        <?php else: ?>
                        <span style="margin-left: 24px;"><?php echo $hesklang['ticket_formatting_rich_text']; ?> - <?php echo $hesklang['require_xml']; ?></span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['ticket_followers']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#57','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_multi_eml1" name="s_multi_eml" value="1" <?php if ($hesk_settings['multi_eml']) {echo 'checked';} ?>>
                        <label for="s_multi_eml1"><?php echo $hesklang['ticket_followers2']; ?></label>
                    </div>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['nicknames']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>370.html#3','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_staff_nicknames" name="s_staff_nicknames" value="1" <?php if ($hesk_settings['staff_nicknames']) {echo 'checked';} ?>>
                        <label for="s_staff_nicknames"><?php echo $hesklang['staff_nicknames']; ?></label>
                    </div>
                </div>
            </section>
            <section class="settings__form_block">
                <h3><?php echo $hesklang['barcode']; ?></h3>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['barcode_use'];?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#90','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <?php
                    $div = $hesk_settings['barcode']['print'] ? 'block' : 'none';
                    ?>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['barcode']; ?>">
                        <input type="checkbox" name="s_barcode_print" value="1" <?php if ($hesk_settings['barcode']['print']) { echo 'checked'; } ?> onclick="hesk_toggleLayerDisplay('barcode')">
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div id="barcode" style="display: <?php echo $div; ?>;">
                    <div class="checkbox-group">
                        <h5 aria-label="<?php echo $hesklang['barcode_staff_only']; ?>"></h5>
                        <div class="checkbox-custom">
                            <input type="checkbox" id="s_staff_only" name="s_staff_only" value="1" <?php if ($hesk_settings['barcode']['staff_only']) {echo 'checked';} ?>>
                            <label for="s_staff_only"><?php echo $hesklang['barcode_staff_only']; ?></label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="barcode-type-select">
                            <span><?php echo $hesklang['barcode_type']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#90','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <div class="dropdown-select center out-close">
                            <select name="s_barcode_type" id="barcode-type-select">
                                <?php foreach ($hesk_settings['barcode_types'] as $type => $description): ?>
                                <option value="<?php echo $type; ?>" <?php echo $type == $hesk_settings['barcode']['type'] ? 'selected' : '' ?>>
                                    <?php echo $description; ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="barcode-format-select">
                            <span><?php echo $hesklang['barcode_format']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#90','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <div class="dropdown-select center out-close">
                            <select name="s_barcode_format" id="barcode-format-select">
                                <?php foreach ($hesk_settings['barcode_formats'] as $format => $description): ?>
                                <option value="<?php echo $format; ?>" <?php echo $format == $hesk_settings['barcode']['format'] ? 'selected' : '' ?>>
                                    <?php echo $description; ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="form-group short">
                        <label for="s_barcode_width">
                            <span><?php echo $hesklang['barcode_width']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#90','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" class="form-control" id="s_barcode_width" name="s_barcode_width" maxlength="30" value="<?php echo $hesk_settings['barcode']['width']; ?>">
                    </div>
                    <div class="form-group short">
                        <label for="s_barcode_height">
                            <span><?php echo $hesklang['barcode_height']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#90','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" class="form-control" id="s_barcode_height" name="s_barcode_height" maxlength="30" value="<?php echo $hesk_settings['barcode']['height']; ?>">
                    </div>
                    <div class="form-group short">
                        <label for="s_barcode_color">
                            <span><?php echo $hesklang['barcode_color']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#90','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" class="form-control" id="s_barcode_color" name="s_barcode_color" maxlength="30" value="<?php echo $hesk_settings['barcode']['color']; ?>">
                    </div>
                    <div class="form-group short">
                        <label for="s_barcode_bg">
                            <span><?php echo $hesklang['barcode_bg']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#90','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" class="form-control" id="s_barcode_bg" name="s_barcode_bg" maxlength="30" value="<?php echo $hesk_settings['barcode']['bg']; ?>">
                    </div>
                </div>
            </section>
            <section class="settings__form_block">
                <h3><?php echo $hesklang['customer_accounts_heading']; ?></h3>
                <div class="radio-group">
                    <h5>
                        <span><?php echo $hesklang['customer_accounts']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#87','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <?php
                    if ($hesk_settings['customer_accounts'] == 0) {
                        $ca0 = 'checked';
                        $ca1 = '';
                        $ca2 = '';
                        $ca3 = '';
                        $div = 'none';
                    } elseif ($hesk_settings['customer_accounts_required'] == 0) {
                        $ca0 = '';
                        $ca1 = 'checked';
                        $ca2 = '';
                        $ca3 = '';
                        $div = 'block';
                    } elseif ($hesk_settings['customer_accounts_required'] == 2) {
                        $ca0 = '';
                        $ca1 = '';
                        $ca2 = '';
                        $ca3 = 'checked';
                        $div = 'block';
                    } else {
                        $ca0 = '';
                        $ca1 = '';
                        $ca2 = 'checked';
                        $ca3 = '';
                        $div = 'block';
                    }
                    ?>
                    <div class="radio-list">
                        <div class="radio-custom">
                            <input type="radio" id="s_customer_accounts0" name="s_customer_accounts" value="0" <?php echo $ca0; ?> onclick="hesk_toggleLayer('ca','none')">
                            <label for="s_customer_accounts0"><?php echo $hesklang['customer_accounts_off']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_customer_accounts1" name="s_customer_accounts" value="1" <?php echo $ca1; ?> onclick="hesk_toggleLayer('ca','block')">
                            <label for="s_customer_accounts1"><?php echo $hesklang['customer_accounts_allowed']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_customer_accounts2" name="s_customer_accounts" value="2" <?php echo $ca2; ?> onclick="hesk_toggleLayer('ca','block')">
                            <label for="s_customer_accounts2"><?php echo $hesklang['customer_accounts_required_to_submit']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_customer_accounts3" name="s_customer_accounts" value="3" <?php echo $ca3; ?> onclick="hesk_toggleLayer('ca','block')">
                            <label for="s_customer_accounts3"><?php echo $hesklang['customer_accounts_required']; ?></label>
                        </div>
                    </div>
                </div>
                <div id="ca" style="display: <?php echo $div; ?>;">
                    <?php
                    if ($hesk_settings['customer_accounts_customer_self_register'] == 0) {
                        $ca0 = '';
                        $ca1 = '';
                        $ca2 = 'checked';
                        $div = 'none';
                    } elseif ($hesk_settings['customer_accounts_admin_approvals'] == 1) {
                        $ca0 = '';
                        $ca1 = 'checked';
                        $ca2 = '';
                        $div = 'block';
                    } else {
                        $ca0 = 'checked';
                        $ca1 = '';
                        $ca2 = '';
                        $div = 'block';
                    }
                    ?>
                    <div class="radio-group">
                        <h5>
                            <span><?php echo $hesklang['customer_accounts_reg']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#88','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </h5>
                        <div class="radio-list">
                            <div class="radio-custom">
                                <input type="radio" id="s_customer_accounts_register0" name="s_customer_accounts_register" value="0" <?php echo $ca0; ?>>
                                <label for="s_customer_accounts_register0"><?php echo $hesklang['customer_accounts_reg_customer']; ?></label>
                            </div>
                            <div class="radio-custom">
                                <input type="radio" id="s_customer_accounts_register1" name="s_customer_accounts_register" value="1" <?php echo $ca1; ?>>
                                <label for="s_customer_accounts_register1"><?php echo $hesklang['customer_accounts_reg_approve']; ?></label>
                            </div>
                            <div class="radio-custom">
                                <input type="radio" id="s_customer_accounts_register2" name="s_customer_accounts_register" value="2" <?php echo $ca2; ?>>
                                <label for="s_customer_accounts_register2"><?php echo $hesklang['customer_accounts_reg_staff']; ?></label>
                            </div>
                        </div>
                    </div>
                    <div class="checkbox-group row">
                        <h5>
                            <span><?php echo $hesklang['alo']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#94','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </h5>
                        <label class="switch-checkbox" aria-label="<?php echo $hesklang['alo']; ?>">
                            <input type="checkbox" name="s_customer_autologin" value="1" <?php if ($hesk_settings['customer_autologin']) { echo 'checked'; } ?>>
                            <div class="switch-checkbox__bullet">
                                <i>
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                    <svg class="icon icon-tick">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                    </svg>
                                </i>
                            </div>
                        </label>
                    </div>
                    <div class="checkbox-group row">
                        <h5>
                            <span><?php echo $hesklang['customer_accounts_allow_email_changes']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#92','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </h5>
                        <label class="switch-checkbox" aria-label="<?php echo $hesklang['customer_accounts_allow_email_changes']; ?>">
                            <input type="checkbox" name="s_customer_accounts_allow_email_changes" value="1"
                                <?php if ($hesk_settings['customer_accounts_allow_email_changes']) { echo 'checked'; } ?>>
                            <div class="switch-checkbox__bullet">
                                <i>
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                    <svg class="icon icon-tick">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                    </svg>
                                </i>
                            </div>
                        </label>
                    </div>
                    <div class="form-group short">
                        <label for="s_customer_accounts_verify_email_cooldown">
                            <span><?php echo $hesklang['customer_accounts_allow_email_resends']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#93','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" class="form-control" id="s_customer_accounts_verify_email_cooldown" name="s_customer_accounts_verify_email_cooldown" size="5" maxlength="3" value="<?php echo $hesk_settings['customer_accounts_verify_email_cooldown']; ?>">
                        <span><?php echo $hesklang['mm']; ?></span>
                    </div>
                </div>
            </section>
            <section class="settings__form_block">
                <h3><?php echo $hesklang['sp']; ?></h3>
                <div class="radio-group">
                    <h5>
                        <span><?php echo $hesklang['use_secimg']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#13','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <?php
                    $onc = $hesk_settings['secimg_use'] == 1 ? 'checked' : '';
                    $ons = $hesk_settings['secimg_use'] == 2 ? 'checked' : '';
                    $off = $hesk_settings['secimg_use'] ? '' : 'checked';
                    $div = $hesk_settings['secimg_use'] ? 'block' : 'none';
                    ?>
                    <div class="radio-list">
                        <div class="radio-custom">
                            <input type="radio" id="s_secimg_use0" name="s_secimg_use" value="0" <?php echo $off; ?> onclick="hesk_toggleLayer('captcha','none')">
                            <label for="s_secimg_use0"><?php echo $hesklang['off']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_secimg_use1" name="s_secimg_use" value="1" <?php echo $onc; ?> onclick="hesk_toggleLayer('captcha','block')">
                            <label for="s_secimg_use1"><?php echo $hesklang['onc']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_secimg_use2" name="s_secimg_use" value="2" <?php echo $ons; ?> onclick="hesk_toggleLayer('captcha','block')">
                            <label for="s_secimg_use2"><?php echo $hesklang['ons']; ?></label>
                        </div>
                    </div>
                </div>
                <div id="captcha" style="display: <?php echo $div; ?>;">
                    <?php

                    $on  = '';
                    $on2 = '';
                    $off = '';
                    $div = 'block';

                    if ($hesk_settings['recaptcha_use'] == 1) {
                        $on = 'checked';
                    } elseif ($hesk_settings['recaptcha_use'] == 2) {
                        $on2 = 'checked';
                    } else {
                        $off = 'checked';
                        $div = 'none';
                    }
                    ?>
                    <div class="radio-group">
                        <h5>
                            <span><?php echo $hesklang['sit']; ?></span>
                        </h5>
                        <div class="radio-list">
                            <div class="radio-custom">
                                <input type="radio" id="s_recaptcha_use0" name="s_recaptcha_use" value="0" onclick="hesk_toggleLayer('recaptcha','none')" <?php echo $off; ?>>
                                <label for="s_recaptcha_use0"><?php echo $hesklang['sis']; ?></label>
                            </div>
                            <div class="radio-custom">
                                <input type="radio" id="s_recaptcha_use2" name="s_recaptcha_use" value="2" onclick="hesk_toggleLayer('recaptcha','block')" <?php echo $on2; ?>>
                                <label for="s_recaptcha_use2"><?php echo $hesklang['recaptcha']; ?> v2</label>
                                <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#64','400','500')">
                                    <div class="tooltype right">
                                        <svg class="icon icon-info">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                        </svg>
                                    </div>
                                </a>
                            </div>
                            <div class="radio-custom">
                                <input type="radio" id="s_recaptcha_use1" name="s_recaptcha_use" value="1" onclick="hesk_toggleLayer('recaptcha','block')" <?php echo $on; ?>>
                                <label for="s_recaptcha_use1"><?php echo $hesklang['sir3']; ?></label>
                                <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#64','400','500')">
                                    <div class="tooltype right">
                                        <svg class="icon icon-info">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                        </svg>
                                    </div>
                                </a>
                            </div>
                        </div>
                    </div>
                    <div id="recaptcha" style="display: <?php echo $div; ?>; margin-bottom: 20px">
                        <div class="form-group">
                            <label for="s_recaptcha_public_key">
                                <span><?php echo $hesklang['rcpb']; ?></span>
                                <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#64','400','500')">
                                    <div class="tooltype right">
                                        <svg class="icon icon-info">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                        </svg>
                                    </div>
                                </a>
                            </label>
                            <input type="text" class="form-control" id="s_recaptcha_public_key" name="s_recaptcha_public_key" maxlength="255" value="<?php echo $hesk_settings['recaptcha_public_key']; ?>">
                        </div>
                        <div class="form-group">
                            <label for="s_recaptcha_private_key">
                                <span><?php echo $hesklang['rcpv']; ?></span>
                                <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#64','400','500')">
                                    <div class="tooltype right">
                                        <svg class="icon icon-info">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                        </svg>
                                    </div>
                                </a>
                            </label>
                            <input type="text" class="form-control" id="s_recaptcha_private_key" name="s_recaptcha_private_key" maxlength="255" value="<?php echo $hesk_settings['recaptcha_private_key']; ?>">
                        </div>
                    </div>
                    <div class="divider"></div>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['use_q']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#42','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <?php
                    $div = $hesk_settings['question_use'] ? 'block' : 'none';
                    ?>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['use_q']; ?>">
                        <input type="checkbox" name="s_question_use" value="1" <?php if ($hesk_settings['question_use']) { echo 'checked'; } ?> onclick="hesk_toggleLayerDisplay('question')">
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div id="question" style="display: <?php echo $div; ?>;">
                    <div class="form-group">
                        <h5 aria-label="<?php echo $hesklang['genq']; ?>"></h5>
                        <button style="margin-left: 24px" type="button" class="btn btn--blue-border" onclick="Javascript:hesk_rate('generate_spam_question.php','question')">
                            <?php echo $hesklang['genq']; ?>
                        </button>
                    </div>
                    <div class="form-group">
                        <h5><span><?php echo $hesklang['q_q']; ?></span></h5>
                        <textarea style="margin-left: 24px;" name="s_question_ask" class="form-control" rows="3" cols="40" aria-label="<?php echo $hesklang['err_qask']; ?>"><?php echo hesk_htmlentities($hesk_settings['question_ask']); ?></textarea>
                    </div>
                    <div class="form-group">
                        <h5><span><?php echo $hesklang['q_a']; ?></span></h5>
                        <input class="form-control" type="text" name="s_question_ans" value="<?php echo $hesk_settings['question_ans']; ?>" aria-label="<?php echo $hesklang['err_qans']; ?>">
                    </div>
                </div>
            </section>
            <section class="settings__form_block">
                <h3><?php echo $hesklang['security']; ?></h3>
                <div class="form-group short">
                    <label for="s_attempt_limit">
                        <span><?php echo $hesklang['banlim']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#47','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_attempt_limit" name="s_attempt_limit" maxlength="30" value="<?php echo ($hesk_settings['attempt_limit'] ? ($hesk_settings['attempt_limit']-1) : 0); ?>">
                </div>
                <div class="form-group short">
                    <label for="s_attempt_banmin">
                        <span><?php echo $hesklang['banmin']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#47','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_attempt_banmin" name="s_attempt_banmin" maxlength="3" value="<?php echo $hesk_settings['attempt_banmin']; ?>">
                </div>
                <div class="form-group short">
                    <label for="s_flood">
                        <span><?php echo $hesklang['flood']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#81','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_flood" name="s_flood" maxlength="3" value="<?php echo $hesk_settings['flood']; ?>">
                    <span><?php echo $hesklang['seconds']; ?></span>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['passr']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#69','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_reset_pass" name="s_reset_pass" value="1" <?php if ($hesk_settings['reset_pass']) {echo 'checked';} ?>>
                        <label for="s_reset_pass"><?php echo $hesklang['passa']; ?></label>
                    </div>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['viewvtic']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#46','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_email_view_ticket" name="s_email_view_ticket" onclick="return checkRequiredEmail('s_email_view_ticket');" value="1" <?php if ($hesk_settings['email_view_ticket']) {echo 'checked';} ?>>
                        <label for="s_email_view_ticket"><?php echo $hesklang['reqetv']; ?></label>
                    </div>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['frames']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#76','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_x_frame_opt" name="s_x_frame_opt" value="1" <?php if ($hesk_settings['x_frame_opt']) {echo 'checked';} ?>>
                        <label for="s_x_frame_opt"><?php echo $hesklang['frames2']; ?></label>
                    </div>
                </div>
                <div class="form-group">
                    <label for="samesite-select">
                        <span><?php echo $hesklang['cookies']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#82','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <div class="dropdown-select center out-close">
                        <select name="s_samesite" id="samesite-select">
                        <?php
                        $samesite_options = array('Strict', 'Lax', 'None');
                        foreach ($samesite_options as $samesite_option)
                        {
                            echo '<option value="' . $samesite_option . '"' . ($hesk_settings['samesite'] == $samesite_option ? ' selected' : '') . '>' . $samesite_option . '</option>';
                        }
                        ?>
                        </select>
                    </div>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['ssl']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#75','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <?php if (HESK_SSL): ?>
                            <input type="checkbox" id="s_force_ssl" name="s_force_ssl" value="1" <?php echo ($hesk_settings['force_ssl'] ? 'checked' : ''); ?>>
                            <label for="s_force_ssl"><?php echo $hesklang['force_ssl']; ?></label>
                        <?php else: ?>
                            <label for="s_force_ssl"><?php echo $hesklang['d_ssl']; ?></label>
                        <?php endif; ?>
                    </div>
                </div>
                <div>
                    <div class="form-group flex-row">
                        <label for="s_url_key">
                            <span><?php echo $hesklang['ukey']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#83','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input class="form-control" type="text" id="url_key" name="s_url_key"
                               value="<?php echo hesk_htmlentities($hesk_settings['url_key']); ?>" aria-label="<?php echo $hesklang['ukey']; ?>">
                    </div>
                    <div class="form-group">
                        <h5 aria-label="<?php echo $hesklang['ukeyg']; ?>"></h5>
                        <button style="margin-left: 24px" type="button" class="btn btn--blue-border" onclick="Javascript:hesk_generateUrlAccessKey('url_key')">
                            <?php echo $hesklang['ukeyg']; ?>
                        </button>
                    </div>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['mfa_required']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#85','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div style="display:block;">
                        <label class="switch-checkbox">
                            <input type="checkbox" name="s_require_mfa" value="1" <?php if($hesk_settings['require_mfa'] === 1) {echo 'checked';} ?>>
                            <div class="switch-checkbox__bullet">
                                <i>
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                    <svg class="icon icon-tick">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                    </svg>
                                </i>
                            </div>
                            <span><?php echo $hesklang['for_staff']; ?></span>
                        </label>
                        <br>
                        <label class="switch-checkbox">
                            <input type="checkbox" name="s_require_mfa_customers" value="1" <?php if($hesk_settings['require_mfa_customers'] === 1) {echo 'checked';} ?>>
                            <div class="switch-checkbox__bullet">
                                <i>
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                    <svg class="icon icon-tick">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                    </svg>
                                </i>
                            </div>
                            <span><?php echo $hesklang['for_customers']; ?></span>
                        </label>
                    </div>
                </div>
                <div class="form-group short flex-row">
                    <?php
                    //-- Default value if duration in settings is invalid
                    $elevator_amount = 60;
                    $elevator_unit = 'M';

                    preg_match('/(\\d+)([MHD])/', $hesk_settings['elevator_duration'], $elevator_matches);
                    if (count($elevator_matches) === 3) {
                        $elevator_amount = $elevator_matches[1];
                        $elevator_unit = $elevator_matches[2];
                    }
                    ?>
                    <label for="s_elevator_amount">
                        <span><?php echo $hesklang['elevator_duration_setting_title']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#86','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_elevator_amount" name="s_elevator_amount" maxlength="6" value="<?php echo $elevator_amount; ?>">
                    <div class="dropdown-select center out-close">
                        <select name="s_elevator_unit">
                            <option value="M" <?php echo $elevator_unit === 'M' ? 'selected' : '' ?>>
                                <?php echo $hesklang['escalate']['minutes']; ?>
                            </option>
                            <option value="H" <?php echo $elevator_unit === 'H' ? 'selected' : '' ?>>
                                <?php echo $hesklang['escalate']['hours']; ?>
                            </option>
                            <option value="D" <?php echo $elevator_unit === 'D' ? 'selected' : '' ?>>
                                <?php echo $hesklang['escalate']['days']; ?>
                            </option>
                        </select>
                    </div>
                </div>
            </section>
            <section class="settings__form_block">
                <h3><?php echo $hesklang['attachments']; ?></h3>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['attach_use']; $onload_status=''; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#37','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <?php if ($enable_use_attachments) { ?>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['attach_use']; ?>">
                        <input type="checkbox" name="s_attach_use" value="1" <?php if($hesk_settings['attachments']['use']) {echo 'checked'; $layer_onload = 'block';} else {$onload_status = 'disabled';$layer_onload = 'none';} ?> onchange="hesk_attach_handle(this, new Array('a1','a2','a3','a4')); hesk_toggleLayerDisplay('attachment_restrictions')">
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                        <?php if (!defined('HESK_DEMO')): ?>
                            <a href="javascript:void(0);" onclick="hesk_toggleLayerDisplay('attachments_limits');"><?php echo $hesklang['vscl']; ?></a>
                        <?php endif; ?>
                    </label>
                            <?php
                    } else {
                        $onload_status=' disabled="disabled" ';
                        $layer_onload = 'none';
                        echo '<input type="hidden" name="s_attach_use" value="0" /><span style="margin-left: 24px;" class="notice">'.$hesklang['e_attach'].'</span>';
                    }
                    ?>
                </div>
                <?php if (!defined('HESK_DEMO')): ?>
                <div class="form-group">
                    <h5 aria-label="Attachment limits"></h5>
                    <div id="attachments_limits" style="margin-left: 24px; display:none">
                        <i>upload_max_filesize</i>: <?php echo @ini_get('upload_max_filesize'); ?><br />
                        <?php
                        if (version_compare(phpversion(), '5.2.12', '>=')) {
                            echo '<i>max_file_uploads</i>: ' . @ini_get('max_file_uploads') . '<br />';
                        }
                        ?>
                        <i>post_max_size</i>: <?php echo @ini_get('post_max_size'); ?><br />
                    </div>
                </div>
                <?php endif; ?>
                <div id="attachment_restrictions" style="display:<?php echo $layer_onload; ?>;">
                    <div class="form-group short">
                        <label for="a1">
                            <span><?php echo $hesklang['attach_num']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#38','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" class="form-control" name="s_max_number" maxlength="2" id="a1" value="<?php echo $hesk_settings['attachments']['max_number']; ?>" <?php echo $onload_status; ?>>
                    </div>
                    <?php
                    $suffixes = array(
                        'B'  => $hesklang['B'] . ' (' . $hesklang['bytes'] . ')',
                        'kB' => $hesklang['kB'] . ' (' . $hesklang['kilobytes'] . ')',
                        'MB' => $hesklang['MB'] . ' (' . $hesklang['megabytes'] . ')',
                        'GB' => $hesklang['GB'] . ' (' . $hesklang['gigabytes'] . ')',
                    );
                    $tmp = hesk_formatBytes($hesk_settings['attachments']['max_size'], 0);
                    list($size, $unit) = explode(' ', $tmp);
                    ?>
                    <div class="form-group short flex-row">
                        <label for="a2">
                            <span><?php echo $hesklang['attach_size']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#39','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" class="form-control" name="s_max_size" maxlength="6" id="a2" value="<?php echo $size; ?>" <?php echo $onload_status; ?>>
                        <div class="dropdown-select center out-close">
                            <select name="s_max_unit" id="a4" <?php echo $onload_status; ?>>
                                <?php
                                foreach ($suffixes as $k => $v) {
                                    if ($k == $unit) {
                                        echo '<option value="'.$k.'" selected>'.$v.'</option>';
                                    } else {
                                        echo '<option value="'.$k.'">'.$v.'</option>';
                                    }
                                }
                                ?>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="a3">
                            <span><?php echo $hesklang['attach_type']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#40','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </label>
                        <input type="text" class="form-control" name="s_allowed_types" maxlength="255" id="a3" value="<?php echo implode(',',$hesk_settings['attachments']['allowed_types']); ?>" <?php echo $onload_status; ?>>
                    </div>
                    <!-- Section For Email Attachment Options -->
                    <div class="radio-group">
                        <h5>
                            <span><?php echo $hesklang['file_attachment_options']; ?></span>
                            <a onclick="hesk_window('<?php echo $help_folder; ?>helpdesk.html#41','400','500')">
                                <div class="tooltype right">
                                    <svg class="icon icon-info">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                    </svg>
                                </div>
                            </a>
                        </h5>
                        <?php
                            /*Email Attachment settings*/
                            $link_to_attachments_in_emails = (isset($hesk_settings['attachments']["attachment_in_email_type"]) && $hesk_settings['attachments']["attachment_in_email_type"] == "0")?"checked":"";
                            $add_attachments_directly_to_emails = (isset($hesk_settings['attachments']["attachment_in_email_type"]) && $hesk_settings['attachments']["attachment_in_email_type"] == "1")?"checked":"";
                            $directly_attach_file_smaller_than = (isset($hesk_settings['attachments']["direct_attachment_in_email"]) && $hesk_settings['attachments']["direct_attachment_in_email"] == "0")?"checked":"";
                            $directly_attach_file_of_any_size = (isset($hesk_settings['attachments']["direct_attachment_in_email"]) && $hesk_settings['attachments']["direct_attachment_in_email"] == "1")?"checked":"";
                            $directly_attach_only_first_x_attachments = (isset($hesk_settings['attachments']["direct_attachment_in_email_no_of_files"]) && $hesk_settings['attachments']["direct_attachment_in_email_no_of_files"] == "2")?"checked":"";
                            $directly_attach_all_attachments = (isset($hesk_settings['attachments']["direct_attachment_in_email_no_of_files"]) && $hesk_settings['attachments']["direct_attachment_in_email_no_of_files"] == "3")?"checked":"";;
                            if(isset($hesk_settings['attachments']["attachment_in_email_type"]) && $hesk_settings['attachments']["attachment_in_email_type"] == "0"){
                                $directly_attach_file_smaller_than = "checked";
                            }
                            $dd_attach_style = "display:none";
                            if(isset($hesk_settings['attachments']["attachment_in_email_type"]) && $hesk_settings['attachments']["attachment_in_email_type"] == "1"){
                                $dd_attach_style = "display:flex";
                                $file_size = 1;
                                $file_max_unit = 'kB';
                                if(isset($hesk_settings['attachments']['file_max_size']) && $hesk_settings['attachments']['file_max_size'] > 0){
                                    $tmp = hesk_formatBytes($hesk_settings['attachments']['file_max_size'], 0);
                                    list($file_size, $file_max_unit) = explode(' ', $tmp);
                                }
                                $first_x_attachments = 2;
                                if(isset($hesk_settings['attachments']['first_x_attachments']) && $hesk_settings['attachments']['first_x_attachments'] > 0){
                                    $first_x_attachments = $hesk_settings['attachments']['first_x_attachments'];
                                }

                            }else{
                                $file_size = 2;
                                $file_max_unit = 'kB';
                                $first_x_attachments = 2;
                            }
                            /*Email Attachment settings*/
                        ?>
                        <div class="radio-list">
                            <div class="radio-custom">
                                <input type="radio" id="attachment_in_email_type0" name="attachment_in_email_type" value="0" <?php echo $link_to_attachments_in_emails;?>>
                                <label for="attachment_in_email_type0"><?php echo $hesklang['link_to_attachments_in_emails']; ?></label>
                            </div>
                            <div class="radio-custom">
                                <input type="radio" id="attachment_in_email_type1" name="attachment_in_email_type" value="1" <?php echo $add_attachments_directly_to_emails;?>>
                                <label for="attachment_in_email_type1"><?php echo $hesklang['add_attachments_directly_to_emails']; ?></label>
                            </div>
                        </div>
                    </div>
                    <div class="radio-group direct_attachment_section" style="<?php echo $dd_attach_style;?>">
                        <h5 aria-label="<?php echo $hesklang['file_attachment_options']; ?>"></h5>
                        <div class="radio-list">
                            <div role="alert" class="notification orange">
                                <b><?php echo $hesklang['warn']; ?>:</b> <?php echo $hesklang['notice_about_directly_attach_files']; ?>        
                            </div>
                            <h5 class ="lbl-attach"><span><?php echo $hesklang['directly_attach_size'].':'; ?></span></h5>
                            <div class="radio-custom">
                                <input type="radio" id="direct_attachment_in_email0" name="direct_attachment_in_email" value="0" <?php echo $directly_attach_file_smaller_than;?>>
                                <label for="direct_attachment_in_email0"><?php echo $hesklang['directly_attach_file_smaller_than']; ?></label>
                                <input type="text" class="form-control form-cs" name="file_max_size" maxlength="6" id="file_max_size"
                                       value="<?php echo $file_size; ?>" <?php echo $onload_status; ?> aria-label="<?php echo $hesklang['directly_attach_no_of_files']; ?>">
                                <div class="dropdown-select center out-close">
                                    <select name="file_max_unit" id="file_max_unit" <?php echo $onload_status; ?>>
                                        <?php
                                        foreach ($suffixes as $k => $v) {
                                            if ($k == $file_max_unit) {
                                                echo '<option value="'.$k.'" selected>'.$v.'</option>';
                                            } else {
                                                echo '<option value="'.$k.'">'.$v.'</option>';
                                            }
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class="radio-custom">
                                <input type="radio" id="direct_attachment_in_email1" name="direct_attachment_in_email" value="1" <?php echo $directly_attach_file_of_any_size;?>>
                                <label for="direct_attachment_in_email1"><?php echo $hesklang['directly_attach_file_of_any_size']; ?></label>
                            </div>
                            <h5 class ="lbl-attach"><span><?php echo $hesklang['directly_attach_no_of_files'].':'; ?></span></h5>
                            <div class="radio-custom">
                                <input type="radio" id="direct_attachment_in_email2" name="direct_attachment_in_email_no_of_files" value="2" <?php echo $directly_attach_only_first_x_attachments;?>>
                                <label for="direct_attachment_in_email2"><?php echo $hesklang['directly_attach_only_first_x_attachments']; ?></label>
                                <input type="text" class="form-control form-cs" name="first_x_attachments" maxlength="" id="first_x_attachments"
                                       value="<?php echo $first_x_attachments; ?>" <?php echo $onload_status; ?> aria-label="Number of attachements">
                                <span class="ml-12"><?php echo strtolower($hesklang['attachments']); ?> </span>
                            </div>
                            <div class="radio-custom">
                                <input type="radio" id="direct_attachment_in_email3" name="direct_attachment_in_email_no_of_files" value="3" <?php echo $directly_attach_all_attachments;?>>
                                <label for="direct_attachment_in_email3"><?php echo $hesklang['directly_attach_all_attachments']; ?></label>
                            </div>
                        </div>
                    </div>
                    <!-- Section For Email Attachment Options -->
                </div>
            </section>
            <div class="settings__form_submit">
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                <input type="hidden" name="section" value="HELP_DESK">
                <button style="display: inline-flex" type="submit" id="submitbutton" class="btn btn-full" ripple="ripple"
                    <?php echo $enable_save_settings ? '' : 'disabled'; ?>>
                    <?php echo $hesklang['save_changes']; ?>
                </button>

                <?php if (!$enable_save_settings): ?>
                    <p>&nbsp;</p>
                    <div role="alert" class="notification red">
                        <?php echo $hesklang['e_save_settings']; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </form>
</div>
<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();
admin_settings_knowledgebase.php
wget 'https://lists2.roe3.org/hesk/admin/admin_settings_knowledgebase.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

define('LOAD_TABS',1);

// Make sure the install folder is deleted
if (is_dir(HESK_PATH . 'install')) {die('Please delete the <b>install</b> folder from your server for security reasons then refresh this page!');}

// Get all the required files and functions
require(HESK_PATH . 'hesk_settings.inc.php');

// Save the default language for the settings page before choosing user's preferred one
$hesk_settings['language_default'] = $hesk_settings['language'];
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/setup_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_man_settings');

// Load custom fields
require_once(HESK_PATH . 'inc/custom_fields.inc.php');

$help_folder = '../language/' . $hesk_settings['languages'][$hesk_settings['language']]['folder'] . '/help_files/';

$enable_save_settings   = 0;
$enable_use_attachments = 0;

// Print header
require_once(HESK_PATH . 'inc/header.inc.php');

// Print main manage users page
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

// Demo mode? Hide values of sensitive settings
if ( defined('HESK_DEMO') )
{
    require_once(HESK_PATH . 'inc/admin_settings_demo.inc.php');
}

/* This will handle error, success and notice messages */
hesk_handle_messages();
?>
<div class="main__content settings">

    <?php require_once(HESK_PATH . 'inc/admin_settings_status.inc.php'); ?>

    <script language="javascript" type="text/javascript"><!--
        function hesk_checkFields() {
            var d = document.form1;

            // DISABLE SUBMIT BUTTON
            d.submitbutton.disabled=true;

            return true;
        }

        function hesk_toggleLayer(nr,setto) {
            if (document.all)
                document.all[nr].style.display = setto;
            else if (document.getElementById)
                document.getElementById(nr).style.display = setto;
        }

        function checkRequiredEmail(field) {
            if (document.getElementById('s_require_email_0').checked && document.getElementById('s_email_view_ticket').checked)
            {
                if (field == 's_require_email_0' && confirm('<?php echo addslashes($hesklang['re_confirm1']); ?>'))
                {
                    document.getElementById('s_email_view_ticket').checked = false;
                    return true;
                }
                else if (field == 's_email_view_ticket' && confirm('<?php echo addslashes($hesklang['re_confirm2']); ?>'))
                {
                    document.getElementById('s_require_email_1').checked = true;
                    return true;
                }
                return false;
            }
            return true;
        }
        //-->
    </script>
    <form method="post" action="admin_settings_save.php" name="form1" onsubmit="return hesk_checkFields()" aria-label="<?php echo $hesklang['tab_3']; ?>">
        <div class="settings__form form">
            <section class="settings__form_block">
                <h3><?php echo $hesklang['tab_3']; ?></h3>
                <div class="radio-group">
                    <h5>
                        <span><?php echo $hesklang['s_ekb']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>knowledgebase.html#22','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <?php
                    $on = $hesk_settings['kb_enable'] == 1 ? 'checked' : '';
                    $off = $hesk_settings['kb_enable'] ? '' : 'checked';
                    $only = $hesk_settings['kb_enable'] == 2 ? 'checked' : '';
                    ?>
                    <div class="radio-list">
                        <div class="radio-custom">
                            <input type="radio" id="s_kb_enable1" name="s_kb_enable" value="1" <?php echo $on; ?>>
                            <label for="s_kb_enable1"><?php echo $hesklang['ekb_y']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_kb_enable2" name="s_kb_enable" value="2" <?php echo $only; ?>>
                            <label for="s_kb_enable2"><?php echo $hesklang['ekb_o']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_kb_enable0" name="s_kb_enable" value="0" <?php echo $off; ?>>
                            <label for="s_kb_enable0"><?php echo $hesklang['ekb_n']; ?></label>
                        </div>
                    </div>
                </div>
            </section>
            <section class="settings__form_block">
                <h3><?php echo $hesklang['kb_set']; ?></h3>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['swyse']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>knowledgebase.html#52','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['swyse']; ?>">
                        <input type="checkbox" name="s_kb_wysiwyg" value="1" <?php if ($hesk_settings['kb_wysiwyg']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['s_suggest']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>knowledgebase.html#23','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['s_suggest']; ?>">
                        <input type="checkbox" name="s_kb_recommendanswers" value="1" <?php if ($hesk_settings['kb_recommendanswers']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['s_kbr']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>knowledgebase.html#24','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['s_kbr']; ?>">
                        <input type="checkbox" name="s_kb_rating" value="1" <?php if ($hesk_settings['kb_rating']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['sav']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>knowledgebase.html#58','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['sav']; ?>">
                        <input type="checkbox" name="s_kb_views" value="1" <?php if ($hesk_settings['kb_views']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <div class="checkbox-group row">
                    <h5>
                        <span><?php echo $hesklang['sad']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>knowledgebase.html#59','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <label class="switch-checkbox" aria-label="<?php echo $hesklang['sad']; ?>">
                        <input type="checkbox" name="s_kb_date" value="1" <?php if ($hesk_settings['kb_date']) { echo 'checked'; } ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                    </label>
                </div>
                <?php
                $off = $hesk_settings['kb_search'] ? '' : 'checked="checked"';
                $small = $hesk_settings['kb_search'] == 1 ? 'checked="checked"' : '';
                $large = $hesk_settings['kb_search'] == 2 ? 'checked="checked"' : '';
                ?>
                <div class="radio-group">
                    <h5>
                        <span><?php echo $hesklang['s_kbs']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>knowledgebase.html#25','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="radio-list">
                        <div class="radio-custom">
                            <input type="radio" id="s_kb_search0" name="s_kb_search" value="0" <?php echo $off; ?>>
                            <label for="s_kb_search0"><?php echo $hesklang['off']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_kb_search1" name="s_kb_search" value="1" <?php echo $small; ?>>
                            <label for="s_kb_search1"><?php echo $hesklang['small']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_kb_search2" name="s_kb_search" value="2" <?php echo $large; ?>>
                            <label for="s_kb_search2"><?php echo $hesklang['large']; ?></label>
                        </div>
                    </div>
                </div>
                <div class="form-group short">
                    <label for="s_kb_search_limit">
                        <span><?php echo $hesklang['s_maxsr']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>knowledgebase.html#26','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_kb_search_limit" name="s_kb_search_limit" maxlength="3" value="<?php echo $hesk_settings['kb_search_limit']; ?>">
                </div>
                <div class="form-group short">
                    <label for="s_kb_substrart">
                        <span><?php echo $hesklang['s_ptxt']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>knowledgebase.html#27','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" id="s_kb_substrart" name="s_kb_substrart" class="form-control" maxlength="5" value="<?php echo $hesk_settings['kb_substrart']; ?>">
                </div>
                <div class="form-group short">
                    <label for="s_kb_cols">
                        <span><?php echo $hesklang['s_scol']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>knowledgebase.html#28','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_kb_cols" name="s_kb_cols" maxlength="2" value="<?php echo $hesk_settings['kb_cols']; ?>">
                </div>
                <div class="form-group short">
                    <label for="s_kb_numshow">
                        <span><?php echo $hesklang['s_psubart']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>knowledgebase.html#29','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_kb_numshow" name="s_kb_numshow" maxlength="2" value="<?php echo $hesk_settings['kb_numshow']; ?>">
                </div>
                <div class="form-group short list">
                    <label for="s_kb_index_popart">
                        <span><?php echo $hesklang['s_spop']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>knowledgebase.html#30','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <ul class="input-list">
                        <li style="display: list-item">
                            <input type="text" class="form-control" id="s_kb_index_popart" name="s_kb_index_popart" maxlength="2"
                                   value="<?php echo $hesk_settings['kb_index_popart']; ?>" aria-label="On help desk index page">
                            <?php echo $hesklang['s_onin']; ?>
                        </li>
                        <li style="display: list-item">
                            <input type="text" class="form-control" name="s_kb_popart" maxlength="2"
                                   value="<?php echo $hesk_settings['kb_popart']; ?>" aria-label="On knowledgebase index page">
                            <?php echo $hesklang['s_onkb']; ?>
                        </li>
                    </ul>
                </div>
                <div class="form-group short list">
                    <label for="s_kb_index_latest">
                        <span><?php echo $hesklang['s_slat']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>knowledgebase.html#31','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <ul class="input-list">
                        <li style="display: list-item">
                            <input type="text" class="form-control" id="s_kb_index_latest" name="s_kb_index_latest" maxlength="2"
                                   value="<?php echo $hesk_settings['kb_index_latest']; ?>" aria-label="On help desk index page">
                            <?php echo $hesklang['s_onin']; ?>
                        </li>
                        <li style="display: list-item">
                            <input type="text" class="form-control" name="s_kb_latest" maxlength="2"
                                   value="<?php echo $hesk_settings['kb_latest']; ?>"  aria-label="On knowledgebase index page">
                            <?php echo $hesklang['s_onkb']; ?>
                        </li>
                    </ul>
                </div>
                <div class="form-group short">
                    <label for="s_kb_related">
                        <span><?php echo $hesklang['s_relart']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>knowledgebase.html#60','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_kb_related" name="s_kb_related" maxlength="2" value="<?php echo $hesk_settings['kb_related']; ?>">
                </div>
            </section>
            <div class="settings__form_submit">
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                <input type="hidden" name="section" value="KNOWLEDGEBASE">
                <button id="submitbutton" style="display: inline-flex" type="submit" class="btn btn-full" ripple="ripple"
                    <?php echo $enable_save_settings ? '' : 'disabled'; ?>>
                    <?php echo $hesklang['save_changes']; ?>
                </button>

                <?php if (!$enable_save_settings): ?>
                    <p>&nbsp;</p>
                    <div role="alert" class="notification red">
                        <?php echo $hesklang['e_save_settings']; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </form>
</div>
<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();
admin_settings_misc.php
wget 'https://lists2.roe3.org/hesk/admin/admin_settings_misc.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

define('LOAD_TABS',1);

// Make sure the install folder is deleted
if (is_dir(HESK_PATH . 'install')) {die('Please delete the <b>install</b> folder from your server for security reasons then refresh this page!');}

// Get all the required files and functions
require(HESK_PATH . 'hesk_settings.inc.php');

// Save the default language for the settings page before choosing user's preferred one
$hesk_settings['language_default'] = $hesk_settings['language'];
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/setup_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_man_settings');

// Load custom fields
require_once(HESK_PATH . 'inc/custom_fields.inc.php');

// Rebuild prod assets function
if (isset($_GET['rebuild_prod_assets'])) {
    if (defined('HESK_DEMO') || ! $hesk_settings['debug_mode']) {
        hesk_exitDemo();
    } else {
        hesk_rebuildProdAssets();
    }
}

// Purge cache function
if (isset($_GET['purge_cache'])) {
    if (defined('HESK_DEMO')) {
        hesk_exitDemo();
    } else {
        hesk_purgeCache();
    }
}

$help_folder = '../language/' . $hesk_settings['languages'][$hesk_settings['language']]['folder'] . '/help_files/';

$enable_save_settings   = 0;
$enable_use_attachments = 0;

// Print header
require_once(HESK_PATH . 'inc/header.inc.php');

// Print main manage users page
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

// Demo mode? Hide values of sensitive settings
if ( defined('HESK_DEMO') )
{
    require_once(HESK_PATH . 'inc/admin_settings_demo.inc.php');
}

/* This will handle error, success and notice messages */
hesk_handle_messages();
?>
<div class="main__content settings">

    <?php require_once(HESK_PATH . 'inc/admin_settings_status.inc.php'); ?>

    <script language="javascript" type="text/javascript"><!--
        function hesk_checkFields() {
            var d = document.form1;

            // DISABLE SUBMIT BUTTON
            d.submitbutton.disabled=true;

            return true;
        }

        function hesk_toggleLayer(nr,setto) {
            if (document.all)
                document.all[nr].style.display = setto;
            else if (document.getElementById)
                document.getElementById(nr).style.display = setto;
        }

        function hesk_rebuildProdAssets()
        {
            window.open('admin_settings_misc.php?rebuild_prod_assets',"Hesk_window","height=400,width=500,menubar=0,location=0,toolbar=0,status=0,resizable=1,scrollbars=1");
            return false;
        }

        function hesk_purgeCache()
        {
            window.open('admin_settings_misc.php?purge_cache',"Hesk_window","height=400,width=500,menubar=0,location=0,toolbar=0,status=0,resizable=1,scrollbars=1");
            return false;
        }
        //-->
    </script>
    <form method="post" action="admin_settings_save.php" name="form1" onsubmit="return hesk_checkFields()" aria-label="<?php echo $hesklang['tab_5']; ?>">
        <div class="settings__form form">
            <section class="settings__form_block">
                <h3><?php echo $hesklang['dat']; ?></h3>
                <div class="form-group timezone">
                    <label for="timezone-select">
                        <span><?php echo $hesklang['TZ']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>misc.html#63','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <?php
                    // Get list of supported timezones
                    $timezone_list = hesk_generate_timezone_list();

                    // Do we need to localize month names?
                    if ($hesk_settings['language'] != 'English')
                    {
                        $timezone_list = hesk_translate_timezone_list($timezone_list);
                    }
                    ?>
                    <select name="s_timezone" id="timezone-select">
                        <?php
                        foreach ($timezone_list as $timezone => $description)
                        {
                            echo '<option value="' . $timezone . '"' . ($hesk_settings['timezone'] == $timezone ? ' selected' : '') . '>' . $description . '</option>';
                        }
                        ?>
                    </select>
                </div>
                <div class="form-group flex-row">
                    <label for="s_format_time">
                        <span><?php echo $hesklang['tfor']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>misc.html#65','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" style="max-width: 200px; margin-right: 5px;" id="s_format_time" name="s_format_time" maxlength="255" value="<?php echo $hesk_settings['format_time']; ?>">
                    <select name="ex-time" id="ex-time">
                        <?php
                        $examples = array(
                            'H:i',
                            'H:i:s',
                            'g:i a',
                        );

                        $is_custom = true;
                        foreach ($examples as $example) {
                            if ($example == $hesk_settings['format_time']) {
                                $is_custom = false;
                                $selected = 'selected';
                            } else {
                                $selected = '';
                            }
                            echo '<option value="'.$example.'" '.$selected.'>'.hesk_date('now', false, true, true, $example).'</option>';
                        }
                        ?>
                        <option value="custom" <?php echo $is_custom ? 'selected' : ''; ?>><?php echo $hesklang['custom']; ?></option>
                    </select>
                    <script>
                        $('#ex-time').selectize();
                        $('#ex-time').on('change', function() {
                            if (this.value != 'custom') {
                                $('#s_format_time').val(this.value);
                            }
                        });
                    </script>
                </div>
                <div class="form-group flex-row">
                    <label for="s_format_date">
                        <span><?php echo $hesklang['dfor']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>misc.html#66','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" style="max-width: 200px; margin-right: 5px;" id="s_format_date" name="s_format_date" maxlength="255" value="<?php echo $hesk_settings['format_date']; ?>">
                    <select name="ex-date" id="ex-date">
                        <?php
                        $examples = array(
                            'm/d/Y',
                            'd/m/Y',
                            'm-d-Y',
                            'd-m-Y',
                            'Y-m-d',
                            'Y-d-m',
                            'd.m.Y',
                            'M j Y',
                            'j M Y',
                            'j M y',
                            'F j, Y',
                        );

                        $is_custom = true;
                        foreach ($examples as $example) {
                            if ($example == $hesk_settings['format_date']) {
                                $is_custom = false;
                                $selected = 'selected';
                            } else {
                                $selected = '';
                            }
                            echo '<option value="'.$example.'" '.$selected.'>'.hesk_date('now', false, true, true, $example).'</option>';
                        }
                        ?>
                        <option value="custom" <?php echo $is_custom ? 'selected' : ''; ?>><?php echo $hesklang['custom']; ?></option>
                    </select>
                    <script>
                        $('#ex-date').selectize();
                        $('#ex-date').on('change', function() {
                            if (this.value != 'custom') {
                                $('#s_format_date').val(this.value);
                            }
                        });
                    </script>
                </div>
                <div class="form-group flex-row">
                    <label for="s_format_timestamp">
                        <span><?php echo $hesklang['dtfor']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>misc.html#67','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" style="max-width: 200px; margin-right: 5px;" id="s_format_timestamp" name="s_format_timestamp" maxlength="255" value="<?php echo $hesk_settings['format_timestamp']; ?>">
                    <select name="ex-timestamp" id="ex-timestamp">
                        <?php
                        $examples = array(
                            'm/d/Y g:i a',
                            'd/m/Y H:i:s',
                            'm-d-Y H:i:s',
                            'd-m-Y H:i:s',
                            'Y-m-d H:i:s',
                            'Y-d-m H:i:s',
                            'd.m.Y H:i:s',
                            'd M Y H:i',
                            'F jS, Y, g:i a',
                        );

                        $is_custom = true;
                        foreach ($examples as $example) {
                            if ($example == $hesk_settings['format_timestamp']) {
                                $is_custom = false;
                                $selected = 'selected';
                            } else {
                                $selected = '';
                            }
                            echo '<option value="'.$example.'" '.$selected.'>'.hesk_date('now', false, true, true, $example).'</option>';
                        }
                        ?>
                        <option value="custom" <?php echo $is_custom ? 'selected' : ''; ?>><?php echo $hesklang['custom']; ?></option>
                    </select>
                    <script>
                        $('#ex-timestamp').selectize();
                        $('#ex-timestamp').on('change', function() {
                            if (this.value != 'custom') {
                                $('#s_format_timestamp').val(this.value);
                            }
                        });
                    </script>
                </div>
                <div class="radio-group">
                    <h5>
                        <span><?php echo $hesklang['tdis']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>misc.html#64','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <?php
                        $on = $hesk_settings['time_display'] ? 'checked="checked"' : '';
                        $off = $hesk_settings['time_display'] ? '' : 'checked="checked"';
                    ?>
                    <div class="radio-list">
                        <div class="radio-custom">
                            <input type="radio" id="s_time_display0" name="s_time_display" value="0" <?php echo $off; ?>>
                            <label for="s_time_display0"><?php echo $hesklang['tdisd']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="s_time_display1" name="s_time_display" value="1" <?php echo $on; ?>>
                            <label for="s_time_display1"><?php echo $hesklang['tdisa']; ?></label>
                        </div>
                    </div>
                </div>
                <p>&nbsp;</p>
                <?php hesk_show_info( sprintf($hesklang['jsc_notice'], '<svg class="icon icon-info"><use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-info"></use></svg>') ); ?>
                <div class="form-group flex-row">
                    <label for="s_format_datepicker_js">
                        <span><?php echo $hesklang['cdfor']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>misc.html#68','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" style="max-width: 200px; margin-right: 5px;" id="s_format_datepicker_js" name="s_format_datepicker_js" maxlength="255" value="<?php echo $hesk_settings['format_datepicker_js']; ?>">
                    <select name="ex-js" id="ex-js">
                        <?php
                        $examples = array(
                            'mm/dd/yyyy',
                            'dd/mm/yyyy',
                            'mm-dd-yyyy',
                            'dd-mm-yyyy',
                            'd M yy',
                            'd M yyyy',
                            'D, d M yyyy'
                        );

                        $is_custom = true;
                        foreach ($examples as $example) {
                            if ($example == $hesk_settings['format_datepicker_js']) {
                                $is_custom = false;
                                $selected = 'selected';
                            } else {
                                $selected = '';
                            }
                            echo '<option value="'.$example.'" '.$selected.'>'.hesk_date('now', false, true, true, hesk_map_datepicker_date_format_to_php($example)).'</option>';
                        }
                        ?>
                        <option value="custom" <?php echo $is_custom ? 'selected' : ''; ?>><?php echo $hesklang['custom']; ?></option>
                    </select>
                    <script>
                        $('#ex-js').selectize();
                        $('#ex-js').on('change', function() {
                            if (this.value != 'custom') {
                                $('#s_format_datepicker_js').val(this.value);
                            }
                        });
                    </script>
                </div>
            </section>
            <section class="settings__form_block">
                <h3><?php echo $hesklang['other']; ?></h3>
                <div class="form-group">
                    <label for="s_ip_whois_url">
                        <span><?php echo $hesklang['ip_whois']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>misc.html#61','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <input type="text" class="form-control" id="s_ip_whois_url" name="s_ip_whois_url" maxlength="255" value="<?php echo $hesk_settings['ip_whois']; ?>">
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['mms']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>misc.html#62','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_maintenance_mode1" name="s_maintenance_mode" value="1" <?php if ($hesk_settings['maintenance_mode']) {echo 'checked';} ?>>
                        <label for="s_maintenance_mode1"><?php echo $hesklang['mmd']; ?></label>
                    </div>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['al']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>misc.html#21','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_alink1" name="s_alink" value="1" <?php if ($hesk_settings['alink']) {echo 'checked';} ?>/>
                        <label for="s_alink1"><?php echo $hesklang['dap']; ?></label>
                    </div>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['subnot']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>misc.html#48','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_submit_notice1" name="s_submit_notice" value="1" <?php if ($hesk_settings['submit_notice']) {echo 'checked';} ?>/>
                        <label for="s_submit_notice1"><?php echo $hesklang['subnot2']; ?></label>
                    </div>
                </div>
                <div class="checkbox-group multiple-emails">
                    <h5>
                        <span><?php echo $hesklang['sonline']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>misc.html#56','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_online1" name="s_online" value="1" <?php if ($hesk_settings['online']) {echo 'checked';} ?>>
                        <label for="s_online1"><?php echo $hesklang['sonline2']; ?></label>
                        <div class="form-group">
                            <input type="text" name="s_online_min" class="form-control" maxlength="4"
                                   value="<?php echo $hesk_settings['online_min']; ?>" aria-label="<?php echo $hesklang['sonline2']; ?>">
                        </div>
                    </div>
                </div>
                <div class="checkbox-group">
                    <h5>
                        <span><?php echo $hesklang['updates']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>misc.html#59','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h5>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="s_check_updates1" name="s_check_updates" value="1" <?php if ($hesk_settings['check_updates']) {echo 'checked';} ?>>
                        <label for="s_check_updates1"><?php echo $hesklang['updates2']; ?></label>
                    </div>
                </div>
            </section>
            <section class="settings__form_block">
                <h3><?php echo $hesklang['tools']; ?></h3>
                <div class="form-group row flex-row">
                    <label>
                        <span><?php echo $hesklang['purge_cache']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>370.html#4','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <button type="button" class="btn btn--blue-border" style="margin-left: 20px" ripple="ripple" id="purge_cache"
                            onclick="return hesk_purgeCache()">
                        <?php echo $hesklang['purge_cache_btn']; ?>
                    </button>
                </div>
                <?php if ($hesk_settings['debug_mode']): ?>
                <div class="form-group row flex-row">
                    <label>
                        <span><?php echo $hesklang['rebuild_assets']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>370.html#5','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <button type="button" class="btn btn--blue-border" style="margin-left: 20px" ripple="ripple" id="rebuild_assets"
                            onclick="return hesk_rebuildProdAssets()">
                        <?php echo $hesklang['rebuild_assets_btn']; ?>
                    </button>
                </div>
                <?php endif; ?>
            </section>
            <div class="settings__form_submit">
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                <input type="hidden" name="section" value="MISC">
                <button id="submitbutton" style="display: inline-flex" type="submit" class="btn btn-full" ripple="ripple"
                    <?php echo $enable_save_settings ? '' : 'disabled'; ?>>
                    <?php echo $hesklang['save_changes']; ?>
                </button>

                <?php if (!$enable_save_settings): ?>
                    <p>&nbsp;</p>
                    <div role="alert" class="notification red">
                        <?php echo $hesklang['e_save_settings']; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </form>
</div>
<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


// START hesk_rebuildProdAssets()
function hesk_rebuildProdAssetsAtPath($path, $matchFilesPath, $distPath = '', $ignoreNonMinifiedWrite = false) {
    global $hesklang;
    $coreCssPath = $path . $matchFilesPath;
    try {
        require_once __DIR__ . '/..'.'/vendor/autoload.php'; // Make sure autoloader is included

        if ( ! class_exists('\MatthiasMullie\Minify\CSS')) {
            return 'The <b>MatthiasMullie\Minify\CSS</b> class is not installed. 
                Please install it using Composer: <b>"composer require matthiasmullie/minify"</b>.
                ';
        }

        $cssMinifier = new \MatthiasMullie\Minify\CSS();

        $coreCssFiles = glob($coreCssPath);
        // 1. Get all .css files in the core folder, alphabetically
        if (is_array($coreCssFiles)) {

            // Remove the file if its name contains "default_theme_vars"
            // Note: unfortunately have to load that first separately (NOT bundled), so it can then get overwritten by any theme vars, BEFORE any color calculations are done
            // TODO alternatively, could simply print those contents into a style tag directly, to avoid loading the extra css file?
            // Remove any file containing "default_theme_vars" right away
            $coreCssFiles = array_filter($coreCssFiles, function ($file) {
                return strpos(basename($file), 'default_theme_vars') === false;
            });

            sort($coreCssFiles); // sort alphabetically
        }

        // Make sure dist folder for bundled assets is available and writable
        $distPath = $path . $distPath;
        if ( ! is_dir($distPath)) {
            // -> Try to create it
            //mkdir($distPath, 0755, true);

            // -> Is the folder now there?
            if ( ! is_dir($distPath) )
            {
                return '
                    Folder <b>' . $distPath . '</b> does not exist, and an attempt to create it failed.<br /><br />
                    &raquo;Make sure PHP has permission to write in folder <b>' . $distPath . '</b><br />
                    &raquo; contact your hosting company for help with setting up folder permissions.
                    ';
            }

            // -> Is it writable?
            if ( ! is__writable($distPath) )
            {
                // -> try to CHMOD it
                @chmod($distPath, 0777);

                // -> test again
                if ( ! is__writable($distPath) )
                {
                    // Note: Secondary check if folder is writable
                    $rebuildResult = '
                        Folder <b>' . $distPath . '</b> is not writable by PHP.<br /><br />
                        Make sure PHP has permission to write to folder <b>' . $distPath . '</b><br /><br />
                        &raquo; on <b>Linux</b> servers <a href="https://www.phpjunkyard.com/tutorials/ftp-chmod-tutorial.php">CHMOD</a> this folder to 777 (rwxrwxrwx)<br />
                        &raquo; on <b>Windows</b> servers allow Internet Guest Account to modify the folder<br />
                        &raquo; contact your hosting company for help with setting up folder permissions.
                        ';
                    return $rebuildResult;
                }
            }
        }

        // Combine into one big non-minified string
        $combinedCss = '';
        foreach ($coreCssFiles as $file) {
            $cssContent = file_get_contents($file);
            // TODO note: Minified version does this automatically, but this is hardcoded to just replace ../../ with ../ -> works for now,
            // TODO note -> but if paths were to be changed it might need ot be adjusted.
            $cssContent = preg_replace('/\.\.\/\.\.\//', '../', $cssContent);
            $combinedCss .= $cssContent . "\n";
            $cssMinifier->add($file); // for minified version, don't jsut add content, as it otherwise won't properly rewrite paths relatively to output folder.
        }

        if (!$ignoreNonMinifiedWrite) {
            // 3. Write non-minified version (optional, i.e. not necessary for admin currently)
            file_put_contents($distPath . '/app.css', $combinedCss);
        }

        // 4. Minify and write minified version
        $cssMinifier->minify($distPath . '/app.min.css');

        $rebuildResult = '✅ Combined and minified all CSS files from ' . $coreCssPath;
        $rebuildResult .= "\n Into: " . $distPath . '/app.min.css';

        $rebuildResult .= '<p><i>' . $hesklang['rebuilt_assets'] . '</i></p>';
        $rebuildResult .= '<pre>' . htmlspecialchars(implode("\n", $coreCssFiles)) . '</pre>';
    } catch (Exception $e) {
        error_log("hesk_rebuildProdAssets - Error bundling assets, error: " . $e->getMessage());
        $rebuildResult = '❌ Issue combining and minifying all CSS files from ' . $coreCssPath;
        $rebuildResult .= "\n Error details: " . $e->getMessage();
    }
    return $rebuildResult;
}


function hesk_rebuildProdAssets() {
    global $hesk_settings, $hesklang;

    // Note: We need to rebuild both Customer AND admin assets
    $path = HESK_PATH . 'theme/' . $hesk_settings['site_theme'] . '/customer';
    $matchFilesPath = '/css/core/*.css';
    $customerRebuildResult = hesk_rebuildProdAssetsAtPath($path, $matchFilesPath, '/dist');

    $path = HESK_PATH;
    $matchFilesPath = 'css/app.css'; // For admin, we currently just minify the main app.css one as it's not decoupled yet
    $adminRebuildResult = hesk_rebuildProdAssetsAtPath($path, $matchFilesPath, 'css', true);

    $rebuildResult = '<h5>Rebuilding Customer assets...</h5><p>' . $customerRebuildResult . '</p>';
    $rebuildResult .= '<h5>Rebuilding Admin assets...</h5><p>' . $adminRebuildResult . '</p>';

    // TODO consider reworking the various requests popup to a more modular/reusable approach/template, as currently it's a mess with this long code etc.
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML; 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
    <head>
        <title><?php echo $hesklang['s_inl']; ?></title>
        <meta http-equiv="Content-Type" content="text/html;charset=<?php echo $hesklang['ENCODING']; ?>" />
        <style type="text/css">
            body
            {
                margin:5px 5px;
                padding:0;
                background:#fff;
                color: black;
                font : 68.8%/1.5 Verdana, Geneva, Arial, Helvetica, sans-serif;
                text-align:left;
            }

            p
            {
                color : black;
                font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
                font-size: 1.0em;
            }
            h3
            {
                color : #AF0000;
                font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
                font-weight: bold;
                font-size: 1.0em;
                text-align:center;
            }
            .title
            {
                color : black;
                font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
                font-weight: bold;
                font-size: 1.0em;
            }
            .wrong   {color : red;}
            .correct {color : green;}
            pre {font-size:1.2em;}
        </style>
    </head>
    <body>
    <h3><?php echo $hesklang['rebuild_assets_btn']; ?></h3>
    <?php echo $rebuildResult; ?>
    <p>&nbsp;</p>
    <p align="center"><a href="admin_settings_misc.php?rebuild_prod_assets&amp;<?php echo rand(10000,99999); ?>"><?php echo $hesklang['rebuild_again']; ?></a> | <a href="#" onclick="Javascript:window.close()"><?php echo $hesklang['cwin']; ?></a></p>
    <p>&nbsp;</p>
    </body>
    </html>
    <?php
    exit();
}
// END hesk_rebuildProdAssets()


function hesk_purgeCache()
{
    global $hesk_settings, $hesklang;

    hesk_purge_cache();
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML; 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
    <head>
        <title><?php echo $hesklang['s_inl']; ?></title>
        <meta http-equiv="Content-Type" content="text/html;charset=<?php echo $hesklang['ENCODING']; ?>" />
        <style type="text/css">
            body
            {
                margin:5px 5px;
                padding:0;
                background:#fff;
                color: black;
                font : 68.8%/1.5 Verdana, Geneva, Arial, Helvetica, sans-serif;
                text-align:left;
            }

            p
            {
                color : black;
                font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
                font-size: 1.0em;
            }
            h3
            {
                color : #AF0000;
                font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
                font-weight: bold;
                font-size: 1.0em;
                text-align:center;
            }
            .title
            {
                color : black;
                font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
                font-weight: bold;
                font-size: 1.0em;
            }
            .wrong   {color : red;}
            .correct {color : green;}
            pre {font-size:1.2em;}
        </style>
    </head>
    <body>
    <h3><?php echo $hesklang['purge_cache']; ?></h3>
    <p align="center"><?php echo $hesklang['purge_cache_done']; ?></p>
    <p>&nbsp;</p>
    <p align="center"><a href="#" onclick="Javascript:window.close()"><?php echo $hesklang['cwin']; ?></a></p>
    <p>&nbsp;</p>
    </body>
    </html>
    <?php
    exit();
} // END hesk_purgeCache()


function hesk_exitDemo($message = null)
{
    global $hesk_settings, $hesklang;

    if ( ! $message) {
        $message = $hesklang['ddemo'];
    }
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML; 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
    <head>
        <title><?php echo $hesklang['s_inl']; ?></title>
        <meta http-equiv="Content-Type" content="text/html;charset=<?php echo $hesklang['ENCODING']; ?>" />
        <style type="text/css">
            body
            {
                margin:5px 5px;
                padding:0;
                background:#fff;
                color: black;
                font : 68.8%/1.5 Verdana, Geneva, Arial, Helvetica, sans-serif;
                text-align:left;
            }

            p
            {
                color : black;
                font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
                font-size: 1.0em;
            }
            h3
            {
                color : #AF0000;
                font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
                font-weight: bold;
                font-size: 1.0em;
                text-align:center;
            }
            .title
            {
                color : black;
                font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
                font-weight: bold;
                font-size: 1.0em;
            }
            .wrong   {color : red;}
            .correct {color : green;}
            pre {font-size:1.2em;}
        </style>
    </head>
    <body>
    <p align="center"><?php echo $message; ?></p>
    <p>&nbsp;</p>
    <p align="center"><a href="#" onclick="Javascript:window.close()"><?php echo $hesklang['cwin']; ?></a></p>
    <p>&nbsp;</p>
    </body>
    </html>
    <?php
    exit();
} // END hesk_exitDemo()
admin_settings_save.php
wget 'https://lists2.roe3.org/hesk/admin/admin_settings_save.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
$hesk_settings['language_default'] = $hesk_settings['language'];
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/email_functions.inc.php');
require(HESK_PATH . 'inc/setup_functions.inc.php');
require(HESK_PATH . 'inc/oauth_functions.inc.php');
require(HESK_PATH . 'inc/theme_variables.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_man_settings');

// A security check
hesk_token_check('POST');

// Make sure OPcache is reset when modifying settings
if ( function_exists('opcache_reset') )
{
	opcache_reset();
}

$section = hesk_input(hesk_POST('section'));
if (!in_array($section, array('GENERAL', 'HELP_DESK', 'KNOWLEDGEBASE', 'EMAIL', 'TICKET_LIST', 'MISC', 'THEME'))) {
    hesk_process_messages($hesklang['err_no_settings_section'], 'admin_settings_general.php');
}

// Demo mode
if ( defined('HESK_DEMO') )
{
	hesk_process_messages($hesklang['sdemo'], 'admin_settings_' . strtolower($section) . '.php', 'NOTICE');
}

$set=array();
$set['language'] = $hesk_settings['language_default'];

$smtp_OK = true;
$pop3_OK = true;
if ($section === 'GENERAL') {
	/* --> General settings */
	$set['site_title']		= hesk_input( hesk_POST('s_site_title'), $hesklang['err_sname']);
	$set['site_title']		= str_replace('\\&quot;','&quot;',$set['site_title']);
	$set['site_url']		= hesk_validateURL( hesk_POST('s_site_url'), $hesklang['err_surl']);
	$set['hesk_title']		= hesk_input( hesk_POST('s_hesk_title'), $hesklang['err_htitle']);
	$set['hesk_title']		= str_replace('\\&quot;','&quot;',$set['hesk_title']);
	$set['hesk_url']		= rtrim( hesk_validateURL( hesk_POST('s_hesk_url'), $hesklang['err_hurl']), '/');
	$set['webmaster_mail']	= hesk_validateEmail( hesk_POST('s_webmaster_mail'), $hesklang['err_wmmail']);
	$valid_themes           = hesk_getValidThemes();
	$theme                  = hesk_input(hesk_POST('s_site_theme'));
	if (isset($theme) && in_array($theme, $valid_themes)) {
	    $set['site_theme'] = $theme;
    } else {
	    hesk_error($hesklang['err_site_theme']);
    }
    $set['admin_css']     = empty($_POST['s_admin_css']) ? 0 : 1;
    $set['admin_css_url'] = hesk_validateURL( hesk_POST('s_admin_css_url', 'https://www.example.com/hesk-style.css'));
    if ($set['admin_css_url'] == '' || $set['admin_css_url'] == 'https://www.example.com/hesk-style.css') {
        $set['admin_css'] = 0;
        $set['admin_css_url'] = 'https://www.example.com/hesk-style.css';
    }
    $set['admin_js'] = empty($_POST['s_admin_js']) ? 0 : 1;
    $set['admin_js_url'] = hesk_validateURL( hesk_POST('s_admin_js_url', 'https://www.example.com/hesk-script.js'));
    if ($set['admin_js_url'] == '' || $set['admin_js_url'] == 'https://www.example.com/hesk-script.js') {
        $set['admin_js'] = 0;
        $set['admin_js_url'] = 'https://www.example.com/hesk-script.js';
    }

	/* --> Language settings */
	$set['can_sel_lang']	= empty($_POST['s_can_sel_lang']) ? 0 : 1;
	$set['languages'] 		= hesk_getLanguagesArray();
	$lang					= explode('|', hesk_input( hesk_POST('s_language') ) );
	if (isset($lang[1]) && in_array($lang[1],hesk_getLanguagesArray(1) ))
	{
		$set['language'] = $lang[1];
	}
	else
	{
		hesk_error($hesklang['err_lang']);
	}

	/* --> Database settings */
	hesk_dbClose();

	if ( hesk_testMySQL() )
	{
		// Database connection OK
	}
	elseif ($mysql_log)
	{
		hesk_error($mysql_error . '<br /><br /><b>' . $hesklang['mysql_said'] . ':</b> ' . $mysql_log);
	}
	else
	{
		hesk_error($mysql_error);
	}
} elseif ($section === 'HELP_DESK') {
	// ---> check admin folder
	$set['admin_dir'] = isset($_POST['s_admin_dir']) && ! is_array($_POST['s_admin_dir']) ? preg_replace('/[^a-zA-Z0-9_-]/', '', $_POST['s_admin_dir']) : 'admin';
	/*
    if ( ! is_dir(HESK_PATH . $set['admin_dir']) )
    {
        hesk_error( sprintf($hesklang['err_adf'], $set['admin_dir']) );
    }
    */

// ---> check attachments folder
	$set['attach_dir'] = isset($_POST['s_attach_dir']) && ! is_array($_POST['s_attach_dir']) ? preg_replace('/[^a-zA-Z0-9_-]/', '', $_POST['s_attach_dir']) : 'attachments';
	/*
    if ( ! is_dir(HESK_PATH . $set['attach_dir']) )
    {
        hesk_error( sprintf($hesklang['err_atf'], $set['attach_dir']) );
    }
    if ( ! is_writable(HESK_PATH . $set['attach_dir']) )
    {
        hesk_error( sprintf($hesklang['err_atr'], $set['attach_dir']) );
    }
    */

// ---> check cache folder
	$set['cache_dir'] = isset($_POST['s_cache_dir']) && ! is_array($_POST['s_cache_dir']) ? preg_replace('/[^a-zA-Z0-9_-]/', '', $_POST['s_cache_dir']) : 'cache';

	$set['max_listings']	= hesk_checkMinMax( intval( hesk_POST('s_max_listings') ) , 1, 999, 10);
	$set['print_font_size']	= hesk_checkMinMax( intval( hesk_POST('s_print_font_size') ) , 1, 99, 12);
	$set['autoclose']		= hesk_checkMinMax( intval( hesk_POST('s_autoclose') ) , 0, 999, 7);
	$set['max_open']		= hesk_checkMinMax( intval( hesk_POST('s_max_open') ) , 0, 999, 0);
	$set['due_soon']		= hesk_checkMinMax( intval( hesk_POST('s_due_soon') ) , 1, 999, 7);
	$set['new_top']			= empty($_POST['s_new_top']) ? 0 : 1;
	$set['reply_top']		= empty($_POST['s_reply_top']) ? 0 : 1;
    $set['hide_replies']	= hesk_checkMinMax( intval( hesk_POST('s_hide_replies') ) , -1, 1, -1);
    if ($set['hide_replies'] == 1)
    {
        $set['hide_replies'] = hesk_checkMinMax( intval( hesk_POST('s_hide_replies_num') ) , 1, 99, 10);
    }
    $set['limit_width']	= empty($_POST['s_limit_width']) ? 0 : 1;
    if ($set['limit_width'])
    {
        $set['limit_width'] = hesk_checkMinMax( intval( hesk_POST('s_limit_width_num') ) , 50, 9999, 800);
    }

	/* --> Features */
	$set['autologin']		= empty($_POST['s_autologin']) ? 0 : 1;
	$set['autoassign']		= empty($_POST['s_autoassign']) ? 0 : 1;
	$set['require_email']	= empty($_POST['s_require_email']) ? 0 : 1;
	$set['require_owner']	= empty($_POST['s_require_owner']) ? 0 : 1;
	$set['require_subject']	= hesk_checkMinMax( intval( hesk_POST('s_require_subject') ) , -1, 1, 1);
	$set['require_message']	= hesk_checkMinMax( intval( hesk_POST('s_require_message') ) , -1, 1, 1);
	$set['custclose']		= empty($_POST['s_custclose']) ? 0 : 1;
	$set['custopen']		= empty($_POST['s_custopen']) ? 0 : 1;
	$set['rating']			= empty($_POST['s_rating']) ? 0 : 1;
	$set['cust_urgency']	= empty($_POST['s_cust_urgency']) ? 0 : 1;
	$set['sequential']		= empty($_POST['s_sequential']) ? 0 : 1;
	$set['time_worked']		= empty($_POST['s_time_worked']) ? 0 : 1;
	$set['spam_notice']		= empty($_POST['s_spam_notice']) ? 0 : 1;
	$set['list_users']		= empty($_POST['s_list_users']) ? 0 : 1;
	$set['debug_mode']		= empty($_POST['s_debug_mode']) ? 0 : 1;
	$set['short_link']		= empty($_POST['s_short_link']) ? 0 : 1;
    $set['submitting_wait'] = empty($_POST['s_submitting_wait']) ? 0 : 1;
    $set['remember_custom_field_values'] = empty($_POST['s_remember_custom_field_values']) ? 0 : 1;
    $set['disable_autofill_admin'] = empty($_POST['s_disable_autofill_admin']) ? 0 : 1;
    $set['disable_autofill_customer'] = empty($_POST['s_disable_autofill_customer']) ? 0 : 1;
    $set['extend_admin']    = empty($_POST['s_extend_admin']) ? 0 : 1;
    $set['extend_customer'] = empty($_POST['s_extend_customer']) ? 0 : 1;
	$set['select_cat']		= empty($_POST['s_select_cat']) ? 0 : 1;
	$set['select_pri']		= empty($_POST['s_select_pri']) ? 0 : 1;
	$set['cat_show_select'] = hesk_checkMinMax( intval( hesk_POST('s_cat_show_select') ) , 0, 999, 10);
    $set['staff_ticket_formatting']	= hesk_checkMinMax( intval( hesk_POST('s_ticket_formatting_staff') ) , 0, 2, 0);
    // Temporary until Markdown support
    if ($set['staff_ticket_formatting'] == 1) {
        $set['staff_ticket_formatting'] = 0;
    }
    $set['multi_eml']		= empty($_POST['s_multi_eml']) ? 0 : 1;
    $set['staff_nicknames'] = empty($_POST['s_staff_nicknames']) ? 0 : 1;

    // Barcode
	$set['barcode']['print'] = empty($_POST['s_barcode_print']) ? 0 : 1;
	if ($set['barcode']['print']) {
        $set['barcode']['staff_only'] = empty($_POST['s_staff_only']) ? 0 : 1;
        $set['barcode']['type'] = hesk_POST('s_barcode_type', 'C128');
        if ( ! isset($hesk_settings['barcode_types'][$set['barcode']['type']])) {
            $set['barcode']['type'] = 'C128';
        }
        $set['barcode']['format'] = hesk_POST('s_barcode_format', 'svg');
        if ( ! isset($hesk_settings['barcode_formats'][$set['barcode']['format']])) {
            $set['barcode']['format'] = 'svg';
        }
        $set['barcode']['width'] = hesk_checkMinMax( intval( hesk_POST('s_barcode_width') ) , 10, 99999, 250);
        $set['barcode']['height'] = hesk_checkMinMax( intval( hesk_POST('s_barcode_height') ) , 10, 99999, 100);
        $set['barcode']['color'] = hesk_POST('s_barcode_color', 'black');
        $set['barcode']['bg'] = hesk_POST('s_barcode_bg', 'white');

        // Colors must be hex like "#ff0000" or words like "red"
        if ( ! preg_match('/\A(?:#[a-fA-F0-9]{3,8}|[a-zA-Z]+)\z/', $set['barcode']['color'])) {
            $set['barcode']['color'] = 'black';
        }

        if ( ! preg_match('/\A(?:#[a-fA-F0-9]{3,8}|[a-zA-Z]+)\z/', $set['barcode']['bg'])) {
            $set['barcode']['bg'] = 'white';
        }

        require(HESK_PATH . 'inc/tecnick/autoload.php');
        $barcode = new \Com\Tecnick\Barcode\Barcode();
        try {
            $bobj = $barcode->getBarcodeObj(
                $set['barcode']['type'],
                'TEST123',
                $set['barcode']['width'],
                $set['barcode']['height'],
                $set['barcode']['color'],
                array(2, 2, 20, 2)
            )->setBackgroundColor($set['barcode']['bg']);
            // echo '<img alt="Barcode" src="data:image/png;base64,'.base64_encode($bobj->getPngData()).'">';
        } catch (Exception $e) {
            $set['barcode']['color'] = 'black';
            $set['barcode']['bg'] = 'white';
        }
	} else {
        $set['barcode'] = $hesk_settings['barcode'];
        $set['barcode']['print'] = 0;
    }

    // Customer Accounts
    $set['customer_accounts'] = hesk_checkMinMax( intval( hesk_POST('s_customer_accounts') ) , 0, 3, 0);
    if ($set['customer_accounts']) {
        if ($set['customer_accounts'] == 3) {
            $set['customer_accounts'] = 1;
            $set['customer_accounts_required'] = 2;
        } elseif ($set['customer_accounts'] == 2) {
            $set['customer_accounts'] = 1;
            $set['customer_accounts_required'] = 1;
        } else {
            $set['customer_accounts_required'] = 0;
        }

        $set['customer_accounts_register'] = hesk_checkMinMax( intval( hesk_POST('s_customer_accounts_register') ) , 0, 2, 0);
        if ($set['customer_accounts_register'] == 2) {
            $set['customer_accounts_customer_self_register'] = 0;
            $set['customer_accounts_admin_approvals'] = 1;
        } elseif ($set['customer_accounts_register'] == 1) {
            $set['customer_accounts_customer_self_register'] = 1;
            $set['customer_accounts_admin_approvals'] = 1;
        } else {
            $set['customer_accounts_customer_self_register'] = 1;
            $set['customer_accounts_admin_approvals'] = 0;
        }

        $set['customer_accounts_allow_email_changes'] = empty($_POST['s_customer_accounts_allow_email_changes']) ? 0 : 1;
        $set['customer_accounts_verify_email_cooldown'] = intval($_POST['s_customer_accounts_verify_email_cooldown']);
        $set['customer_autologin'] = empty($_POST['s_customer_autologin']) ? 0 : 1;
    } else {
        // Disabled, preserve other settings
        $set['customer_accounts'] = 0;
        $set['customer_accounts_required'] = $hesk_settings['customer_accounts_required'];
        $set['customer_accounts_customer_self_register'] = $hesk_settings['customer_accounts_customer_self_register'];
        $set['customer_accounts_admin_approvals'] = $hesk_settings['customer_accounts_admin_approvals'];
        $set['customer_accounts_allow_email_changes'] = $hesk_settings['customer_accounts_allow_email_changes'];
        $set['customer_accounts_verify_email_cooldown'] = $hesk_settings['customer_accounts_verify_email_cooldown'];
        $set['customer_autologin'] = $hesk_settings['customer_autologin'];
    }

	/* --> SPAM prevention */
	$set['secimg_use']		= empty($_POST['s_secimg_use']) ? 0 : ( hesk_POST('s_secimg_use') == 2 ? 2 : 1);
	$set['secimg_sum']		= '';
	for ($i=1;$i<=10;$i++)
	{
		$set['secimg_sum'] .= substr('AEUYBDGHJLMNPQRSTVWXZ123456789', rand(0,29), 1);
	}
	$set['recaptcha_use']	= hesk_checkMinMax( intval( hesk_POST('s_recaptcha_use') ) , 0, 2, 0);
	$set['recaptcha_public_key']	= hesk_input( hesk_POST('s_recaptcha_public_key') );
	$set['recaptcha_private_key']	= hesk_input( hesk_POST('s_recaptcha_private_key') );
	$set['question_use']	= empty($_POST['s_question_use']) ? 0 : 1;
	$set['question_ask']	= hesk_getHTML( hesk_POST('s_question_ask') ) or hesk_error($hesklang['err_qask']);
	$set['question_ans']	= hesk_input( hesk_POST('s_question_ans'), $hesklang['err_qans']);

	/* --> Security */
	$set['attempt_limit']	= hesk_checkMinMax( intval( hesk_POST('s_attempt_limit') ) , 0, 999, 5);
	if ($set['attempt_limit'] > 0)
	{
		$set['attempt_limit']++;
	}
	$set['attempt_banmin']	= hesk_checkMinMax( intval( hesk_POST('s_attempt_banmin') ) , 5, 99999, 60);
    $set['flood'] = hesk_checkMinMax( intval( hesk_POST('s_flood') ) , 0, 999, 3);
	$set['reset_pass'] = empty($_POST['s_reset_pass']) ? 0 : 1;
	$set['email_view_ticket'] = ($set['require_email'] == 0) ? 0 : (empty($_POST['s_email_view_ticket']) ? 0 : 1);
	$set['x_frame_opt'] = empty($_POST['s_x_frame_opt']) ? 0 : 1;
    $set['require_mfa'] = empty($_POST['s_require_mfa']) ? 0 : 1;
    $set['require_mfa_customers'] = empty($_POST['s_require_mfa_customers']) ? 0 : 1;
    $set['samesite'] = hesk_POST('s_samesite', 'Lax');
    if ( ! in_array($set['samesite'], array('Strict', 'Lax', 'None'))) {
        $set['samesite'] = 'Lax';
    }
	$set['force_ssl'] = HESK_SSL && isset($_POST['s_force_ssl']) && $_POST['s_force_ssl'] == 1 ? 1 : 0;

    // Make sure help desk URL starts with https if forcing SSL
	if ($set['force_ssl'])
	{
		$set['hesk_url'] = preg_replace('/^http:/i', 'https:', hesk_getProperty($set, 'hesk_url') );
	}

    $set['url_key'] = hesk_input( hesk_POST('s_url_key') );
    $set['url_key'] = preg_replace('/[^a-zA-Z0-9_.-]/', '', $set['url_key']);
    $elevator_duration = hesk_checkMinMax( intval(hesk_input(hesk_POST('s_elevator_amount'))), 1, 999999, 60);
    $elevator_amount = hesk_input(hesk_POST('s_elevator_unit'));
    if ( ! in_array($elevator_amount, array('M', 'H', 'D'))) {
        $elevator_duration = 60;
        $elevator_amount = 'M';
    }
    $set['elevator_duration'] = $elevator_duration.$elevator_amount;

	/* --> Attachments */
    $set['attachments']['use'] = empty($_POST['s_attach_use']) ? 0 : 1;

    if ($set['attachments']['use'])
    {
        $set['attachments']['max_number'] = intval(hesk_POST('s_max_number', 2));

        $size = floatval(hesk_POST('s_max_size', '1.0'));
        $unit = hesk_POST('s_max_unit', 'MB');

        if ( ! in_array($unit, array('B', 'kB', 'MB', 'GB')))
        {
            $unit = 'MB';
        }

        $set['attachments']['max_size'] = hesk_formatUnits($size . ' ' . $unit);

        if ($set['attachments']['max_size'] === false || $set['attachments']['max_size'] < 1)
        {
            $set['attachments']['max_size'] = 1048576;
        }

        $set['attachments']['allowed_types'] = isset($_POST['s_allowed_types']) && ! is_array($_POST['s_allowed_types']) && strlen($_POST['s_allowed_types']) ? explode(',', strtolower(preg_replace('/[^a-zA-Z0-9,]/', '', $_POST['s_allowed_types']))) : array();
        $set['attachments']['allowed_types'] = array_diff($set['attachments']['allowed_types'], array('php', 'php4', 'php3', 'php5', 'php7', 'php8', 'phps', 'phar', 'phtml', 'shtml', 'shtm', 'cgi', 'pl'));

        // Attachment-in-email settings
        $set['attachments']['attachment_in_email_type'] = isset($_POST['attachment_in_email_type']) && $_POST['attachment_in_email_type'] == '1' ? 1 : 0;

        if ($set['attachments']['attachment_in_email_type'])
        {
            $set['attachments']['direct_attachment_in_email'] = isset($_POST['direct_attachment_in_email']) && $_POST['direct_attachment_in_email'] == '1' ? 1 : 0;

            $set['attachments']['direct_attachment_in_email_no_of_files'] = intval(hesk_POST('direct_attachment_in_email_no_of_files', 2));
            $set['attachments']['direct_attachment_in_email_no_of_files'] = $set['attachments']['direct_attachment_in_email_no_of_files'] == 3 ? 3 : 2;

            if (isset($_POST['file_max_size']) && $_POST['file_max_size'] > 0)
            {
                $file_max_size = floatval(hesk_POST('file_max_size', '1.0'));
                $file_max_unit = hesk_POST('file_max_unit', 'MB');

                if ( ! in_array($file_max_unit, array('B', 'kB', 'MB', 'GB')))
                {
                    $file_max_unit = 'MB';
                }

                $set['attachments']['file_max_size'] = hesk_formatUnits($file_max_size . ' ' . $file_max_unit);

                if ($set['attachments']['file_max_size'] === false || $set['attachments']['file_max_size'] < 1)
                {
                    $set['attachments']['file_max_size'] = 512000;
                }
            }

            if (isset($_POST['first_x_attachments']) && $_POST['first_x_attachments'] > 0)
            {
                $set['attachments']['first_x_attachments'] = hesk_checkMinMax(intval(hesk_POST('first_x_attachments', 2)), 1, 999, 2);
            }
        }
        else
        {
            $set['attachments']['direct_attachment_in_email'] = 0;
            $set['attachments']['direct_attachment_in_email_no_of_files'] = 2;
            $set['attachments']['file_max_size'] = 512000;
            $set['attachments']['first_x_attachments'] = 2;
        }

        if (count($set['attachments']['allowed_types']))
        {
            $keep_these = array();

            foreach ($set['attachments']['allowed_types'] as $ext)
            {
                if (strlen($ext) > 0)
                {
                    $keep_these[] = '.' . $ext;
                }
            }

            $set['attachments']['allowed_types'] = $keep_these;
        }
        else
        {
            $set['attachments']['allowed_types'] = array('.gif','.jpg','.png','.zip','.rar','.csv','.doc','.docx','.xls','.xlsx','.txt','.pdf');
        }
    }
    else
    {
        $set['attachments']['max_number'] = 2;
        $set['attachments']['max_size'] = 1048576;
        $set['attachments']['allowed_types'] = array('.gif','.jpg','.png','.zip','.rar','.csv','.doc','.docx','.xls','.xlsx','.txt','.pdf');

        // Default attachment-in-email settings
        $set['attachments']['attachment_in_email_type'] = 0;
        $set['attachments']['direct_attachment_in_email'] = 0;
        $set['attachments']['direct_attachment_in_email_no_of_files'] = 2;
        $set['attachments']['file_max_size'] = 512000;
        $set['attachments']['first_x_attachments'] = 2;
    }
} elseif ($section === 'KNOWLEDGEBASE') {
	/* --> Knowledgebase settings */
	$set['kb_enable']			= hesk_checkMinMax( intval( hesk_POST('s_kb_enable') ) , 0, 2, 1);
	$set['kb_wysiwyg']			= empty($_POST['s_kb_wysiwyg']) ? 0 : 1;
	$set['kb_search']			= empty($_POST['s_kb_search']) ? 0 : ( hesk_POST('s_kb_search') == 2 ? 2 : 1);
	$set['kb_recommendanswers']	= empty($_POST['s_kb_recommendanswers']) ? 0 : 1;
	$set['kb_views']			= empty($_POST['s_kb_views']) ? 0 : 1;
	$set['kb_date']				= empty($_POST['s_kb_date']) ? 0 : 1;
	$set['kb_rating']			= empty($_POST['s_kb_rating']) ? 0 : 1;
	$set['kb_search_limit']		= hesk_checkMinMax( intval( hesk_POST('s_kb_search_limit') ) , 1, 99, 10);
	$set['kb_substrart']		= hesk_checkMinMax( intval( hesk_POST('s_kb_substrart') ) , 20, 9999, 200);
	$set['kb_cols']				= hesk_checkMinMax( intval( hesk_POST('s_kb_cols') ) , 1, 5, 2);
	$set['kb_numshow']			= intval( hesk_POST('s_kb_numshow') ); // Popular articles on subcat listing
	$set['kb_popart']			= intval( hesk_POST('s_kb_popart') ); // Popular articles on main category page
	$set['kb_latest']			= intval( hesk_POST('s_kb_latest') ); // Popular articles on main category page
	$set['kb_index_popart']		= intval( hesk_POST('s_kb_index_popart') );
	$set['kb_index_latest']		= intval( hesk_POST('s_kb_index_latest') );
	$set['kb_related']			= intval( hesk_POST('s_kb_related') );
} elseif ($section === 'EMAIL') {
	/* --> Email sending */
    $set['noreply_mail']     = hesk_validateEmail( hesk_POST('s_noreply_mail'), $hesklang['err_nomail']);
    $set['noreply_name']     = hesk_input( hesk_POST('s_noreply_name') );
    $set['noreply_name']     = str_replace(array('\\&quot;','&lt;','&gt;'),'',$set['noreply_name']);
    $set['noreply_name']     = trim( preg_replace('/\s{2,}/', ' ', $set['noreply_name']) );
    $set['noreply_name']     = preg_replace("/\n|\r|\t|%0A|%0D|%08|%09/", '', $set['noreply_name']);
    $set['email_max_recipients'] = hesk_checkMinMax( intval( hesk_POST('s_email_max_recipients') ) , 0, 99999, 50);
    $set['email_formatting'] = hesk_checkMinMax( intval( hesk_POST('s_email_formatting') ) , 0, 3, 3);

	$set['smtp'] = empty($_POST['s_smtp']) ? 0 : 1;
	if ($set['smtp'])
	{
		// Test SMTP connection
		$smtp_OK = hesk_testSMTP(true);

		// If SMTP not working, disable it
		if ( ! $smtp_OK)
		{
			$set['smtp'] = 0;
		}
	}
	else
	{
		$set['smtp_host_name']	= hesk_input( hesk_POST('tmp_smtp_host_name', 'mail.example.com') );
        if (stripos($set['smtp_host_name'], 'ssl://') === 0) {
            $set['smtp_host_name'] = substr($set['smtp_host_name'], 6);
        }
		$set['smtp_host_port']	= intval( hesk_POST('tmp_smtp_host_port', 25) );
		$set['smtp_timeout']	= intval( hesk_POST('tmp_smtp_timeout', 10) );
        $set['tmp_smtp_enc']    = hesk_POST('tmp_smtp_enc');
        $set['tmp_smtp_enc']    = ($set['tmp_smtp_enc'] == 'ssl' || $set['tmp_smtp_enc'] == 'tls') ? $set['tmp_smtp_enc'] : '';
        $set['tmp_smtp_noval_cert'] = empty($_POST['tmp_smtp_noval_cert']) ? 0 : 1;
		$set['smtp_user']		= hesk_input( hesk_POST('tmp_smtp_user') );
		$set['smtp_password']	= hesk_input( hesk_POST('tmp_smtp_password') );
        $set['smtp_conn_type']  = (hesk_POST('tmp_smtp_conn_type') == 'oauth') ? 'oauth' : 'basic';
        $set['smtp_oauth_provider'] = intval(hesk_POST('tmp_smtp_oauth_provider'));
	}

    // Sanity-check SMTP timeout to ensure it's greater than 5
    $set['smtp_timeout']    = $set['smtp_timeout'] > 5 ? $set['smtp_timeout'] : 10;

	/* --> Email piping */
	$set['email_piping']	= empty($_POST['s_email_piping']) ? 0 : 1;

	/* --> IMAP fetching */
	$imap_OK = true;
	$set['imap'] = function_exists('imap_open') ? (empty($_POST['s_imap']) ? 0 : 1) : 0;

	if ($set['imap'])
	{
		// Get IMAP fetching timeout
		$set['imap_job_wait'] = hesk_checkMinMax( intval( hesk_POST('s_imap_job_wait') ) , 0, 1440, 15);

		// Test IMAP connection
		$imap_OK = hesk_testIMAP(true);

		// If IMAP not working, disable it
		if ($imap_OK === false) {
			$set['imap'] = 0;
		}
	}
	else
	{
		$set['imap_job_wait']	= intval( hesk_POST('s_imap_job_wait', 15) );
		$set['imap_host_name']	= hesk_input( hesk_POST('tmp_imap_host_name', 'mail.example.com') );
		$set['imap_host_port']	= intval( hesk_POST('tmp_imap_host_port', 110) );
		$set['imap_enc']		= hesk_POST('tmp_imap_enc');
		$set['imap_enc']		= ($set['imap_enc'] == 'ssl' || $set['imap_enc'] == 'tls') ? $set['imap_enc'] : '';
		$set['imap_noval_cert'] = empty($_POST['tmp_imap_noval_cert']) ? 0 : 1;
        $set['imap_disable_GSSAPI'] = empty($_POST['tmp_imap_disable_GSSAPI']) ? 0 : 1;
		$set['imap_keep']		= empty($_POST['tmp_imap_keep']) ? 0 : 1;
		$set['imap_user']		= hesk_input( hesk_POST('tmp_imap_user') );
		$set['imap_password']	= hesk_input( hesk_POST('tmp_imap_password') );
        $set['imap_conn_type']  = hesk_input(hesk_POST('tmp_imap_conn_type'));
        $set['imap_oauth_provider'] = intval(hesk_POST('tmp_imap_oauth_provider'));
	}

	/* --> POP3 fetching */
	$set['pop3'] = empty($_POST['s_pop3']) ? 0 : 1;

	if ($set['pop3'])
	{
		// Get POP3 fetching timeout
		$set['pop3_job_wait'] = hesk_checkMinMax( intval( hesk_POST('s_pop3_job_wait') ) , 0, 1440, 15);

		// Test POP3 connection
		$pop3_OK = hesk_testPOP3(true);

		// If POP3 not working, disable it
		if ( ! $pop3_OK)
		{
			$set['pop3'] = 0;
		}
	}
	else
	{
		$set['pop3_job_wait']	= intval( hesk_POST('s_pop3_job_wait', 15) );
		$set['pop3_host_name']	= hesk_input( hesk_POST('tmp_pop3_host_name', 'mail.example.com') );
		$set['pop3_host_port']	= intval( hesk_POST('tmp_pop3_host_port', 110) );
		$set['pop3_tls']		= empty($_POST['tmp_pop3_tls']) ? 0 : 1;
		$set['pop3_keep']		= empty($_POST['tmp_pop3_keep']) ? 0 : 1;
		$set['pop3_user']		= hesk_input( hesk_POST('tmp_pop3_user') );
		$set['pop3_password']	= hesk_input( hesk_POST('tmp_pop3_password') );
        $set['pop3_conn_type']  = hesk_input(hesk_POST('tmp_pop3_conn_type'));
        $set['pop3_oauth_provider'] = intval(hesk_POST('tmp_pop3_oauth_provider'));
	}

	$set['strip_quoted']  = empty($_POST['s_strip_quoted']) ? 0 : 1;
	$set['eml_req_msg']   = empty($_POST['s_eml_req_msg']) ? 0 : 1;
	$set['save_embedded'] = empty($_POST['s_save_embedded']) ? 0 : 1;
    $set['email_include_to'] = empty($_POST['s_email_include_to']) ? 0 : 1;
    $set['email_include_cc'] = empty($_POST['s_email_include_cc']) ? 0 : 1;

    /* --> Ignore emails */
    $set['pipe_block_noreply']   = empty($_POST['s_pipe_block_noreply']) ? 0 : 1;
    $set['pipe_block_returned']  = empty($_POST['s_pipe_block_returned']) ? 0 : 1;
    $set['pipe_block_duplicate'] = empty($_POST['s_pipe_block_duplicate']) ? 0 : 1;
    $set['loop_hits']            = hesk_checkMinMax( intval( hesk_POST('s_loop_hits') ) , 0, 999, 5);
    $set['loop_time']            = hesk_checkMinMax( intval( hesk_POST('s_loop_time') ) , 1, 86400, 300);
    $set['pipe_customer_rejection_notification'] = empty($_POST['s_pipe_customer_rejection_notification']) ? 0 : 1;
    if ($set['pipe_customer_rejection_notification']) {
        $set['pipe_customer_rejection_email_cooldown_hours'] = hesk_checkMinMax(intval(hesk_POST('s_pipe_customer_rejection_email_cooldown_hours')), 0, 999, 24);
    }

	/* --> Detect email typos */
	$set['detect_typos']	= empty($_POST['s_detect_typos']) ? 0 : 1;
	$set['email_providers'] = array();

	if ( ! empty($_POST['s_email_providers']) && ! is_array($_POST['s_email_providers']) )
	{
		$lines = preg_split('/$\R?^/m', hesk_input($_POST['s_email_providers']) );
		foreach ($lines as $domain)
		{
			$domain = trim($domain);
			$domain = str_replace('@', '', $domain);
			$domainLen = strlen($domain);

			/* Check domain part length */
			if ($domainLen < 1 || $domainLen > 254)
			{
				continue;
			}

			/* Check domain part characters */
			if ( ! preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain) )
			{
				continue;
			}

			/* Domain part mustn't have two consecutive dots */
			if ( strpos($domain, '..') !== false  )
			{
				continue;
			}

			$set['email_providers'][] = $domain;
		}
	}

	if ( ! $set['detect_typos'] || count($set['email_providers']) < 1 )
	{
		$set['detect_typos'] = 0;
		$set['email_providers']=array('aim.com','aol.co.uk','aol.com','att.net','bellsouth.net','blueyonder.co.uk','bt.com','btinternet.com','btopenworld.com','charter.net','comcast.net','cox.net','earthlink.net','email.com','facebook.com','fastmail.fm','free.fr','freeserve.co.uk','gmail.com','gmx.at','gmx.ch','gmx.com','gmx.de','gmx.fr','gmx.net','gmx.us','googlemail.com','hotmail.be','hotmail.co.uk','hotmail.com','hotmail.com.ar','hotmail.com.mx','hotmail.de','hotmail.es','hotmail.fr','hushmail.com','icloud.com','inbox.com','laposte.net','lavabit.com','list.ru','live.be','live.co.uk','live.com','live.com.ar','live.com.mx','live.de','live.fr','love.com','lycos.com','mac.com','mail.com','mail.ru','me.com','msn.com','nate.com','naver.com','neuf.fr','ntlworld.com','o2.co.uk','online.de','orange.fr','orange.net','outlook.com','pobox.com','prodigy.net.mx','qq.com','rambler.ru','rocketmail.com','safe-mail.net','sbcglobal.net','t-online.de','talktalk.co.uk','tiscali.co.uk','verizon.net','virgin.net','virginmedia.com','wanadoo.co.uk','wanadoo.fr','yahoo.co.id','yahoo.co.in','yahoo.co.jp','yahoo.co.kr','yahoo.co.uk','yahoo.com','yahoo.com.ar','yahoo.com.mx','yahoo.com.ph','yahoo.com.sg','yahoo.de','yahoo.fr','yandex.com','yandex.ru','ymail.com');
	}

	$set['email_providers'] = count($set['email_providers']) ?  "'" . implode("','", array_unique($set['email_providers'])) . "'" : '';

	/* --> Notify customer when */
	$set['notify_new']		= empty($_POST['s_notify_new']) ? 0 : 1;
	$set['notify_closed']	= empty($_POST['s_notify_closed']) ? 0 : 1;

// SPAM tags
	$set['notify_skip_spam'] = empty($_POST['s_notify_skip_spam']) ? 0 : 1;
	$set['notify_spam_tags'] = array();

	if ( ! empty($_POST['s_notify_spam_tags']) && ! is_array($_POST['s_notify_spam_tags']) )
	{
		$lines = preg_split('/$\R?^/m', $_POST['s_notify_spam_tags']);

		foreach ($lines as $tag)
		{
			// Remove dangerous tags just as an extra precaution
			$tag = str_replace( array('<?php', '<?', '<%', '<script'), '', $tag);

			// Remove excess spaces
			$tag = trim($tag);

			// Remove anything not utf-8
			$tag = hesk_clean_utf8($tag);

			// Limit tag length
			if ( strlen($tag) < 1 || strlen($tag) > 50)
			{
				continue;
			}

			// Escape single quotes and backslashes
			$set['notify_spam_tags'][] = str_replace( array("\\", "'"), array("\\\\", "\\'"), $tag); // '
		}
	}

	if ( count($set['notify_spam_tags']) < 1 )
	{
		$set['notify_skip_spam'] = 0;
		$set['notify_spam_tags'] = array('Spam?}','***SPAM***','[SPAM]','SPAM-LOW:','SPAM-MED:');
	}

	$set['notify_spam_tags'] = count($set['notify_spam_tags']) ?  "'" . implode("','", $set['notify_spam_tags']) . "'" : '';

	/* --> Other */
	$set['confirm_email']				= empty($_POST['s_confirm_email']) ? 0 : 1;
	$set['open_only']					= empty($_POST['s_open_only']) ? 0 : 1;
} elseif ($section === 'TICKET_LIST') {
	$set['ticket_list'] = array();
	foreach ($hesk_settings['possible_ticket_list'] as $key => $title)
	{
		if ( hesk_POST('s_tl_'.$key, 0) == 1)
		{
			$set['ticket_list'][] = $key;
		}
	}

    $set['customer_ticket_list'] = array();
    foreach ($hesk_settings['possible_customer_ticket_list'] as $key => $title)
    {
        if ( hesk_POST('c_tl_'.$key, 0) == 1)
        {
            $set['customer_ticket_list'][] = $key;
        }
    }

    // We need at least one of these: id, trackid, subject
	if ( ! in_array('id', $set['ticket_list']) && ! in_array('trackid', $set['ticket_list']) && ! in_array('subject', $set['ticket_list']) )
	{
		// Non of the required fields are there, add "trackid" as the first one
		array_unshift($set['ticket_list'], 'trackid');
	}

	$set['ticket_list'] = count($set['ticket_list']) ?  "'" . implode("','", $set['ticket_list']) . "'" : 'trackid';

    if ( ! in_array('id', $set['customer_ticket_list']) && ! in_array('trackid', $set['customer_ticket_list']) && ! in_array('subject', $set['customer_ticket_list']) )
    {
        array_unshift($set['customer_ticket_list'], 'trackid');
    }

    $set['customer_ticket_list'] = count($set['customer_ticket_list']) ?  "'" . implode("','", $set['customer_ticket_list']) . "'" : 'trackid';

	/* --> Other */
	$set['submittedformat']	= hesk_checkMinMax( intval( hesk_POST('s_submittedformat') ) , 0, 4, 2);
	$set['updatedformat']	= hesk_checkMinMax( intval( hesk_POST('s_updatedformat') ) , 0, 4, 2);
    $set['format_submitted'] = hesk_input( hesk_POST('s_format_submitted') ) or $set['format_submitted'] = 'Y-m-d H:i:s';
    $set['format_updated'] = hesk_input( hesk_POST('s_format_updated') ) or $set['format_updated'] = 'Y-m-d H:i:s';
    $set['email_column'] = empty($_POST['s_email_column']) ? 0 : 1;
} elseif ($section === 'MISC') {
	/* --> Date & Time */
	$set['timezone'] = hesk_input( hesk_POST('s_timezone') );
	if ( ! in_array($set['timezone'], timezone_identifiers_list()) )
	{
		$set['timezone'] = 'UTC';
	}

    $set['format_time']      = hesk_input( hesk_POST('s_format_time') ) or $set['format_time'] = 'H:i:s';
    $set['format_date']      = hesk_input( hesk_POST('s_format_date') ) or $set['format_date'] = 'Y-m-d';
    $set['format_timestamp'] = hesk_input( hesk_POST('s_format_timestamp') ) or $set['format_timestamp'] = 'Y-m-d H:i:s';
    $set['time_display']     = empty($_POST['s_time_display']) ? 0 : 1;

    $set['format_datepicker_js'] = hesk_input( hesk_POST('s_format_datepicker_js') );
    $set['format_datepicker_php'] = hesk_map_datepicker_date_format_to_php($set['format_datepicker_js']);
    if (empty($set['format_datepicker_php'])) {
        $set['format_datepicker_js'] = 'mm/dd/yyyy';
        $set['format_datepicker_php'] = 'm/d/Y';
    }

	/* --> Other */
	$set['ip_whois']		= hesk_validateURL( hesk_POST('s_ip_whois_url', 'https://whois.domaintools.com/{IP}') );

// If no {IP} tag append it to the end
	if ( strlen($set['ip_whois']) == 0 )
	{
		$set['ip_whois'] = 'https://whois.domaintools.com/{IP}';
	}
	elseif ( strpos($set['ip_whois'], '{IP}') === false )
	{
		$set['ip_whois'] .= '{IP}';
	}

	$set['maintenance_mode']= empty($_POST['s_maintenance_mode']) ? 0 : 1;
	$set['alink']			= empty($_POST['s_alink']) ? 0 : 1;
	$set['submit_notice']	= empty($_POST['s_submit_notice']) ? 0 : 1;
	$set['online']			= empty($_POST['s_online']) ? 0 : 1;
	$set['online_min']		= hesk_checkMinMax( intval( hesk_POST('s_online_min') ) , 1, 999, 10);
	$set['check_updates']	= empty($_POST['s_check_updates']) ? 0 : 1;
} elseif ($section === 'THEME') {
	/* --> Look & Feel */

    $customer_theme_changed = false;
    $valid_customer_themes           = hesk_getValidCustomerThemes();
    $customer_theme         = hesk_input(hesk_POST('s_customer_theme'));
    if (isset($customer_theme) && in_array($customer_theme, $valid_customer_themes)) {
        $set['customer_theme'] = $customer_theme;
        if ($customer_theme !== $hesk_settings['customer_theme']) {
            // set flag that customer theme has changed, in which case we override any of their overwrites.
            $customer_theme_changed = true;
        }
    } else {
        hesk_error($hesklang['err_customer_theme']);
    }

    // By default has to be an empty array, even if no overrides set
    $set['theme_overrides']  = array();
    if ( ! empty($_POST['s_theme_overrides']) && ! is_array($_POST['s_theme_overrides']) )
    {
        // Read all overriden POSTed settings
        $theme_overrides = json_decode($_POST['s_theme_overrides'], true);
        if (is_array($theme_overrides)) {
            foreach ($theme_overrides as $css_variable => $color) {
                $css_variable = hesk_input($css_variable);

                // Skip invalid value
                if ($css_variable == '0') {
                    continue;
                }
                // Process and save each overridden color
                // Check if setting exists
                $color_setting = get_theme_color_setting($css_variable);
                /*
                 TODO just an example for @klemen of how you can easily test for fake/wrong data from settings page/console:
                Just copy this in console:
                themeOverrides["--primary"] = "#000000"; // you can find legit var names at theme_variables.inc.php. Using any other should throw an error.
                updateThemeOverrides(); // IMPORTANT to also run after!
                 */
                if (!$color_setting) {
                    // Tried to save some invalid/non-existent/unsupported variable
                    error_log(sprintf($hesklang['invalid_theme_setting'], $css_variable));
                    hesk_error(sprintf($hesklang['invalid_theme_setting'], $css_variable));
                    continue;
                }
                if (is_array($color)) {
                    $color = '';
                }

                $parsed_color = hesk_input($color);
                if (!hesk_is_valid_color_hex($parsed_color)) {
                    // Tried to save an invalid HEX color value
                    error_log(sprintf($hesklang['invalid_hex_color'], $parsed_color, $css_variable));
                    hesk_error(sprintf($hesklang['invalid_hex_color'], $parsed_color, $css_variable));
                    continue;
                }

                // Check if setting override is a valid HTML color ( hex format?)
                // Store these into a theme_overridess array
                $set['theme_overrides'][$css_variable] = $parsed_color;
            }
        }
    }

    /*// TODO new change - we actually do NOT remove overrides, anymore, but just show a note to user that they might want to reset them
    // TODO leaving here for now, in case we change our mind still
     * if ($customer_theme_changed) {
        // if customer theme has changed, let's reset the theme overrides, as in most cases likely it would be expected by users?
        $set['theme_overrides'] = array();
    }*/
}

$set['hesk_version'] = $hesk_settings['hesk_version'];

// Prepare settings file and save it
$settings_file_content='<?php
// Settings file for HESK ' . $set['hesk_version'] . '

// ==> GENERAL

// --> General settings
$hesk_settings[\'site_title\']=\'' . hesk_getProperty($set, 'site_title') . '\';
$hesk_settings[\'site_url\']=\'' . hesk_getProperty($set, 'site_url') . '\';
$hesk_settings[\'hesk_title\']=\'' . hesk_getProperty($set, 'hesk_title') . '\';
$hesk_settings[\'hesk_url\']=\'' . hesk_getProperty($set, 'hesk_url') . '\';
$hesk_settings[\'webmaster_mail\']=\'' . hesk_getProperty($set, 'webmaster_mail') . '\';
$hesk_settings[\'site_theme\']=\'' . hesk_getProperty($set, 'site_theme') . '\';
$hesk_settings[\'admin_css\']=' . hesk_getProperty($set, 'admin_css') . ';
$hesk_settings[\'admin_css_url\']=\'' . hesk_getProperty($set, 'admin_css_url') . '\';
$hesk_settings[\'admin_js\']=' . hesk_getProperty($set, 'admin_js') . ';
$hesk_settings[\'admin_js_url\']=\'' . hesk_getProperty($set, 'admin_js_url') . '\';

// --> Language settings
$hesk_settings[\'can_sel_lang\']=' . hesk_getProperty($set, 'can_sel_lang') . ';
$hesk_settings[\'language\']=\'' . hesk_getProperty($set, 'language') . '\';
$hesk_settings[\'languages\']=array(
'.hesk_getLanguageForFile($set, 'languages').');

// --> Database settings
$hesk_settings[\'db_host\']=\'' . hesk_getProperty($set, 'db_host') . '\';
$hesk_settings[\'db_name\']=\'' . hesk_getProperty($set, 'db_name') . '\';
$hesk_settings[\'db_user\']=\'' . hesk_getProperty($set, 'db_user') . '\';
$hesk_settings[\'db_pass\']=\'' . hesk_getProperty($set, 'db_pass') . '\';
$hesk_settings[\'db_pfix\']=\'' . hesk_getProperty($set, 'db_pfix') . '\';


// ==> HELP DESK

// --> Help desk settings
$hesk_settings[\'admin_dir\']=\'' . hesk_getProperty($set, 'admin_dir') . '\';
$hesk_settings[\'attach_dir\']=\'' . hesk_getProperty($set, 'attach_dir') . '\';
$hesk_settings[\'cache_dir\']=\'' . hesk_getProperty($set, 'cache_dir') . '\';
$hesk_settings[\'max_listings\']=' . hesk_getProperty($set, 'max_listings') . ';
$hesk_settings[\'print_font_size\']=' . hesk_getProperty($set, 'print_font_size') . ';
$hesk_settings[\'autoclose\']=' . hesk_getProperty($set, 'autoclose') . ';
$hesk_settings[\'max_open\']=' . hesk_getProperty($set, 'max_open') . ';
$hesk_settings[\'due_soon\']=' . hesk_getProperty($set, 'due_soon') . ';
$hesk_settings[\'new_top\']=' . hesk_getProperty($set, 'new_top') . ';
$hesk_settings[\'reply_top\']=' . hesk_getProperty($set, 'reply_top') . ';
$hesk_settings[\'hide_replies\']=' . hesk_getProperty($set, 'hide_replies') . ';
$hesk_settings[\'limit_width\']=' . hesk_getProperty($set, 'limit_width') . ';

// --> Features
$hesk_settings[\'autologin\']=' . hesk_getProperty($set, 'autologin') . ';
$hesk_settings[\'autoassign\']=' . hesk_getProperty($set, 'autoassign') . ';
$hesk_settings[\'require_email\']=' . hesk_getProperty($set, 'require_email') . ';
$hesk_settings[\'require_owner\']=' . hesk_getProperty($set, 'require_owner') . ';
$hesk_settings[\'require_subject\']=' . hesk_getProperty($set, 'require_subject') . ';
$hesk_settings[\'require_message\']=' . hesk_getProperty($set, 'require_message') . ';
$hesk_settings[\'custclose\']=' . hesk_getProperty($set, 'custclose') . ';
$hesk_settings[\'custopen\']=' . hesk_getProperty($set, 'custopen') . ';
$hesk_settings[\'rating\']=' . hesk_getProperty($set, 'rating') . ';
$hesk_settings[\'cust_urgency\']=' . hesk_getProperty($set, 'cust_urgency') . ';
$hesk_settings[\'sequential\']=' . hesk_getProperty($set, 'sequential') . ';
$hesk_settings[\'time_worked\']=' . hesk_getProperty($set, 'time_worked') . ';
$hesk_settings[\'spam_notice\']=' . hesk_getProperty($set, 'spam_notice') . ';
$hesk_settings[\'list_users\']=' . hesk_getProperty($set, 'list_users') . ';
$hesk_settings[\'debug_mode\']=' . hesk_getProperty($set, 'debug_mode') . ';
$hesk_settings[\'short_link\']=' . hesk_getProperty($set, 'short_link') . ';
$hesk_settings[\'submitting_wait\']=' . hesk_getProperty($set, 'submitting_wait') . ';
$hesk_settings[\'remember_custom_field_values\']=' . hesk_getProperty($set, 'remember_custom_field_values') . ';
$hesk_settings[\'disable_autofill_admin\']=' . hesk_getProperty($set, 'disable_autofill_admin') . ';
$hesk_settings[\'disable_autofill_customer\']=' . hesk_getProperty($set, 'disable_autofill_customer') . ';
$hesk_settings[\'extend_admin\']=' . hesk_getProperty($set, 'extend_admin') . ';
$hesk_settings[\'extend_customer\']=' . hesk_getProperty($set, 'extend_customer') . ';
$hesk_settings[\'select_cat\']=' . hesk_getProperty($set, 'select_cat') . ';
$hesk_settings[\'select_pri\']=' . hesk_getProperty($set, 'select_pri') . ';
$hesk_settings[\'cat_show_select\']=' . hesk_getProperty($set, 'cat_show_select') . ';
$hesk_settings[\'staff_ticket_formatting\']=' . hesk_getProperty($set, 'staff_ticket_formatting') . ';
$hesk_settings[\'staff_nicknames\']=' . hesk_getProperty($set, 'staff_nicknames') . ';

// --> Barcode
$hesk_settings[\'barcode\']=array(
\'print\' => ' . (isset($set['barcode']) ? $set['barcode']['print'] : $hesk_settings['barcode']['print']) . ',
\'staff_only\' => ' . (isset($set['barcode']) ? $set['barcode']['staff_only'] : $hesk_settings['barcode']['staff_only']) . ',
\'type\' => \'' . (isset($set['barcode']) ? $set['barcode']['type'] : $hesk_settings['barcode']['type']) . '\',
\'format\' => \'' . (isset($set['barcode']) ? $set['barcode']['format'] : $hesk_settings['barcode']['format']) . '\',
\'width\' => ' . (isset($set['barcode']) ? $set['barcode']['width'] : $hesk_settings['barcode']['width']) . ',
\'height\' => ' . (isset($set['barcode']) ? $set['barcode']['height'] : $hesk_settings['barcode']['height']) . ',
\'color\' => \'' . (isset($set['barcode']) ? $set['barcode']['color'] : $hesk_settings['barcode']['color']) . '\',
\'bg\' => \'' . (isset($set['barcode']) ? $set['barcode']['bg'] : $hesk_settings['barcode']['bg']) . '\',
);

// --> Customer Accounts
$hesk_settings[\'customer_accounts\']=' . hesk_getProperty($set, 'customer_accounts') . ';
$hesk_settings[\'customer_accounts_required\']=' . hesk_getProperty($set, 'customer_accounts_required') . ';
$hesk_settings[\'customer_accounts_customer_self_register\']=' . hesk_getProperty($set, 'customer_accounts_customer_self_register') . ';
$hesk_settings[\'customer_accounts_admin_approvals\']=' . hesk_getProperty($set, 'customer_accounts_admin_approvals') . ';
$hesk_settings[\'customer_autologin\']=' . hesk_getProperty($set, 'customer_autologin') . ';
$hesk_settings[\'customer_accounts_allow_email_changes\']=' . hesk_getProperty($set, 'customer_accounts_allow_email_changes') . ';
$hesk_settings[\'customer_accounts_verify_email_cooldown\']=' . hesk_getProperty($set, 'customer_accounts_verify_email_cooldown') . ';

// --> SPAM Prevention
$hesk_settings[\'secimg_use\']=' . hesk_getProperty($set, 'secimg_use') . ';
$hesk_settings[\'secimg_sum\']=\'' . hesk_getProperty($set, 'secimg_sum') . '\';
$hesk_settings[\'recaptcha_use\']=' . hesk_getProperty($set, 'recaptcha_use') . ';
$hesk_settings[\'recaptcha_public_key\']=\'' . hesk_getProperty($set, 'recaptcha_public_key') . '\';
$hesk_settings[\'recaptcha_private_key\']=\'' . hesk_getProperty($set, 'recaptcha_private_key') . '\';
$hesk_settings[\'question_use\']=' . hesk_getProperty($set, 'question_use') . ';
$hesk_settings[\'question_ask\']=\'' . hesk_getProperty($set, 'question_ask') . '\';
$hesk_settings[\'question_ans\']=\'' . hesk_getProperty($set, 'question_ans') . '\';

// --> Security
$hesk_settings[\'attempt_limit\']=' . hesk_getProperty($set, 'attempt_limit') . ';
$hesk_settings[\'attempt_banmin\']=' . hesk_getProperty($set, 'attempt_banmin') . ';
$hesk_settings[\'flood\']=' . hesk_getProperty($set, 'flood') . ';
$hesk_settings[\'reset_pass\']=' . hesk_getProperty($set, 'reset_pass') . ';
$hesk_settings[\'email_view_ticket\']=' . hesk_getProperty($set, 'email_view_ticket') . ';
$hesk_settings[\'x_frame_opt\']=' . hesk_getProperty($set, 'x_frame_opt') . ';
$hesk_settings[\'samesite\']=\'' . hesk_getProperty($set, 'samesite') . '\';
$hesk_settings[\'force_ssl\']=' . hesk_getProperty($set, 'force_ssl') . ';
$hesk_settings[\'url_key\']=\'' . hesk_getProperty($set, 'url_key') . '\';
$hesk_settings[\'require_mfa\']='. hesk_getProperty($set, 'require_mfa') . ';
$hesk_settings[\'require_mfa_customers\']='. hesk_getProperty($set, 'require_mfa_customers') . ';
$hesk_settings[\'elevator_duration\']=\''. hesk_getProperty($set, 'elevator_duration') .'\';

// --> Attachments
$hesk_settings[\'attachments\']=array(
\'use\' => ' . (isset($set['attachments']) ? $set['attachments']['use'] : $hesk_settings['attachments']['use']) . ',
\'max_number\' => ' . (isset($set['attachments']) ? $set['attachments']['max_number'] : $hesk_settings['attachments']['max_number']) . ',
\'max_size\' => ' . (isset($set['attachments']) ? $set['attachments']['max_size'] : $hesk_settings['attachments']['max_size']) . ',
\'allowed_types\' => array(\'' . implode('\',\'',hesk_getAllowedAttachmentTypes($set)) . '\'),
\'attachment_in_email_type\' => ' . (isset($set['attachments']['attachment_in_email_type']) ? $set['attachments']['attachment_in_email_type'] : $hesk_settings['attachments']['attachment_in_email_type']) . ',
\'direct_attachment_in_email\' => ' . (isset($set['attachments']['direct_attachment_in_email']) ? $set['attachments']['direct_attachment_in_email'] : $hesk_settings['attachments']['direct_attachment_in_email']) . ',
\'direct_attachment_in_email_no_of_files\' => ' . (isset($set['attachments']['direct_attachment_in_email_no_of_files']) ? $set['attachments']['direct_attachment_in_email_no_of_files'] :  $hesk_settings['attachments']['direct_attachment_in_email_no_of_files']) .',
\'first_x_attachments\' => ' . (isset($set['attachments']['first_x_attachments']) ? $set['attachments']['first_x_attachments'] :  $hesk_settings['attachments']['first_x_attachments']) .',
\'file_max_size\' => ' . (isset($set['attachments']['file_max_size']) ? $set['attachments']['file_max_size'] :  $hesk_settings['attachments']['file_max_size']) .',
);


// ==> KNOWLEDGEBASE

// --> Knowledgebase settings
$hesk_settings[\'kb_enable\']=' . hesk_getProperty($set, 'kb_enable') . ';
$hesk_settings[\'kb_wysiwyg\']=' . hesk_getProperty($set, 'kb_wysiwyg') . ';
$hesk_settings[\'kb_search\']=' . hesk_getProperty($set, 'kb_search') . ';
$hesk_settings[\'kb_search_limit\']=' . hesk_getProperty($set, 'kb_search_limit') . ';
$hesk_settings[\'kb_views\']=' . hesk_getProperty($set, 'kb_views') . ';
$hesk_settings[\'kb_date\']=' . hesk_getProperty($set, 'kb_date') . ';
$hesk_settings[\'kb_recommendanswers\']=' . hesk_getProperty($set, 'kb_recommendanswers') . ';
$hesk_settings[\'kb_rating\']=' . hesk_getProperty($set, 'kb_rating') . ';
$hesk_settings[\'kb_substrart\']=' . hesk_getProperty($set, 'kb_substrart') . ';
$hesk_settings[\'kb_cols\']=' . hesk_getProperty($set, 'kb_cols') . ';
$hesk_settings[\'kb_numshow\']=' . hesk_getProperty($set, 'kb_numshow') . ';
$hesk_settings[\'kb_popart\']=' . hesk_getProperty($set, 'kb_popart') . ';
$hesk_settings[\'kb_latest\']=' . hesk_getProperty($set, 'kb_latest') . ';
$hesk_settings[\'kb_index_popart\']=' . hesk_getProperty($set, 'kb_index_popart') . ';
$hesk_settings[\'kb_index_latest\']=' . hesk_getProperty($set, 'kb_index_latest') . ';
$hesk_settings[\'kb_related\']=' . hesk_getProperty($set, 'kb_related') . ';


// ==> EMAIL

// --> Email sending
$hesk_settings[\'noreply_mail\']=\'' . hesk_getProperty($set, 'noreply_mail') . '\';
$hesk_settings[\'noreply_name\']=\'' . hesk_getProperty($set, 'noreply_name') . '\';
$hesk_settings[\'email_max_recipients\']=' . hesk_getProperty($set, 'email_max_recipients') . ';
$hesk_settings[\'email_formatting\']=' . hesk_getProperty($set, 'email_formatting') . ';
$hesk_settings[\'smtp\']=' . hesk_getProperty($set, 'smtp') . ';
$hesk_settings[\'smtp_host_name\']=\'' . hesk_getProperty($set, 'smtp_host_name') . '\';
$hesk_settings[\'smtp_host_port\']=' . hesk_getProperty($set, 'smtp_host_port') . ';
$hesk_settings[\'smtp_timeout\']=' . hesk_getProperty($set, 'smtp_timeout') . ';
$hesk_settings[\'smtp_enc\']=\'' . hesk_getProperty($set, 'smtp_enc') . '\';
$hesk_settings[\'smtp_noval_cert\']=' . hesk_getProperty($set, 'smtp_noval_cert') . ';
$hesk_settings[\'smtp_user\']=\'' . hesk_getProperty($set, 'smtp_user') . '\';
$hesk_settings[\'smtp_password\']=\'' . hesk_getProperty($set, 'smtp_password') . '\';
$hesk_settings[\'smtp_conn_type\']=\'' . hesk_getProperty($set, 'smtp_conn_type') . '\';
$hesk_settings[\'smtp_oauth_provider\']=' . hesk_getProperty($set, 'smtp_oauth_provider') . ';

// --> Email piping
$hesk_settings[\'email_piping\']=' . hesk_getProperty($set, 'email_piping') . ';

// --> IMAP Fetching
$hesk_settings[\'imap\']=' . hesk_getProperty($set, 'imap') . ';
$hesk_settings[\'imap_job_wait\']=' . hesk_getProperty($set, 'imap_job_wait') . ';
$hesk_settings[\'imap_host_name\']=\'' . hesk_getProperty($set, 'imap_host_name') . '\';
$hesk_settings[\'imap_host_port\']=' . hesk_getProperty($set, 'imap_host_port') . ';
$hesk_settings[\'imap_enc\']=\'' . hesk_getProperty($set, 'imap_enc') . '\';
$hesk_settings[\'imap_noval_cert\']=' . hesk_getProperty($set, 'imap_noval_cert') . ';
$hesk_settings[\'imap_disable_GSSAPI\']=' . hesk_getProperty($set, 'imap_disable_GSSAPI') . ';
$hesk_settings[\'imap_keep\']=' . hesk_getProperty($set, 'imap_keep') . ';
$hesk_settings[\'imap_user\']=\'' . hesk_getProperty($set, 'imap_user') . '\';
$hesk_settings[\'imap_password\']=\'' . hesk_getProperty($set, 'imap_password') . '\';
$hesk_settings[\'imap_conn_type\']=\'' . hesk_getProperty($set, 'imap_conn_type') . '\';
$hesk_settings[\'imap_oauth_provider\']=' . hesk_getProperty($set, 'imap_oauth_provider') . ';
$hesk_settings[\'imap_mailbox\']=\'' . hesk_getProperty($set, 'imap_mailbox') . '\';

// --> POP3 Fetching
$hesk_settings[\'pop3\']=' . hesk_getProperty($set, 'pop3') . ';
$hesk_settings[\'pop3_job_wait\']=' . hesk_getProperty($set, 'pop3_job_wait') . ';
$hesk_settings[\'pop3_host_name\']=\'' . hesk_getProperty($set, 'pop3_host_name') . '\';
$hesk_settings[\'pop3_host_port\']=' . hesk_getProperty($set, 'pop3_host_port') . ';
$hesk_settings[\'pop3_tls\']=' . hesk_getProperty($set, 'pop3_tls') . ';
$hesk_settings[\'pop3_keep\']=' . hesk_getProperty($set, 'pop3_keep') . ';
$hesk_settings[\'pop3_user\']=\'' . hesk_getProperty($set, 'pop3_user') . '\';
$hesk_settings[\'pop3_password\']=\'' . hesk_getProperty($set, 'pop3_password') . '\';
$hesk_settings[\'pop3_conn_type\']=\'' . hesk_getProperty($set, 'pop3_conn_type') . '\';
$hesk_settings[\'pop3_oauth_provider\']=' . hesk_getProperty($set, 'pop3_oauth_provider') . ';

$hesk_settings[\'strip_quoted\']=' . hesk_getProperty($set, 'strip_quoted') . ';
$hesk_settings[\'eml_req_msg\']=' . hesk_getProperty($set, 'eml_req_msg') . ';
$hesk_settings[\'save_embedded\']=' . hesk_getProperty($set, 'save_embedded') . ';
$hesk_settings[\'email_include_to\']=' . hesk_getProperty($set, 'email_include_to') . ';
$hesk_settings[\'email_include_cc\']=' . hesk_getProperty($set, 'email_include_cc') . ';

// --> Ignore emails
$hesk_settings[\'pipe_block_noreply\']=' . hesk_getProperty($set, 'pipe_block_noreply') . ';
$hesk_settings[\'pipe_block_returned\']=' . hesk_getProperty($set, 'pipe_block_returned') . ';
$hesk_settings[\'pipe_block_duplicate\']=' . hesk_getProperty($set, 'pipe_block_duplicate') . ';
$hesk_settings[\'loop_hits\']=' . hesk_getProperty($set, 'loop_hits') . ';
$hesk_settings[\'loop_time\']=' . hesk_getProperty($set, 'loop_time') . ';
$hesk_settings[\'pipe_customer_rejection_notification\']=' . hesk_getProperty($set, 'pipe_customer_rejection_notification') . ';
$hesk_settings[\'pipe_customer_rejection_email_cooldown_hours\']=' . hesk_getProperty($set, 'pipe_customer_rejection_email_cooldown_hours') . ';

// --> Detect email typos
$hesk_settings[\'detect_typos\']=' . hesk_getProperty($set, 'detect_typos') . ';
$hesk_settings[\'email_providers\']=array(' . hesk_getProperty($set, 'email_providers') . ');

// --> Notify customer when
$hesk_settings[\'notify_new\']=' . hesk_getProperty($set, 'notify_new') . ';
$hesk_settings[\'notify_skip_spam\']=' . hesk_getProperty($set, 'notify_skip_spam') . ';
$hesk_settings[\'notify_spam_tags\']=array(' . hesk_getProperty($set, 'notify_spam_tags') . ');
$hesk_settings[\'notify_closed\']=' . hesk_getProperty($set, 'notify_closed') . ';

// --> Other
$hesk_settings[\'multi_eml\']=' . hesk_getProperty($set, 'multi_eml') . ';
$hesk_settings[\'confirm_email\']=' . hesk_getProperty($set, 'confirm_email') . ';
$hesk_settings[\'open_only\']=' . hesk_getProperty($set, 'open_only') . ';


// ==> TICKET LIST

$hesk_settings[\'ticket_list\']=array(' . hesk_getProperty($set, 'ticket_list') . ');
$hesk_settings[\'customer_ticket_list\']=array(' . hesk_getProperty($set, 'customer_ticket_list') . ');

// --> Other
$hesk_settings[\'submittedformat\']=' . hesk_getProperty($set, 'submittedformat') . ';
$hesk_settings[\'updatedformat\']=' . hesk_getProperty($set, 'updatedformat') . ';
$hesk_settings[\'format_submitted\']=\'' . hesk_getProperty($set, 'format_submitted') . '\';
$hesk_settings[\'format_updated\']=\'' . hesk_getProperty($set, 'format_updated') . '\';
$hesk_settings[\'email_column\']=' . hesk_getProperty($set, 'email_column') . ';


// ==> MISC

// --> Date & Time
$hesk_settings[\'timezone\']=\'' . hesk_getProperty($set, 'timezone') . '\';
$hesk_settings[\'format_time\']=\'' . hesk_getProperty($set, 'format_time') . '\';
$hesk_settings[\'format_date\']=\'' . hesk_getProperty($set, 'format_date') . '\';
$hesk_settings[\'format_timestamp\']=\'' . hesk_getProperty($set, 'format_timestamp') . '\';
$hesk_settings[\'time_display\']=' . hesk_getProperty($set, 'time_display') . ';
$hesk_settings[\'format_datepicker_js\']=\'' . hesk_getProperty($set, 'format_datepicker_js') . '\';
$hesk_settings[\'format_datepicker_php\']=\'' . hesk_getProperty($set, 'format_datepicker_php') . '\';

// --> Other
$hesk_settings[\'ip_whois\']=\'' . hesk_getProperty($set, 'ip_whois') . '\';
$hesk_settings[\'maintenance_mode\']=' . hesk_getProperty($set, 'maintenance_mode') . ';
$hesk_settings[\'alink\']=' . hesk_getProperty($set, 'alink') . ';
$hesk_settings[\'submit_notice\']=' . hesk_getProperty($set, 'submit_notice') . ';
$hesk_settings[\'online\']=' . hesk_getProperty($set, 'online') . ';
$hesk_settings[\'online_min\']=' . hesk_getProperty($set, 'online_min') . ';
$hesk_settings[\'check_updates\']=' . hesk_getProperty($set, 'check_updates') . ';


// ==> LOOK & FEEL
$hesk_settings[\'customer_theme\']=\'' . hesk_getProperty($set, 'customer_theme') . '\';
$hesk_settings[\'theme_overrides\']=array(' . hesk_getProperty($set, 'theme_overrides', true) . ');


#############################
#     DO NOT EDIT BELOW     #
#############################
$hesk_settings[\'hesk_version\']=\'' . $set['hesk_version'] . '\';
if ($hesk_settings[\'debug_mode\'])
{
    error_reporting(E_ALL);
}
else
{
    error_reporting(0);
}
if (!defined(\'IN_SCRIPT\')) {die(\'Invalid attempt!\');}';

// Write to the settings file
if ( ! file_put_contents(HESK_PATH . 'hesk_settings.inc.php', $settings_file_content, LOCK_EX) )
{
	hesk_error($hesklang['err_openset']);
}

// Invalidate remember-me tokens when MFA or remember-me requirements change
if (isset($set['require_mfa']) && intval($set['require_mfa']) !== intval($hesk_settings['require_mfa'])) {
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."auth_tokens` WHERE `user_type` = 'STAFF'");
}
if (isset($set['require_mfa_customers']) && intval($set['require_mfa_customers']) !== intval($hesk_settings['require_mfa_customers'])) {
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."auth_tokens` WHERE `user_type` = 'CUSTOMER'");
}
if (isset($set['autologin']) && intval($set['autologin']) !== intval($hesk_settings['autologin'])) {
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."auth_tokens` WHERE `user_type` = 'STAFF'");
}
if (isset($set['customer_autologin']) && intval($set['customer_autologin']) !== intval($hesk_settings['customer_autologin'])) {
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."auth_tokens` WHERE `user_type` = 'CUSTOMER'");
}

// Any settings problems?
$tmp = array();

if ( ! $smtp_OK)
{
    $tmp[] = '<span class="text-danger">'.$hesklang['sme'].':</span> '.$smtp_error.'<br /><br /><a href="Javascript:void(0)" onclick="Javascript:hesk_toggleLayerDisplay(\'smtplog\')">'.$hesklang['scl'].'</a><div id="smtplog" style="display:none">&nbsp;<br /><textarea name="log" rows="10" cols="60">'.$smtp_log.'</textarea></div>';
}

if ( ! $pop3_OK)
{
    $tmp[] = '<span class="text-danger">'.$hesklang['pop3e'].':</span> '.$pop3_error.'<br /><br /><a href="Javascript:void(0)" onclick="Javascript:hesk_toggleLayerDisplay(\'pop3log\')">'.$hesklang['pop3log'].'</a><div id="pop3log" style="display:none">&nbsp;<br /><textarea name="log" rows="10" cols="60">'.$pop3_log.'</textarea></div>';
}

// Clear the cache folder
hesk_purge_cache('kb');
hesk_purge_cache('cf');
hesk_purge_cache('export', 14400);
hesk_purge_cache('status');
hesk_purge_cache('priority');

// Show the settings page and display any notices or success
$return_location = 'admin_settings_' . strtolower($section) . '.php';
if ( count($tmp) )
{
	$errors = implode('<br /><br />', $tmp);
    hesk_process_messages( $hesklang['sns'] . '<br /><br />' . $errors,$return_location,'NOTICE');
}
else
{
	hesk_process_messages($hesklang['set_were_saved'],$return_location,'SUCCESS');
}
exit();


/** FUNCTIONS **/
function hesk_getLanguagesArray($returnArray=0)
{
	global $hesk_settings, $hesklang;

	/* Get a list of valid emails */
    $valid_emails = array_keys( hesk_validEmails() );

	$dir = HESK_PATH . 'language/';
	$path = opendir($dir);
    $code = '';
    $langArray = array();

    /* Test all folders inside the language folder */
	while (false !== ($subdir = readdir($path)))
	{
		if ($subdir == "." || $subdir == "..")
	    {
	    	continue;
	    }

		if (filetype($dir . $subdir) == 'dir')
		{
        	$add   = 1;
	    	$langu = $dir . $subdir . '/text.php';
            $langc = $dir . $subdir . '/custom-text.php';
	        $email = $dir . $subdir . '/emails';
            $html_email = $dir . $subdir . '/html_emails';

			/* Check the text.php */
	        if (file_exists($langu))
	        {
	        	$tmp = file_get_contents($langu);

				// Some servers add slashes to file_get_contents output
				if ( strpos ($tmp, '[\\\'LANGUAGE\\\']') !== false )
				{
					$tmp = stripslashes($tmp);
				}                

	            $err = '';
	        	if ( ! preg_match('/\$hesklang\[\'LANGUAGE\'\]\=\'(.*)\'\;/', $tmp, $l) )
	            {
	                $add = 0;
	            }
	            elseif ( ! preg_match('/\$hesklang\[\'ENCODING\'\]\=\'(.*)\'\;/', $tmp) )
	            {
	            	$add = 0;
	            }
                elseif ( ! preg_match('/\$hesklang\[\'_COLLATE\'\]\=\'(.*)\'\;/', $tmp) )
                {
                	$add = 0;
                }
                elseif ( ! preg_match('/\$hesklang\[\'EMAIL_HR\'\]\=\'(.*)\'\;/', $tmp, $hr) )
                {
                	$add = 0;
                }
                // Is it latest version?
                elseif ( ! preg_match('/\$hesklang\[\'email_authentication_method\'\]/', $tmp) )
                {
                	$add = 0;
                }
	        }
	        else
	        {
                $add   = 0;
	        }

            /* Check emails folder */
	        if (file_exists($email) && filetype($email) == 'dir')
	        {
	            foreach ($valid_emails as $eml)
	            {
	            	if (!file_exists($email.'/'.$eml.'.txt'))
	                {
	                	$add = 0;
	                }
	            }
	        }
	        else
	        {
	        	$add = 0;
	        }

            if (file_exists($html_email) && filetype($html_email) == 'dir')
            {
                foreach ($valid_emails as $eml)
                {
                    if (!file_exists($html_email.'/'.$eml.'.txt'))
                    {
                        $add = 0;
                    }
                }
            }
            else
            {
                $add = 0;
            }

            /* Add an option for the <select> if needed */
            if ($add)
            {
                // If EMAIL_HR is in the custom-text.php file, use that one
                if (file_exists($langc)) {
                    $tmp = file_get_contents($langc);
                    preg_match('/\$hesklang\[\'EMAIL_HR\'\]\=\'(.*)\'\;/', $tmp, $custom_hr);
                    if (isset($custom_hr[1])) {
                        $hr[1] = $custom_hr[1];
                    }
                }

				$code .= "'".addslashes($l[1])."' => array('folder'=>'".$subdir."','hr'=>'".addslashes($hr[1])."'),\n";
                $langArray[] = $l[1];
            }
		}
	}

	closedir($path);

    if ($returnArray)
    {
		return $langArray;
    }
    else
    {
    	return $code;
    }
} // END hesk_getLanguagesArray()

function hesk_getValidThemes() {
    global $hesk_settings, $hesklang;

    $dir = HESK_PATH . 'theme/';
    $path = opendir($dir);

    $valid_themes = array();
    /* Test all folders inside the theme folder */
    while (false !== ($subdir = readdir($path))) {
        if ($subdir === '.' || $subdir === '..') {
            continue;
        }

        if (filetype($dir . $subdir) === 'dir') {
            $add = 1;

            //region Create Ticket
            $files_to_test = array('category-select.php', 'create-ticket.php', 'create-ticket-confirmation.php');
            foreach ($files_to_test as $test_file) {
                if (!file_exists($dir . $subdir . '/customer/create-ticket/' . $test_file)) {
                    $add = 0;
                }
            }

            //endregion
            //region Knowledgebase
            $files_to_test = array('search-results.php', 'view-article.php', 'view-category.php');
            foreach ($files_to_test as $test_file) {
                if (!file_exists($dir . $subdir . '/customer/knowledgebase/' . $test_file)) {
                    $add = 0;
                }
            }
            //endregion
            //region View Ticket
            $files_to_test = array('form.php', 'view-ticket.php');
            foreach ($files_to_test as $test_file) {
                if (!file_exists($dir . $subdir . '/customer/view-ticket/' . $test_file)) {
                    $add = 0;
                }
            }
            //endregion
            //region Solo files
            $files_to_test = array('error.php', 'index.php', 'maintenance.php');
            foreach ($files_to_test as $test_file) {
                if (!file_exists($dir . $subdir . '/customer/' . $test_file)) {
                    $add = 0;
                }
            }
            //endregion
            if (!file_exists($dir . $subdir . '/print-ticket.php')) {
                $add = 0;
            }
            if (!file_exists($dir . $subdir . '/config.json')) {
                $add = 0;
            }
        }

        // Build markup
        if ($add) {
            // Pull the name from config.json
            $config = file_get_contents($dir . $subdir . '/config.json');
            $config_json = json_decode($config, true);

            $valid_themes[] = $subdir;
        }
    }

    return $valid_themes;
}
function hesk_getValidCustomerThemes() {
    global $hesk_settings, $hesklang;

    $path = HESK_PATH . 'theme/' . $hesk_settings['site_theme'] . '/customer/css/themes/';

    $valid_themes = array('');

    $themeCssFiles = glob($path.'*.css');
    if (is_array($themeCssFiles)) {
        foreach ($themeCssFiles as $file) {
            $filename = pathinfo($file, PATHINFO_FILENAME); // Get filename without extension
            $valid_themes[] = $filename;
        }
    }

    return $valid_themes;
}


function hesk_formatUnits($size)
{
    $units = array(
    	'GB' => 1073741824,
        'MB' => 1048576,
        'kB' => 1024,
        'B'  => 1
    );

    list($size, $suffix) = explode(' ', $size);

    if ( isset($units[$suffix]) )
    {
    	return round( $size * $units[$suffix] );
    }

    return false;
} // End hesk_formatBytes()

function hesk_getProperty($set, $property, $returnAsArray = false) {
	global $hesk_settings;

	if (isset($set[$property])) {
        if ($returnAsArray && is_array($set[$property])) {
            $result = array();
            foreach ($set[$property] as $key => $value) {
                $result[] = "'" . addslashes($key) . "' => '" . addslashes($value) . "'";
            }
            if (count($result) === 0) {
                return '';
            }
            return implode(', ', $result);
        }
		return $set[$property];
	}

	if (is_array($hesk_settings[$property])) {
        if ($returnAsArray) {
            if (count($hesk_settings[$property]) === 0) {
                // For some settings, i.e. like theme_overrides, it is valid for the settings to have an empty array
                return '';
            }
            $result = array();
            foreach ($hesk_settings[$property] as $key => $value) {
                $result[] = "'" . addslashes($key) . "' => '" . addslashes($value) . "'";
            }
            return implode(', ', $result);
        }
		return "'" . implode('\',\'', hesk_slashArray($hesk_settings[$property])) . "'";
	}

	return isset($set[$property]) ? $set[$property] : addslashes($hesk_settings[$property]);
}

function hesk_getLanguageForFile($set) {
	global $hesk_settings;

	if (isset($set['languages'])) {
		return $set['languages'];
	}

	$languages = '';
	foreach ($hesk_settings['languages'] as $name => $info) {
		$languages .= "'".addslashes($name)."' => array('folder'=>'".$info['folder']."','hr'=>'".addslashes($info['hr'])."'),\n";
	}

	return $languages;
}

function hesk_getAllowedAttachmentTypes($set) {
	global $hesk_settings;

	return isset($set['attachments']) ? $set['attachments']['allowed_types'] : $hesk_settings['attachments']['allowed_types'];
}
admin_settings_theme.php
wget 'https://lists2.roe3.org/hesk/admin/admin_settings_theme.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

define('LOAD_TABS',1);

define('LOAD_CUSTOMER_THEME_VARS',1); // Need this here to show off calculated colors as examples and make them work properly

// Make sure the install folder is deleted
if (is_dir(HESK_PATH . 'install')) {die('Please delete the <b>install</b> folder from your server for security reasons then refresh this page!');}

// Get all the required files and functions
require(HESK_PATH . 'hesk_settings.inc.php');

// Save the default language for the settings page before choosing user's preferred one
$hesk_settings['language_default'] = $hesk_settings['language'];
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/setup_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_man_settings');

// Load custom fields
require_once(HESK_PATH . 'inc/custom_fields.inc.php');

// Test languages function
if (isset($_GET['test_themes'])) {
    hesk_testTheme(0);
}
$help_folder = '../language/' . $hesk_settings['languages'][$hesk_settings['language']]['folder'] . '/help_files/';

$enable_save_settings   = 0;
$enable_use_attachments = 0;

// prefix to be used when referencing lang files and hesk settings
$php_css_var_prefix = 'theme_var';
require_once(HESK_PATH . 'inc/theme_variables.inc.php');
global $theme_color_settings_groups;

// Print header
require_once(HESK_PATH . 'inc/header.inc.php');

// Print main manage users page
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

// Demo mode? Hide values of sensitive settings
if ( defined('HESK_DEMO') )
{
    require_once(HESK_PATH . 'inc/admin_settings_demo.inc.php');
}

/* This will handle error, success and notice messages */
hesk_handle_messages();
?>
<div class="main__content settings admin_settings_theme">

    <?php require_once(HESK_PATH . 'inc/admin_settings_status.inc.php'); ?>

    <script language="javascript" type="text/javascript"><!--
        function hesk_checkFields() {
            var d = document.form1;

            // DISABLE SUBMIT BUTTON
            d.submitbutton.disabled=true;

            return true;
        }

        function hesk_toggleLayer(nr,setto) {
            if (document.all)
                document.all[nr].style.display = setto;
            else if (document.getElementById)
                document.getElementById(nr).style.display = setto;
        }

        function hesk_testTheme()
        {
            window.open('admin_settings_theme.php?test_themes=1',"Hesk_window","height=400,width=500,menubar=0,location=0,toolbar=0,status=0,resizable=1,scrollbars=1");
            return false;
        }
        //-->
    </script>
    <form method="post" action="admin_settings_save.php" name="form1" onsubmit="return hesk_checkFields()" aria-label="<?php echo $hesklang['laf']; ?>">
        <div class="settings__form form" data-expanded="false">
            <section class="settings__form_block">
                <h3><?php echo $hesklang['laf']; ?></h3>

                <div role="alert" class="theme-changed-note notification blue added-left-offset">
                    <b><?php echo $hesklang['note']; ?>:</b> <?php echo $hesklang['theme_colors_note_co']; ?>
                </div>
                <?php if ( ! file_exists(HESK_PATH . 'disable_custom_html_ui.txt')): ?>
                <div class="form-group flex-row">
                    <label>
                        <span><?php echo $hesklang['custom_html']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>theme.html#2','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <a href="admin_settings_custom_html.php" class="btn btn--blue-border" ripple="ripple" style="margin-left: 24px"><?php echo $hesklang['custom_html_link']; ?></a>
                </div>
                <?php endif; ?>
                <div class="form-group flex-row">
                    <label>
                        <span><?php echo $hesklang['customer_theme']; ?></span>
                        <a onclick="hesk_window('<?php echo $help_folder; ?>theme.html#1','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </label>
                    <div class="dropdown-select center out-close" style="background-color: #fff;">
                        <select name="s_customer_theme" onchange="hesk_customerThemeChanged(this.value)">
                            <?php echo hesk_displayCustomerThemes(1); ?>
                        </select>
                    </div>
                </div>
                <div role="alert" class="theme-changed-note notification blue added-left-offset d_hide">
                    <b><?php echo $hesklang['note']; ?>:</b> <?php echo $hesklang['theme_changed_note']; ?>
                </div>
            </section>
            <section class="settings__form_block theme-overrides empty-section">
                <h3><?php echo $hesklang['theme_overrides']; ?>
                    <a onclick="hesk_window('<?php echo $help_folder; ?>theme.html#2','400','500')">
                        <div class="tooltype right">
                            <svg class="icon icon-info">
                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                            </svg>
                        </div>
                    </a>
                </h3>
                <div role="alert" class="notification blue added-left-offset">
                    <?php echo $hesklang['theme_colors_note']; ?>
                </div>
                <button type="button" class="btn btn--blue-border reset-color" style="margin-left: 20px" ripple="ripple"
                        onclick="return hesk_resetAllThemeOverrides()">
                    <?php echo $hesklang['reset_all_overrides']; ?>
                </button>
            </section>
            <?php foreach ($theme_color_settings_groups as $group_key => $group_variables): ?>
                <section class="settings__form_block theme-overrides theme-group-<?php echo $group_key; ?>">
                    <h3><?php echo $hesklang['theme_group_' . $group_key]; ?><a onclick="hesk_window('<?php echo $help_folder; ?>theme.html#<?php echo $group_key;?>','400','500')">
                            <div class="tooltype right">
                                <svg class="icon icon-info">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                                </svg>
                            </div>
                        </a>
                    </h3>
                    <?php
                    foreach ($group_variables as $css_variable) {
                        $color_setting = get_theme_color_setting($css_variable);
                        if (!$color_setting) {
                            continue;
                        }

                        $hesk_sett_value = isset($hesk_settings['theme_overrides'][$css_variable]) ? $hesk_settings['theme_overrides'][$css_variable] : '';
                        ?>
                        <div class="form-group row flex-row color">
                            <label for="<?php echo $php_css_var_prefix . $css_variable; ?>">
                                <span><?php echo ($color_setting['derivative'] ? '<span class="left-asterix"></span>' : ''); ?><?php echo $hesklang[$php_css_var_prefix . $css_variable]; ?></span>
                            </label>
                            <?php $color = hesk_validate_color_hex(isset($hesk_sett_value) ? $hesk_sett_value : ''); ?>

                            <!-- Besides just the onFineChange, we need the oninput here, if we want keystrokes/typing to work with preview properly always too! -->
                            <input type="text"
                                   class="form-control jscolor {hash:true, uppercase:false, onFineChange:'hesk_preview_color(this, \'<?php echo $css_variable; ?>\', \'<?php echo $php_css_var_prefix ?>\')'}"
                                   id="<?php echo $php_css_var_prefix . $css_variable; ?>"
                                   name="<?php echo $php_css_var_prefix . $css_variable; ?>"
                                   oninput="hesk_preview_color('<?php echo $color; ?>', '<?php echo $css_variable; ?>', '<?php echo $php_css_var_prefix ?>')"
                            >
                            <span id="<?php echo $php_css_var_prefix . $css_variable; ?>_preview" style="color:<?php echo $color; ?>"><?php echo $hesklang['clr_view']; ?></span>
                            <button type="button" class="btn btn--blue-border reset-color" style="margin-left: 20px" ripple="ripple"
                                    onclick="return hesk_resetThemeColor('<?php echo $css_variable; ?>')">
                                <?php echo $hesklang['reset']; ?>
                            </button>
                        </div>
                    <?php } ?>
                    <!-- We use a hidden input field, to which we only store any overwritten values, which are then posted on save. -->

                    <!-- After main_brand, we also print a view/hide advanced settings-->
                    <?php if ($group_key === 'main_brand') { ?>
                        <button type="button" class="btn btn--blue-border toggle-advanced-settings" style="margin-left: 20px" ripple="ripple"
                                onclick="return hesk_toggleAdvancedSettings(this)" data-expanded="false">
                        <span data-type="advanced">
                            <?php echo $hesklang['view_advanced']; ?>
                            <svg class="icon icon-chevron-down">
                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                            </svg>
                        </span>
                            <span data-type="basic">
                            <?php echo $hesklang['view_basic']; ?>
                            <svg class="icon icon-chevron-up">
                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                            </svg>
                        </span>
                        </button>
                    <?php } ?>
                </section>
            <?php endforeach; ?>

            <div class="settings__form_submit">
                <input type="hidden" name="s_theme_overrides" id="s_theme_overrides" value="">
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                <input type="hidden" name="section" value="THEME">
                <button id="submitbutton" style="display: inline-flex" type="submit" class="btn btn-full" ripple="ripple"
                    <?php echo $enable_save_settings ? '' : 'disabled'; ?>>
                    <?php echo $hesklang['save_changes']; ?>
                </button>

                <?php if (!$enable_save_settings): ?>
                    <p>&nbsp;</p>
                    <div role="alert" class="notification red">
                        <?php echo $hesklang['e_save_settings']; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </form>
</div>

<script type="text/javascript" src="<?php echo HESK_PATH; ?>inc/jscolor/jscolor.min.js"></script>
<script type="text/javascript">

    // Storing any used DOM refs to avoid re-querying the DOM for the same elements.
    // For performance/lag/stutter considerations, which might otherwise happens with 100s of refs being updated on color changes
    let cachedDomRefs = {};
    const cssVarPrefix = '<?php echo $php_css_var_prefix; ?>';
    function getCachedDomRef(selector, useJquery = false, queryAll = false) {
        // just adding option for jQuery and regular, depending on implementation
        let cacheRef = (useJquery? "jq_" : "") + selector; // need to store them separately, as they might be used in both ways
        if (/*true ||*/ !cachedDomRefs[cacheRef]) {
            let domRef;
            if (useJquery) {
                domRef = $(selector);
            } else {
                if (queryAll) {
                    domRef = document.querySelectorAll(selector);
                } else {
                    domRef = document.querySelector(selector);
                }
            }
            if (domRef && (!useJquery || domRef.length > 0)) {
                // only store cache if the domElement exists (if jQuery selecting, also check for length > 0!)
                cachedDomRefs[cacheRef] = domRef;
            } else {
                // if not caching, still return the result, so any chaining in case of jQuery will still work properly
                return domRef;
            }
        }
        return cachedDomRefs[cacheRef];
    }

    function clearCachedDomRef(selector, useJquery = false, queryAll = false) {
        let cacheRef = (useJquery? "jq_" : "") + selector;
        if (cachedDomRefs[cacheRef]) {
            delete cachedDomRefs[cacheRef];
        }
    }

    function hesk_customerThemeChanged(themeName) {
        const templatePath = "<?php echo TEMPLATE_PATH; ?>";

        let themeLink = getCachedDomRef("#loaded_theme");
        if (!themeLink) {
            // themeLink not existing yet (i.e. happens if no specific theme is loaded)

            const defaultThemeLink = getCachedDomRef("#default_theme");
            if (!defaultThemeLink) {
                console.error("Default theme element not found at all, can't really load themes anyway!");
                return;
            }

            // If themeLink does not already exist, then create a new link element to load the loaded theme into it, after the defaultThemeLink element
            themeLink = document.createElement("link");
            themeLink.rel = "stylesheet";
            themeLink.type = "text/css";
            themeLink.id = "loaded_theme";

            // append newThemeLink after defaultThemeLink
            defaultThemeLink.insertAdjacentElement('afterend', themeLink);
        }

        if (themeName === '') {
            // If themeName is empty, then remove the loaded theme link
            themeLink.remove();

            // Need to clear cached ref, as otherwise on next theme select it won't be added properly
            clearCachedDomRef("#loaded_theme");

            // Finally, we have to recalculate all the input colors
            recalculateInputColors();
            attemptToggleChangedThemeNote();
            return;
        }

        // Construct the new href (adjust path if needed)
        const newHref = templatePath + 'customer/css/themes/' + themeName + '.css';

        // Set the new href to load the new theme
        themeLink.setAttribute("href", newHref);

        // wait for new CSS to load completely before we update the color preview
        themeLink.onload = function() {
            // Finally, we have to recalculate all the input colors
            recalculateInputColors();
            attemptToggleChangedThemeNote();
        };
    }

    function attemptToggleChangedThemeNote() {
        let $changedThemeNote = getCachedDomRef('.theme-changed-note', true);

        let showChangedThemeNote = Object.keys(themeOverrides).length > 0;
        $changedThemeNote.toggleClass('d_hide', !showChangedThemeNote);
    }

    function hesk_toggleAdvancedSettings(element) {
        element.setAttribute('data-expanded', element.dataset.expanded === 'false'? 'true' : 'false');

        // Get closest form, and add data-expanded attribute to the form
        const form = element.closest('.settings__form');
        form.setAttribute('data-expanded', element.dataset.expanded);
    }

    // Initialize the hidden field with an empty object
    // On any theme color changes, we will store them here, as this way we can identify if a setting has been overriden.
    // Note: we can directly use the variables HEX values, as they might just be dynamically calculated from other colors.
    // So we have to listen/check for these changes specifically.
    let themeOverrides = {};

    function updateThemeOverrides() {
        getCachedDomRef('#s_theme_overrides').value = JSON.stringify(themeOverrides);
    }
    function setInputOverrideClass(cssVariable, isOverridden = false) {
        const $input = getCachedDomRef(`input[name="<?php echo $php_css_var_prefix ?>${cssVariable}"]`, true);
        $input.closest('.form-group').toggleClass('is-overridden', isOverridden);
    }
    function setColorOverride(cssVariable, color) {
        themeOverrides[cssVariable] = color;
        updateThemeOverrides();
        setInputOverrideClass(cssVariable, true);
    }
    function removeColorOverride(cssVariable) {
        delete themeOverrides[cssVariable];
        document.documentElement.style.removeProperty(cssVariable);
        updateThemeOverrides();
        setInputOverrideClass(cssVariable, false);

        // If there was a note shown for overrides, we can also attempt to hide it now.
        attemptToggleChangedThemeNote();
    }
    function handleColorChange(color, cssVariable) {
        if (color !== '') {
            setColorOverride(cssVariable, color);
        } else {
            removeColorOverride(cssVariable);
        }
    }

    function hesk_resetThemeColor(cssVariable) {
        const input = getCachedDomRef(`input[name="<?php echo $php_css_var_prefix ?>${cssVariable}"]`);
        input.jscolor.fromString('');
        removeColorOverride(cssVariable);
        // While we could just recalculate for the specific variable here, it's best to just do all,
        // as if this color was part of calculations ofr other colors, others still need ot be recalculated as well
        recalculateInputColors();
        return false;
    }

    function hesk_resetAllThemeOverrides() {
        for (let cssVariable in themeOverrides) {
            hesk_resetThemeColor(cssVariable);
        }
    }

    // Updated preview color fro mGPT: It's similar, just with some extras
    function hesk_preview_color(jscolorOrString, cssVariable, idSelectorPrefix = 'theme_var', previewElementSuffix = '_preview') {
        //console.log("heskpreview.color , cssVariable: " + cssVariable + " , jsColoroRsintr: ", jscolorOrString)
        let input, color;
        if (typeof jscolorOrString === 'object' && jscolorOrString.valueElement) {
            // It's a jscolor object
            input = jscolorOrString.valueElement;
            color = jscolorOrString.toHEXString();
        } else if (jscolorOrString instanceof HTMLInputElement) {
            // normal input element, e.g. from keyup
            input = jscolorOrString;

            if (input.jscolor) {
                color = input.jscolor.toHEXString();
            } else {
                color = input.value.startsWith('#')
                    ? input.value
                    : "#" + input.value;
            }
        } else {
            // It's a string
            input = getCachedDomRef(`input[name="${idSelectorPrefix}${cssVariable}"]`);
            color = jscolorOrString.startsWith('#') ? jscolorOrString : "#" + jscolorOrString;
        }
        color = formatColorForCss(color);

        // Check if the input is currently focused (user is typing)
        let colorIsComplete = true;
        if (document.activeElement === input) {
            // User is typing - only update if the value is a valid complete hex color
            let inputValue = input.value.trim();
            if (!/^#?[0-9A-Fa-f]{6}$/.test(inputValue)) {
                // Incomplete or invalid color - mark as incomplete, so that we don't force/change the text from incomplete to complete/normalized
                // In other words - normalized is only to show immediate preview, the same as jscolor does on color picker
                colorIsComplete = false;
            }
            inputValue = normalizeHexColor(inputValue);
            color = inputValue;
        }

        const previewElement = getCachedDomRef('#' + idSelectorPrefix + cssVariable + previewElementSuffix);
        if (previewElement) {
            previewElement.style.color = color;
        }

        // set the :root value of the css variable
        document.documentElement.style.setProperty(cssVariable, color);

        if (colorIsComplete) {
            handleColorChange(color, cssVariable);
            recalculateInputColors();
        }
    }

    document.addEventListener('DOMContentLoaded', function() {
        // The jscolor fields are not automatically updated on render (as PHP does NOT have css color calculations yet), so on page load, we have to check for color values and update the jscolor fields with the computed values
        recalculateInputColors();

        <?php
        foreach($hesk_settings['theme_overrides'] as $css_variable => $color) {
            ?>
            var input = getCachedDomRef(`input[name="<?php echo $php_css_var_prefix . $css_variable?>"]`)
            hesk_preview_color('<?php echo $color; ?>', '<?php echo $css_variable; ?>');

        <?php }
        ?>

        function handleColorInputChangeEvent(e) {
            let id = e.target.id;
            const cssVariable = id.slice(cssVarPrefix.length);
            hesk_preview_color(
                e.target,
                cssVariable,
                cssVarPrefix
            );
        };

        // If we want keyup/typing to immediatel update preview colors, we also need this listener,
        // as colorjs won't handle it mid-changes otherwise
        document.addEventListener('keyup', function (e) {
            if (e.target.matches('.jscolor')) {
                handleColorInputChangeEvent(e);
            }
        });

        // Also handle input offocus, so that preview acccurately refreshes on of focous,
        // and uses jscolor's hexshort logic I.e. #1221 -> #112222 etc.
        document.addEventListener('focusout', function(e) {
            if (!e.target.matches('.form-control.jscolor')) {
                return;
            }
            handleColorInputChangeEvent(e);
        });
    });

    function normalizeHexColor(value) {
        value = value.trim();

        if (value[0] !== '#') {
            value = '#' + value;
        }

        // #ff0 -> #ffff00
        if (/^#[0-9a-f]{3}$/i.test(value)) {
            value = '#' + value[1] + value[1] + value[2] + value[2] + value[3] + value[3];
        }

        if (/^#[0-9a-f]{6}$/i.test(value)) {
            return value.toLowerCase();
        }

        return null;
    }

    function formatColorForCss(color) {
        color = String(color).trim();

        // Already valid CSS color formats/functions
        if (
            color.startsWith('#') ||
            color.startsWith('rgb(') ||
            color.startsWith('rgba(') ||
            color.startsWith('hsl(') ||
            color.startsWith('hsla(') ||
            color.startsWith('color(') ||
            color.startsWith('color-mix(') ||
            color.startsWith('var(')
        ) {
            return color;
        }

        // Assume plain hex without #
        return '#' + color;
    }

    function resolveCssVariableToColor(cssVariable) {
        var probe = document.createElement('div');
        probe.style.color = `var(${cssVariable})`;
        document.body.appendChild(probe);

        var resolvedColor = getComputedStyle(probe).color;
        probe.remove();

        return resolvedColor;
    }

    function cssColorToHex(color) {
        color = String(color).trim();

        // #fff / #ffffff
        var hexMatch = color.match(/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i);
        if (hexMatch) {
            var hex = hexMatch[1];

            if (hex.length === 3) {
                hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
            }

            return hex.toLowerCase();
        }

        // rgb(183, 199, 227) / rgba(...)
        var rgbMatch = color.match(/rgba?\(\s*(\d+),\s*(\d+),\s*(\d+)/i);
        if (rgbMatch) {
            return [rgbMatch[1], rgbMatch[2], rgbMatch[3]]
                .map(function(v) {
                    return parseInt(v, 10).toString(16).padStart(2, '0');
                })
                .join('');
        }

        // color(srgb 0.719608 0.78098 0.891373)
        var srgbMatch = color.match(/color\(srgb\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)/i);
        if (srgbMatch) {
            return [srgbMatch[1], srgbMatch[2], srgbMatch[3]]
                .map(function(v) {
                    return Math.round(parseFloat(v) * 255).toString(16).padStart(2, '0');
                })
                .join('');
        }

        return null;
    }

    function recalculateInputColors() {
        var colorInputs = getCachedDomRef('.form-control.jscolor', false, true);

        colorInputs.forEach(function(input) {
            var cssVariable = input.name.replace('<?php echo $php_css_var_prefix; ?>', '');

            // Raw CSS variable value, e.g. "#ffffff" or "color-mix(...)"
            var rawColor = getComputedStyle(document.documentElement)
                .getPropertyValue(cssVariable)
                .trim();

            if (!rawColor) {
                return;
            }

            var previewSpan = getCachedDomRef('#' + input.name + '_preview');

            // Preview text can use CSS-native values like color-mix(...)
            if (previewSpan) {
                previewSpan.style.color = formatColorForCss(rawColor);
            }

            // jscolor needs a plain hex value
            var resolvedColor = resolveCssVariableToColor(cssVariable);
            var resolvedHex = cssColorToHex(resolvedColor);

            if (!resolvedHex) {
                console.warn('Could not resolve color for:', cssVariable, rawColor, resolvedColor);
                return;
            }

            if (input.jscolor) {
                input.jscolor.fromString(resolvedHex);
            }

            input.value = '#' + resolvedHex;
        });
    }
</script>
<script src="<?php echo HESK_PATH; ?>js/jquery-ui.js?<?php echo $hesk_settings['hesk_version']; ?>"></script>
<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


function hesk_displayCustomerThemes() {
    global $hesk_settings, $hesklang;

    $path = HESK_PATH . 'theme/' . $hesk_settings['site_theme'] . '/customer/css/themes/';

    $html = '';
    $html .= '<option value="" ' . (!isset($hesk_settings['customer_theme']) || $hesk_settings['customer_theme'] === ''  ? 'selected' : '') . '>' . $hesklang['theme_name_default'] . '</option>';

    $themeCssFiles = glob($path.'*.css');
    if (is_array($themeCssFiles)) {
        foreach ($themeCssFiles as $file) {
            $filename = pathinfo($file, PATHINFO_FILENAME); // Get filename without extension
            $formattedText = ucwords(str_replace('_', ' ', $filename)); // Replace underscores & capitalize words
            if (!empty($hesklang['theme_name_' . $filename])) {
                $formattedText = $hesklang['theme_name_' . $filename];
            }
            $html .= '<option value="' . $filename . '" ' . ($hesk_settings['customer_theme'] === $filename ? 'selected' : '') . '>' . $formattedText . '</option>';
        }
    }

    return $html;
}


function hesk_validate_color_hex($hex, $def = '#000000')
{
    $hex = strtolower($hex);
    return preg_match('/^\#[a-f0-9]{6}$/', $hex) ? $hex : $def;
} // END hesk_validate_color_hex()


function hesk_get_text_color($bg_color)
{
    // Get RGB values
    list($r, $g, $b) = sscanf($bg_color, "#%02x%02x%02x");

    // Is Black a good text color?
    if (hesk_color_diff($r, $g, $b, 0, 0, 0) >= 500)
    {
        return '#000000';
    }

    // Use white instead
    return '#ffffff';
} // END hesk_get_text_color()


function hesk_color_diff($R1,$G1,$B1,$R2,$G2,$B2)
{
    return max($R1,$R2) - min($R1,$R2) +
        max($G1,$G2) - min($G1,$G2) +
        max($B1,$B2) - min($B1,$B2);
} // END hesk_color_diff()
admin_settings_ticket_list.php
wget 'https://lists2.roe3.org/hesk/admin/admin_settings_ticket_list.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

define('LOAD_TABS',1);

// Make sure the install folder is deleted
if (is_dir(HESK_PATH . 'install')) {die('Please delete the <b>install</b> folder from your server for security reasons then refresh this page!');}

// Get all the required files and functions
require(HESK_PATH . 'hesk_settings.inc.php');

// Save the default language for the settings page before choosing user's preferred one
$hesk_settings['language_default'] = $hesk_settings['language'];
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/setup_functions.inc.php');
require(HESK_PATH . 'inc/customer_accounts.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_man_settings');

// Load custom fields
require_once(HESK_PATH . 'inc/custom_fields.inc.php');

$help_folder = '../language/' . $hesk_settings['languages'][$hesk_settings['language']]['folder'] . '/help_files/';

$enable_save_settings   = 0;
$enable_use_attachments = 0;

// Print header
require_once(HESK_PATH . 'inc/header.inc.php');

// Print main manage users page
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

// Demo mode? Hide values of sensitive settings
if ( defined('HESK_DEMO') )
{
    require_once(HESK_PATH . 'inc/admin_settings_demo.inc.php');
}

/* This will handle error, success and notice messages */
hesk_handle_messages();
?>
<div class="main__content settings">

    <?php require_once(HESK_PATH . 'inc/admin_settings_status.inc.php'); ?>

    <script language="javascript" type="text/javascript"><!--
        function hesk_checkFields() {
            var d = document.form1;

            // DISABLE SUBMIT BUTTON
            d.submitbutton.disabled=true;

            return true;
        }

        function hesk_toggleLayer(nr,setto) {
            if (document.all)
                document.all[nr].style.display = setto;
            else if (document.getElementById)
                document.getElementById(nr).style.display = setto;
        }
        //-->
    </script>
    <form method="post" action="admin_settings_save.php" name="form1" onsubmit="return hesk_checkFields()">
        <section class="settings__form">
            <h3>
                <?php echo $hesklang['fitl']; ?>
                <a onclick="hesk_window('<?php echo $help_folder; ?>ticket_list.html#1','400','500')">
                    <div class="tooltype right">
                        <svg class="icon icon-info">
                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                        </svg>
                    </div>
                </a>
            </h3>
            <div class="checkbox-group list">
                <?php foreach ($hesk_settings['possible_ticket_list'] as $key => $title): ?>
                    <div class="checkbox-custom">
                        <input type="checkbox" name="s_tl_<?php echo $key; ?>" id="s_tl_<?php echo $key; ?>1" value="1" <?php echo in_array($key, $hesk_settings['ticket_list']) ? 'checked' : ''; ?>>
                        <label for="s_tl_<?php echo $key; ?>1"><?php echo $title; ?></label>
                    </div>
                <?php endforeach; ?>
            </div>
        </section>
        <section class="settings__form">
            <h3>
                <?php echo $hesklang['fictl']; ?>
                <a onclick="hesk_window('<?php echo $help_folder; ?>ticket_list.html#1','400','500')">
                    <div class="tooltype right">
                        <svg class="icon icon-info">
                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                        </svg>
                    </div>
                </a>
            </h3>
            <div class="checkbox-group list">
                <?php foreach ($hesk_settings['possible_customer_ticket_list'] as $key => $title): ?>
                    <div class="checkbox-custom">
                        <input type="checkbox" name="c_tl_<?php echo $key; ?>" id="c_tl_<?php echo $key; ?>1" value="1" <?php echo in_array($key, $hesk_settings['customer_ticket_list']) ? 'checked' : ''; ?>>
                        <label for="c_tl_<?php echo $key; ?>1"><?php echo $title; ?></label>
                    </div>
                <?php endforeach; ?>
            </div>
        </section>
        <section class="settings__form">
            <h3><?php echo $hesklang['other']; ?></h3>
            <div class="radio-group">
                <h5>
                    <span><?php echo $hesklang['sdf']; ?></span>
                    <a onclick="hesk_window('<?php echo $help_folder; ?>ticket_list.html#2','400','500')">
                        <div class="tooltype right">
                            <svg class="icon icon-info">
                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                            </svg>
                        </div>
                    </a>
                </h5>
                <div class="radio-list">
                    <div class="radio-custom">
                        <input type="radio" id="s_submittedformat2" name="s_submittedformat" value="2" <?php echo $hesk_settings['submittedformat'] == 2 ? 'checked' : ''; ?>>
                        <label for="s_submittedformat2"><?php echo $hesklang['lcf2']; ?></label>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" id="s_submittedformat1" name="s_submittedformat" value="1" <?php echo $hesk_settings['submittedformat'] == 1 ? 'checked' : ''; ?>>
                        <label for="s_submittedformat1"><?php echo $hesklang['lcf1']; ?> (<?php echo hesk_date(false, false, true, true, $hesk_settings['format_timestamp']); ?>)</label>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" id="s_submittedformat3" name="s_submittedformat" value="3" <?php echo $hesk_settings['submittedformat'] == 3 ? 'checked' : ''; ?>>
                        <label for="s_submittedformat3"><?php echo $hesklang['lcf3']; ?> (<?php echo hesk_date(false, false, true, true, $hesk_settings['format_date']); ?>)</label>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" id="s_submittedformat0" name="s_submittedformat" value="0" <?php echo $hesk_settings['submittedformat'] == 0 ? 'checked' : ''; ?>>
                        <label for="s_submittedformat0"><?php echo $hesklang['lcf0']; ?></label>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" id="s_submittedformat4" name="s_submittedformat" value="4" <?php echo $hesk_settings['submittedformat'] == 4 ? 'checked' : ''; ?>>
                        <label for="s_submittedformat4"><?php echo $hesklang['custom']; ?>:</label>
                        <input type="text" class="form-control" style="max-width: 200px; margin-left: 5px;" id="s_format_submitted" name="s_format_submitted" maxlength="255"
                               value="<?php echo $hesk_settings['format_submitted']; ?>" aria-label="<?php echo $hesklang['custom']; ?>">
                    </div>
                </div>
            </div>
            <div class="radio-group">
                <h5>
                    <span><?php echo $hesklang['lcf']; ?></span>
                    <a onclick="hesk_window('<?php echo $help_folder; ?>ticket_list.html#2','400','500')">
                        <div class="tooltype right">
                            <svg class="icon icon-info">
                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                            </svg>
                        </div>
                    </a>
                </h5>
                <div class="radio-list">
                    <div class="radio-custom">
                        <input type="radio" id="s_updatedformat2" name="s_updatedformat" value="2" <?php echo $hesk_settings['updatedformat'] == 2 ? 'checked' : ''; ?>>
                        <label for="s_updatedformat2"><?php echo $hesklang['lcf2']; ?></label>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" id="s_updatedformat1" name="s_updatedformat" value="1" <?php echo $hesk_settings['updatedformat'] == 1 ? 'checked' : ''; ?>>
                        <label for="s_updatedformat1"><?php echo $hesklang['lcf1']; ?> (<?php echo hesk_date(false, false, true, true, $hesk_settings['format_timestamp']); ?>)</label>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" id="s_updatedformat3" name="s_updatedformat" value="3" <?php echo $hesk_settings['updatedformat'] == 3 ? 'checked' : ''; ?>>
                        <label for="s_updatedformat3"><?php echo $hesklang['lcf3']; ?> (<?php echo hesk_date(false, false, true, true, $hesk_settings['format_date']); ?>)</label>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" id="s_updatedformat0" name="s_updatedformat" value="0" <?php echo $hesk_settings['updatedformat'] == 0 ? 'checked' : ''; ?>>
                        <label for="s_updatedformat0"><?php echo $hesklang['lcf0']; ?></label>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" id="s_updatedformat4" name="s_updatedformat" value="4" <?php echo $hesk_settings['updatedformat'] == 4 ? 'checked' : ''; ?>>
                        <label for="s_updatedformat4"><?php echo $hesklang['custom']; ?>:</label>
                        <input type="text" class="form-control" style="max-width: 200px; margin-left: 5px;" id="s_format_updated" name="s_format_updated" maxlength="255"
                               value="<?php echo $hesk_settings['format_updated']; ?>" aria-label="<?php echo $hesklang['custom']; ?>">
                    </div>
                </div>
            </div>
            <div class="radio-group">
                <h5>
                    <span><?php echo $hesklang['email_column_display']; ?></span>
                </h5>
                <div class="radio-list">
                    <div class="radio-custom">
                        <input type="radio" id="s_email_column0" name="s_email_column" value="0" <?php echo $hesk_settings['email_column'] == 0 ? 'checked' : ''; ?>>
                        <label for="s_email_column0"><?php echo $hesklang['email_show_view']; ?></label>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" id="s_email_column1" name="s_email_column" value="1" <?php echo $hesk_settings['email_column'] == 1 ? 'checked' : ''; ?>>
                        <label for="s_email_column1"><?php echo $hesklang['email_show_full']; ?></label>
                    </div>
                </div>
            </div>
        </section>
        <div class="settings__form form" style="padding-top: 30px">
            <div class="settings__form_submit">
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                <input type="hidden" name="section" value="TICKET_LIST">
                <button id="submitbutton" style="display: inline-flex" type="submit" class="btn btn-full" ripple="ripple"
                    <?php echo $enable_save_settings ? '' : 'disabled'; ?>>
                    <?php echo $hesklang['save_changes']; ?>
                </button>

                <?php if (!$enable_save_settings): ?>
                    <p>&nbsp;</p>
                    <div role="alert" class="notification red">
                        <?php echo $hesklang['e_save_settings']; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </form>
</div>
<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();
admin_submit_ticket.php
wget 'https://lists2.roe3.org/hesk/admin/admin_submit_ticket.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

// Get all the required files and functions
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();
require(HESK_PATH . 'inc/email_functions.inc.php');
require(HESK_PATH . 'inc/posting_functions.inc.php');

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// We only allow POST requests from the HESK form to this file
if ( $_SERVER['REQUEST_METHOD'] != 'POST' )
{
	header('Location: admin_main.php');
	exit();
}

// Check for POST requests larger than what the server can handle
if ( empty($_POST) && ! empty($_SERVER['CONTENT_LENGTH']) )
{
	hesk_error($hesklang['maxpost']);
}

// A security check
hesk_token_check('POST');

// Changing category? Remember data and redirect to category select page
if (hesk_POST('change_category') == 1)
{
    $_SESSION['as_customer_id'] = hesk_POST('customer_id');
    $_SESSION['as_follower_ids'] = hesk_POST_array('follower_id');
    $_SESSION['as_priority'] = hesk_POST('priority');
    $_SESSION['as_status']   = hesk_POST('status');
    $_SESSION['as_subject']  = hesk_POST('subject');
    $_SESSION['as_message']  = hesk_POST('message');
    $_SESSION['as_due_date'] = hesk_POST('due_date');
    $_SESSION['as_owner']    = hesk_POST('owner');
    $_SESSION['as_notify']   = hesk_POST('notify');
    $_SESSION['as_show']     = hesk_POST('show');
    $_SESSION['as_language'] = hesk_POST('as_language');

    foreach ($hesk_settings['custom_fields'] as $k=>$v)
    {
        if ($v['use'] && ! in_array($v['type'], array('date', 'email')))
        {
            $_SESSION["as_$k"] = ($v['type'] == 'checkbox') ? hesk_POST_array($k) : hesk_POST($k);
        }
    }

    header('Location: new_ticket.php');
    exit();
}

$hesk_error_buffer = array();


$tmpvar['customer_id'] = hesk_POST('customer_id') or $hesk_error_buffer['customer-id']=$hesklang['customer_required'];

// Ensure that the customer (1) exists and (2) isn't pending approval
$customer_verification_rs = hesk_dbQuery("SELECT 1 FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` 
    WHERE `id` = ".intval($tmpvar['customer_id'])."
        AND `verified` <> 2");
if (hesk_dbNumRows($customer_verification_rs) < 1) {
    $hesk_error_buffer['customer-id'] = $hesklang['customer_required'];
}

$tmpvar['follower_ids'] = hesk_POST_array('follower_id');

// Remove followers that are also the requester, and remove duplicate followers
$actual_followers = [];
foreach ($tmpvar['follower_ids'] as $follower_id) {
    $follower_id_int = intval($follower_id);
    if ($follower_id_int === intval($tmpvar['customer_id']) || in_array($follower_id_int, $actual_followers)) {
        continue;
    }

    $follower_record = hesk_get_customer_account_by_id($follower_id_int);
    if ($follower_record['email'] && !hesk_isBannedEmail($follower_record['email'])) {
        $actual_followers[] = $follower_id_int;
    }
}
$tmpvar['follower_ids'] = $actual_followers;

$tmpvar['category'] = intval( hesk_POST('category') ) or $hesk_error_buffer['category']=$hesklang['sel_app_cat'];
$tmpvar['priority'] = hesk_POST('priority');
$tmpvar['priority'] = strlen($tmpvar['priority']) && hesk_is_valid_priority_id($tmpvar['priority']) ? intval($tmpvar['priority']) : -1;

$tmpvar['status'] = intval(hesk_POST('status', 0));
if ( ! isset($hesk_settings['statuses'][$tmpvar['status']])) {
    $tmpvar['status'] = 0;
}

$tmpvar['subject'] = hesk_input( hesk_POST('subject') );
if ($hesk_settings['require_subject'] == 1 && $tmpvar['subject'] == '')
{
    $hesk_error_buffer['subject'] = $hesklang['enter_ticket_subject'];
}

$tmpvar['message']  = hesk_input( hesk_POST('message') );
if ($hesk_settings['require_message'] == 1 && $tmpvar['message'] == '')
{
    $hesk_error_buffer['message'] = $hesklang['enter_message'];
}

if ($hesk_settings['staff_ticket_formatting'] == 2 && ! class_exists('DOMDocument')) {
    $hesk_error_buffer['message'] = $hesklang['require_xml'];
}

// Is category a valid choice?
if ($tmpvar['category'])
{
    if ( ! hesk_checkPermission('can_submit_any_cat', 0) && ! hesk_okCategory($tmpvar['category'], 0) )
    {
        hesk_process_messages($hesklang['noauth_submit'],'new_ticket.php');
    }

	hesk_verifyCategory(1);
}

// Custom fields
foreach ($hesk_settings['custom_fields'] as $k=>$v)
{
	if ($v['use'] && hesk_is_custom_field_in_category($k, $tmpvar['category']))
	{
        if ($v['type'] == 'checkbox')
        {
			$tmpvar[$k]='';

        	if (isset($_POST[$k]) && is_array($_POST[$k]))
            {
				foreach ($_POST[$k] as $myCB)
				{
					$tmpvar[$k] .= ( is_array($myCB) ? '' : hesk_input($myCB) ) . '<br />';;
				}
				$tmpvar[$k]=substr($tmpvar[$k],0,-6);
            }
            else
            {
            	if ($v['req'] == 2)
                {
					$hesk_error_buffer[$k]=$hesklang['fill_all'].': '.$v['name'];
                }
            	$_POST[$k] = '';
            }
        }
        elseif ($v['type'] == 'date')
        {
        	$tmpvar[$k] = hesk_POST($k);
            $_SESSION["as_$k"] = '';

            if ($date = hesk_datepicker_get_date($tmpvar[$k], false, 'UTC'))
            {
                $_SESSION["as_$k"] = $tmpvar[$k];

                $date->setTime(0, 0);
                $dmin = strlen($v['value']['dmin']) ? new DateTime($v['value']['dmin'] . ' t00:00:00 UTC') : false;
                $dmax = strlen($v['value']['dmax']) ? new DateTime($v['value']['dmax'] . ' t00:00:00 UTC') : false;

                if ($dmin && $dmin->format('Y-m-d') > $date->format('Y-m-d'))
	            {
					$hesk_error_buffer[$k] = sprintf($hesklang['d_emin'], $v['name'], hesk_translate_date_string($dmin->format($hesk_settings['format_datepicker_php'])));
	            }
	            elseif ($dmax && $dmax->format('Y-m-d') < $date->format('Y-m-d'))
	            {
					$hesk_error_buffer[$k] = sprintf($hesklang['d_emax'], $v['name'], hesk_translate_date_string($dmax->format($hesk_settings['format_datepicker_php'])));
	            }
                else
                {
                	$tmpvar[$k] = $date->getTimestamp();
                }
			}
            else
            {
            	$tmpvar[$k] = '';

				if ($v['req'] == 2)
				{
					$hesk_error_buffer[$k]=$hesklang['fill_all'].': '.$v['name'];
				}
            }
        }
        elseif ($v['type'] == 'email')
        {
			$tmp = $hesk_settings['multi_eml'];
            $hesk_settings['multi_eml'] = $v['value']['multiple'];
			$tmpvar[$k] = hesk_validateEmail( hesk_POST($k), 'ERR', 0);
            $hesk_settings['multi_eml'] = $tmp;

            if ($tmpvar[$k] != '')
            {
				$_SESSION["as_$k"] = hesk_input($tmpvar[$k]);
            }
            else
            {
            	$_SESSION["as_$k"] = '';

                if ($v['req'] == 2)
                {
            		$hesk_error_buffer[$k] = $v['value']['multiple'] ? sprintf($hesklang['cf_noem'], $v['name']) : sprintf($hesklang['cf_noe'], $v['name']);
                }
            }
        }
		elseif ($v['req'] == 2)
        {
        	$tmpvar[$k]=hesk_makeURL(nl2br(hesk_input( hesk_POST($k) )));
            if ($tmpvar[$k] == '')
            {
            	$hesk_error_buffer[$k]=$hesklang['fill_all'].': '.$v['name'];
            }
        }
        else
        {
    		$tmpvar[$k]=hesk_makeURL(nl2br(hesk_input(hesk_POST($k))));
        }
	}
    else
    {
    	$tmpvar[$k] = '';
    }
}


// If use doesn't have permission to set due dates, try using the category default due date
if (hesk_checkPermission('can_due_date',0)) {
    $tmpvar['due_date'] = hesk_input(hesk_POST('due_date'));
    if ($tmpvar['due_date'] != '') {
        $date = hesk_datepicker_get_date($tmpvar['due_date']);
        if ($date === false) {
            $hesk_error_buffer['due_date'] = $hesklang['invalid_due_date'];
        }
    }
} else {
    $tmpvar['due_date'] = '';
    if (($default_due_date_info = hesk_getCategoryDueDateInfo($tmpvar['category'])) !== null) {
        $due_date = new DateTime('today midnight');
        $due_date->add(DateInterval::createFromDateString("+{$default_due_date_info['amount']} {$default_due_date_info['unit']}s"));
        $tmpvar['due_date'] = hesk_datepicker_format_date($due_date->getTimestamp());

        // Don't set a due date if any unexpected errors
        if ($tmpvar['due_date'] === false) {
            $tmpvar['due_date'] = '';
        }
    }
}

// Generate tracking ID
$tmpvar['trackid'] = hesk_createID();

// Log who submitted ticket
$tmpvar['history'] = sprintf($hesklang['thist7'], hesk_date(), addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
$tmpvar['openedby'] = $_SESSION['id'];

// Was the ticket submitted as "Resolved"?
if ($tmpvar['status'] == 3) {
    // Check permission
    if ( ! hesk_checkPermission('can_resolve', 0))  {
        $hesk_error_buffer['status'] = $hesklang['noauth_resolve'];
    }

    $tmpvar['history'] .= sprintf($hesklang['thist3'], hesk_date(), addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');

    if ($hesk_settings['custopen'] != 1)  {
        $tmpvar['locked'] = 1;
    }

    // Log who marked the ticket resolved
    $tmpvar['closedat'] = 1;
    $tmpvar['closedby'] = intval($_SESSION['id']);
} elseif ($tmpvar['status'] != 0) {
    // Status set to something different than "New" or "Resolved", let's log it
    $status_name = hesk_get_status_name($tmpvar['status']);
    $tmpvar['history'] .= sprintf($hesklang['thist9'], hesk_date(), addslashes($status_name), addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
}

// Owner
$tmpvar['owner'] = 0;
if (hesk_checkPermission('can_assign_others',0))
{
	$tmpvar['owner'] = intval( hesk_POST('owner') );

	// If ID is -1 the ticket will be unassigned
	if ($tmpvar['owner'] == -1)
	{
		$tmpvar['owner'] = 0;
	}
    // Automatically assign owner?
    elseif ($tmpvar['owner'] == -2 && $hesk_settings['autoassign'] == 1)
    {
		$autoassign_owner = hesk_autoAssignTicket($tmpvar['category']);
		if ($autoassign_owner)
		{
			$tmpvar['owner']    = intval($autoassign_owner['id']);
			$tmpvar['history'] .= sprintf($hesklang['thist10'],hesk_date(),addslashes($autoassign_owner['name']).' ('.$autoassign_owner['user'].')');
		}
        else
        {
        	$tmpvar['owner'] = 0;
        }
    }
    // Check for invalid owner values
	elseif ($tmpvar['owner'] < 1)
	{
	    $tmpvar['owner'] = 0;
	}
    else
    {
	    // Has the new owner access to the selected category?
		$res = hesk_dbQuery("SELECT `name`,`user`,`isadmin`,`categories`,
            CASE WHEN EXISTS (
                SELECT 1 FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_categories` AS `inner_category`
                INNER JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_members` AS `inner_member`
                    ON `inner_category`.`group_id` = `inner_member`.`group_id`
                WHERE `inner_member`.`user_id` = {$tmpvar['owner']}
                    AND `inner_category`.`category_id` = ".intval($tmpvar['category'])."
            ) THEN 1 ELSE 0 END AS `category_access_via_permission_group`
            FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` 
            WHERE `id`='{$tmpvar['owner']}' 
                AND `active` = 1 
            LIMIT 1");
	    if (hesk_dbNumRows($res) == 1)
	    {
	    	$row = hesk_dbFetchAssoc($res);
	        if (!$row['isadmin'] && !$row['category_access_via_permission_group'])
	        {
				$row['categories']=explode(',',$row['categories']);
				if (!in_array($tmpvar['category'],$row['categories']))
				{
                	$_SESSION['isnotice'][] = 'category';
					$hesk_error_buffer['owner']=$hesklang['onasc'];
				}
	        }
            $tmpvar['history'] .= sprintf($hesklang['thist2'],hesk_date(),addslashes($row['name']).' ('.$row['user'].')',addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
	    }
	    else
	    {
        	$_SESSION['isnotice'][] = 'category';
	    	$hesk_error_buffer['owner']=$hesklang['onasc'];
	    }
    }
}
elseif (hesk_checkPermission('can_assign_self',0) && hesk_okCategory($tmpvar['category'],0) && !empty($_POST['assing_to_self']))
{
	$tmpvar['owner'] = intval($_SESSION['id']);
}

// Notify customer of the ticket?
$notify = ! empty($_POST['notify']) ? 1 : 0;

// Show ticket after submission?
$show = ! empty($_POST['show']) ? 1 : 0;

// Is the ticket language different than current language?
if ($hesk_settings['can_sel_lang'])
{
    $new_lang = hesk_POST('as_language');
    if (isset($hesk_settings['languages'][$new_lang]))
    {
        $hesklang['LANGUAGE'] = $new_lang;
    }
}

// Attachments
$use_legacy_attachments = hesk_POST('use-legacy-attachments', 0);
if ($hesk_settings['attachments']['use'])
{
    require_once(HESK_PATH . 'inc/attachments.inc.php');

    $attachments = array();
    $trackingID  = $tmpvar['trackid'];

    if ($use_legacy_attachments) {
        for ($i = 1; $i <= $hesk_settings['attachments']['max_number']; $i++) {
            $att = hesk_uploadFile($i);
            if ($att !== false && !empty($att)) {
                $attachments[$i] = $att;
            }
        }
    } else {
        // The user used the new drag-and-drop system.
        $temp_attachment_names = hesk_POST_array('attachments');
        foreach ($temp_attachment_names as $temp_attachment_name) {
            $temp_attachment = hesk_getTemporaryAttachment($temp_attachment_name);

            if ($temp_attachment !== null) {
                $attachments[] = $temp_attachment;
            }
        }
    }
}
$tmpvar['attachments'] = '';

// If we have any errors lets store info in session to avoid re-typing everything
if (count($hesk_error_buffer)!=0)
{
	$_SESSION['iserror'] = array_keys($hesk_error_buffer);

    $_SESSION['as_customer_id'] = $tmpvar['customer_id'];
    $_SESSION['as_follower_ids'] = $tmpvar['follower_ids'];
    $_SESSION['as_priority'] = $tmpvar['priority'];
    $_SESSION['as_status']   = $tmpvar['status'];
    $_SESSION['as_subject']  = hesk_POST('subject');
    $_SESSION['as_message']  = hesk_POST('message');
    $_SESSION['as_due_date'] = hesk_POST('due_date');
    $_SESSION['as_owner']    = $tmpvar['owner'];
    $_SESSION['as_notify']   = $notify;
    $_SESSION['as_show']     = $show;
    $_SESSION['as_language'] = hesk_POST('as_language');

	foreach ($hesk_settings['custom_fields'] as $k=>$v)
	{
		if ($v['use'] && ! in_array($v['type'], array('date', 'email')))
		{
			$_SESSION["as_$k"] = ($v['type'] == 'checkbox') ? hesk_POST_array($k) : hesk_POST($k);
		}
	}

    $tmp = '';
    foreach ($hesk_error_buffer as $error)
    {
        $tmp .= "<li>$error</li>\n";
    }
    $hesk_error_buffer = $tmp;

	// Remove any successfully uploaded attachments
	if ($hesk_settings['attachments']['use'])
	{
        if ($use_legacy_attachments) {
            hesk_removeAttachments($attachments);
        } else {
            $_SESSION['as_attachments'] = $attachments;
        }
	}

    $hesk_error_buffer = $hesklang['pcer'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
    hesk_process_messages($hesk_error_buffer,'new_ticket.php?category='.$tmpvar['category']);
}

if ($hesk_settings['attachments']['use'] && !empty($attachments))
{
    // Delete temp attachment records and set the new filename
    if (!$use_legacy_attachments) {
        $attachments = hesk_migrateTempAttachments($attachments, $tmpvar['trackid']);
    }

    foreach ($attachments as $myatt)
    {
        hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."attachments` (`ticket_id`,`saved_name`,`real_name`,`size`) VALUES ('".hesk_dbEscape($tmpvar['trackid'])."','".hesk_dbEscape($myatt['saved_name'])."','".hesk_dbEscape($myatt['real_name'])."','".intval($myatt['size'])."')");
        $tmpvar['attachments'] .= hesk_dbInsertID() . '#' . $myatt['real_name'] .',';
    }
}

$tmpvar['message_html'] = $tmpvar['message'];

if ($hesk_settings['staff_ticket_formatting'] == 2) {
    // Decode the message we encoded earlier
    $tmpvar['message_html'] = hesk_html_entity_decode($tmpvar['message_html']);

    // Clean the HTML code and set the plaintext version
    require(HESK_PATH . 'inc/htmlpurifier/HeskHTMLPurifier.php');
    require(HESK_PATH . 'inc/html2text/html2text.php');
    $purifier = new HeskHTMLPurifier($hesk_settings['cache_dir']);
    $tmpvar['message_html'] = $purifier->heskPurify($tmpvar['message_html']);

    $tmpvar['message'] = convert_html_to_text($tmpvar['message_html']);
    $tmpvar['message'] = fix_newlines($tmpvar['message']);

    // Prepare plain message for storage as HTML
    $tmpvar['message'] = hesk_htmlspecialchars($tmpvar['message']);
    $tmpvar['message'] = nl2br($tmpvar['message']);
} else {
    // `message` already contains a HTML friendly version. May as well just re-use it
    $tmpvar['message'] = hesk_makeURL($tmpvar['message']);
    $tmpvar['message'] = nl2br($tmpvar['message']);
    $tmpvar['message_html'] = $tmpvar['message'];
}

// Track who assigned the ticket
if ($tmpvar['owner'] > 0)
{
    $tmpvar['assignedby'] = ! empty($autoassign_owner) ? -1 : $_SESSION['id'];
}

// Demo mode
if ( defined('HESK_DEMO') ) {
    hesk_process_messages(sprintf($hesklang['antdemo'], 'https://www.hesk.com/demo/index.php?a=add'), 'new_ticket.php?category='.$tmpvar['category']);
}

// Let's not add staff IP address as the ticket IP address
$hesk_settings['client_IP'] = '';

// Insert ticket to database
$ticket = hesk_newTicket($tmpvar);
$customers = hesk_get_customers_for_ticket($ticket['id']);
$email_available = count(array_filter($customers, function($customer) { return $customer['email'] !== ''; })) > 0;

// Notify the customer about the ticket?
if ($notify && $email_available)
{
    if ($tmpvar['status'] == 3) {
        hesk_notifyCustomer('ticket_closed');
    } else {
        hesk_notifyCustomer('new_ticket_by_staff');
    }
}

// If ticket is assigned to someone notify them?
if ($ticket['owner'] && $ticket['owner'] != intval($_SESSION['id']))
{
	// If we don't have info from auto-assign get it from database
    if ( ! isset($autoassign_owner['email']) )
    {
		hesk_notifyAssignedStaff(false, 'ticket_assigned_to_you', 'notify_assigned', false);
	}
    else
    {
		hesk_notifyAssignedStaff($autoassign_owner, 'ticket_assigned_to_you', 'notify_assigned', false);
    }
}

// Ticket unassigned, notify everyone that selected to be notified about unassigned tickets
elseif ( ! $ticket['owner'])
{
	hesk_notifyStaff('new_ticket_staff', " `id` != ".intval($_SESSION['id'])." AND `notify_new_unassigned` = '1' ");
}

// Unset temporary variables
unset($tmpvar);
hesk_cleanSessionVars('tmpvar');
hesk_cleanSessionVars('as_customer_id');
hesk_cleanSessionVars('as_follower_ids');
hesk_cleanSessionVars('as_name');
hesk_cleanSessionVars('as_email');
hesk_cleanSessionVars('as_category');
hesk_cleanSessionVars('as_priority');
hesk_cleanSessionVars('as_status');
hesk_cleanSessionVars('as_subject');
hesk_cleanSessionVars('as_message');
hesk_cleanSessionVars('as_owner');
hesk_cleanSessionVars('as_notify');
hesk_cleanSessionVars('as_show');
hesk_cleanSessionVars('as_due_date');
hesk_cleanSessionVars('as_language');
hesk_cleanSessionVars('as_attachments');
foreach ($hesk_settings['custom_fields'] as $k=>$v)
{
    hesk_cleanSessionVars("as_$k");
}

// If ticket has been assigned to the person submitting it lets show a message saying so
if ($ticket['owner'] && $ticket['owner'] == intval($_SESSION['id']))
{
	$hesklang['new_ticket_submitted'] .= '<br />&nbsp;<br />
    <b>' . (isset($autoassign_owner) ? $hesklang['taasy'] : $hesklang['tasy']) . '</b>';
}

// Show the ticket or just a success message

// --> Cannot view tickets, go back to the new_ticket.php page
if ( ! hesk_checkPermission('can_view_tickets',0)) {
    hesk_process_messages($hesklang['new_ticket_submitted'], 'new_ticket.php', 'SUCCESS');
}

// --> Unassigned ticket with no view permission, go back to the new_ticket.php page
if ($ticket['owner'] == 0 && ! hesk_checkPermission('can_view_unassigned',0)) {
    hesk_process_messages($hesklang['new_ticket_submitted'], 'new_ticket.php', 'SUCCESS');
}

// --> Ticket assigned to someone else automatically which I cannot view
if ($ticket['owner'] && $ticket['owner'] != $_SESSION['id'] && isset($autoassign_owner) && ! hesk_checkPermission('can_view_ass_others', 0) ) {
    hesk_process_messages($hesklang['new_ticket_submitted'], 'new_ticket.php', 'SUCCESS');
}

// --> Ticket assigned to someone else by me, but I don't have permission to view tickets I assign to others
if ($ticket['owner'] && $ticket['owner'] != $_SESSION['id'] && ! isset($autoassign_owner) && ! hesk_checkPermission('can_view_ass_others', 0) && ! hesk_checkPermission('can_view_ass_by', 0) ) {
    hesk_process_messages($hesklang['new_ticket_submitted'], 'new_ticket.php', 'SUCCESS');
}

// --> Show the ticket
if ($show) {
    hesk_process_messages($hesklang['new_ticket_submitted'],'admin_ticket.php?track=' . $ticket['trackid'] . '&Refresh=' . mt_rand(10000,99999), 'SUCCESS');
}

// --> No matches, show a success message with a link to the ticket
hesk_process_messages($hesklang['new_ticket_submitted'].'. <a href="admin_ticket.php?track=' . $ticket['trackid'] . '&Refresh=' . mt_rand(10000,99999) . '">' . $hesklang['view_ticket'] . '</a>', 'new_ticket.php', 'SUCCESS');

admin_suggest_articles.php
wget 'https://lists2.roe3.org/hesk/admin/admin_suggest_articles.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Is Knowledgebase enabled?
if ( ! $hesk_settings['kb_enable'])
{
    die('');
}

/* Print XML header */
header('Content-Type: text/html; charset='.$hesklang['ENCODING']);

/* Get the search query composed of the subject and message */
$query = hesk_REQUEST('q') or die('');

/* Get relevant articles from the database, include private ones */
$res = hesk_dbQuery("SELECT `id`, `subject`, `content` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `type` IN ('0','1') AND MATCH(`subject`,`content`,`keywords`) AGAINST ('".hesk_dbEscape($query)."') LIMIT ".intval($hesk_settings['kb_search_limit']));
$num = hesk_dbNumRows($res);

/* Solve some spacing issues */
if ( hesk_isREQUEST('p') )
{
	echo '&nbsp;<br />';
}

/* Return found articles */
?>
<div class="main__content notice-flash" style="padding: 0">
    <div role="log" class="notification-bar white notice-flash" style="display: block; border-left: solid 1px #d4d6e3; border-right: solid 1px #d4d6e3">
        <div class="notification--text" style="display: block; margin: 10px">
            <div>
                <b><?php echo $hesklang['sc']; ?></b>
            </div>
            <span>
                <?php
                if (!$num)
                {
                    echo '<i>'.$hesklang['nsfo'].'</i>';
                }
                else
                {
                    while ($article = hesk_dbFetchAssoc($res))
                    {
                        $txt = strip_tags($article['content']);
                        if (hesk_mb_strlen($txt) > $hesk_settings['kb_substrart'])
                        {
                            $txt = hesk_mb_substr($txt, 0, $hesk_settings['kb_substrart']).'...';
                        }

                        echo '
			<a class="link" href="knowledgebase_private.php?article='.$article['id'].'&amp;suggest=1" target="_blank">'.$article['subject'].'</a>
		    <br />'.$txt.'<br /><br />';
                    }
                }
                ?>
            </span>
        </div>
    </div>
</div>
<?php
exit();
?>
admin_ticket.php
wget 'https://lists2.roe3.org/hesk/admin/admin_ticket.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');
define('CALENDAR',1);

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require_once(HESK_PATH . 'inc/customer_accounts.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
hesk_checkPermission('can_view_tickets');
$can_del_notes		 = hesk_checkPermission('can_del_notes',0);
$can_reply			 = hesk_checkPermission('can_reply_tickets',0);
$can_delete			 = hesk_checkPermission('can_del_tickets',0);
$can_edit			 = hesk_checkPermission('can_edit_tickets',0);
$can_archive		 = hesk_checkPermission('can_add_archive',0);
$can_assign_self	 = hesk_checkPermission('can_assign_self',0);
$can_assign_others   = hesk_checkPermission('can_assign_others',0);
$can_view_unassigned = hesk_checkPermission('can_view_unassigned',0);
$can_change_cat		 = hesk_checkPermission('can_change_cat',0);
$can_change_own_cat  = hesk_checkPermission('can_change_own_cat',0);
$can_ban_emails		 = hesk_checkPermission('can_ban_emails', 0);
$can_unban_emails	 = hesk_checkPermission('can_unban_emails', 0);
$can_ban_ips		 = hesk_checkPermission('can_ban_ips', 0);
$can_unban_ips		 = hesk_checkPermission('can_unban_ips', 0);
$can_resolve		 = hesk_checkPermission('can_resolve', 0);
$can_view_ass_by     = hesk_checkPermission('can_view_ass_by', 0);
$can_privacy		 = hesk_checkPermission('can_privacy',0);
$can_export          = hesk_checkPermission('can_export',0);
$can_due_date        = hesk_checkPermission('can_due_date',0);
$can_man_customers   = hesk_checkPermission('can_man_customers',0);
$can_link_tickets    = hesk_checkPermission('can_link_tickets',0);
$can_mute_emails     = hesk_checkPermission('can_mute_emails',0);
$can_unmute_emails   = hesk_checkPermission('can_unmute_emails',0);

// Get ticket ID
$trackingID = hesk_cleanID() or print_form();

// Load custom fields
require_once(HESK_PATH . 'inc/custom_fields.inc.php');

// Load priorities
require_once(HESK_PATH . 'inc/priorities.inc.php');

// Load statuses
require_once(HESK_PATH . 'inc/statuses.inc.php');

$_SERVER['PHP_SELF'] = 'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999);

// We will need some extra functions
if ($hesk_settings['time_worked']) {
    define('TIMER',1);
}
define('BACK2TOP',1);
define('ATTACHMENTS',1);
if ($hesk_settings['time_display']) {
    define('TIMEAGO',1);
}
if ($hesk_settings['staff_ticket_formatting'] == 2) {
    define('WYSIWYG',1);
    define('STYLE_CODE',1);
}

/* Get ticket info */
$res = hesk_dbQuery("SELECT `t1`.* , `t2`.name AS `repliername`
    FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` AS `t1` 
    LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."users` AS `t2` 
        ON `t1`.`replierid` = `t2`.`id`
    WHERE `trackid`='".hesk_dbEscape($trackingID)."' LIMIT 1");


/* Ticket found? */
if (hesk_dbNumRows($res) != 1)
{
	/* Ticket not found, perhaps it was merged with another ticket? */
	$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `merged` LIKE '%#".hesk_dbEscape($trackingID)."#%' LIMIT 1");

	if (hesk_dbNumRows($res) == 1)
	{
    	/* OK, found in a merged ticket. Get info */
     	$ticket = hesk_dbFetchAssoc($res);
        hesk_process_messages( sprintf($hesklang['tme'], $trackingID, $ticket['trackid']) ,'NOREDIRECT','NOTICE');
        $trackingID = $ticket['trackid'];
	}
    else
    {
    	/* Nothing found, error out */
	    hesk_process_messages($hesklang['ticket_not_found'],'NOREDIRECT');
	    print_form();
    }
}
else
{
	/* We have a match, get ticket info */
	$ticket = hesk_dbFetchAssoc($res);
}
$ticket['is_bookmark'] = hesk_isTicketBookmarked($ticket['id'], $_SESSION['id']);
$ticket['collaborators'] = hesk_getTicketsCollaboratorIDs($ticket['id']);
$ticket['am_I_collaborator'] = in_array($_SESSION['id'], $ticket['collaborators']);
$customers = hesk_get_customers_for_ticket($ticket['id']);
$found_requester = false;
$requester = [];
$followers = [];
foreach ($customers as $customer) {
    if ($customer['customer_type'] === 'REQUESTER') {
        $found_requester = true;
        $requester = $customer;
    } elseif ($customer['customer_type'] === 'FOLLOWER') {
        $followers[] = $customer;
    }
}
if (!$found_requester) {
    $requester = [
        'name' => $hesklang['anon_name'],
        'email' => $hesklang['anon_email']
    ];
}
// TODO REMOVE
$customer_emails = '';
foreach ($customers as $customer) {
    $customer_emails = $customer_emails === '' ? $customer['email'] : $customer_emails.';'.$customer['email'];
}

// Has this ticket been anonymized?
$ticket['anonymized'] = empty($customers) &&
    $ticket['subject'] == $hesklang['anon_subject'] &&
    $ticket['message'] == $hesklang['anon_message'] &&
    $ticket['message_html'] == $hesklang['anon_message'] &&
    $ticket['ip'] == $hesklang['anon_IP'];

/* Permission to view this ticket? */
if ($ticket['owner'] && $ticket['owner'] != $_SESSION['id'] && ! hesk_checkPermission('can_view_ass_others',0) && ! $ticket['am_I_collaborator'])
{
    // Maybe this user is allowed to view tickets he/she assigned or is collaborator?
    if ( ! $can_view_ass_by || $ticket['assignedby'] != $_SESSION['id'])
    {
        hesk_error($hesklang['ycvtao']);
    }
}

if (!$ticket['owner'] && ! $can_view_unassigned && ! $ticket['am_I_collaborator'])
{
	hesk_error($hesklang['ycovtay']);
}

/* Set last replier name */
if ($ticket['lastreplier']) {
    if (empty($ticket['repliername'])) {
        $ticket['repliername'] = $hesklang['staff'];
    }
} else {
    $last_replier = hesk_getReplierNameArray($ticket);
    $ticket['repliername'] = $last_replier['name'];
}

/* Get category name and ID */
$result = hesk_dbQuery("SELECT `id`, `name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE `id`='".intval($ticket['category'])."' LIMIT 1");

/* If this category has been deleted use the default category with ID 1 */
if (hesk_dbNumRows($result) != 1)
{
	$result = hesk_dbQuery("SELECT `id`, `name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE `id`='1' LIMIT 1");
}

$category = hesk_dbFetchAssoc($result);

/* Is this user allowed to view tickets inside this category? */
hesk_okCategory($category['id']);

/* Delete post action */
if (isset($_GET['delete_post']) && $can_delete && hesk_token_check())
{
	$n = intval( hesk_GET('delete_post') );
    if ($n)
    {
		/* Get last reply ID, we'll need it later */
		$res = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` WHERE `replyto`='".intval($ticket['id'])."' ORDER BY `id` DESC LIMIT 1");
        $last_reply_id = hesk_dbResult($res,0,0);

		// Was this post submitted by staff and does it have any attachments?
		$res = hesk_dbQuery("SELECT `dt`, `staffid`, `attachments` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` WHERE `id`='".intval($n)."' AND `replyto`='".intval($ticket['id'])."' LIMIT 1");
		$reply = hesk_dbFetchAssoc($res);

		// If the reply was by a staff member update the appropriate columns
		if ( $reply['staffid'] )
		{
			// Is this the only staff reply? Delete "firstreply" and "firstreplyby" columns
			if ($ticket['staffreplies'] <= 1)
			{
				$staffreplies_sql = ' , `firstreply`=NULL, `firstreplyby`=NULL, `staffreplies`=0 ';
			}
			// Are we deleting the first staff reply? Update "firstreply" and "firstreplyby" columns
			elseif ($reply['dt'] == $ticket['firstreply'] && $reply['staffid'] == $ticket['firstreplyby'])
			{
				// Get the new first reply info
				$res = hesk_dbQuery("SELECT `dt`, `staffid` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` WHERE `replyto`='".intval($ticket['id'])."' AND `id`!='".intval($n)."' AND `staffid`!=0 ORDER BY `id` ASC LIMIT 1");

				// Did we find the new first reply?
				if ( hesk_dbNumRows($res) )
				{
					$firstreply = hesk_dbFetchAssoc($res);
					$staffreplies_sql = " , `firstreply`='".hesk_dbEscape($firstreply['dt'])."', `firstreplyby`='".hesk_dbEscape($firstreply['staffid'])."', `staffreplies`=`staffreplies`-1 ";
				}
				// The count must have been wrong, update it
				else
				{
					$staffreplies_sql = ' , `firstreply`=NULL, `firstreplyby`=NULL, `staffreplies`=0 ';
				}
			}
			// OK, this is not the first and not the only staff reply, just reduce number
			else
			{
            	$staffreplies_sql = ' , `staffreplies`=`staffreplies`-1 ';
			}
		}
		else
		{
			$staffreplies_sql = '';
		}

		/* Delete any attachments to this post */
		if ( strlen($reply['attachments']) )
		{
        	$hesk_settings['server_path'] = dirname(dirname(__FILE__));

			/* List of attachments */
			$att=explode(',',substr($reply['attachments'], 0, -1));
			foreach ($att as $myatt)
			{
				list($att_id, $att_name) = explode('#', $myatt);

				/* Delete attachment files */
				$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."attachments` WHERE `att_id`='".intval($att_id)."' LIMIT 1");
				if (hesk_dbNumRows($res) && $file = hesk_dbFetchAssoc($res))
				{
					hesk_unlink($hesk_settings['server_path'].'/'.$hesk_settings['attach_dir'].'/'.$file['saved_name']);
				}

				/* Delete attachments info from the database */
				hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."attachments` WHERE `att_id`='".intval($att_id)."'");
			}
		}

		/* Delete this reply */
		hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` WHERE `id`='".intval($n)."' AND `replyto`='".intval($ticket['id'])."'");

        /* Reply wasn't deleted */
        if (hesk_dbAffectedRows() != 1)
        {
			hesk_process_messages($hesklang['repl1'],$_SERVER['PHP_SELF']);
        }
        else
        {
			$closed_sql = '';

            // Delete ticket/email ID mappings for this reply
            hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."email_id_to_ticket` WHERE `reply_id` = ".intval($n));

			/* Reply deleted. Need to update status and last replier? */
			$res = hesk_dbQuery("SELECT `dt`, `staffid` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` WHERE `replyto`='".intval($ticket['id'])."' ORDER BY `id` DESC LIMIT 1");
			if (hesk_dbNumRows($res))
			{
				$replier_id = hesk_dbResult($res,0,1);
                $last_replier = $replier_id ? 1 : 0;

				/* Change status? */
                $status_sql = '';
				if ($last_reply_id == $n)
				{
					$status = $ticket['locked'] ? 3 : ($last_replier ? 2 : 1);
                    $status_sql = " , `status`='".intval($status)."' ";

					// Update closedat and closedby columns as required
					if ($status == 3)
					{
						$closed_sql = " , `closedat`=NOW(), `closedby`=".intval($_SESSION['id'])." ";
					}
				}

				hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `lastchange`=NOW(), `lastreplier`='{$last_replier}', `replierid`='".intval($replier_id)."', `replies`=`replies`-1 $status_sql $closed_sql $staffreplies_sql WHERE `id`='".intval($ticket['id'])."'");
			}
			else
			{
				// Update status, closedat and closedby columns as required
				if ($ticket['locked'])
				{
					$status = 3;
					$closed_sql = " , `closedat`=NOW(), `closedby`=".intval($_SESSION['id'])." ";
				}
				else
				{
                	$status = 0;
					$closed_sql = " , `closedat`=NULL, `closedby`=NULL ";
				}

				hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `lastchange`=NOW(), `lastreplier`='0', `replierid`=NULL, `status`='$status', `replies`=0 $staffreplies_sql WHERE `id`='".intval($ticket['id'])."'");
			}

			hesk_process_messages($hesklang['repl'],$_SERVER['PHP_SELF'],'SUCCESS');
        }
    }
    else
    {
    	hesk_process_messages($hesklang['repl0'],$_SERVER['PHP_SELF']);
    }
}

/* Delete notes action */
if (isset($_GET['delnote']) && hesk_token_check())
{
	$n = intval( hesk_GET('delnote') );
    if ($n)
    {
		// Get note info
		$res = hesk_dbQuery("SELECT `who`, `attachments` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."notes` WHERE `id`={$n}");

		if ( hesk_dbNumRows($res) )
		{
			$note = hesk_dbFetchAssoc($res);

			// Permission to delete note?
			if ($can_del_notes || $note['who'] == $_SESSION['id'])
			{
				// Delete note
				hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."notes` WHERE `id`='".intval($n)."'");

			    // Delete attachments
				if ( strlen($note['attachments']) )
				{
					$hesk_settings['server_path'] = dirname(dirname(__FILE__));

		            $attachments = array();

					$att=explode(',',substr($note['attachments'], 0, -1));
					foreach ($att as $myatt)
					{
						list($att_id, $att_name) = explode('#', $myatt);
						$attachments[] = intval($att_id);
					}

					if ( count($attachments) )
					{
						$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."attachments` WHERE `att_id` IN (".implode(',', $attachments).") ");
						while ($file = hesk_dbFetchAssoc($res))
						{
							hesk_unlink($hesk_settings['server_path'].'/'.$hesk_settings['attach_dir'].'/'.$file['saved_name']);
						}
						hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."attachments` WHERE `att_id` IN (".implode(',', $attachments).") ");
					}
				}
			}
		}
	}

    header('Location: admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999));
    exit();
}

/* Add a note action */
if (isset($_POST['notemsg']) && hesk_token_check('POST'))
{
	// Error buffer
	$hesk_error_buffer = array();

	// Get message
	$msg = hesk_input( hesk_POST('notemsg') );

	// Get attachments
    $use_legacy_attachments = hesk_POST('use-legacy-attachments', 0);
	if ($hesk_settings['attachments']['use'])
	{
		require(HESK_PATH . 'inc/posting_functions.inc.php');
		require(HESK_PATH . 'inc/attachments.inc.php');
		$attachments = array();

        if ($use_legacy_attachments) {
            for ($i = 1; $i <= $hesk_settings['attachments']['max_number']; $i++) {
                $att = hesk_uploadFile($i);
                if ($att !== false && !empty($att)) {
                    $attachments[$i] = $att;
                }
            }
        } else {
            // The user used the new drag-and-drop system.
            $temp_attachment_names = hesk_POST_array('attachments');
            foreach ($temp_attachment_names as $temp_attachment_name) {
                $temp_attachment = hesk_getTemporaryAttachment($temp_attachment_name);

                if ($temp_attachment !== null) {
                    $attachments[] = $temp_attachment;
                }
            }
        }
	}
	$myattachments='';

	// We need message and/or attachments to accept note
	if ( (!empty($attachments) && count($attachments)) || strlen($msg) || count($hesk_error_buffer) )
	{
		// Any errors?
		if ( count($hesk_error_buffer) != 0 )
		{
			$_SESSION['note_message'] = hesk_POST('notemsg');

			// Remove any successfully uploaded attachments
			if ($hesk_settings['attachments']['use'])
			{
                if ($use_legacy_attachments) {
                    hesk_removeAttachments($attachments);
                } else {
                    $_SESSION['note_attachments'] = $attachments;
                }
			}

			$tmp = '';
			foreach ($hesk_error_buffer as $error)
			{
				$tmp .= "<li>$error</li>\n";
			}
			$hesk_error_buffer = $tmp;

			$hesk_error_buffer = $hesklang['pcer'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
			hesk_process_messages($hesk_error_buffer,'admin_ticket.php?track='.$ticket['trackid'].'&Refresh='.rand(10000,99999));
		}

		// Process attachments
		if ($hesk_settings['attachments']['use'] && ! empty($attachments) )
		{
            if (!$use_legacy_attachments) {
                $attachments = hesk_migrateTempAttachments($attachments, $trackingID);
            }

			foreach ($attachments as $myatt)
			{
				hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."attachments` (`ticket_id`,`saved_name`,`real_name`,`size`,`type`) VALUES ('".hesk_dbEscape($trackingID)."','".hesk_dbEscape($myatt['saved_name'])."','".hesk_dbEscape($myatt['real_name'])."','".intval($myatt['size'])."', '1')");
				$myattachments .= hesk_dbInsertID() . '#' . $myatt['real_name'] .',';
			}
		}

		// Add note to database
		$msg = nl2br(hesk_makeURL($msg));
		hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."notes` (`ticket`,`who`,`dt`,`message`,`attachments`) VALUES ('".intval($ticket['id'])."','".intval($_SESSION['id'])."',NOW(),'".hesk_dbEscape($msg)."','".hesk_dbEscape($myattachments)."')");

        // Update time worked
        if ($hesk_settings['time_worked'] && ($time_worked = hesk_getTime(hesk_POST('time_worked_notes'))) && $time_worked != '00:00:00')
        {
            $parts = explode(':', $ticket['time_worked']);
            $seconds = ($parts[0] * 3600) + ($parts[1] * 60) + $parts[2];

            $parts = explode(':', $time_worked);
            $seconds += ($parts[0] * 3600) + ($parts[1] * 60) + $parts[2];

            require(HESK_PATH . 'inc/reporting_functions.inc.php');
            $ticket['time_worked'] = hesk_SecondsToHHMMSS($seconds);

            hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `time_worked` = ADDTIME(`time_worked`,'" . hesk_dbEscape($time_worked) . "') WHERE `trackid`='" . hesk_dbEscape($trackingID) . "'");
        }

        // Notify staff (owner and collaborators) of a new note
        if (($ticket['owner'] && $ticket['owner'] != $_SESSION['id']) || count($ticket['collaborators']))
        {
            $sql_note = "SELECT COUNT(*) FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `active` = 1 AND (";
            if ($ticket['owner'] && $ticket['owner'] != $_SESSION['id']) {
                $sql_note .= " (`id`=".intval($ticket['owner'])." AND `notify_note`='1') ";
            } else {
                $sql_note .= " 1 ";
            }

            if (count($ticket['collaborators'])) {
                $sql_note .= " OR (`notify_collaborator_note`='1' AND `id` IN (".implode(",", $ticket['collaborators'])."))";
            }
            $sql_note .= ")";

            $res = hesk_dbQuery($sql_note);

			if (hesk_dbNumRows($res) > 0)
			{
				// 1. Generate the array with ticket info that can be used in emails
				$info = array(
				'email'			=> $customer_emails,
				'category'		=> $ticket['category'],
				'priority'		=> $ticket['priority'],
				'owner'			=> $ticket['owner'],
                'collaborators' => $ticket['collaborators'],
				'trackid'		=> $ticket['trackid'],
				'status'		=> $ticket['status'],
				'name'			=> $_SESSION['name'],
				'subject'		=> $ticket['subject'],
				'message'		=> stripslashes($msg),
				'dt'			=> hesk_date($ticket['dt'], true),
				'lastchange'	=> hesk_date($ticket['lastchange'], true),
				'attachments'	=> $myattachments,
                'due_date'      => hesk_format_due_date($ticket['due_date']),
				'id'			=> $ticket['id'],
                'time_worked'   => $ticket['time_worked'],
                'last_reply_by' => $ticket['repliername'],
				);

				// 2. Add custom fields to the array
				foreach ($hesk_settings['custom_fields'] as $k => $v)
				{
					$info[$k] = $v['use'] ? $ticket[$k] : '';
				}

                // 3. Add HTML message to the array
                $info['message_html'] = $info['message'];

                // 4. Make sure all values are properly formatted for email
				$ticket = hesk_ticketToPlain($info, 1, 0);

                // 5. Send notification(s)
				require(HESK_PATH . 'inc/email_functions.inc.php');
                hesk_notifyAssignedStaff(false, 'new_note', 'notify_note', 'notify_collaborator_note', array($_SESSION['id']));
			}
        }
	}

	header('Location: admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999));
	exit();
}

/* Update time worked */
if ($hesk_settings['time_worked'] && ($can_reply || $can_edit) && isset($_POST['h']) && isset($_POST['m']) && isset($_POST['s']) && hesk_token_check('POST'))
{
	$h = intval( hesk_POST('h') );
	$m = intval( hesk_POST('m') );
	$s = intval( hesk_POST('s') );

	/* Get time worked in proper format */
    $time_worked = hesk_getTime($h . ':' . $m . ':' . $s);

	/* Update database */
    if (hesk_dbAffectedRows(hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `time_worked`='" . hesk_dbEscape($time_worked) . "' WHERE `trackid`='" . hesk_dbEscape($trackingID) . "'"))) {
        $revision = sprintf($hesklang['thist14'],hesk_date(),$time_worked,addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `history`=CONCAT(`history`,'" . hesk_dbEscape($revision) . "') WHERE `trackid`='" . hesk_dbEscape($trackingID) . "'");
    }

	/* Show ticket */
	hesk_process_messages($hesklang['twu'],'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999),'SUCCESS');
}

/* Update due date */
if (isset($_POST['action']) && $_POST['action'] == 'due_date' && hesk_token_check('POST')) {

    // Check permission
    if ( ! $can_due_date) {
        hesk_process_messages($hesklang['can_due_date_e'],'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999),'ERROR');
    }

    $new_due_date = hesk_POST('new-due-date');
    $sql_overdue_email = '';

    if ($new_due_date == '') {
        $formatted_date = false;
        $revision = sprintf($hesklang['thist20'], hesk_date(), addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
    } else {
        $date = hesk_datepicker_get_date($new_due_date);
        if ($date === false) {
            hesk_process_messages($hesklang['invalid_due_date'], 'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999));
        }

        $formatted_date = $date->format('Y-m-d');
        $revision = sprintf($hesklang['thist19'], hesk_date(), $formatted_date, addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');

        // If this is a future date, we'll reset the
        $current_date = new DateTime();
        if ($date > $current_date)
        {
            $sql_overdue_email = '`overdue_email_sent`=0,';
        }
    }

    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `due_date` = " . ($formatted_date === false ? 'NULL' : "'".hesk_dbEscape($formatted_date)."'") . ", {$sql_overdue_email} `history`=CONCAT(`history`,'" . hesk_dbEscape($revision) . "') WHERE `trackid`='" . hesk_dbEscape($trackingID) . "' AND (`due_date` IS " . ($formatted_date === false ? 'NOT NULL' : "NULL OR `due_date` != '".hesk_dbEscape($formatted_date)."'") . ")");

    /* Show ticket */
    hesk_process_messages($hesklang['due_date_updated'],'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999),'SUCCESS');
}

/* Delete attachment action */
if (isset($_GET['delatt']) && hesk_token_check())
{
    if ( ! $can_delete || ! $can_edit) {
        hesk_process_messages($hesklang['no_permission'],'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999));
    }

    $delatt = preg_replace('/[^0-9,]/', '', hesk_GET('delatt'));
    if (strlen($delatt) == 0) {
        hesk_error($hesklang['inv_att_id']);
    }
    $att_ids = explode(',', $delatt);

    $reply = intval( hesk_GET('reply', 0) );
    if ($reply < 1) {
        $reply = 0;
    }

    $note = intval( hesk_GET('note', 0) );
    if ($note < 1) {
        $note = 0;
    }

    foreach ($att_ids as $att_id):

        // Get attachment info
        $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."attachments` WHERE `att_id`='".intval($att_id)."' LIMIT 1");
        if (hesk_dbNumRows($res) != 1) {
            hesk_process_messages($hesklang['id_not_valid'].' (att_id)','admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999));
        }
        $att = hesk_dbFetchAssoc($res);

        // Is ticket ID valid for this attachment?
        if ($att['ticket_id'] != $trackingID) {
            hesk_process_messages($hesklang['trackID_not_found'],'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999));
        }

        // Delete file from server
        hesk_unlink(HESK_PATH.$hesk_settings['attach_dir'].'/'.$att['saved_name']);

        // Delete attachment from database
        hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."attachments` WHERE `att_id`='".intval($att_id)."'");

        // Update ticket or reply in the database
        $revision = sprintf($hesklang['thist12'],hesk_date(),$att['real_name'],addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
        if ($reply) {
            hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` SET `attachments`=REPLACE(`attachments`,'".hesk_dbEscape($att_id.'#'.$att['real_name']).",','') WHERE `id`='".intval($reply)."'");
            hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') WHERE `id`='".intval($ticket['id'])."'");
        } elseif ($note) {
            hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."notes` SET `attachments`=REPLACE(`attachments`,'".hesk_dbEscape($att_id.'#'.$att['real_name']).",','') WHERE `id`={$note}");
        } else {
            hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `attachments`=REPLACE(`attachments`,'".hesk_dbEscape($att_id.'#'.$att['real_name']).",',''), `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') WHERE `id`='".intval($ticket['id'])."'");
        }

    endforeach;

	hesk_process_messages($hesklang['kb_att_rem'],'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999),'SUCCESS');
}

// Add to bookmarks
if (isset($_GET['bm_add']) && hesk_token_check()) {
    if ($_GET['bm_add'] == 1 && empty($ticket['is_bookmark'])) {
        hesk_dbQuery("
            INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."bookmarks` (`user_id`, `ticket_id`)
            SELECT ".intval($_SESSION['id']).", {$ticket['id']}
            WHERE NOT EXISTS (
                SELECT 1
                FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."bookmarks`
                WHERE `user_id`=".intval($_SESSION['id'])." AND `ticket_id`={$ticket['id']}
            )
        " );
        hesk_process_messages($hesklang['bookmarks_added'],'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999),'SUCCESS');
    } elseif (! empty($ticket['is_bookmark'])) {
        hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."bookmarks` WHERE `ticket_id`={$ticket['id']} AND `user_id`=".intval($_SESSION['id']));
        hesk_process_messages($hesklang['bookmarks_removed'],'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999),'SUCCESS');
    }
}

// Link Ticket
if (isset($_POST['action_type']) && $_POST['action_type'] == 'linked_ticket' && hesk_token_check('POST')) {
    $json_data = [];

    $ticket_track_id = hesk_cleanID('', hesk_POST('ticket_track_id'));

    //Tracking ID Required
    if ($ticket_track_id == "") {
        $json_data['status'] = 'ERROR';
        $json_data['message'] = '<div role="alert" class="notification red"><b>'.$hesklang['error'].': </b>'.$hesklang['link_ticket_required_error'].'</div>';
        $json_data['redirect'] = 'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999);
        echo json_encode($json_data);
        exit;
    }
    //Check for ticket itself linking
    if ($ticket_track_id == $ticket['trackid'] || $ticket_track_id == $ticket['id']) {
        $json_data['status'] = 'ERROR';
        $json_data['message'] = '<div role="alert" class="notification red"><b>'.$hesklang['error'].': </b>'.$hesklang['link_ticket_itself_error'].'</div>';
        $json_data['redirect'] = 'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999);
        echo json_encode($json_data);
        exit;
    }

    // Check permission
    if ( ! $can_link_tickets) {
        $json_data['status'] = 'ERROR';
        $json_data['message'] = '<div role="alert" class="notification red"><b>'.$hesklang['error'].': </b>'.$hesklang['can_link_tickets_e'].'</div>';
        $json_data['redirect'] = 'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999);
        echo json_encode($json_data);
        exit;
    }

    // Fetch the ticket data from table using ticket sequential (numeric) ID or tracking ID
    if (is_numeric($ticket_track_id)) {
        $res_ticket = hesk_dbQuery("SELECT `id`,`trackid`,`category`,`owner`,`assignedby` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets`
         WHERE `id` = '".intval($ticket_track_id)."'");
    } else {
        $res_ticket = hesk_dbQuery("SELECT `id`,`trackid`,`category`,`owner`,`assignedby` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets`
         WHERE `trackid` = '".hesk_dbEscape($ticket_track_id)."'");
    }
    $get_ticket_data = hesk_dbFetchAssoc($res_ticket);

    //Check for ticket data
    if (!empty($get_ticket_data)) {

        // Staff must be allowed to view the target ticket before linking it.
        if ( ! hesk_staffCanAccessTicketNoError($get_ticket_data)) {
            $json_data['status'] = 'ERROR';
            $json_data['message'] = '<div role="alert" class="notification red"><b>'.$hesklang['error'].': </b>'.$hesklang['no_permission'].'</div>';
            $json_data['redirect'] = '';
            echo json_encode($json_data);
            exit;
        }
        //Check for linked data in table
        $q = "SELECT `id`,`ticket_id1`,`ticket_id2` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."linked_tickets`
        WHERE ((`ticket_id1` = ".intval($get_ticket_data['id'])." AND `ticket_id2` = ".intval($ticket['id']).") OR (`ticket_id1` = ".intval($ticket['id'])." AND `ticket_id2` = ".intval($get_ticket_data['id'])."))";

        $res_linked = hesk_dbQuery($q);

        $check_ticket_data = hesk_dbFetchAssoc($res_linked);
        //Check for already linked ticket for same user/customer
        if (!empty($check_ticket_data)) {
            $json_data['status'] = 'ERROR';
            $json_data['message'] = '<div role="alert" class="notification red"><b>'.$hesklang['error'].': </b>'.$hesklang['already_linked_error'].'</div>';
            $json_data['redirect'] = '';
            echo json_encode($json_data);
            exit;
        } else {
            // Insert ticket relation into database
            $q = "INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."linked_tickets` (`ticket_id1`, `ticket_id2`, `dt_created`) VALUES ('".intval($ticket['id'])."', '".intval($get_ticket_data['id'])."',NOW())";
            hesk_dbQuery($q);
            //Update insert history log
            $link_ticket_log = sprintf($hesklang['link_history'], hesk_date(), $ticket_track_id, addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');;
            hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `history`=CONCAT(`history`,'".hesk_dbEscape($link_ticket_log)."') WHERE `id`='".intval($ticket['id'])."'");

            //Get Linked Ticket Html View
            $linked_html = getLinkedHtml($customers, $ticket, $can_link_tickets);

            // Get ticket history log
            $q = hesk_dbQuery("SELECT `history` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` `tickets` WHERE `id`='".intval($ticket['id'])."'");
            $ticket_history = hesk_dbFetchAssoc($q);

            $history_pieces = explode('</li>', $ticket_history['history'], -1);
            $history_html = getTicketHistory($history_pieces);

            $json_data['status'] = 'SUCCESS';
            $json_data['message'] = '<div role="status" class="notification green"><b>'.$hesklang['success'].': </b>'.$hesklang['link_ticket_success'].'</div>';
            $json_data['redirect'] = '';
            $json_data['linked_html'] = $linked_html;
            $json_data['history_html'] = $history_html;
            echo json_encode($json_data);
            exit;
        }
    } else {
        //Ticket Not Found
        $json_data['status'] = 'ERROR';
        $json_data['message'] = '<div role="alert" class="notification red"><b>'.$hesklang['error'].': </b>'.$hesklang['ticket_not_found'].'</div>';
        $json_data['redirect'] = 'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999);
        echo json_encode($json_data);
        exit;
    }
}

// Unlink Ticket
if (isset($_POST['action_type']) && $_POST['action_type'] == 'unlink_ticket') {

    // Check permission
    if ( ! $can_link_tickets) {
        $json_data['status'] = 'ERROR';
        $json_data['message'] = '<div role="alert" class="notification red"><b>'.$hesklang['error'].': </b>'.$hesklang['can_link_tickets_e'].'</div>';
        $json_data['redirect'] = 'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999);
        echo json_encode($json_data);
        exit;
    }

    // A security check
    hesk_token_check('POST');

    $json_data = [];
    $ticket1 = intval(hesk_POST('ticket1', 0));
    $ticket2 = intval(hesk_POST('ticket2', 0));
    $trackid = hesk_cleanID('', hesk_POST('trackid'));

    if ($ticket1 < 1 || $ticket2 < 1) {
        $json_data['status'] = 'ERROR';
        $json_data['message'] = '<div role="alert" class="notification red"><b>'.$hesklang['error'].': </b>'.$hesklang['id_not_valid'].'</div>';
        $json_data['redirect'] = '';
        echo json_encode($json_data);
        exit;
    }

    // The unlink request must involve the ticket currently open on this page.
    if ($ticket1 != intval($ticket['id']) && $ticket2 != intval($ticket['id'])) {
        $json_data['status'] = 'ERROR';
        $json_data['message'] = '<div role="alert" class="notification red"><b>'.$hesklang['error'].': </b>'.$hesklang['no_permission'].'</div>';
        $json_data['redirect'] = '';
        echo json_encode($json_data);
        exit;
    }

    $other_ticket_id = ($ticket1 == intval($ticket['id'])) ? $ticket2 : $ticket1;
    $res_other_ticket = hesk_dbQuery("SELECT `id`,`trackid`,`category`,`owner`,`assignedby` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`=".intval($other_ticket_id)." LIMIT 1");
    if (hesk_dbNumRows($res_other_ticket) != 1) {
        $json_data['status'] = 'ERROR';
        $json_data['message'] = '<div role="alert" class="notification red"><b>'.$hesklang['error'].': </b>'.$hesklang['ticket_not_found'].'</div>';
        $json_data['redirect'] = '';
        echo json_encode($json_data);
        exit;
    }

    $other_ticket = hesk_dbFetchAssoc($res_other_ticket);
    if ( ! hesk_staffCanAccessTicketNoError($other_ticket)) {
        $json_data['status'] = 'ERROR';
        $json_data['message'] = '<div role="alert" class="notification red"><b>'.$hesklang['error'].': </b>'.$hesklang['no_permission'].'</div>';
        $json_data['redirect'] = '';
        echo json_encode($json_data);
        exit;
    }

    $trackid = $other_ticket['trackid'];

    $res_linked = hesk_dbQuery("SELECT `id`,`ticket_id1`,`ticket_id2` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."linked_tickets`
        WHERE ((`ticket_id1` = ".intval($ticket['id'])." AND `ticket_id2` = ".intval($other_ticket_id).") OR (`ticket_id1` = ".intval($other_ticket_id)." AND `ticket_id2` = ".intval($ticket['id'])."))");

    $check_ticket_data = hesk_dbFetchAssoc($res_linked);

    if (!empty($check_ticket_data)) {

        $id = intval($check_ticket_data['id']);
        hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."linked_tickets` WHERE `id`={$id}");

        if ( hesk_dbAffectedRows() == 1 ){
            //Update delete history log
            $delete_link = sprintf($hesklang['unlink_history'], hesk_date(), $trackid ,addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');;
            hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `history`=CONCAT(`history`,'".hesk_dbEscape($delete_link)."') WHERE `id`='".intval($ticket['id'])."'");

            $linked_html = getLinkedHtml($customers, $ticket, $can_link_tickets);
            // Get ticket history log
            $q = hesk_dbQuery("SELECT `history` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` `tickets` WHERE `id`='".intval($ticket['id'])."'");
            $ticket_history = hesk_dbFetchAssoc($q);

            $history_pieces = explode('</li>', $ticket_history['history'], -1);
            $history_html = getTicketHistory($history_pieces);

            $json_data['status'] = 'SUCCESS';
            $json_data['message'] = '<div role="status" class="notification green"><b>'.$hesklang['success'].': </b>'.$hesklang['unlink_success'].'</div>';
            $json_data['redirect'] = '';
            $json_data['linked_html'] = $linked_html;
            $json_data['history_html'] = $history_html;
            echo json_encode($json_data);
            exit;
        } else {
            $json_data['status'] = 'ERROR';
            $json_data['message'] = '<div role="alert" class="notification red"><b>'.$hesklang['error'].': </b>'.$hesklang['unlink_error'].'</div>';
            $json_data['redirect'] = '';
            echo json_encode($json_data);
            exit;
        }

    } else {
        $json_data['status'] = 'ERROR';
        $json_data['message'] = '<div role="alert" class="notification red"><b>'.$hesklang['error'].': </b>'.$hesklang['unlink_error'].'</div>';
        $json_data['redirect'] = '';
        echo json_encode($json_data);
        exit;
    }

}

// Collaborator
if (isset($_GET['collaborator']) && hesk_token_check()) {
    if ($_GET['collaborator'] == 1 && empty($ticket['am_I_collaborator'])) {
        hesk_dbQuery("
            INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_collaborator` (`user_id`, `ticket_id`)
            SELECT ".intval($_SESSION['id']).", {$ticket['id']}
            WHERE NOT EXISTS (
                SELECT 1
                FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_collaborator`
                WHERE `user_id`=".intval($_SESSION['id'])." AND `ticket_id`={$ticket['id']}
            )
        " );

        $revision = sprintf($hesklang['thist24'], hesk_date(), addslashes($_SESSION['name']).' ('.$_SESSION['user'].')', addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `history`=CONCAT(`history`,'" . hesk_dbEscape($revision) . "') WHERE `id`=" . intval($ticket['id']));

        hesk_process_messages($hesklang['collaborating'],'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999),'SUCCESS');
    } elseif ($_GET['collaborator'] == 0 && ! empty($ticket['am_I_collaborator'])) {
        hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_collaborator` WHERE `ticket_id`={$ticket['id']} AND `user_id`=".intval($_SESSION['id']));

        $revision = sprintf($hesklang['thist25'], hesk_date(), addslashes($_SESSION['name']).' ('.$_SESSION['user'].')', addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `history`=CONCAT(`history`,'" . hesk_dbEscape($revision) . "') WHERE `id`=" . intval($ticket['id']));

        hesk_process_messages($hesklang['not_collaborating'],'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999),'SUCCESS');
    }
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* List of categories */
if ($can_change_cat)
{
    $result = hesk_dbQuery("SELECT `id`,`name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` ORDER BY `cat_order` ASC");
}
else
{
    $result = hesk_dbQuery("SELECT `id`,`name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE ".hesk_myCategories('id')." ORDER BY `cat_order` ASC");
}
$categories_options='';
while ($row=hesk_dbFetchAssoc($result))
{
    $categories_options.='<option value="'.$row['id'].'" '.($row['id'] == $ticket['category'] ? 'selected' : '').'>'.$row['name'].'</option>';
}

/* List of users */
$accessible_users = hesk_getUserIdsWithAccessToFeatureAndCategory('can_view_tickets', $ticket['category']);
$admins = array();
$result = hesk_dbQuery("SELECT `id`,`name`,`isadmin`,`categories`,`heskprivileges` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `active` = 1 ORDER BY `name` ASC");
while ($row=hesk_dbFetchAssoc($result))
{
	/* Is this an administrator or has access via permission group? */
	if ($row['isadmin'] || in_array($row['id'], $accessible_users))
    {
	    $admins[$row['id']]=$row['name'];
	    continue;
    }

	/* Not admin, is user allowed to view tickets? */
	if (strpos($row['heskprivileges'], 'can_view_tickets') !== false)
	{
		/* Is user allowed to access this category? */
		$cat=substr($row['categories'], 0);
		$row['categories']=explode(',',$cat);
		if (in_array($ticket['category'],$row['categories']))
		{
			$admins[$row['id']]=$row['name'];
			continue;
		}
	}
}

/* Get replies */
if ($ticket['replies'])
{
	$reply = '';
	$result = hesk_dbQuery("SELECT `replies`.*, `customers`.`name` AS `customer_name`, `customers`.`email` AS `customer_email`, `users`.`name` AS `staff_name`
        FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` AS `replies`
        LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` AS `customers`
            ON `customers`.`id` = `replies`.`customer_id`
        LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."users` AS `users`
            ON `users`.`id` = `replies`.`staffid` 
        WHERE `replyto`='".intval($ticket['id'])."' ORDER BY `id` " . ($hesk_settings['new_top'] ? 'DESC' : 'ASC') );
}
else
{
	$reply = false;
}

// Demo mode
if ( defined('HESK_DEMO') )
{
    foreach ($customers as $customer) {
        $customer['email'] = 'hidden@demo.com';
    }
	$ticket['ip']	 = '127.0.0.1';
}

/* Print admin navigation */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
hesk_handle_messages();

// Prepare special custom fields
foreach ($hesk_settings['custom_fields'] as $k=>$v)
{
	if ($v['use'] && (strlen($ticket[$k]) || hesk_is_custom_field_in_category($k, $ticket['category'])) )
	{
		switch ($v['type'])
		{
			case 'date':
				$ticket[$k] = hesk_custom_date_display_format($ticket[$k], $v['value']['date_format']);
				break;
		}
	}
}

/* Do we need or have any canned responses? */
$can_options = hesk_printCanned();

$options = [];
foreach ($hesk_settings['priorities'] as $key => $value) {
    $data_style ='border-top-color:'.$value['color'].';border-left-color:'.$value['color'].';border-bottom-color:'.$value['color'].';';
    $options[$value['id']] = '<option value="'.$value['id'].'" '.($ticket['priority'] == $value['id'] ? 'selected' : '').' data-class="priority_img priority_dwn" data-style='.$data_style.' >'.$value['name'].'</option>';
}

// Get linked tickets data
function getLinkedTickets($customers , $ticket){
    global $hesk_settings, $hesklang;

    if (empty($customers)) {
        $result["linked_num"] = 0;
        $result["res"] = "";
        $result["show_linked_tickets"] = 0;
        return $result;
    }

    $r = $result = $ids = [];
    // How many linked tickets should we show?
    $show_linked_tickets = 5;

    $first_customer = $customers[0];
    // Get Linked ticket ids
    $res_linked = hesk_dbQuery("SELECT `id`,`ticket_id1`,`ticket_id2` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."linked_tickets`
     WHERE (`ticket_id1` = ".$ticket['id']." OR `ticket_id2` = ".$ticket['id'].")");

    while ($row = hesk_dbFetchAssoc($res_linked))
	{
        if($row["ticket_id1"] != $ticket['id']){
            $ids[] = $row["ticket_id1"];
        }
        if($row["ticket_id2"] != $ticket['id']){
            $ids[] = $row["ticket_id2"];
        }
    }

    $where_in = '';
    if (!empty($ids)) {
        $id = implode(", ", $ids);
        $where_in = "`id` IN (".$id.") AND ";
    } else {
        $result["linked_num"] = 0;
        $result["res"] = "";
        $result["show_linked_tickets"] = $show_linked_tickets;
        return $result;
    }
    // Get recent tickets, ordered by last change
    $res = hesk_dbQuery("SELECT `id`, `trackid`, `status`, `subject` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` `tickets`
        WHERE ".$where_in."".hesk_myCategories()."
            AND ".hesk_myOwnership()."
        ORDER BY `lastchange` DESC
        LIMIT " . ($show_linked_tickets+1));
    $result["linked_num"] = hesk_dbNumRows($res);
    $result["res"] = $res;
    $result["show_linked_tickets"] = $show_linked_tickets;
    return $result;
}

// Get linked tickets html view
function getLinkedHtml($customers, $ticket, $can_link_tickets){
    global $hesk_settings, $hesklang;

    if (empty($customers)) {
        return '';
    }

    $result = getLinkedTickets($customers, $ticket);

    $trackingID = $ticket['trackid'];
    $first_customer = $customers[0];

    $linked_num = $result['linked_num'];
    $res = $result['res'];
    $show_linked_tickets = $result['show_linked_tickets'];
    $i = 0;
    $html = "";
    if ($linked_num > 0){
        while ($linked_ticket = hesk_dbFetchAssoc($res)) {
            $i++;
            if ($i > $show_linked_tickets) {
                hesk_dbFreeResult($res);
                break;
            }

            $linked_trackid = hesk_htmlspecialchars($linked_ticket['trackid']);
            $linked_subject = hesk_htmlspecialchars($linked_ticket['subject']);
            $linked_status = isset($hesk_settings['statuses'][$linked_ticket['status']]) ? $hesk_settings['statuses'][$linked_ticket['status']] : array('name' => '', 'color' => '');
            $linked_status_name = hesk_htmlspecialchars($linked_status['name']);

            $html.="<div class = 'linked_ticket_html mb-5'>";
                if (isset($linked_status['class'])):
                $html.='<span class="dot bg-'.hesk_htmlspecialchars($linked_status['class']).'" title="'.$linked_status_name.'"></span>';
                else:
                $html.='<span class="dot" style="background-color:'.hesk_htmlspecialchars($linked_status['color']).'" title="'.$linked_status_name.'"></span>';
                endif;
            $html.='<a href="admin_ticket.php?track='.urlencode($linked_ticket['trackid']).'&amp;Refresh='.rand(10000,99999).'">'.$linked_subject.'</a>';
            if($can_link_tickets){
                $html.='<a class="btn btn-links unlink" data-ticket1="'.intval($linked_ticket['id']).'" data-ticket2="'.intval($ticket['id']).'" data-trackid="'.$linked_trackid.'" data-action="admin_ticket.php?track='.urlencode($trackingID).'&amp;Refresh='.rand(10000,99999).'" href="javascript:;">'.$hesklang['unlink_btn'].'</a>';
            }
            $html.="</div>";
        }
    }
    if ($linked_num > 0 && $i > $show_linked_tickets) {
        $html.= '<br><a href="find_tickets.php?q='.urlencode($first_customer['email']).'&amp;what=email&amp;s_my=1&amp;s_ot=1&amp;s_un=1">'.$hesklang['all_previous'].'</a>';
    } elseif ($linked_num == 0) {
        $html.= '<div class = "linked_ticket_html">'.$hesklang['no_linked_tickets'].'</div>';
    }
    return $html;
}

// Get ticket history html view
function getTicketHistory($history_pieces){
    $html = '';
    foreach ($history_pieces as $history_piece) {
        $history_piece = str_replace('<li class="smaller">', '', $history_piece);
        $date_and_contents = explode(' | ', $history_piece);
        if ( ! isset($date_and_contents[1])) {
            $date_and_contents[1] = $date_and_contents[0];
            $date_and_contents[0] = '';
        }

        $html.='<div class="row">';
        $html.='<div class="title">'.$date_and_contents[0].'</div>';
        $html.=' <div class="value">'.$date_and_contents[1].'</div>';
        $html.='</div>';
    }
    return $html;
}
?>
<div class="main__content ticket">
    <div class="ticket__body" <?php echo ($hesk_settings['limit_width'] ? 'style="max-width:'.$hesk_settings['limit_width'].'px"' : ''); ?>>

        <?php if ($hesk_settings['new_top']): ?>
        <!-- START new replies on top subject line -->
        <article class="ticket__body_block original-message" style="padding-bottom: 0px; margin-bottom: 16px; min-height: 48px; border-radius: 2px; box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1);">
            <div style="display:flex; justify-content: space-between; flex-wrap: wrap;">
            <h3>
                <?php if ($ticket['archive']): ?>
                    <div class="tooltype right out-close">
                        <svg class="icon icon-tag">
                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tag"></use>
                        </svg>
                        <div class="tooltype__content">
                            <div class="tooltype__wrapper">
                                <?php echo $hesklang['archived']; ?>
                            </div>
                        </div>
                    </div>
                <?php
                endif;
                if ($ticket['is_bookmark']):
                ?>
                    <div class="tooltype right out-close">
                        <svg class="icon icon-pin is-bookmark">
                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-pin"></use>
                        </svg>
                        <div class="tooltype__content">
                            <div class="tooltype__wrapper">
                                <?php echo $hesklang['bookmark']; ?>
                            </div>
                        </div>
                    </div>
                <?php
                endif;
                if ($ticket['locked']):
                ?>
                    <div class="tooltype right out-close">
                        <svg class="icon icon-lock">
                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-lock"></use>
                        </svg>
                        <div class="tooltype__content">
                            <div class="tooltype__wrapper">
                                <?php echo $hesklang['loc'].' - '.$hesklang['isloc']; ?>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
                <?php echo $ticket['subject']; ?>
            </h3>
            <div class="note__link">
                <?php if ($can_reply): ?>
                <a href="#reply-form" title="<?php echo $hesklang['add_a_reply']; ?>" style="margin-right: 15px;">
                    <svg class="icon icon-edit-ticket">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-edit-ticket"></use>
                    </svg>&nbsp;&nbsp;
                    <?php echo $hesklang['add_a_reply']; ?>
                </a>
                <?php endif; ?>
                <a href="javascript:" title="<?php echo $hesklang['add_a_note']; ?>" onclick="hesk_toggleLayerDisplay('notesDivTop'); $('#notemsg').focus();">
                    <svg class="icon icon-note">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-note"></use>
                    </svg>&nbsp;&nbsp;
                    <?php echo $hesklang['add_a_note']; ?>
                </a>
            </div>
            </div>

            <?php
            $res = hesk_dbQuery("SELECT t1.*, t2.`name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."notes` AS t1 LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."users` AS t2 ON t1.`who` = t2.`id` WHERE `ticket`='".intval($ticket['id'])."' ORDER BY t1.`id` " . ($hesk_settings['new_top'] ? 'DESC' : 'ASC') );
            ?>
            <div class="block--notes" <?php echo hesk_dbNumRows($res) ? 'style="padding-bottom: 15px"' : ''; ?>>
                <div id="notesDivTop" style="display:<?php echo isset($_SESSION['note_message']) ? 'block' : 'none'; ?>; margin-top: 20px; padding-bottom: 15px;">
                    <form id="notesformTop" method="post" action="admin_ticket.php" class="form" enctype="multipart/form-data" aria-label="<?php echo $hesklang['ts']; ?>">
                        <i><?php echo $hesklang['nhid']; ?></i><br>
                        <textarea class="form-control" name="notemsg" id="notemsg" rows="6" cols="60" style="height: auto; resize: vertical; transition: none;" aria-label="<?php echo $hesklang['notes']; ?>"><?php echo isset($_SESSION['note_message']) ? stripslashes(hesk_input($_SESSION['note_message'])) : ''; ?></textarea>
                        <?php
                        // attachments
                        if ($hesk_settings['attachments']['use'])
                        {
                        ?>
                        <div class="attachments">
                            <div class="block--attach">
                                <svg class="icon icon-attach">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-attach"></use>
                                </svg>
                                <div>
                                    <?php echo $hesklang['attachments'] . ':<br>'; ?>
                                </div>
                            </div>
                            <?php
                            require_once(HESK_PATH . 'inc/attachments.inc.php');
                            build_dropzone_markup(true, 'notesFiledropTop');
                            display_dropzone_field(HESK_PATH . 'upload_attachment.php', true, 'notesFiledropTop');
                            dropzone_display_existing_files(hesk_SESSION_array('note_attachments'), 'notesFiledropTop');
                            ?>
                        </div>
                        <?php
                        }
                        ?>
                        <button type="submit" class="btn btn-full">
                            <?php echo $hesklang['sub_note']; ?>
                        </button>
                        <input type="hidden" name="track" value="<?php echo $trackingID; ?>">
                        <input type="hidden" id="time_worked_notesTop" name="time_worked_notes" value="">
                        <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                    </form>
                </div>
                <?php
                while ($note = hesk_dbFetchAssoc($res)) {
                    ?>
                    <div class="note">
                        <div class="note__head">
                            <div class="name">
                                <?php echo $hesklang['noteby']; ?>
                                <b><?php echo ($note['name'] ? $note['name'] : $hesklang['e_udel']); ?></b>
                                &raquo;
                                <time class="timeago tooltip" datetime="<?php echo date("c", strtotime($note['dt'])) ; ?>" title="<?php echo hesk_date($note['dt'], true); ?>"><?php echo hesk_date($note['dt'], true); ?></time>
                            </div>
                            <?php
                            if ($can_del_notes || $note['who'] == $_SESSION['id'])
                            {
                            ?>
                            <?php $delnote_modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'], $hesklang['delnote'].'?', 'admin_ticket.php?track='.$trackingID.'&amp;Refresh='.mt_rand(10000,99999).'&amp;delnote='.$note['id'].'&amp;token='.hesk_token_echo(0)); ?>
                            <div class="actions">
                                <a class="tooltip" href="edit_note.php?track=<?php echo $trackingID; ?>&amp;Refresh=<?php echo mt_rand(10000,99999); ?>&amp;note=<?php echo $note['id']; ?>&amp;token=<?php hesk_token_echo(); ?>" title="<?php echo $hesklang['ednote']; ?>">
                                    <svg class="icon icon-edit-ticket">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-edit-ticket"></use>
                                    </svg>
                                </a>
                                <a class="tooltip" href="javascript:" data-modal="[data-modal-id='<?php echo $delnote_modal_id; ?>']" title="<?php echo $hesklang['delnote']; ?>">
                                    <svg class="icon icon-delete">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-delete"></use>
                                    </svg>
                                </a>
                            </div>
                            <?php } ?>
                        </div>
                        <div class="note__description">
                            <p><?php echo $note['message']; ?></p>
                        </div>
                        <div class="note__attachments">
                            <?php
                            // Attachments
                            if ( $hesk_settings['attachments']['use'] && strlen($note['attachments']) )
                            {
                                echo strlen($note['message']) ? '<br>' : '';

                                $att = explode(',', substr($note['attachments'], 0, -1) );
                                $num = count($att);
                                $div_id = "d" . mt_rand(100000,999999);
                                $att_ids = array();
                                foreach ($att as $myatt)
                                {
                                    list($att_id, $att_name) = explode('#', $myatt);
                                    $att_ids[] = $att_id;

                                    // Can edit and delete note (attachments)?
                                    if ($can_del_notes || $note['who'] == $_SESSION['id'])
                                    {
                                        if ($num > 2){
                                            echo '<div class="checkbox-custom d-inline-flex">
                                                <input type="checkbox" id="attachment_note_'.$att_id.'" name="id[]" value="'.$att_id.'" class="group attach_check group_'.$div_id.'" data-id="'.$div_id.'" data-note='.$note['id'].' data-token='.hesk_token_echo(0).' data-track='.$trackingID.' data-flag="note">
                                                <label for="attachment_note_'.$att_id.'">&nbsp;</label>
                                            </div>';
                                        }

                                        // If this is the last attachment and no message, show "delete ticket" link
                                        if ($num == 1 && strlen($note['message']) == 0)
                                        {
                                            echo '<a class="tooltip" data-ztt_vertical_offset="0" style="margin-right: 8px;" href="admin_ticket.php?delnote='.$note['id'].'&amp;track='.$trackingID.'&amp;Refresh='.mt_rand(10000,99999).'&amp;token='.hesk_token_echo(0).'" onclick="return hesk_confirmExecute(\''.hesk_makeJsString($hesklang['pda']).'\');" title="'.$hesklang['dela'].'">
                                                    <svg class="icon icon-delete" style="text-decoration: none; vertical-align: text-bottom;">
                                                        <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-delete"></use>
                                                    </svg>
                                                </a> &raquo;';
                                        }
                                        // Show "delete attachment" link
                                        else
                                        {
                                            echo '<a class="tooltip" data-ztt_vertical_offset="0" style="margin-right: 8px;" href="admin_ticket.php?delatt='.$att_id.'&amp;note='.$note['id'].'&amp;track='.$trackingID.'&amp;Refresh='.mt_rand(10000,99999).'&amp;token='.hesk_token_echo(0).'" onclick="return hesk_confirmExecute(\''.hesk_makeJsString($hesklang['pda']).'\');" title="'.$hesklang['dela'].'">
                                                    <svg class="icon icon-delete" style="vertical-align: text-bottom;">
                                                        <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-delete"></use>
                                                    </svg>
                                                </a> &raquo;';
                                        }
                                    }

                                    echo '
                                    <a href="download_attachment.php?att_id='.$att_id.'&amp;track='.$trackingID.'" title="'.$hesklang['dnl'].' '.$att_name.'">
                                        <svg class="icon icon-attach" style="vertical-align: text-bottom;">
                                            <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-attach"></use>
                                        </svg>
                                    </a>
                                    <a class="underline" href="download_attachment.php?att_id='.$att_id.'&amp;track='.$trackingID.'" title="'.$hesklang['dnl'].' '.$att_name.'">'.$att_name.'</a><br>
                                    ';
                                }
                                if (count($att) > 0 && class_exists('ZipArchive')) {
                                    if (count($att_ids) > 2) {
                                        $html = '';
                                        $html = '<p id="'.$div_id.'" class="d-inline-flex">';
                                        $html .= '<a class="underline" title="'.$hesklang['download_all'].'" href="../download_all.php?att_id='.implode(',', $att_ids).'&amp;track='.$trackingID.'" onclick="document.getElementById(\''.$div_id.'\').innerHTML=\''.hesk_makeJsString($hesklang['download_prep']).'\'">'.$hesklang['download_all'].'</a>';
                                        $html .= '<a class="underline ds ds_'.$div_id.' dwn_'.$div_id.' d_hide ml-10" title="'.$hesklang['download_selected'].'" href="" onclick="document.getElementById(\''.$div_id.'\').innerHTML=\''.hesk_makeJsString($hesklang['download_prep']).'\'">'.$hesklang['download_selected'].'</a> ';
                                        if ($can_edit && $can_delete) {
                                            $html .= '<a class="underline ds ds_'.$div_id.' del_'.$div_id.' d_hide ml-10" title="'.$hesklang['delete_selected'].'" href="" onclick="return hesk_confirmExecute(\''.hesk_makeJsString($hesklang['pda']).'\');">'.$hesklang['delete_selected'].'</a>';
                                        }
                                        $html .= '</p>';
                                        echo $html;
                                    } else {
                                        echo '<p id="'.$div_id.'"><a class="underline" title="'.$hesklang['download_all'].'" href="../download_all.php?att_id='.implode(',', $att_ids).'&amp;track='.$trackingID.'" onclick="document.getElementById(\''.$div_id.'\').innerHTML=\''.hesk_makeJsString($hesklang['download_prep']).'\'">'.$hesklang['download_all'].'</a></p>';
                                    }
                                }
                            }
                            ?>
                        </div>
                    </div>
                    <?php
                }
                ?>
            </div>

        </article>
        <!-- END new replies on top subject line -->
        <?php endif; ?>

        <?php
        /* Reply form on top? */
        if ($can_reply && $hesk_settings['reply_top'] == 1)
        {
            hesk_printReplyForm();
        }

        if ($hesk_settings['new_top'])
        {
            $i = hesk_printTicketReplies() ? 0 : 1;
        }
        else
        {
            $i = 1;
        }
        ?>
        <article class="ticket__body_block original-message">
            <?php if ( ! $hesk_settings['new_top'] || ($hesk_settings['new_top'] && ! $ticket['replies'])): ?>
            <h3 aria-label="Ticket Tags">
                <?php if ($ticket['archive']): ?>
                    <div class="tooltype right out-close">
                        <svg class="icon icon-tag">
                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tag"></use>
                        </svg>
                        <div class="tooltype__content">
                            <div class="tooltype__wrapper">
                                <?php echo $hesklang['archived']; ?>
                            </div>
                        </div>
                    </div>
                <?php
                endif;
                if ($ticket['is_bookmark']):
                ?>
                    <div class="tooltype right out-close">
                        <svg class="icon icon-pin is-bookmark">
                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-pin"></use>
                        </svg>
                        <div class="tooltype__content">
                            <div class="tooltype__wrapper">
                                <?php echo $hesklang['bookmark']; ?>
                            </div>
                        </div>
                    </div>
                <?php
                endif;
                if ($ticket['locked']):
                ?>
                    <div class="tooltype right out-close">
                        <svg class="icon icon-lock">
                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-lock"></use>
                        </svg>
                        <div class="tooltype__content">
                            <div class="tooltype__wrapper">
                                <?php echo $hesklang['loc'].' - '.$hesklang['isloc']; ?>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
                <?php if ( ! $hesk_settings['new_top']) {echo $ticket['subject'];} ?>
            </h3>
            <?php endif; ?>
            <div class="block--head">
                <div class="contact grid">
                    <div class="requester-header">
                        <span><?php echo $hesklang['m_from'] ?>:</span>
                    </div>
                    <div class="requester">
                        <?php
                        if (!$found_requester):
                            echo $hesklang['anon_name'];
                        else:
                            ?>
                            <div class="dropdown customer left out-close">
                                <label>
                                    <svg class="icon icon-person">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-person"></use>
                                    </svg>
                                    <span><?php echo (strlen($requester['name']) ? $requester['name'] : ( ! empty($requester['email']) ? $requester['email'] : $hesklang['pde'] )) ; ?></span>
                                    <svg class="icon icon-chevron-down">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                    </svg>
                                </label>
                                <ul class="dropdown-list">
                                    <?php
                                    if ($requester['email'] != '')
                                    {
                                        ?>
                                        <li class="noclose">
                                            <span class="title"><?php echo $hesklang['email']; ?>:</span>
                                            <span class="value"><a href="mailto:<?php echo $requester['email']; ?>" aria-label="Mail to"><?php echo $requester['email']; ?></a></span>
                                            <a href="javascript:" title="<?php echo $hesklang['copy_value']; ?>" onclick="navigator.clipboard.writeText('<?php echo $requester['email']; ?>');$('#copy-email').addClass('copied');setTimeout(function(){$('#copy-email').removeClass('copied')}, 150);">
                                                <svg class="icon icon-merge copy-me" id="copy-email">
                                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-merge"></use>
                                                </svg>
                                            </a>
                                        </li>
                                        <?php
                                    }
                                    ?>
                                    <li class="noclose">
                                        <span class="title"><?php echo $hesklang['ip']; ?>:</span>
                                        <?php if ($ticket['ip'] == '' || $ticket['ip'] == 'Unknown' || $ticket['ip'] == $hesklang['unknown']): ?>
                                        <span class="value"><?php echo $hesklang['unknown']; ?></span>
                                        <?php else: ?>
                                        <span class="value"><a href="../ip_whois.php?ip=<?php echo urlencode($ticket['ip']); ?>"><?php echo $ticket['ip']; ?></a></span>
                                        <a href="javascript:" title="<?php echo $hesklang['copy_value']; ?>" onclick="navigator.clipboard.writeText('<?php echo $ticket['ip']; ?>');$('#copy-ip').addClass('copied');setTimeout(function(){$('#copy-ip').removeClass('copied')}, 150);">
                                            <svg class="icon icon-merge copy-me" id="copy-ip">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-merge"></use>
                                            </svg>
                                        </a>
                                        <?php endif; ?>
                                    </li>
                                    <li class="separator"></li>
                                    <?php if (($hesk_settings['customer_accounts'] && $can_man_customers) ||
                                        (!$hesk_settings['customer_accounts'] && $can_edit)): ?>
                                    <li>
                                        <svg class="icon icon-edit">
                                            <use xlink:href="../img/sprite.svg#icon-edit"></use>
                                        </svg>
                                        <a href="manage_customers.php?a=edit&track=<?php echo $trackingID; ?>&id=<?php echo intval($requester['id']); ?>">
                                            <?php echo $hesklang['customer_manage_edit']; ?>
                                        </a>
                                    </li>
                                    <li class="separator"></li>
                                    <?php endif; ?>
                                    <?php
                                    if ($requester['email'] != '' && $can_ban_emails) {
                                        echo '<li>';
                                        if ( $email_id = hesk_isBannedEmail($requester['email']) ) {
                                            if ($can_unban_emails) {
                                                echo '
                                        <svg class="icon icon-eye-close">
                                            <use xlink:href="../img/sprite.svg#icon-eye-close"></use>
                                        </svg>
                                        <a href="banned_emails.php?a=unban&amp;track='.$trackingID.'&amp;id='.intval($email_id).'&amp;token='.hesk_token_echo(0).'">'.$hesklang['unban_email'].'</a>
                                    ';
                                            } else {
                                                echo $hesklang['eisban'];
                                            }
                                        } else {
                                            echo '
                                    <svg class="icon icon-eye-open">
                                        <use xlink:href="../img/sprite.svg#icon-eye-open"></use>
                                    </svg>
                                    <a href="banned_emails.php?a=ban&amp;track='.$trackingID.'&amp;email='.urlencode($requester['email']).'&amp;token='.hesk_token_echo(0).'">'.$hesklang['savebanemail'].'</a>
                                ';
                                        }
                                        echo '</li>';
                                    }

                                    // Format IP for lookup
                                    if ($ticket['ip'] != '' && $ticket['ip'] != 'Unknown' && $ticket['ip'] != $hesklang['unknown']) {
                                        echo '<li>';
                                        if ($can_ban_ips) {
                                            if ( $ip_id = hesk_isBannedIP($ticket['ip']) ) {
                                                if ($can_unban_ips) {
                                                    echo '
                                            <svg class="icon icon-eye-close">
                                                <use xlink:href="../img/sprite.svg#icon-eye-close"></use>
                                            </svg>
                                            <a href="banned_ips.php?a=unban&amp;track='.$trackingID.'&amp;id='.intval($ip_id).'&amp;token='.hesk_token_echo(0).'">'.$hesklang['unban_ip'].'</a>
                                        ';
                                                } else {
                                                    echo $hesklang['ipisban'];
                                                }
                                            } else {
                                                echo '
                                        <svg class="icon icon-eye-open">
                                            <use xlink:href="../img/sprite.svg#icon-eye-open"></use>
                                        </svg>
                                        <a href="banned_ips.php?a=ban&amp;track='.$trackingID.'&amp;ip='.urlencode($ticket['ip']).'&amp;token='.hesk_token_echo(0).'">'.$hesklang['savebanip'].'</a>
                                    ';
                                            }
                                        }
                                        echo '</li>';
                                    }

                                    if ($requester['email'] != '' && $can_mute_emails) {
                                        echo '<li class="separator"></li>';
                                        echo '<li>';
                                        if ( $email_id = hesk_isMutedEmail($requester['email']) ) {
                                            if ($can_unmute_emails) {
                                                echo '
                                        <svg class="icon icon-unmute">
                                            <use xlink:href="../img/sprite.svg#icon-unmute"></use>
                                        </svg>
                                        <a href="muted_emails.php?a=unmute&amp;track='.$trackingID.'&amp;id='.intval($email_id).'&amp;token='.hesk_token_echo(0).'">'.$hesklang['unmute_email'].'</a>
                                    ';
                                            } else {
                                                echo $hesklang['eis_mute'];
                                            }
                                        } else {
                                            echo '
                                    <svg class="icon icon-mute">
                                        <use xlink:href="../img/sprite.svg#icon-mute"></use>
                                    </svg>
                                    <a href="muted_emails.php?a=mute&amp;track='.$trackingID.'&amp;email='.urlencode($requester['email']).'&amp;token='.hesk_token_echo(0).'">'.$hesklang['save_mute_email'].'</a>
                                ';
                                        }
                                        echo '</li>';
                                    }
                                    ?>
                                </ul>
                            </div>
                        <?php endif; ?>
                        &raquo; <time class="timeago tooltip" datetime="<?php echo date("c", strtotime($ticket['dt'])) ; ?>" title="<?php echo hesk_date($ticket['dt'], true); ?>"><?php echo hesk_date($ticket['dt'], true); ?></time>
                    </div>
                    <?php
                    if (count($followers) > 0):
                    ?>
                    <div class="cc-header">
                        <span><?php echo $hesklang['cc']; ?>:</span>
                    </div>
                    <div class="cc">
                        <?php foreach ($followers as $customer): ?>
                            <?php
                            $customer_name = hesk_htmlspecialchars(hesk_htmlspecialchars_decode($customer['name']));
                            $customer_email = hesk_htmlspecialchars(hesk_htmlspecialchars_decode($customer['email']));
                            ?>
                            <div class="dropdown customer left out-close">
                                <label aria-label="<?php echo $hesklang['move_dn']; ?>">
                                    <svg class="icon icon-person">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-person"></use>
                                    </svg>
                                    <span><?php echo $customer_name === '' ? $customer_email : $customer_name; ?></span>
                                    <svg class="icon icon-chevron-down">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                    </svg>
                                </label>
                                <ul class="dropdown-list">
                                    <?php
                                    if ($customer_email != '')
                                    {
                                        ?>
                                        <li class="noclose">
                                            <span class="title"><?php echo $hesklang['email']; ?>:</span>
                                            <span class="value"><a href="mailto:<?php echo $customer_email; ?>" aria-label="Mail to"><?php echo $customer_email; ?></a></span>
                                        </li>
                                        <?php
                                    }
                                    ?>
                                    <li class="noclose">
                                        <span class="title"><?php echo $hesklang['ip']; ?>:</span>
                                        <span class="value">
                                <?php
                                if ($ticket['ip'] == '' || $ticket['ip'] == 'Unknown' || $ticket['ip'] == $hesklang['unknown']) {
                                    echo $hesklang['unknown'];
                                } else {
                                    ?>
                                    <a href="../ip_whois.php?ip=<?php echo urlencode($ticket['ip']); ?>"><?php echo $ticket['ip']; ?></a>
                                <?php } ?>
                            </span>
                                    </li>
                                    <li class="separator"></li>
                                    <?php if (($hesk_settings['customer_accounts'] && $can_man_customers) ||
                                        (!$hesk_settings['customer_accounts'] && $can_edit)): ?>
                                        <li>
                                            <svg class="icon icon-edit">
                                                <use xlink:href="../img/sprite.svg#icon-edit"></use>
                                            </svg>
                                            <a href="manage_customers.php?a=edit&track=<?php echo $trackingID; ?>&id=<?php echo intval($customer['id']); ?>">
                                                <?php echo $hesklang['customer_manage_edit']; ?>
                                            </a>
                                        </li>
                                        <li class="separator"></li>
                                    <?php endif;
                                    if ($customer['email'] != '' && $can_ban_emails) {
                                        echo '<li>';
                                        if ( $email_id = hesk_isBannedEmail($customer['email']) ) {
                                            if ($can_unban_emails) {
                                                echo '
                                        <svg class="icon icon-eye-close">
                                            <use xlink:href="../img/sprite.svg#icon-eye-close"></use>
                                        </svg>
                                        <a href="banned_emails.php?a=unban&amp;track='.$trackingID.'&amp;id='.intval($email_id).'&amp;token='.hesk_token_echo(0).'">'.$hesklang['unban_email'].'</a>
                                    ';
                                            } else {
                                                echo $hesklang['eisban'];
                                            }
                                        } else {
                                            echo '
                                    <svg class="icon icon-eye-open">
                                        <use xlink:href="../img/sprite.svg#icon-eye-open"></use>
                                    </svg>
                                    <a href="banned_emails.php?a=ban&amp;track='.$trackingID.'&amp;email='.urlencode($customer['email']).'&amp;token='.hesk_token_echo(0).'">'.$hesklang['savebanemail'].'</a>
                                ';
                                        }
                                        echo '</li>';
                                    }

                                    // Format IP for lookup
                                    if ($ticket['ip'] != '' && $ticket['ip'] != 'Unknown' && $ticket['ip'] != $hesklang['unknown']) {
                                        echo '<li>';
                                        if ($can_ban_ips) {
                                            if ( $ip_id = hesk_isBannedIP($ticket['ip']) ) {
                                                if ($can_unban_ips) {
                                                    echo '
                                            <svg class="icon icon-eye-close">
                                                <use xlink:href="../img/sprite.svg#icon-eye-close"></use>
                                            </svg>
                                            <a href="banned_ips.php?a=unban&amp;track='.$trackingID.'&amp;id='.intval($ip_id).'&amp;token='.hesk_token_echo(0).'">'.$hesklang['unban_ip'].'</a>
                                        ';
                                                } else {
                                                    echo $hesklang['ipisban'];
                                                }
                                            } else {
                                                echo '
                                        <svg class="icon icon-eye-open">
                                            <use xlink:href="../img/sprite.svg#icon-eye-open"></use>
                                        </svg>
                                        <a href="banned_ips.php?a=ban&amp;track='.$trackingID.'&amp;ip='.urlencode($ticket['ip']).'&amp;token='.hesk_token_echo(0).'">'.$hesklang['savebanip'].'</a>
                                    ';
                                            }
                                        }
                                        echo '</li>';
                                    }

                                    if ($customer['email'] != '' && $can_mute_emails) {
                                        echo '<li class="separator"></li>';
                                        echo '<li>';
                                        if ( $email_id = hesk_isMutedEmail($customer['email']) ) {
                                            if ($can_unmute_emails) {
                                                echo '
                                        <svg class="icon icon-unmute">
                                            <use xlink:href="../img/sprite.svg#icon-unmute"></use>
                                        </svg>
                                        <a href="muted_emails.php?a=unmute&amp;track='.$trackingID.'&amp;id='.intval($email_id).'&amp;token='.hesk_token_echo(0).'">'.$hesklang['unmute_email'].'</a>
                                    ';
                                            } else {
                                                echo $hesklang['eis_mute'];
                                            }
                                        } else {
                                            echo '
                                    <svg class="icon icon-mute">
                                        <use xlink:href="../img/sprite.svg#icon-mute"></use>
                                    </svg>
                                    <a href="muted_emails.php?a=mute&amp;track='.$trackingID.'&amp;email='.urlencode($customer['email']).'&amp;token='.hesk_token_echo(0).'">'.$hesklang['save_mute_email'].'</a>
                                ';
                                        }
                                        echo '</li>';
                                    }
                                    ?>
                                </ul>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php
            foreach ($hesk_settings['custom_fields'] as $k=>$v)
            {
                if ($v['use'] && $v['place']==0 && (strlen($ticket[$k]) || hesk_is_custom_field_in_category($k, $ticket['category'])) )
                {

                    switch ($v['type'])
                    {
                        case 'email':
                            $ticket[$k] = '<a href="mailto:'.$ticket[$k].'" aria-label="Mail to">'.$ticket[$k].'</a>';
                            break;
                    }

                    echo '
					<div>
                        <span class="custom-field-title">'.$v['name:'].'</span>
                        <span>'.$ticket[$k].'</span>
					</div>';
                }
            }

            if ($ticket['message_html'] != '')
            {
                ?>
                <div class="block--description browser-default">
                    <p><?php echo $ticket['message_html']; ?></p>
                    <p></p>
                </div>
                <?php
            }

            /* custom fields after message */
            foreach ($hesk_settings['custom_fields'] as $k=>$v)
            {
                if ($v['use'] && $v['place'] && (strlen($ticket[$k]) || hesk_is_custom_field_in_category($k, $ticket['category'])) )
                {
                    switch ($v['type'])
                    {
                        case 'email':
                            $ticket[$k] = '<a href="mailto:'.$ticket[$k].'" aria-label="Mail to">'.$ticket[$k].'</a>';
                            break;
                    }

                    echo '
					<div>
                        <span class="custom-field-title">'.$v['name:'].'</span>
                        <span>'.$ticket[$k].'</span>
					</div>';
                }
            }

            /* Print attachments */
            hesk_listAttachments($ticket['attachments'], 0 , $i);

            // Show suggested KB articles
            if ($hesk_settings['kb_enable'] && $hesk_settings['kb_recommendanswers'] && ! empty($ticket['articles']) )
            {
                $suggested = array();
                $suggested_list = '';

                // Get article info from the database
                $articles = hesk_dbQuery("SELECT `id`,`subject` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `id` IN (".preg_replace('/[^0-9\,]/', '', $ticket['articles']).")");
                while ($article=hesk_dbFetchAssoc($articles))
                {
                    $suggested[$article['id']] = '<a href="../knowledgebase.php?article='.$article['id'].'">'.$article['subject'].'</a>';
                }

                // Loop through the IDs to preserve the order they were suggested in
                $articles = explode(',', $ticket['articles']);
                foreach ($articles as $article)
                {
                    if ( isset($suggested[$article]) )
                    {
                        $suggested_list .= $suggested[$article];
                    }
                }

                // Finally print suggested articles
                if ( strlen($suggested_list) )
                {
                    ?>
                    <div class="block--suggested">
                        <b><?php echo $hesklang['taws']; ?></b>
                        <?php
                        if ($_SESSION['show_suggested']){
                            echo $suggested_list;
                        } else {
                            echo '<a href="Javascript:void(0)" onclick="hesk_toggleLayerDisplay(\'suggested_articles\', \'flex\')">'.$hesklang['sska'].'</a>
                                        <span id="suggested_articles" style="display:none">'.$suggested_list.'</span>';
                        }
                        ?>
                    </div>
                    <?php
                }
            }
            ?>

            <?php if ( ! $hesk_settings['new_top']): ?>
            <div class="block--notes">
                <?php
                $res = hesk_dbQuery("SELECT t1.*, t2.`name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."notes` AS t1 LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."users` AS t2 ON t1.`who` = t2.`id` WHERE `ticket`='".intval($ticket['id'])."' ORDER BY t1.`id` " . ($hesk_settings['new_top'] ? 'DESC' : 'ASC') );
                while ($note = hesk_dbFetchAssoc($res)) {
                    ?>
                    <div class="note">
                        <div class="note__head">
                            <div class="name">
                                <?php echo $hesklang['noteby']; ?>
                                <b><?php echo ($note['name'] ? $note['name'] : $hesklang['e_udel']); ?></b>
                                &raquo;
                                <time class="timeago tooltip" datetime="<?php echo date("c", strtotime($note['dt'])) ; ?>" title="<?php echo hesk_date($note['dt'], true); ?>"><?php echo hesk_date($note['dt'], true); ?></time>
                            </div>
                            <?php
                            if ($can_del_notes || $note['who'] == $_SESSION['id'])
                            {
                            ?>
                            <?php $delnote_modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'], $hesklang['delnote'].'?', 'admin_ticket.php?track='.$trackingID.'&amp;Refresh='.mt_rand(10000,99999).'&amp;delnote='.$note['id'].'&amp;token='.hesk_token_echo(0)); ?>
                            <div class="actions">
                                <a class="tooltip" href="edit_note.php?track=<?php echo $trackingID; ?>&amp;Refresh=<?php echo mt_rand(10000,99999); ?>&amp;note=<?php echo $note['id']; ?>&amp;token=<?php hesk_token_echo(); ?>" title="<?php echo $hesklang['ednote']; ?>">
                                    <svg class="icon icon-edit-ticket">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-edit-ticket"></use>
                                    </svg>
                                </a>
                                <a class="tooltip" href="javascript:" data-modal="[data-modal-id='<?php echo $delnote_modal_id; ?>']" title="<?php echo $hesklang['delnote']; ?>">
                                    <svg class="icon icon-delete">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-delete"></use>
                                    </svg>
                                </a>
                            </div>
                            <?php } ?>
                        </div>
                        <div class="note__description">
                            <p><?php echo $note['message']; ?></p>
                        </div>
                        <div class="note__attachments">
                            <?php
                            // Attachments
                            if ( $hesk_settings['attachments']['use'] && strlen($note['attachments']) )
                            {
                                echo strlen($note['message']) ? '<br>' : '';

                                $att = explode(',', substr($note['attachments'], 0, -1) );
                                $num = count($att);
                                $div_id = "d" . mt_rand(100000,999999);
                                $att_ids = array();
                                foreach ($att as $myatt)
                                {
                                    list($att_id, $att_name) = explode('#', $myatt);
                                    $att_ids[] = $att_id;

                                    // Can edit and delete note (attachments)?
                                    if ($can_del_notes || $note['who'] == $_SESSION['id'])
                                    {
                                        if ($num > 2){
                                            echo '<div class="checkbox-custom d-inline-flex">
                                                <input type="checkbox" id="attachment_note_'.$att_id.'" name="id[]" value="'.$att_id.'" class="group attach_check group_'.$div_id.'" data-id="'.$div_id.'" data-note='.$note['id'].' data-token='.hesk_token_echo(0).' data-track='.$trackingID.' data-flag="note">
                                                <label for="attachment_note_'.$att_id.'">&nbsp;</label>
                                            </div>';
                                        }
                                        // If this is the last attachment and no message, show "delete ticket" link
                                        if ($num == 1 && strlen($note['message']) == 0)
                                        {
                                            echo '<a class="tooltip" data-ztt_vertical_offset="0" style="margin-right: 8px;" href="admin_ticket.php?delnote='.$note['id'].'&amp;track='.$trackingID.'&amp;Refresh='.mt_rand(10000,99999).'&amp;token='.hesk_token_echo(0).'" onclick="return hesk_confirmExecute(\''.hesk_makeJsString($hesklang['pda']).'\');" title="'.$hesklang['dela'].'">
                                                    <svg class="icon icon-delete" style="text-decoration: none; vertical-align: text-bottom;">
                                                        <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-delete"></use>
                                                    </svg>
                                                </a> &raquo;';
                                        }
                                        // Show "delete attachment" link
                                        else
                                        {
                                            echo '<a class="tooltip" data-ztt_vertical_offset="0" style="margin-right: 8px;" href="admin_ticket.php?delatt='.$att_id.'&amp;note='.$note['id'].'&amp;track='.$trackingID.'&amp;Refresh='.mt_rand(10000,99999).'&amp;token='.hesk_token_echo(0).'" onclick="return hesk_confirmExecute(\''.hesk_makeJsString($hesklang['pda']).'\');" title="'.$hesklang['dela'].'">
                                                    <svg class="icon icon-delete" style="vertical-align: text-bottom;">
                                                        <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-delete"></use>
                                                    </svg>
                                                </a> &raquo;';
                                        }
                                    }

                                    echo '
                                    <a href="download_attachment.php?att_id='.$att_id.'&amp;track='.$trackingID.'" title="'.$hesklang['dnl'].' '.$att_name.'">
                                        <svg class="icon icon-attach" style="vertical-align: text-bottom;">
                                            <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-attach"></use>
                                        </svg>
                                    </a>
                                    <a class="underline" href="download_attachment.php?att_id='.$att_id.'&amp;track='.$trackingID.'" title="'.$hesklang['dnl'].' '.$att_name.'">'.$att_name.'</a><br>
                                    ';
                                }
                                if (count($att) > 0 && class_exists('ZipArchive')) {
                                    if (count($att_ids) > 2) {
                                        $html = '';
                                        $html = '<p id="'.$div_id.'" class="d-inline-flex">';
                                        $html .= '<a class="underline" title="'.$hesklang['download_all'].'" href="../download_all.php?att_id='.implode(',', $att_ids).'&amp;track='.$trackingID.'" onclick="document.getElementById(\''.$div_id.'\').innerHTML=\''.hesk_makeJsString($hesklang['download_prep']).'\'">'.$hesklang['download_all'].'</a>';
                                        $html .= '<a class="underline ds ds_'.$div_id.' dwn_'.$div_id.' d_hide ml-10" title="'.$hesklang['download_selected'].'" href="" onclick="document.getElementById(\''.$div_id.'\').innerHTML=\''.hesk_makeJsString($hesklang['download_prep']).'\'">'.$hesklang['download_selected'].'</a> ';
                                        if ($can_edit && $can_delete) {
                                            $html .= '<a class="underline ds ds_'.$div_id.' del_'.$div_id.' d_hide ml-10" title="'.$hesklang['delete_selected'].'" href="" onclick="return hesk_confirmExecute(\''.hesk_makeJsString($hesklang['pda']).'\');">'.$hesklang['delete_selected'].'</a>';
                                        }
                                        $html .= '</p>';
                                        echo $html;
                                    } else {
                                        echo '<p id="'.$div_id.'"><a class="underline" title="'.$hesklang['download_all'].'" href="../download_all.php?att_id='.implode(',', $att_ids).'&amp;track='.$trackingID.'" onclick="document.getElementById(\''.$div_id.'\').innerHTML=\''.hesk_makeJsString($hesklang['download_prep']).'\'">'.$hesklang['download_all'].'</a></p>';
                                    }
                                }
                            }
                            ?>
                        </div>
                    </div>
                    <?php
                }
                ?>
                <button class="btn btn--blue-border" type="button" onclick="hesk_toggleLayerDisplay('notesDiv')">
                    <svg class="icon icon-note">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-note"></use>
                    </svg>&nbsp;&nbsp;
                    <?php echo $hesklang['add_a_note']; ?>
                </button>
                <div id="notesDiv" style="display:<?php echo isset($_SESSION['note_message']) ? 'block' : 'none'; ?>; margin-top: 20px">
                    <form id="notesform" method="post" action="admin_ticket.php" class="form" enctype="multipart/form-data" aria-label="<?php echo $hesklang['notes']; ?>">
                        <i><?php echo $hesklang['nhid']; ?></i><br>
                        <textarea class="form-control" name="notemsg" rows="6" cols="60" style="height: auto; resize: vertical; transition: none;"><?php echo isset($_SESSION['note_message']) ? stripslashes(hesk_input($_SESSION['note_message'])) : ''; ?></textarea>
                        <?php
                        // attachments
                        if ($hesk_settings['attachments']['use'])
                        {
                        ?>
                            <div class="attachments">
                                <div class="block--attach">
                                    <svg class="icon icon-attach">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-attach"></use>
                                    </svg>
                                    <div>
                                        <?php echo $hesklang['attachments'] . ':<br>'; ?>
                                    </div>
                                </div>
                                <?php
                                require_once(HESK_PATH . 'inc/attachments.inc.php');
                                build_dropzone_markup(true, 'notesFiledrop');
                                display_dropzone_field(HESK_PATH . 'upload_attachment.php', true, 'notesFiledrop');
                                dropzone_display_existing_files(hesk_SESSION_array('note_attachments'), 'notesFiledrop');
                                ?>
                            </div>
                        <?php
                        }
                        ?>
                        <button type="submit" class="btn btn-full">
                            <?php echo $hesklang['sub_note']; ?>
                        </button>
                        <input type="hidden" name="track" value="<?php echo $trackingID; ?>">
                        <input type="hidden" id="time_worked_notes" name="time_worked_notes" value="">
                        &nbsp;
                        <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                    </form>
                    <?php
                    // Track time worked?
                    if ($hesk_settings['time_worked']) {
                        ?>
                            <script>
                                $('#notesform').submit(function() {
                                     $('#time_worked_notes').val($('#time_worked').val());
                                });
                            </script>
                        </section>
                        <?php
                    }
                    ?>
                </div>
            </div>
            <?php endif; ?>
        </article>
        <?php

        if ( ! $hesk_settings['new_top'])
        {
            hesk_printTicketReplies();
        }

        /* Reply form on bottom? */
        if ($can_reply && ! $hesk_settings['reply_top'])
        {
            hesk_printReplyForm();
        }

        $random=rand(10000,99999);

        // Prepare one-click action to open/resolve a ticket
        $status_action = '';
        if ($ticket['status'] == 3)
        {
            if ($can_reply)
            {
                $status_action = '[<a href="change_status.php?track='.$trackingID.'&amp;s=1&amp;Refresh='.$random.'&amp;token='.hesk_token_echo(0).'">'.$hesklang['open_action'].'</a>]';
            }
        }
        elseif ($can_resolve)
        {
            $status_action = '[<a href="change_status.php?track='.$trackingID.'&amp;s=3&amp;Refresh='.$random.'&amp;token='.hesk_token_echo(0).'">'.$hesklang['close_action'].'</a>]';
        }
        ?>
    </div>
    <div class="ticket__params" <?php echo ($hesk_settings['limit_width'] ? 'style="max-width:'.$hesk_settings['limit_width'].'px"' : ''); ?>>
        <section class="params--bar" style="padding-left: 0">
            <?php echo hesk_getAdminButtons(); ?>
        </section>
        <section class="params--block params">
            <!-- Ticket status -->
            <div class="row ts" id="ticket-status-div" <?php echo strlen($status_action) ? 'style="margin-bottom: 10px;"' : ''; ?>>
                <div class="title"><label for="select_s"><?php echo $hesklang['ticket_status']; ?>:</label></div>
                <?php if ($can_reply): ?>
                <div class="value dropdown-select center out-close">
                    <form action="change_status.php" method="post" aria-label="<?php echo $hesklang['ticket_status']; ?>">
                        <select id="select_s" name="s" onchange="this.form.submit()">
                            <?php echo hesk_get_status_select('', $can_resolve, $ticket['status']); ?>
                        </select>
                        <input type="hidden" name="track" value="<?php echo $trackingID; ?>">
                        <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                    </form>
                </div>
                <?php else: ?>
                <div class="value center">
                    <?php echo hesk_get_admin_ticket_status($ticket['status']); ?>
                </div>
                <?php
                endif;
                ?>
            </div>

            <!-- Ticket one click open/resolve -->
            <?php if (strlen($status_action)): ?>
            <div class="row">
                <div class="title">&nbsp;</div>
                <div class="value center out-close">
                    <?php echo $status_action; ?>
                </div>
            </div>
            <?php
            endif;
            ?>

            <!-- Ticket category -->
            <div class="row">
                <div class="title">
                    <label for="select_category">
                        <?php echo $hesklang['category']; ?>:
                    </label>
                </div>
                <?php if (strlen($categories_options) && ($can_change_cat || $can_change_own_cat)): ?>
                <form action="move_category.php" method="post" aria-label="<?php echo $hesklang['category']; ?>">
                    <div class="value dropdown-select center out-close">
                        <select id="select_category" name="category" onchange="this.form.submit()">
                            <?php echo $categories_options; ?>
                        </select>
                    </div>
                    <input type="hidden" name="track" value="<?php echo $trackingID; ?>">
                    <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                </form>
                <?php else: ?>
                <div class="value center out-close">
                    <?php echo $category['name']; ?>
                </div>
                <?php
                endif;
                ?>
            </div>

            <!-- Ticket priority -->
            <div class="row">
                <div class="title">
                    <label for="select_priority">
                        <?php echo $hesklang['priority']; ?>:
                    </label>
                </div>
                <?php if ($can_reply): ?>
                <form action="priority.php" method="post" aria-label="<?php echo $hesklang['priority']; ?>">
                    <div class="dropdown-select center out-close priority select-priority">
                        <select id="select_priority" name="priority" onchange="this.form.submit()">
                            <?php echo implode('', $options); ?>
                        </select>
                    </div>
                    <input type="hidden" name="track" value="<?php echo $trackingID; ?>">
                    <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                </form>
                <?php else: ?>
                <div class="value center out-close">
                    <?php
                    foreach ($hesk_settings['priorities'] as $key => $value) {
                        if($ticket['priority'] == $value['id']){
                            $data_style ='border-top-color:'.$value['color'].';border-left-color:'.$value['color'].';border-bottom-color:'.$value['color'].';';
                            ?>
                            <span class=""> <div class='priority_img' style='<?php echo $data_style; ?>'></div> <?php echo $value['name']; ?></span>
                            <?php
                        }
                    }
                    ?>
                </div>
                <?php endif; ?>
            </div>

            <!-- Ticket assigned to -->
            <div class="row">
                <div class="title">
                    <label for="select_owner">
                        <?php echo $hesklang['assigned_to']; ?>:
                    </label>
                </div>
                <?php if ($can_assign_others): ?>
                <form action="assign_owner.php" method="post" aria-label="<?php echo $hesklang['asst2']; ?>">
                    <div class="value dropdown-select center out-close">
                        <select id="select_owner" name="owner" onchange="this.form.submit()" data-append-icon-class="icon-person">
                            <option value="-1"> &gt; <?php echo $hesklang['unas']; ?> &lt; </option>
                            <?php
                            foreach ($admins as $k=>$v)
                            {
                                echo '<option value="'.$k.'" '.($k == $ticket['owner'] ? 'selected' : '').'>'.$v.'</option>';
                            }
                            ?>
                        </select>
                        <input type="hidden" name="track" value="<?php echo $trackingID; ?>">
                        <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                        <?php
                        if (!$ticket['owner'])
                        {
                            echo '<input type="hidden" name="unassigned" value="1">';
                        }
                        ?>
                    </div>
                </form>
                <?php else: ?>
                <div class="value center out-close">
                    <?php
                    echo isset($admins[$ticket['owner']]) ? '<b>'.$admins[$ticket['owner']].'</b>' : '<b>'.$hesklang['unas'].'</b>';
                    ?>
                </div>
                <?php
                endif;
                ?>
            </div>

            <!-- Ticket one click assign to self -->
            <?php if (!$ticket['owner'] && $can_assign_self): ?>
            <div class="row">
                <div class="title">&nbsp;</div>
                <div class="value center out-close">
                    <?php echo '[<a class="link" href="assign_owner.php?track='.$trackingID.'&amp;owner='.$_SESSION['id'].'&amp;token='.hesk_token_echo(0).'&amp;unassigned=1">'.$hesklang['asss'].'</a>]'; ?>
                </div>
            </div>
            <?php
            endif;
            ?>

            <!-- Ticket collaborators -->
            <?php
            // Get existing ticket collaborators
            $collaborators = array();
            $res_w = hesk_dbQuery("SELECT `u`.`id`,`u`.`name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_collaborator` AS `w` LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."users` AS `u` ON `w`.`user_id` = `u`.`id` AND `u`.`active` = 1 WHERE `w`.`ticket_id`=".intval($ticket['id']));
            while ($collaborator = hesk_dbFetchAssoc($res_w)) {
                $collaborators[] = $collaborator;
            }

            // Get list of users who can be added as a collaborator on this ticket
            $possible_new_collaborators = array();
            foreach ($admins as $k=>$v) {
                // If the ticket is assigned to you, you cannot be a collaborator
                if ($k == $ticket['owner']) {
                    continue;
                }

                // Remove people who are already collaborators
                if (hesk_isTicketCollaborator($ticket['id'], $k)) {
                    continue;
                }

                $possible_new_collaborators[$k] = $v;
            }

            // Only display collaborators if we have existing or possible collaborators
            if (count($collaborators) || ($can_assign_others && count($possible_new_collaborators))): ?>
                <div class="row">
                    <div class="title">
                        <label for="select_user">
                            <?php echo $hesklang['collaborators']; ?>:
                        </label>
                    </div>
                    <?php if ($can_assign_others): ?>
                    <form action="collaborator.php" method="post" aria-label="<?php echo $hesklang['collaborators']; ?>">
                        <div class="value center out-close removable-list">
                        <?php foreach($collaborators as $collaborator) {
                            echo '<div class="removable-list-item">
                                    <span>' . $collaborator['name'] . '</span>
                                    <a href="collaborator.php?track='.$trackingID.'&amp;user='.intval($collaborator['id']).'&amp;token='.hesk_token_echo(0).'&amp;collaborator=0">
                                        <i class="close">
                                            <svg class="icon icon-close">
                                              <use xlink:href="'. HESK_PATH.'img/sprite.svg#icon-close"></use>
                                            </svg>
                                        </i>
                                    </a>
                                </div>';
                        }

                        if (count($possible_new_collaborators) > 0) {
                            ?>

                                <div class="dropdown-select dropdown-fit-full-width">
                                <select id="select_user" name="user" onchange="this.form.submit()" data-append-icon-class="icon-person">
                                    <option value=""> &gt; <?php echo $hesklang['add_collaborator']; ?> &lt; </option>
                                    <?php
                                    foreach ($possible_new_collaborators as $k=>$v) {
                                        echo '<option value="'.$k.'">'.$v.'</option>';
                                    }
                                    ?>
                                </select>
                                <input type="hidden" name="collaborator" value="1">
                                <input type="hidden" name="track" value="<?php echo $trackingID; ?>">
                                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                                </div>
                            </div>
                        </form>
                        <?php
                    }
                    ?>
                    <?php else: ?>
                    <div class="value center out-close removable-list">
                        <?php foreach($collaborators as $collaborator) {
                            echo '<div class="removable-list-item">
                                    <span>' . $collaborator['name'] . '</span>
                                </div>';
                        }
                        ?>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- Collaborate link -->
                <?php if (empty($ticket['am_I_collaborator']) && $ticket['owner'] != $_SESSION['id']): ?>
                <div class="row">
                    <div class="title">&nbsp;</div>
                    <div class="value center out-close">
                        <?php echo '[<a class="link" href="admin_ticket.php?track='.$trackingID.'&amp;token='.hesk_token_echo(0).'&amp;collaborator=1">'.$hesklang['collaborate'].'</a>]'; ?>
                    </div>
                </div>
                <?php endif; ?>
            <?php endif; ?>
        </section>
        <section class="params--block details accordion visible">
            <h4 class="accordion-title">
                <span><?php echo $hesklang['ticket_details']; ?></span>
                <svg class="icon icon-chevron-down">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                </svg>
            </h4>
            <div class="accordion-body" style="display:block">
                <div class="row">
                    <div class="title"><?php echo $hesklang['trackID']; ?>:</div>
                    <div class="value"><?php echo $trackingID; ?>
                    <a href="javascript:" title="<?php echo $hesklang['copy_value']; ?>" onclick="navigator.clipboard.writeText('<?php echo $trackingID; ?>');$('#copy-tid').addClass('copied');setTimeout(function(){$('#copy-tid').removeClass('copied')}, 150);">
                        <svg class="icon icon-merge copy-me" id="copy-tid">
                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-merge"></use>
                        </svg>
                    </a>
                    </div>
                </div>
                <div class="row">
                    <div class="title">&nbsp;</div>
                    <div class="value">
                        <a class="tooltip" href="javascript:"
                           title="<?php echo $hesklang['copy_link_title']; ?>"
                           data-action="generate-link"
                           data-link="<?php echo htmlspecialchars($hesk_settings['hesk_url']) . '/ticket.php?track='.urlencode($trackingID).'&e='.urlencode(strpos($requester['email'], ',') ? strstr($requester['email'], ',', true) : $requester['email']); ?>">
                           <?php echo $hesklang['copy_link']; ?>
                        </a>
                        <div role="status" class="notification-flash green" data-type="link-generate-message">
                            <i class="close">
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                            </i>
                            <div class="notification--title error-title"><?php echo $hesklang['genl_not_copied']; ?></div>
                            <div class="notification--title"><?php echo $hesklang['genl']; ?></div>
                            <div class="notification--text"><?php echo $hesklang['copy_link_exp']; ?></div>
                        </div>
                    </div>
                </div>
                <?php
                if ($hesk_settings['sequential'])
                {
                    ?>
                    <div class="row">
                        <div class="title"><?php echo $hesklang['seqid']; ?>:</div>
                        <div class="value"><?php echo $ticket['id']; ?></div>
                    </div>
                    <?php
                }
                ?>
                <div class="row">
                    <div class="title"><?php echo $hesklang['created_on']; ?>:</div>
                    <div class="value"><?php echo hesk_date($ticket['dt'], true); ?></div>
                </div>
                <div class="row">
                    <div class="title"><?php echo $hesklang['last_update']; ?>:</div>
                    <div class="value"><?php echo hesk_date($ticket['lastchange'], true); ?></div>
                </div>
                <div class="row">
                    <div class="title"><?php echo $hesklang['replies']; ?>:</div>
                    <div class="value"><?php echo $ticket['replies']; ?></div>
                </div>
                <div class="row">
                    <div class="title"><?php echo $hesklang['last_replier']; ?>:</div>
                    <div class="value"><?php echo $ticket['repliername']; ?></div>
                </div>
                <?php
                if ($hesk_settings['time_worked'])
                {
                ?>
                <div class="row">
                    <div class="title"><?php echo $hesklang['ts']; ?>:</div>
                    <?php
                    if ($can_reply || $can_edit)
                    {
                        ?>
                    <div class="value">
                        <a href="javascript:" onclick="hesk_toggleLayerDisplay('modifytime')">
                            <?php echo $ticket['time_worked']; ?>
                        </a>

                        <?php $t = hesk_getHHMMSS($ticket['time_worked']); ?>

                        <div id="modifytime" style="display:none">
                            <form class="form" method="post" action="admin_ticket.php" aria-label="<?php echo $hesklang['ts']; ?>">
                                <div class="form-group">
                                    <label for="hours"><?php echo $hesklang['hh']; ?></label>
                                    <input class="form-control" type="text" id="hours" name="h" value="<?php echo $t[0]; ?>" autocomplete="off">
                                </div>
                                <div class="form-group">
                                    <label for="minutes"><?php echo $hesklang['mm']; ?></label>
                                    <input class="form-control" type="text" id="minutes" name="m" value="<?php echo $t[1]; ?>" autocomplete="off">
                                </div>
                                <div class="form-group">
                                    <label for="seconds"><?php echo $hesklang['ss']; ?></label>
                                    <input class="form-control" type="text" id="seconds" name="s" value="<?php echo $t[2]; ?>" autocomplete="off">
                                </div>

                                <button style="display: inline-flex; width: auto; height: 40px; padding: 0 16px; margin-bottom: 5px;" class="btn btn-full" type="submit"><?php echo $hesklang['save']; ?></button>
                                <a class="btn btn--blue-border" href="Javascript:void(0)" onclick="Javascript:hesk_toggleLayerDisplay('modifytime')"><?php echo $hesklang['cancel']; ?></a>
                                <input type="hidden" name="track" value="<?php echo $trackingID; ?>" />
                                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
                            </form>
                        </div>
                    </div>
                        <?php
                    }
                    else
                    {
                        echo '<div class="value">' . $ticket['time_worked'] . '</div>';
                    }
                    ?>
                </div>
                <?php
                }
                ?>
                <div class="row">
                    <div class="title"><?php echo $hesklang['due_date']; ?></div>
                    <?php
                    $hesk_settings['datepicker'] = array();
                    $due_date = $hesklang['none'];
                    $datepicker_due_date = '';
                    if ($ticket['due_date'] != null) {
                        $datepicker_due_date = hesk_date($ticket['due_date'], true, true, false);
                        $hesk_settings['datepicker']['#new-due-date']['timestamp'] = $datepicker_due_date;
                        $due_date = hesk_format_due_date($datepicker_due_date, false);
                        $datepicker_due_date = hesk_datepicker_format_date($datepicker_due_date);
                    }

                    if ($can_due_date)
                    {
                        $hesk_settings['datepicker']['#new-due-date']['position'] = 'left bottom';
                        ?>
                        <div class="value">
                            <a href="javascript:" onclick="hesk_toggleLayerDisplay('modifyduedate')" class="showme" id="toggleDP">
                                <?php echo $due_date; ?>
                            </a>
                            <div id="modifyduedate" style="display:none">
                                <form class="form" method="post" action="admin_ticket.php" aria-label="<?php echo $hesklang['due_date']; ?>">
                                    <section class="param calendar">
                                        <div class="calendar--button" id="due-date-button">
                                            <!--
                                            <button type="button">
                                                <svg class="icon icon-calendar">
                                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-calendar"></use>
                                                </svg>
                                            </button>
                                            -->
                                            <input name="new-due-date" id="new-due-date"
                                                   data-datepicker-position="left top"
                                                   value="<?php echo $datepicker_due_date; ?>"
                                                   type="text" class="datepicker" aria-label="<?php echo $hesklang['due_date']; ?>">
                                        </div>
                                        <div class="calendar--value pt10 pb10" style="<?php echo $datepicker_due_date == '' ? '' : 'display: block'; ?>;">
                                            <span><?php echo $datepicker_due_date; ?></span>
                                            <i class="close">
                                                <svg class="icon icon-close">
                                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                                </svg>
                                            </i>
                                        </div>
                                    </section>
                                    <button style="display: inline-flex; width: auto; height: 40px; padding: 0 16px; margin-bottom: 5px;" class="btn btn-full" type="submit"><?php echo $hesklang['save']; ?></button>
                                    <a class="btn btn--blue-border" href="Javascript:void(0)" onclick="Javascript:hesk_toggleLayerDisplay('modifyduedate')"><?php echo $hesklang['cancel']; ?></a>
                                    <input type="hidden" name="track" value="<?php echo $trackingID; ?>" />
                                    <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
                                    <input type="hidden" name="action" value="due_date">
                                </form>
                            </div>
                        </div>
                        <?php
                    } else {
                        ?>
                        <div class="value">
                            <?php echo $due_date; ?>
                        </div>
                        <?php
                    }
                    ?>
                </div>
            </div>
        </section>
        <?php
        // Display previous tickets
        if (!empty($customers) && !empty($customers[0]['email']))
        {
            // How many previous tickets should we show?
            $show_previous_tickets = 5;

            $first_customer = $customers[0];

            // Get recent tickets, ordered by last change
            if ($hesk_settings['customer_accounts'] == 0 || $hesk_settings['customer_accounts_required'] == 0) {
                $res = hesk_dbQuery("SELECT `trackid`, `status`, `subject` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` `tickets`
                    WHERE ".hesk_myCategories()."
                        AND ".hesk_myOwnership()."
                        AND `tickets`.`id` <> ".$ticket['id']."
                        AND `tickets`.`id` IN (
                            SELECT `ticket_id`
                            FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_customer` AS `ticket_to_customer`
                            INNER JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` AS `customer`
                            ON `ticket_to_customer`.`customer_id` = `customer`.`id`
                            AND `customer`.`email`  LIKE '%".hesk_dbEscape($first_customer['email'])."%'
                        )
                    ORDER BY `lastchange` DESC
                    LIMIT " . ($show_previous_tickets+1));
            } else {
                $res = hesk_dbQuery("SELECT `trackid`, `status`, `subject` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` `tickets`
                    WHERE ".hesk_myCategories()."
                        AND ".hesk_myOwnership()."
                        AND `tickets`.`id` <> ".$ticket['id']."
                        AND EXISTS (
                            SELECT 1
                            FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_customer`
                            WHERE `ticket_id` = `tickets`.`id`
                            AND `customer_id` = ".intval($first_customer['id'])."
                        )
                    ORDER BY `lastchange` DESC
                    LIMIT " . ($show_previous_tickets+1));
            }

            $past_num = hesk_dbNumRows($res);
            ?>
            <section class="params--block details accordion <?php if ($past_num > 0) echo 'visible'; ?>">
                <h4 class="accordion-title">
                    <span><?php echo $hesklang['previous_tickets']; ?></span>
                    <svg class="icon icon-chevron-down">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                    </svg>
                </h4>
                <div class="accordion-body" <?php if ($past_num > 0) echo 'style="display:block"'; ?>>
                    <?php
                    $i = 0;
                    while ($past_ticket = hesk_dbFetchAssoc($res)) {
                        $i++;
                        if ($i > $show_previous_tickets) {
                            hesk_dbFreeResult($res);
                            break;
                        }
                        ?>
                        <div>
                            <?php if (isset($hesk_settings['statuses'][$past_ticket['status']]['class'])): ?>
                                <span class="dot bg-<?php echo $hesk_settings['statuses'][$past_ticket['status']]['class']; ?>" title="<?php echo $hesk_settings['statuses'][$past_ticket['status']]['name']; ?>"></span>
                            <?php else: ?>
                                <span class="dot" style="background-color:<?php echo $hesk_settings['statuses'][$past_ticket['status']]['color']; ?>" title="<?php echo $hesk_settings['statuses'][$past_ticket['status']]['name']; ?>"></span>
                            <?php endif; ?>
                            <a href="admin_ticket.php?track=<?php echo $past_ticket['trackid']; ?>&amp;Refresh=<?php echo rand(10000,99999); ?>"><?php echo $past_ticket['subject']; ?></a>
                        </div>
                        <?php
                    }

                    if ($past_num > 0 && $i > $show_previous_tickets) {
                        echo '<br><a href="find_tickets.php?q='.urlencode($first_customer['email']).'&amp;what=email&amp;s_my=1&amp;s_ot=1&amp;s_un=1">'.$hesklang['all_previous'].'</a>';
                    } elseif ($past_num == 0) {
                        echo sprintf($hesklang['no_previous'], hesk_htmlspecialchars($first_customer['email']));
                    }
                    ?>
                </div>
            </section>
            <?php
        }
        // Display linked tickets

        if (count($customers)) {
            $result = getLinkedTickets($customers, $ticket);
            $linked_num = $result['linked_num'];
            $res = $result['res'];
            $show_linked_tickets = $result['show_linked_tickets'];
            ?>
            <section class="params--block details accordion <?php if ($linked_num > 0) echo 'visible'; ?>">
                <h4 class="accordion-title">
                    <span><?php echo $hesklang['linked_tickets']; ?></span>
                    <svg class="icon icon-chevron-down">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                    </svg>
                </h4>
                <div class="accordion-body" <?php if ($linked_num > 0) echo 'style="display:block"'; ?>>
                    <div class="custom_ajax_msg"></div>
                    <div class="linked_html_view mb-10">
                        <?php
                            // get html view of linked ticket
                            echo getLinkedHtml($customers, $ticket, $can_link_tickets);
                        ?>
                    </div>
                    <?php 
                        if ($can_link_tickets) {
                    ?>        
                        <div class="show_link_a_ticket">
                            <a href="javascript:;" class="href_show_linked"><?php echo $hesklang['link_a_ticket'];?></a>
                        </div>
                        <div class="show_linked_form d_hide">
                            <form method="post" class="form" action="admin_ticket.php?track=<?php echo $trackingID; ?>&amp;Refresh=<?php echo rand(10000,99999); ?>" name="linked_ticket" id="linked_ticket" aria-label="<?php echo $hesklang['link_a_ticket']; ?>">
                                <div class="form-group">
                                    <label for="ticket_track_id">
                                        <?php echo $hesklang['link_id']; ?>: <span class="important">*</span>
                                    </label>
                                    <input type="text" name="ticket_track_id" class="form-control" id="ticket_track_id" maxlength="100" value="">
                                </div>
                                <input type="hidden" name="token" id="linked_token" value="<?php hesk_token_echo(); ?>">
                                <input type="hidden" name="action_type" value="linked_ticket">
                                <div class="d-inline-flex">
                                    <button class="btn btn-full linked" type="button" ripple="ripple"><?php echo $hesklang['link_ticket']; ?></button>
                                    <button class="btn btn--blue-border cancel ml-10" type="button" ripple="ripple"><?php echo $hesklang['cancel']; ?></button>
                                </div>    
                            </form>
                        </div>
                    <?php
                        }
                    ?>

                </div>
            </section>
            <?php
        } // END if count($customers)

        /* Display ticket history */
        if (strlen($ticket['history']))
        {
            $history_pieces = explode('</li>', $ticket['history'], -1);

            ?>
            <section class="params--block history accordion">
                <h4 class="accordion-title">
                    <span><?php echo $hesklang['thist']; ?></span>
                    <svg class="icon icon-chevron-down">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                    </svg>
                </h4>
                <div class="accordion-body history_html_view">
                    <?php
                        // get ticket history view
                        echo getTicketHistory($history_pieces);
                    ?>
                </div>
            </section>
            <?php
        }
        ?>
    </div>
</div>

<a href="#" class="back-to-top"><?php echo $hesklang['btt']; ?></a>
<div id="loading-overlay" class="loading-overlay">
    <div id="loading-message" class="loading-message">
        <div class="spinner"></div>
        <p><?php echo $hesklang['sending_wait']; ?></p>
    </div>
</div>

<script>
// Delete Selected and Download Selected
$('body').on('change','.attach_check', function() {
    let id = $(this).attr('data-id');
    let flag = $(this).attr('data-flag');
    let atr = natr = '';
    let track = $('input[name="track"]').val();
    // Check if the checkbox is currently checked
    $('.ds').removeClass('d_show').addClass('d_hide');
    $('.attach_check:checked').each(function() {
        // Unchecked other group attachment
        if (!$(this).hasClass('group_'+id)) {
            $(this).prop('checked', false);
        }
    });
    $('.attach_check:checked').each(function() {
        // If checked, show the button container
        $('.ds_'+id).removeClass('d_hide').addClass('d_show');
        atr += $(this).val()+',';
    });
    if(atr.length > 0){
        natr = atr.replace(/,$/, '');
    }
    let del_url,dwn_url;
    if(flag == 'reply'){
        let reply = $(this).attr('data-reply');
        let token = $(this).attr('data-token');
        del_url = 'admin_ticket.php?delatt='+natr+'&track='+track+'&'+flag+'='+reply+'&token='+token;
        dwn_url = '../download_all.php?att_id='+natr+'&track='+track+'&flag=selected&'+flag+'='+reply+'&token='+token;
    }else if(flag == 'note'){
        let note = $(this).attr('data-note');
        let token = $(this).attr('data-token');
        del_url = 'admin_ticket.php?delatt='+natr+'&track='+track+'&'+flag+'='+note+'&token='+token;
        dwn_url = '../download_all.php?att_id='+natr+'&track='+track+'&flag=selected&'+flag+'='+note+'&token='+token;
    }
    $('.del_'+id).attr('href',del_url);
    $('.dwn_'+id).attr('href',dwn_url);
});
</script>

<?php
/* Clear unneeded session variables */
hesk_cleanSessionVars('ticket_message');
hesk_cleanSessionVars('time_worked');
hesk_cleanSessionVars('note_message');
hesk_cleanSessionVars('ar_attachments');
hesk_cleanSessionVars('note_attachments');

$hesk_settings['print_status_select_box_jquery'] = true;

require_once(HESK_PATH . 'inc/footer.inc.php');


/*** START FUNCTIONS ***/


function hesk_listAttachments($attachments='', $reply=0, $white=1)
{
	global $hesk_settings, $hesklang, $trackingID, $can_edit, $can_delete;

	/* Attachments disabled or not available */
	if ( ! $hesk_settings['attachments']['use'] || ! strlen($attachments) )
    {
    	return false;
    }

	/* List attachments */
    $att_ids = array();
	$att=explode(',',substr($attachments, 0, -1));
    echo '<div class="block--uploads" style="display: block;">';
    $div_id = "d" . mt_rand(100000,999999);
	foreach ($att as $myatt)
	{
		list($att_id, $att_name) = explode('#', $myatt);
        $att_ids[] = $att_id;

        /* Can edit and delete tickets? */
        if ($can_edit && $can_delete)
        {
            if (count($att) > 2) {
                echo '<div class="checkbox-custom d-inline-flex">
                    <input type="checkbox" id="attachment_check_'.$att_id.'" name="id[]" value="'.$att_id.'" class="group attach_check group_'.$div_id.'" data-id="'.$div_id.'" data-reply='.$reply.' data-token='.hesk_token_echo(0).' data-flag="reply">
                    <label for="attachment_check_'.$att_id.'">&nbsp;</label>
                </div>';
            }
        	echo '<a class="tooltip" data-ztt_vertical_offset="0" style="margin-right: 8px;" title="'.$hesklang['dela'].'" href="admin_ticket.php?delatt='.$att_id.'&amp;reply='.$reply.'&amp;track='.$trackingID.'&amp;Refresh='.mt_rand(10000,99999).'&amp;token='.hesk_token_echo(0).'" onclick="return hesk_confirmExecute(\''.hesk_makeJsString($hesklang['pda']).'\');">
        	    <svg class="icon icon-delete" style="width: 16px; height: 16px; vertical-align: text-bottom;">
                    <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-delete"></use>
                </svg>
            </a> &raquo;';
        }

		echo '
		<a title="'.$hesklang['dnl'].' '.$att_name.'" href="download_attachment.php?att_id='.$att_id.'&amp;track='.$trackingID.'">
            <svg class="icon icon-attach" style="width: 16px; height: 16px; margin-right: 0px; vertical-align: text-bottom;">
                <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-attach"></use>
            </svg>
        </a>
		<a class="underline" title="'.$hesklang['dnl'].' '.$att_name.'" href="download_attachment.php?att_id='.$att_id.'&amp;track='.$trackingID.'">'.$att_name.'</a><br />
        ';
	}

    if (count($att_ids) > 0 && class_exists('ZipArchive')) {
        if (count($att_ids) > 2) {
            $html = '';
            $html = '<p id="'.$div_id.'" class="d-inline-flex">';
            $html .= '<a class="underline" title="'.$hesklang['download_all'].'" href="../download_all.php?att_id='.implode(',', $att_ids).'&amp;track='.$trackingID.'" onclick="document.getElementById(\''.$div_id.'\').innerHTML=\''.hesk_makeJsString($hesklang['download_prep']).'\'">'.$hesklang['download_all'].'</a>';
            $html .= '<a class="underline ds ds_'.$div_id.' dwn_'.$div_id.' d_hide ml-10" title="'.$hesklang['download_selected'].'" href="" onclick="document.getElementById(\''.$div_id.'\').innerHTML=\''.hesk_makeJsString($hesklang['download_prep']).'\'">'.$hesklang['download_selected'].'</a> ';
            if ($can_edit && $can_delete) {
                $html .= '<a class="underline ds ds_'.$div_id.' del_'.$div_id.' d_hide ml-10" title="'.$hesklang['delete_selected'].'" href="" onclick="return hesk_confirmExecute(\''.hesk_makeJsString($hesklang['pda']).'\');">'.$hesklang['delete_selected'].'</a>';
            }
            $html .= '</p>';
            echo $html;
        } else {
            echo '<p id="'.$div_id.'"><a class="underline" title="'.$hesklang['download_all'].'" href="../download_all.php?att_id='.implode(',', $att_ids).'&amp;track='.$trackingID.'" onclick="document.getElementById(\''.$div_id.'\').innerHTML=\''.hesk_makeJsString($hesklang['download_prep']).'\'">'.$hesklang['download_all'].'</a></p>';
        }
    }

    echo '</div>';

    return true;
} // End hesk_listAttachments()


function hesk_getAdminButtons($isReply=0,$white=1)
{
	global $hesk_settings, $hesklang, $ticket, $reply, $trackingID, $can_edit, $can_archive, $can_delete, $can_resolve, $can_privacy, $can_export;

	$buttons = array();

    // Edit
    if ($can_edit)
    {
        $tmp = $isReply ? '&amp;reply='.$reply['id'] : '';
        if ($isReply) {
            $buttons['more']['edit'] = '
        <a id="editreply'.$reply['id'].'" href="edit_post.php?track='.$trackingID.$tmp.'" title="'.$hesklang['btn_edit'].'" style="margin-right: 15px">
            <svg class="icon icon-edit-ticket">
                <use xlink:href="'. HESK_PATH . 'img/sprite.svg#icon-edit-ticket"></use>
            </svg>
            '.$hesklang['btn_edit'].'
        </a>';
        } else {
            $buttons[] = '
        <a id="editticket" href="edit_post.php?track='.$trackingID.$tmp.'" title="'.$hesklang['btn_edit'].'">
            <svg class="icon icon-edit-ticket">
                <use xlink:href="'. HESK_PATH . 'img/sprite.svg#icon-edit-ticket"></use>
            </svg>
            '.$hesklang['btn_edit'].'
        </a>';
        }

    }


    if (!$isReply) {
        // Print ticket button
        $buttons[] = '
        <a href="print.php?track='.$trackingID.'" title="'.$hesklang['btn_print'].'" target="_blank">
            <svg class="icon icon-print">
                <use xlink:href="' . HESK_PATH .'img/sprite.svg#icon-print"></use>
            </svg>
            '.$hesklang['btn_print'].'
        </a>';
    }


    // Lock ticket button
	if (!$isReply && $can_resolve) {
		if ($ticket['locked']) {
			$des = $hesklang['tul'] . ' - ' . $hesklang['isloc'];
            $buttons['more'][] = '
            <a id="unlock" href="lock.php?track='.$trackingID.'&amp;locked=0&amp;Refresh='.mt_rand(10000,99999).'&amp;token='.hesk_token_echo(0).'" title="'.$des.'">
                <svg class="icon icon-lock">
                    <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-lock"></use>
                </svg> 
                '.$hesklang['btn_unlock'].'
            </a>';
		} else {
			$des = $hesklang['tlo'] . ' - ' . $hesklang['isloc'];
            $buttons['more'][] = '
            <a id="lock" href="lock.php?track='.$trackingID.'&amp;locked=1&amp;Refresh='.mt_rand(10000,99999).'&amp;token='.hesk_token_echo(0).'" title="'.$des.'">
                <svg class="icon icon-lock">
                    <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-lock"></use>
                </svg>  
                '.$hesklang['btn_lock'].'
            </a>';
		}
	}

	// Tag ticket button
	if (!$isReply && $can_archive) {
		if ($ticket['archive']) {
        	$buttons['more'][] = '
        	<a id="untag" href="archive.php?track='.$trackingID.'&amp;archived=0&amp;Refresh='.mt_rand(10000,99999).'&amp;token='.hesk_token_echo(0).'" title="'.$hesklang['remove_archive'].'">
        	    <svg class="icon icon-tag">
                    <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-tag"></use>
                </svg>
                '.$hesklang['btn_untag'].'
            </a>';
		} else {
        	$buttons['more'][] = '
        	<a id="tag" href="archive.php?track='.$trackingID.'&amp;archived=1&amp;Refresh='.mt_rand(10000,99999).'&amp;token='.hesk_token_echo(0).'" title="'.$hesklang['add_archive'].'">
        	    <svg class="icon icon-tag">
                    <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-tag"></use>
                </svg>
                '.$hesklang['btn_tag'].'
            </a>';
		}
	}

    // Bookmark ticket button
    if (!$isReply) {
        if (empty($ticket['is_bookmark'])) {
            $buttons['more'][] = '
            <a id="add-bookmark" href="admin_ticket.php?track='.$trackingID.'&amp;bm_add=1&amp;Refresh='.mt_rand(10000,99999).'&amp;token='.hesk_token_echo(0).'" title="'.$hesklang['bookmarks_add'].'">
                <svg class="icon icon-pin">
                    <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-pin"></use>
                </svg>
                '.$hesklang['bookmarks_add'].'
            </a>';
        } else {
            $buttons['more'][] = '
            <a id="remove-bookmark" href="admin_ticket.php?track='.$trackingID.'&amp;bm_add=0&amp;Refresh='.mt_rand(10000,99999).'&amp;token='.hesk_token_echo(0).'" title="'.$hesklang['bookmarks_remove'].'">
                <svg class="icon icon-pin is-bookmark">
                    <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-pin"></use>
                </svg>
                '.$hesklang['bookmarks_remove'].'
            </a>';
        }
    }

	// Resend email notification button
    if (!$ticket['anonymized']) {
        $buttons['more'][] = '
        <a id="resendemail" href="resend_notification.php?track='.$trackingID.'&amp;reply='.($isReply && isset($reply['id']) ? intval($reply['id']) : 0).'&amp;Refresh='.mt_rand(10000,99999).'&amp;token='.hesk_token_echo(0).'" title="'.$hesklang['btn_resend'].'">
            <svg class="icon icon-mail-small">
                <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-mail-small"></use>
            </svg>
            '.$hesklang['btn_resend'].'
        </a>';
    }

    // Resend assigned staff email notification
    if ($ticket['owner']) {
        $buttons['more'][] = '
        <a id="remindstaff" href="resend_notification.php?track='.$trackingID.'&amp;remind=1&amp;Refresh='.mt_rand(10000,99999).'&amp;token='.hesk_token_echo(0).'" title="'.$hesklang['remind_assigned'].'">
            <svg class="icon icon-notification">
                <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-notification"></use>
            </svg>
            '.$hesklang['remind_assigned'].'
        </a>';
    }

	// Import to knowledgebase button
    if (!$isReply && $hesk_settings['kb_enable'] && hesk_checkPermission('can_man_kb',0) && !$ticket['anonymized'])
	{
		$buttons['more'][] = '
		<a id="addtoknow" href="manage_knowledgebase.php?a=import_article&amp;track='.$trackingID.'" title="'.$hesklang['import_kb'].'">
		    <svg class="icon icon-knowledge">
                <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-knowledge"></use>
            </svg>
		    '.$hesklang['btn_import_kb'].'
        </a>';
	}

    // Export ticket
    if (!$isReply && $can_export && !$ticket['anonymized'])
    {
        $buttons['more'][] = '
        <a id="exportticket" href="export_ticket.php?track='.$trackingID.'&amp;Refresh='.mt_rand(10000,99999).'&amp;token='.hesk_token_echo(0).'" title="'.$hesklang['btn_export'].'">
            <svg class="icon icon-export">
                <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-export"></use>
            </svg> 
            '.$hesklang['btn_export'].'
        </a>';
    }

    // Anonymize ticket
    if (!$isReply && $can_privacy)
    {
        $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_anony'], $hesklang['privacy_anon_info'], 'anonymize_ticket.php?track='.$trackingID.'&amp;Refresh='.mt_rand(10000,99999).'&amp;token='.hesk_token_echo(0), $hesklang['confirm']);
		$buttons['more'][] = '
		<a id="anonymizeticket" href="javascript:" title="'.$hesklang['confirm_anony'].'" data-modal="[data-modal-id=\''.$modal_id.'\']">
		    <svg class="icon icon-anonymize">
                <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-anonymize"></use>
            </svg>
             '.$hesklang['btn_anony'].'
        </a>';
    }

	// Delete ticket or reply
	if ($can_delete)
	{
		if ($isReply)
		{
			$url = 'admin_ticket.php';
			$tmp = 'delete_post='.$reply['id'];
			$txt = $hesklang['btn_delr'];
            $modal_text = $hesklang['confirm_delete_reply'];
		}
		else
		{
			$url = 'delete_tickets.php';
			$tmp = 'delete_ticket=1';
			$txt = $hesklang['btn_delt'];
            $modal_text = $hesklang['confirm_delete_ticket'];
		}
        $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'], $modal_text, $url.'?track='.$trackingID.'&amp;'.$tmp.'&amp;Refresh='.mt_rand(10000,99999).'&amp;token='.hesk_token_echo(0));
		$buttons['more'][] = '
		<a id="deleteticket" href="javascript:" title="'.$txt.'" data-modal="[data-modal-id=\''.$modal_id.'\']">
		    <svg class="icon icon-delete">
                <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-delete"></use>
            </svg>
		    '.$txt.'
        </a>';
	}

    // Format and return the HTML for buttons
    $button_code = '';

    foreach ($buttons as $button) {
        if (is_array($button)) {
            $more_class = $isReply ? 'more ' : '';
            $label = '
            <label aria-label="' . $hesklang['move_dn'] . '">
                <span>
                    <svg class="icon icon-chevron-down">
                        <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-chevron-down"></use>
                    </svg>
                </span>
            </label>
            ';

            if ($isReply) {
                $label = '
                <label aria-label="' . $hesklang['move_dn'] . '">
                    <span>' . $hesklang['btn_more'] . '</span>
                    <svg class="icon icon-chevron-down">
                        <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-chevron-down"></use>
                    </svg>
                </label>';
            }

            $button_code .= '<div class="'.$more_class.'dropdown right out-close">';
            if (isset($button['edit']))
            {
                $button_code .= $button['edit'];
                unset($button['edit']);
            }

            $button_code .= $label.'<ul class="dropdown-list">';

            foreach ($button as $sub_button) {
                $button_code .= '<li>'.$sub_button.'</li>';
            }

            $button_code .= '</ul></div>';
        } else {
            $button_code .= $button;
        }
    }

    $button_code .= '';

    return $button_code;

} // END hesk_getAdminButtons()


function print_form()
{
	global $hesk_settings, $hesklang;
    global $trackingID;

	/* Print header */
	require_once(HESK_PATH . 'inc/header.inc.php');

	/* Print admin navigation */
	require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');
	?>

    <div class="main__content categories">
        <div class="table-wrap">
            <?php
            /* This will handle error, success and notice messages */
            hesk_handle_messages();
            ?>
            <h3><?php echo $hesklang['view_existing']; ?></h3>
            <form action="admin_ticket.php" method="get" class="form" aria-label="<?php echo $hesklang['view_existing']; ?>">
                <div class="form-group">
                    <label for="find_ticket_track"><?php echo $hesklang['ticket_trackID']; ?></label>
                    <input id="find_ticket_track" class="form-control" type="text" name="track" maxlength="20" value="<?php echo $trackingID; ?>">
                </div>
                <div class="form-group">
                    <input type="submit" value="<?php echo $hesklang['view_ticket']; ?>" class="btn btn-full">
                    <input type="hidden" name="Refresh" value="<?php echo rand(10000,99999); ?>">
                </div>
            </form>
        </div>
    </div>

	<?php
	require_once(HESK_PATH . 'inc/footer.inc.php');
	exit();
} // End print_form()


function hesk_printTicketReplies() {
	global $hesklang, $hesk_settings, $result, $reply, $ticket;

	$i = $hesk_settings['new_top'] ? 0 : 1;

	if ($reply === false)
	{
		return $i;
	}

    $replies = array();
    $collapsed_replies = array();
    $displayed_replies = array();
	$last_staff_reply_index = -1;
	$i = 0;
	while ($reply = hesk_dbFetchAssoc($result)) {
        if ($reply['staffid']) {
            $reply['name'] = $reply['staff_name'] === null ?
                $hesklang['staff_deleted'] :
                $reply['staff_name'];
        } else {
            if ($reply['customer_name'] === null || $reply['customer_name'] == '') {
                if ($reply['customer_email'] !== null && strlen($reply['customer_email'])) {
                    $reply['name'] = $reply['customer_email'];
                } else {
                    $reply['name'] = $hesklang['anon_name'];
                }
            } else {
                $reply['name'] = $reply['customer_name'];
            }
        }

	    $replies[] = $reply;
        if ($reply['staffid'] && ( ! $hesk_settings['new_top'] || $last_staff_reply_index === -1)) {
	        $last_staff_reply_index = $i;
        }
	    $i++;
    }

    // Hide ticket replies?
    $i = 0;
    foreach ($replies as $reply) {
        // Show the last staff reply and any subsequent customer replies
        if ($hesk_settings['hide_replies'] == -1) {
            if ($hesk_settings['new_top']) {
                if ($i <= $last_staff_reply_index) {
                    $displayed_replies[] = $reply;
                } else {
                    $collapsed_replies[] = $reply;
                }
            } else {
                if ($i < $last_staff_reply_index) {
                    $collapsed_replies[] = $reply;
                } else {
                    $displayed_replies[] = $reply;
                }
            }
        // Hide all replies except the last X
        } elseif ($hesk_settings['hide_replies'] > 0) {
            if ($hesk_settings['new_top']) {
                if ($i >= $hesk_settings['hide_replies']) {
                    $collapsed_replies[] = $reply;
                } else {
                    $displayed_replies[] = $reply;
                }
            } else {
                if ($i < ($ticket['replies'] - $hesk_settings['hide_replies'])) {
                    $collapsed_replies[] = $reply;
                } else {
                    $displayed_replies[] = $reply;
                }
            }
        // Never, always show all replies
        } else {
            $displayed_replies[] = $reply;
        }
        $i++;
    }

    $start_previous_replies = true;
    for ($j = 0; $j < count($collapsed_replies) && $hesk_settings['new_top'] == 0; $j++) {
        $reply = $collapsed_replies[$j];
        if ($start_previous_replies):
            $start_previous_replies = false;
            ?>
            <section class="ticket__replies">
                <div class="ticket__replies_link">
                    <span><?php echo $hesklang['show_previous_replies']; ?></span>
                    <b><?php echo count($collapsed_replies); ?></b>
                    <svg class="icon icon-chevron-down">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                    </svg>
                </div>
                <div class="ticket__replies_list">
            <?php
        endif;
        ?>
        <article class="ticket__body_block <?php echo $reply['staffid'] ? 'response' : ''; ?>">
            <div class="block--head">
                <div class="contact">
                    <?php echo $hesklang['reply_by']; ?>
                    <b><?php echo $reply['name']; ?></b>
                    &raquo;
                    <time class="timeago tooltip" datetime="<?php echo date("c", strtotime($reply['dt'])) ; ?>" title="<?php echo hesk_date($reply['dt'], true); ?>"><?php echo hesk_date($reply['dt'], true); ?></time>
                </div>
                <?php echo hesk_getAdminButtons(1, $i); ?>
            </div>
            <div class="block--description browser-default">
                <p><?php echo $reply['message_html']; ?></p>
            </div>
            <?php

            /* Attachments */
            hesk_listAttachments($reply['attachments'], $reply['id'], $i);

            /* Staff rating */
            if ($hesk_settings['rating'] && $reply['staffid']) {
                if ($reply['rating'] == 1) {
                    echo '<p class="rate">' . $hesklang['rnh'] . '</p>';
                } elseif ($reply['rating'] == 5) {
                    echo '<p class="rate">' . $hesklang['rh'] . '</p>';
                }
            }

            /* Show "unread reply" message? */
            if ($reply['staffid'] && !$reply['read']) {
                echo '<p class="rate">' . $hesklang['unread'] . '</p>';
            }

            ?>
        </article>
        <?php
        if (!$start_previous_replies && $j == count($collapsed_replies) - 1) {
            echo '</div>
            </section>';
        }
    }

    for ($j = 0; $j < count($displayed_replies); $j++) {
        $reply = $displayed_replies[$j];
        ?>
        <article class="ticket__body_block <?php echo $reply['staffid'] ? 'response' : ''; ?>">
            <div class="block--head">
                <div class="contact">
                    <?php echo $hesklang['reply_by']; ?>
                    <b><?php echo $reply['name']; ?></b>
                    &raquo;
                    <time class="timeago tooltip" datetime="<?php echo date("c", strtotime($reply['dt'])) ; ?>" title="<?php echo hesk_date($reply['dt'], true); ?>"><?php echo hesk_date($reply['dt'], true); ?></time>
                </div>
                <?php echo hesk_getAdminButtons(1,$i); ?>
            </div>
            <div class="block--description browser-default">
                <p><?php echo $reply['message_html']; ?></p>
            </div>
            <?php
            /* Attachments */
            hesk_listAttachments($reply['attachments'],$reply['id'],$i);

            /* Staff rating */
            if ($hesk_settings['rating'] && $reply['staffid'])
            {
                if ($reply['rating']==1)
                {
                    echo '<p class="rate">'.$hesklang['rnh'].'</p>';
                }
                elseif ($reply['rating']==5)
                {
                    echo '<p class="rate">'.$hesklang['rh'].'</p>';
                }
            }

            /* Show "unread reply" message? */
            if ($reply['staffid'] && ! $reply['read'])
            {
                echo '<p class="rate">'.$hesklang['unread'].'</p>';
            }
            ?>
        </article>
        <?php
    }

    $start_previous_replies = true;
    for ($j = 0; $j < count($collapsed_replies) && $hesk_settings['new_top']; $j++) {
        $reply = $collapsed_replies[$j];
        if ($start_previous_replies):
            $start_previous_replies = false;
            ?>
            <section class="ticket__replies">
                <div class="ticket__replies_link">
                    <span><?php echo $hesklang['show_previous_replies']; ?></span>
                    <b><?php echo count($collapsed_replies); ?></b>
                    <svg class="icon icon-chevron-down">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                    </svg>
                </div>
                <div class="ticket__replies_list">
            <?php
        endif;
        ?>
        <article class="ticket__body_block <?php echo $reply['staffid'] ? 'response' : ''; ?>">
        <div class="block--head">
            <div class="contact">
                <?php echo $hesklang['reply_by']; ?>
                <b><?php echo $reply['name']; ?></b>
                &raquo;
                <time class="timeago tooltip" datetime="<?php echo date("c", strtotime($reply['dt'])) ; ?>" title="<?php echo hesk_date($reply['dt'], true); ?>"><?php echo hesk_date($reply['dt'], true); ?></time>
            </div>
            <?php echo hesk_getAdminButtons(1, $i); ?>
        </div>
        <div class="block--description browser-default">
            <p><?php echo $reply['message_html']; ?></p>
        </div>
        <?php

        /* Attachments */
        hesk_listAttachments($reply['attachments'], $reply['id'], $i);

        /* Staff rating */
        if ($hesk_settings['rating'] && $reply['staffid']) {
            if ($reply['rating'] == 1) {
                echo '<p class="rate">' . $hesklang['rnh'] . '</p>';
            } elseif ($reply['rating'] == 5) {
                echo '<p class="rate">' . $hesklang['rh'] . '</p>';
            }
        }

        /* Show "unread reply" message? */
        if ($reply['staffid'] && !$reply['read']) {
            echo '<p class="rate">' . $hesklang['unread'] . '</p>';
        }

        ?>
        </article>
        <?php
        if (!$start_previous_replies && $j == count($collapsed_replies) - 1) {
            echo '</div>
            </section>';
        }
    }

    return $i;

} // End hesk_printTicketReplies()

function hesk_printReplyForm() {
	global $hesklang, $hesk_settings, $ticket, $admins, $can_options, $options, $can_assign_self, $can_resolve;

    // Force assigning a ticket before allowing to reply?
    if ($hesk_settings['require_owner'] && ! $ticket['owner'])
    {
        hesk_show_notice($hesklang['atbr'].($can_assign_self ? '<br /><br /><a href="assign_owner.php?track='.$ticket['trackid'].'&amp;owner='.$_SESSION['id'].'&amp;token='.hesk_token_echo(0).'&amp;unassigned=1">'.$hesklang['attm'].'</a>' : ''), $hesklang['owneed']);
        return '';
    }
?>
<!-- START REPLY FORM -->
<article class="ticket__body_block">
    <a name="reply-form"></a>
    <form method="post" class="form" action="admin_reply_ticket.php" enctype="multipart/form-data" name="form1" aria-label="<?php echo $hesklang['add_a_ticket_reply']; ?>"
        onsubmit="
        <?php if ($hesk_settings['time_worked']): ?>force_stop();<?php endif; ?>
        <?php if ($hesk_settings['staff_ticket_formatting'] != 2): ?>clearTimeout(typingTimer);<?php endif; ?>
        <?php if ($hesk_settings['submitting_wait']): ?>hesk_showLoadingMessage('recaptcha-submit');<?php endif; ?>
        return true;"
        >
        <?php
        /* Ticket assigned to someone else? */
        if ($ticket['owner'] && $ticket['owner'] != $_SESSION['id'] && isset($admins[$ticket['owner']])) {
            hesk_show_notice($hesklang['nyt'] . ' ' . $admins[$ticket['owner']]);
        }

        /* Ticket locked? */
        if ($ticket['locked']) {
            hesk_show_notice($hesklang['tislock']);
        }

        if ($hesk_settings['time_worked'] && strlen($can_options)) {
            ?>
            <div class="time-and-canned">
            <?php
        }
        // Track time worked?
        if ($hesk_settings['time_worked']) {
            ?>
            <section class="block--timer">
                <span>
                    <label for="time_worked">
                        <?php echo $hesklang['ts']; ?>:
                    </label>
                </span>
                <div class="form-group short" style="margin-left: 8px; margin-bottom: 0">
                    <input type="text" class="form-control short" name="time_worked" id="time_worked" size="10" value="<?php echo ( isset($_SESSION['time_worked']) ? hesk_getTime($_SESSION['time_worked']) : '00:00:00'); ?>" autocomplete="off">
                </div>

                <a href="javascript:" class="tooltip" id="pause_btn" title="<?php echo $hesklang['start']; ?>">
                    <svg class="icon icon-pause">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-pause"></use>
                    </svg>
                </a>
                <a href="javascript:" class="tooltip" id="reset_btn" title="<?php echo $hesklang['reset']; ?>">
                    <svg class="icon icon-refresh">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-refresh"></use>
                    </svg>
                </a>
                <script>
                    $('#pause_btn').click(function() {
                        ss();
                        updatePauseButton();
                    });

                    $('#reset_btn').click(function() {
                        $('#pause_btn').find('svg').addClass('playing');
                        r();
                    });

                    function updatePauseButton() {
                        if (!timer_running()) {
                            $('#pause_btn').find('svg').addClass('playing');
                        } else {
                            $('#pause_btn').find('svg').removeClass('playing');
                        }
                    }

                    $(document).ready(function() {
                        setTimeout(updatePauseButton, 1000);
                    });

                    <?php if ($hesk_settings['new_top']): ?>
                    $('#notesformTop').submit(function() {
                         $('#time_worked_notesTop').val($('#time_worked').val());
                    });
                    <?php endif; ?>
                </script>
            </section>
            <?php
        }

        /* Do we have any canned responses? */
        if (strlen($can_options))
        {
            ?>
        <section class="block--timer canned-options">
            <div class="canned-header">
                <?php echo $hesklang['saved_replies']; ?>
            </div>
            <div class="options" style="text-align: left">
                <div>
                    <div class="radio-custom">
                        <input type="radio" name="mode" id="modeadd"
                               value="1" checked>
                        <label for="modeadd">
                            <?php echo $hesklang['madd']; ?>
                        </label>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" name="mode" id="moderep"
                               value="0">
                        <label for="moderep">
                            <?php echo $hesklang['mrep']; ?>
                        </label>
                    </div>
                </div>
                <div class="form-group">
                    <label><?php echo $hesklang['select_saved']; ?></label>
                        <select name="saved_replies" id="saved_replies" onchange="setMessage(this.value)">
                            <option value="0"> - <?php echo $hesklang['select_empty']; ?> - </option>
                            <?php echo $can_options; ?>
                        </select>
                        <script>
                            $('#saved_replies').selectize();
                        </script>
                </div>
            </div>
        </section>
            <?php
        }

        if ($hesk_settings['time_worked'] && strlen($can_options)) {
        ?>
            </div>
                <?php
                }
        ?>

            <div class="block--message" id="message-block">
                <textarea name="message" id="message" placeholder="<?php echo $hesklang['type_your_message']; ?>" aria-label="<?php echo $hesklang['message']; ?>"><?php

                    // Do we have any message stored in session?
                    if ( isset($_SESSION['ticket_message']) )
                    {
                        echo stripslashes( hesk_input( $_SESSION['ticket_message'] ) );
                    }
                    // Perhaps a message stored in reply drafts?
                    else
                    {
                        $db_column = $hesk_settings['staff_ticket_formatting'] == 2 ? 'message_html' : 'message';
                        $res = hesk_dbQuery("SELECT `{$db_column}` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."reply_drafts` WHERE `owner`=".intval($_SESSION['id'])." AND `ticket`=".intval($ticket['id'])." LIMIT 1");
                        if (hesk_dbNumRows($res) == 1)
                        {
                            echo $db_column === 'message_html' ? htmlspecialchars(hesk_dbResult($res)) : hesk_dbResult($res);
                        }
                    }

                ?></textarea>
            </div>

        <?php
        if ($hesk_settings['staff_ticket_formatting'] == 2) {
            hesk_tinymce_init('#message', 'hesk_save_draft_async');
        }

        /* attachments */
        if ($hesk_settings['attachments']['use'])
        {
            require_once(HESK_PATH . 'inc/attachments.inc.php');
            ?>
            <div class="attachments">
                <div class="block--attach">
                    <svg class="icon icon-attach">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-attach"></use>
                    </svg>
                    <div>
                        <?php echo $hesklang['attachments'] . ':<br>'; ?>
                    </div>
                </div>
                <?php
                build_dropzone_markup(true);
                display_dropzone_field(HESK_PATH . 'upload_attachment.php', true);
                dropzone_display_existing_files(hesk_SESSION_array('ar_attachments'));
                ?>
            </div>
        <?php
        }
        ?>

        <section class="block--checkboxs">
            <?php
            if ($ticket['owner'] != $_SESSION['id'] && $can_assign_self)
            {
                echo '<div class="checkbox-custom">';
                if (empty($ticket['owner']))
                {
                    echo '<input type="checkbox" id="assign_self" name="assign_self" value="1" autocomplete="off" checked="checked">';
                }
                else
                {
                    echo '<input type="checkbox" id="assign_self" name="assign_self" value="1" autocomplete="off">';
                }
                echo '<label for="assign_self">'.$hesklang['asss2'].'</label>';
                echo '</div>';
            }
            ?>

            <div class="checkbox-custom">
                <input type="checkbox" id="signature" name="signature" value="1" autocomplete="off" checked="checked">
                <label for="signature">
                    <?php echo $hesklang['attach_sign']; ?>
                    (<a class="link" href="profile.php"><?php echo $hesklang['profile_settings']; ?></a>)
                </label>
            </div>

            <div class="checkbox-custom">
                <input type="checkbox" id="set_priority" name="set_priority" autocomplete="off" value="1">
                <label for="set_priority"><?php echo $hesklang['change_priority']; ?></label>

                <div class="dropdown-select center out-close priority select-priority" data-value="low">
                    <select id="replypriority" name="priority">
                        <?php echo implode('',$options); ?>
                    </select>
                </div>
            </div>
            <div class="checkbox-custom">
                <input type="checkbox" id="no_notify" name="no_notify" value="1" autocomplete="off" <?php echo $_SESSION['notify_customer_reply'] ? '' : 'checked'; ?>>
                <label for="no_notify"><?php echo $hesklang['dsen']; ?></label>
            </div>
        </section>
        <section class="block--submit">
            <input type="hidden" name="orig_id" value="<?php echo $ticket['id']; ?>">
            <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
            <input class="btn btn-full" ripple="ripple" type="submit" value="<?php echo $hesklang['submit_reply']; ?>" id="recaptcha-submit">
            &nbsp;
            <input class="btn btn-border" ripple="ripple" type="submit" name="save_reply" value="<?php echo $hesklang['sacl']; ?>">
            <?php
            // If ticket is not locked, show additional submit options
            if ( ! $ticket['locked']) {
                ?>
                <input type="hidden" id="submit_as_name" value="1" name="">
                <div class="submit-us dropdown-select out-close" data-value="" id="submit-as-div">
                    <select onchange="
                        document.getElementById('submit_as_name').name = this.value;
                        <?php if ($hesk_settings['time_worked']): ?>force_stop();<?php endif; ?>
                        <?php if ($hesk_settings['staff_ticket_formatting'] != 2): ?>clearTimeout(typingTimer);<?php endif; ?>
                        <?php if ($hesk_settings['submitting_wait']): ?>hesk_showLoadingMessage('submit-as-div');<?php endif; ?>
                        this.form.submit()
                        ">
                        <option value="" selected><?php echo rtrim($hesklang['submit_as'], ':'); ?></option>
                        <option value="submit_as_customer"><?php echo $hesklang['sasc']; ?></option>
                        <?php
                        $echo_options = '';
                        foreach ($hesk_settings['statuses'] as $k => $v)
                        {
                            if ($k == 3)
                            {
                                if ($can_resolve)
                                {
                                    echo '<option value="submit_as-'.$k.'">'.$hesklang['submit_as'].' '.$v['name'].'</option>';
                                }
                            }
                            else
                            {
                                $echo_options .= '<option value="submit_as-'.$k.'">'.$hesklang['submit_as'].' '.$v['name'].'</option>';
                            }
                        }
                        echo $echo_options;
                        ?>
                    </select>
                </div>
                <?php
            }
            ?>

        </section>
    </form>
</article>

<script>
var draft_message = '';
var previous_draft_message = '';

function debug_to_console(msg) {
    <?php if ($hesk_settings['debug_mode']): ?>
    console.log(msg);
    <?php endif; ?>
}

function hesk_save_draft_async() {
    // Get the new message from the rich text editor or textbox
    <?php if ($hesk_settings['staff_ticket_formatting'] == 2): ?>
        draft_message = tinymce.get("message").getContent('');
    <?php else: ?>
        draft_message = $('#message').val();
    <?php endif; ?>

    // Only proceed if the message has changed
    if (draft_message == previous_draft_message) {
        debug_to_console("Message did not change");
        return true;
    }

    $.ajax({
        type: "POST",
        url: "save_ticket_draft_async.php",
        data:{
            orig_id: <?php echo $ticket['id']; ?>,
            message: draft_message,
            token: '<?php echo hesk_token_echo(0); ?>'
        },
        success: function(result, status){
            previous_draft_message = draft_message;
            debug_to_console("Request result: " + result + " " + status);
        },
        error: function(xhr, status, error) {
            debug_to_console("Ajax Error " + xhr + " " + status + " " + error)
        }
    });
}
/*Linked Button Click*/
$('body').on('click','.linked',function(){
    var action = $('#linked_ticket').attr('action');
    var ticket_track_id = $('#ticket_track_id').val();

    $("#linked_ticket").removeClass("invalid");
        $("#ticket_track_id").removeClass("isError");
    if(ticket_track_id == ""){
        $("#linked_ticket").addClass("invalid");
        $("#ticket_track_id").addClass("isError");
    }

    var data = {
        'action_type':'linked_ticket',
        'ticket_track_id': $('#ticket_track_id').val(),
        'token': $('#linked_token').val()
    }
    $.ajax({
        type: 'POST',
        url: action,
        data: data,
        cache: false,
        success: function(data){
            var result = JSON.parse(data);
            $('.custom_ajax_msg').html('');
            $('.custom_ajax_msg').html(result.message);
            if(result.status=='SUCCESS'){
                $('#ticket_track_id').val('');
                $('.linked_html_view').html('');
                $('.linked_html_view').html(result.linked_html);
                $('.history_html_view').html('');
                $('.history_html_view').html(result.history_html);
            }
        }
    });
});

/*Unlinked Button Click*/
$('body').on('click','.unlink',function(){
    var that = $(this);
    var action = that.attr('data-action');
    var ticket1 = that.attr('data-ticket1');
    var ticket2 = that.attr('data-ticket2');
    var trackid = that.attr('data-trackid');


    $("#linked_ticket").removeClass("invalid");
    $("#ticket_track_id").removeClass("isError");

    var data = {
        'action_type':'unlink_ticket',
        'ticket1': ticket1,
        'ticket2': ticket2,
        'trackid': trackid,
        'token': $('#linked_token').val()
    }
    $.ajax({
        type: 'POST',
        url: action,
        data: data,
        cache: false,
        success: function(data){
            var result = JSON.parse(data);
            $('.custom_ajax_msg').html('');
            $('.custom_ajax_msg').html(result.message);
            if(result.status=='SUCCESS'){
                that.parent().remove();
                $('.linked_html_view').html('');
                $('.linked_html_view').html(result.linked_html);
                $('.history_html_view').html('');
                $('.history_html_view').html(result.history_html);
            }
        }
    });
});

$('body').on('click','.href_show_linked',function(){
    $('.custom_ajax_msg').html('');
    $('.show_link_a_ticket').removeClass('d_show').addClass('d_hide')
    $('.show_linked_form').removeClass('d_hide').addClass('d_show');
    $("#linked_ticket").removeClass("invalid");
    $("#ticket_track_id").removeClass("isError");
    $('#ticket_track_id').val('');
});

$('body').on('click','.cancel',function(){
    $('.show_link_a_ticket').removeClass('d_hide').addClass('d_show')
    $('.show_linked_form').removeClass('d_show').addClass('d_hide');
});
<?php if ($hesk_settings['staff_ticket_formatting'] != 2): ?>
var typingTimer;
var doneTypingInterval = 3000;

$(document).ready(function() {
    $('#message').on('input', function() {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(hesk_save_draft_async, doneTypingInterval);
    });
});
<?php endif; ?>
</script>

<!-- END REPLY FORM -->
<?php
} // End hesk_printReplyForm()


function hesk_printCanned()
{
	global $hesklang, $hesk_settings, $can_reply, $ticket, $admins, $category, $customers, $requester, $followers, $customer_emails;

	/* Can user reply to tickets? */
	if ( ! $can_reply)
    {
    	return '';
    }

	/* Get canned replies from the database */
	$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."std_replies` ORDER BY `reply_order` ASC");

	/* If no canned replies return empty */
    if ( ! hesk_dbNumRows($res) )
    {
    	return '';
    }

	/* We do have some replies, print the required Javascript and select field options */
	$can_options = '';
	?>
	<script language="javascript" type="text/javascript"><!--
    // -->
    var myMsgTxt = new Array();
	myMsgTxt[0]='';

	<?php
	while ($mysaved = hesk_dbFetchAssoc($res))
	{
        $can_options .= '<option value="' . $mysaved['id'] . '">' . $mysaved['title']. "</option>\n";

        $message_text = $hesk_settings['staff_ticket_formatting'] == 2 ? $mysaved['message_html'] : $mysaved['message'];

        echo 'myMsgTxt['.$mysaved['id'].']='.hesk_json_encode_for_js($message_text).";\n";
	}

	?>

	function heskDecodeHtmlEntities(value)
	{
		var textarea = document.createElement('textarea');
		textarea.innerHTML = String(value).replace(/</g, '&lt;').replace(/>/g, '&gt;');
		return textarea.value;
	}

	function setMessage(msgid)
    {
		var myMsg=myMsgTxt[msgid];

        if (myMsg == '')
        {
            if (document.form1.mode[1].checked)
            {
            <?php if ($hesk_settings['staff_ticket_formatting'] == 2): ?>
                tinymce.get("message").setContent('');
            <?php else: ?>
                document.getElementById('message').value = '';
            <?php endif; ?>
                $('.ticket .block--message .placeholder').click();
                return true;
            }
            return true;
        }

        <?php
        $formatted_followers = [];
        $formatted_follower_names = [];
        $formatted_follower_emails = [];
        foreach ($followers as $follower) {
            $formatted_followers[] = hesk_output_customer_name_and_email($follower);
            if ($follower['name'] !== null && $follower['name'] !== '') {
                $formatted_follower_names[] = $follower['name'];
            }
            if ($follower['email'] !== null && $follower['email'] !== '') {
                $formatted_follower_emails[] = $follower['email'];
            }
        }
        ?>

        // replace plain text
		myMsg = myMsg.replace(/%%HESK_ID%%/g, <?php echo hesk_json_encode_jsString($ticket['id']); ?>);
		myMsg = myMsg.replace(/%%HESK_TRACKID%%/g, <?php echo hesk_json_encode_jsString($ticket['trackid']); ?>);
		myMsg = myMsg.replace(/%%HESK_TRACK_ID%%/g, <?php echo hesk_json_encode_jsString($ticket['trackid']); ?>);
		myMsg = myMsg.replace(/%%HESK_SUBJECT%%/g, <?php echo hesk_json_encode_jsString($ticket['subject']); ?>);
		myMsg = myMsg.replace(/%%HESK_REQUESTER%%/g, <?php echo hesk_json_encode_jsString(hesk_output_customer_name_and_email($requester)); ?>);
        myMsg = myMsg.replace(/%%HESK_NAME%%/g, <?php echo hesk_json_encode_jsString($requester !== null ? $requester['name'] : $hesklang['anon_name']); ?>);
		myMsg = myMsg.replace(/%%HESK_REQUESTER_NAME%%/g, <?php echo hesk_json_encode_jsString($requester !== null ? $requester['name'] : $hesklang['anon_name']); ?>);
        myMsg = myMsg.replace(/%%HESK_FIRST_NAME%%/g, <?php echo hesk_json_encode_jsString($requester !== null ? hesk_full_name_to_first_name($requester['name']) : $hesklang['anon_name']); ?>);
		myMsg = myMsg.replace(/%%HESK_REQUESTER_FIRST_NAME%%/g, <?php echo hesk_json_encode_jsString($requester !== null ? hesk_full_name_to_first_name($requester['name']) : $hesklang['anon_name']); ?>);
        myMsg = myMsg.replace(/%%HESK_EMAIL%%/g, <?php echo hesk_json_encode_jsString($requester !== null ? $requester['email'] : $hesklang['anon_email']); ?>);
		myMsg = myMsg.replace(/%%HESK_REQUESTER_EMAIL%%/g, <?php echo hesk_json_encode_jsString($requester !== null ? $requester['email'] : $hesklang['anon_email']); ?>);
        myMsg = myMsg.replace(/%%HESK_FOLLOWERS%%/g, <?php echo hesk_json_encode_jsString(implode(', ', $formatted_followers)); ?>);
        myMsg = myMsg.replace(/%%HESK_FOLLOWER_NAMES%%/g, <?php echo hesk_json_encode_jsString(implode(', ', $formatted_follower_names)); ?>);
        myMsg = myMsg.replace(/%%HESK_FOLLOWER_EMAILS%%/g, <?php echo hesk_json_encode_jsString(implode(', ', $formatted_follower_emails)); ?>);
		myMsg = myMsg.replace(/%%HESK_OWNER%%/g, <?php echo hesk_json_encode_jsString( isset($admins[$ticket['owner']]) ? $admins[$ticket['owner']] : ''); ?>);
        myMsg = myMsg.replace(/%%HESK_CATEGORY%%/g, <?php echo hesk_json_encode_jsString( isset($category['name']) ? $category['name'] : ''); ?>);
        myMsg = myMsg.replace(/%%HESK_DUE_DATE%%/g, <?php echo hesk_json_encode_jsString(hesk_format_due_date($ticket['due_date'])); ?>);

        // replace URL-encoded text
        myMsg = myMsg.replace(/%25%25HESK_ID%25%25/g, encodeURIComponent(<?php echo hesk_json_encode_jsString($ticket['id']); ?>));
        myMsg = myMsg.replace(/%25%25HESK_TRACKID%25%25/g, encodeURIComponent(<?php echo hesk_json_encode_jsString($ticket['trackid']); ?>));
        myMsg = myMsg.replace(/%25%25HESK_TRACK_ID%25%25/g, encodeURIComponent(<?php echo hesk_json_encode_jsString($ticket['trackid']); ?>));
        myMsg = myMsg.replace(/%25%25HESK_SUBJECT%25%25/g, encodeURIComponent(<?php echo hesk_json_encode_jsString($ticket['subject']); ?>));
        myMsg = myMsg.replace(/%25%25HESK_REQUESTER%25%25/g, <?php echo hesk_json_encode_jsString(hesk_output_customer_name_and_email($requester)); ?>);
        myMsg = myMsg.replace(/%25%25HESK_REQUESTER_NAME%25%25/g, <?php echo hesk_json_encode_jsString($requester !== null ? $requester['name'] : $hesklang['anon_name']); ?>);
        myMsg = myMsg.replace(/%25%25HESK_NAME%25%25/g, <?php echo hesk_json_encode_jsString($requester !== null ? $requester['name'] : $hesklang['anon_name']); ?>);
        myMsg = myMsg.replace(/%25%25HESK_REQUESTER_FIRST_NAME%25%25/g, <?php echo hesk_json_encode_jsString($requester !== null ? hesk_full_name_to_first_name($requester['name']) : $hesklang['anon_name']); ?>);
        myMsg = myMsg.replace(/%25%25HESK_FIRST_NAME%25%25/g, <?php echo hesk_json_encode_jsString($requester !== null ? hesk_full_name_to_first_name($requester['name']) : $hesklang['anon_name']); ?>);
        myMsg = myMsg.replace(/%25%25HESK_REQUESTER_EMAIL%25%25/g, <?php echo hesk_json_encode_jsString($requester !== null ? $requester['email'] : $hesklang['anon_email']); ?>);
        myMsg = myMsg.replace(/%25%25HESK_EMAIL%25%25/g, <?php echo hesk_json_encode_jsString($requester !== null ? $requester['email'] : $hesklang['anon_email']); ?>);
        myMsg = myMsg.replace(/%25%25HESK_FOLLOWERS%25%25/g, <?php echo hesk_json_encode_jsString(implode(', ', $formatted_followers)); ?>);
        myMsg = myMsg.replace(/%25%25HESK_FOLLOWER_NAMES%25%25/g, <?php echo hesk_json_encode_jsString(implode(', ', $formatted_follower_names)); ?>);
        myMsg = myMsg.replace(/%25%25HESK_FOLLOWER_EMAILS%25%25/g, <?php echo hesk_json_encode_jsString(implode(', ', $formatted_follower_emails)); ?>);
        myMsg = myMsg.replace(/%25%25HESK_OWNER%25%25/g, encodeURIComponent(<?php echo hesk_json_encode_jsString( isset($admins[$ticket['owner']]) ? $admins[$ticket['owner']] : ''); ?>));
        myMsg = myMsg.replace(/%25%25HESK_CATEGORY%25%25/g, encodeURIComponent(<?php echo hesk_json_encode_jsString( isset($category['name']) ? $category['name'] : ''); ?>));
        myMsg = myMsg.replace(/%25%25HESK_DUE_DATE%25%25/g, encodeURIComponent(<?php echo hesk_json_encode_jsString(hesk_format_due_date($ticket['due_date'])); ?>));

		<?php
        for ($i=1; $i<=100; $i++)
		{
            // replace plain text
        	echo 'myMsg = myMsg.replace(/%%HESK_custom'.$i.'%%/g, '.hesk_json_encode_jsString($ticket['custom'.$i]).');';

            // replace URL-encoded text
            echo 'myMsg = myMsg.replace(/%25%25HESK_custom'.$i.'%25%25/g, encodeURIComponent('.hesk_json_encode_jsString($ticket['custom'.$i]).'));';
		}
		?>

        if (document.getElementById) {
            if (document.getElementById('moderep').checked) {
            <?php if ($hesk_settings['staff_ticket_formatting'] == 2): ?>
                tinymce.get("message").setContent('');
                tinymce.get("message").setContent(myMsg);
            <?php else: ?>
                document.getElementById('message').value = heskDecodeHtmlEntities(myMsg);
            <?php endif; ?>
            } else {
            <?php if ($hesk_settings['staff_ticket_formatting'] == 2): ?>
                var oldMsg = tinymce.get("message").getContent();
                tinymce.get("message").setContent('');
                tinymce.get("message").setContent(oldMsg + myMsg);
            <?php else: ?>
                var oldMsg = document.getElementById('message').value;
                document.getElementById('message').value = oldMsg + heskDecodeHtmlEntities(myMsg);
            <?php endif; ?>
            }
            $('.ticket .block--message .placeholder').click();
	    } else {
            if (document.form1.mode[0].checked) {
                document.form1.message.value = heskDecodeHtmlEntities(myMsg);
            } else {
                var oldMsg = document.form1.message.value;
                document.form1.message.value = oldMsg + heskDecodeHtmlEntities(myMsg);
            }
	    }
	}
	//-->
	</script>
    <?php

    /* Return options for select box */
    return $can_options;

} // End hesk_printCanned()


function hesk_staffCanAccessTicketNoError($ticket)
{
    global $hesk_settings;

    if ( ! is_array($ticket) || ! isset($ticket['id'], $ticket['category'], $ticket['owner'], $ticket['assignedby']))
    {
        return false;
    }

    if ( ! hesk_checkPermission('can_view_tickets', 0))
    {
        return false;
    }

    $collaborators = hesk_getTicketsCollaboratorIDs($ticket['id']);
    $am_I_collaborator = in_array($_SESSION['id'], $collaborators);

    if ($ticket['owner'] && $ticket['owner'] != $_SESSION['id'] && ! hesk_checkPermission('can_view_ass_others', 0) && ! $am_I_collaborator)
    {
        if ( ! hesk_checkPermission('can_view_ass_by', 0) || $ticket['assignedby'] != $_SESSION['id'])
        {
            return false;
        }
    }

    if ( ! $ticket['owner'] && ! hesk_checkPermission('can_view_unassigned', 0) && ! $am_I_collaborator)
    {
        return false;
    }

    // Get category ID; if this category has been deleted use the default category with ID 1
    $result = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE `id`='".intval($ticket['category'])."' LIMIT 1");
    if (hesk_dbNumRows($result) != 1)
    {
        $result = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE `id`='1' LIMIT 1");
    }

    $category = hesk_dbFetchAssoc($result);

    return hesk_okCategory($category['id'], 0);
} // END hesk_staffCanAccessTicketNoError()
admin_upload_attachment.php
wget 'https://lists2.roe3.org/hesk/admin/admin_upload_attachment.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */
define('IN_SCRIPT', 1);
define('HESK_PATH', '../');
require_once(HESK_PATH . 'hesk_settings.inc.php');
require_once(HESK_PATH . 'inc/common.inc.php');
require_once(HESK_PATH . 'inc/admin_functions.inc.php');

// Demo mode?
if ( defined('HESK_DEMO') ) {
    http_response_code(400);
    exit();
}

hesk_load_database_functions();
hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

require_once(HESK_PATH . 'inc/upload_attachment.inc.php');
anonymize_ticket.php
wget 'https://lists2.roe3.org/hesk/admin/anonymize_ticket.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/privacy_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_privacy');

// A security check
hesk_token_check();

// Tracking ID
$trackingID = hesk_cleanID() or die($hesklang['int_error'].': '.$hesklang['no_trackID']);

// Make sure this staff member is allowed to access this ticket
hesk_verifyStaffTicketAccess($trackingID);

// Anonymize the ticket and redirect back
if (hesk_anonymizeTicket(0, $trackingID))
{
    hesk_process_messages($hesklang['success_anon'],'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999),'SUCCESS');
}

hesk_error($hesklang['no_permission']);
archive.php
wget 'https://lists2.roe3.org/hesk/admin/archive.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
hesk_checkPermission('can_view_tickets');
hesk_checkPermission('can_add_archive');

/* A security check */
hesk_token_check();

/* Ticket ID */
$trackingID = hesk_cleanID() or die($hesklang['int_error'].': '.$hesklang['no_trackID']);
hesk_verifyStaffTicketAccess($trackingID);

/* New archived status */
if (empty($_GET['archived']))
{
	$status = 0;
	$tmp = $hesklang['removedfromarchive'];
}
else
{
	$status = 1;
	$tmp = $hesklang['added2archive'];
}

/* Update database */
hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `archive`='$status' WHERE `trackid`='".hesk_dbEscape($trackingID)."'");

/* Back to ticket page and show a success message */
hesk_process_messages($tmp,'admin_ticket.php?track='.$trackingID.'&Refresh='.rand(10000,99999),'SUCCESS');
?>
assign_owner.php
wget 'https://lists2.roe3.org/hesk/admin/assign_owner.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();
require(HESK_PATH . 'inc/email_functions.inc.php');

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

$can_assign_others = hesk_checkPermission('can_assign_others',0);
if ($can_assign_others)
{
	$can_assign_self = TRUE;
}
else
{
	$can_assign_self = hesk_checkPermission('can_assign_self',0);
}

/* A security check */
hesk_token_check();

/* Ticket ID */
$trackingID = hesk_cleanID() or die($hesklang['int_error'].': '.$hesklang['no_trackID']);
$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `trackid`='".hesk_dbEscape($trackingID)."' LIMIT 1");
if (hesk_dbNumRows($res) != 1)
{
	hesk_error($hesklang['ticket_not_found']);
}
$ticket = hesk_dbFetchAssoc($res);
hesk_verifyStaffTicketAccess($trackingID, $ticket);

$_SERVER['PHP_SELF'] = 'admin_ticket.php?track='.$trackingID.'&Refresh='.rand(10000,99999);

/* New owner ID */
$owner = intval( hesk_REQUEST('owner') );

/* If ID is -1 the ticket will be unassigned */
if ($owner == -1)
{
    if ( ! $can_assign_others && ( ! $can_assign_self || intval($ticket['owner']) != intval($_SESSION['id']) ) ) {
        hesk_process_messages($hesklang['no_permission'],'admin_ticket.php?track='.$trackingID.'&Refresh='.rand(10000,99999),'NOTICE');
    }

    if ($ticket['owner'] == 0) {
        hesk_process_messages($hesklang['ticket_already_unassigned'],'admin_ticket.php?track='.$trackingID.'&Refresh='.rand(10000,99999),'NOTICE');
    }

	$revision = sprintf($hesklang['thist2'],hesk_date(),'<i>'.$hesklang['unas'].'</i>',addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
	$res = hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `owner`=0, `assignedby`=NULL, `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') WHERE `trackid`='".hesk_dbEscape($trackingID)."'");

    hesk_process_messages($hesklang['tunasi2'],$_SERVER['PHP_SELF'],'SUCCESS');
}
elseif ($owner < 1)
{
    hesk_process_messages($hesklang['nose'],$_SERVER['PHP_SELF'],'NOTICE');
}

/* Verify the new owner and permissions */
$res = hesk_dbQuery("SELECT `id`,`user`,`name`,`email`,`isadmin`,`categories`,`notify_assigned` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id`='{$owner}' AND `active` = 1 LIMIT 1");
$row = hesk_dbFetchAssoc($res);
if ( ! $row)
{
    hesk_process_messages($hesklang['no_valid_id'], $_SERVER['PHP_SELF']);
}

/* Has new owner access to the category? */
if ( ! $row['isadmin'])
{
	$row['categories']= hesk_getCategoriesForUser($row['id']);
	if (!in_array($ticket['category'],$row['categories']))
	{
		hesk_error($hesklang['unoa']);
	}
}

// Make sure two people don't assign a ticket to a different user at the same time
if ($ticket['owner'] && $ticket['owner'] != $owner && hesk_REQUEST('unassigned') && hesk_GET('confirm') != 'Y')
{
	$new_owner = ($owner == $_SESSION['id']) ? $hesklang['scoy'] : sprintf($hesklang['scot'], $row['name']);

	$res = hesk_dbQuery("SELECT `name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id`='{$ticket['owner']}' AND `active` = 1 LIMIT 1");

	if (hesk_dbNumRows($res) == 1)
	{
		$row = hesk_dbFetchAssoc($res);

		hesk_process_messages(
			sprintf($hesklang['taat'], $row['name']) .
			'<br /><br />' .
			$new_owner .
			'<br /><br />' .
			'<a href="assign_owner.php?track='.$ticket['trackid'].'&amp;owner='.$owner.'&amp;token='.hesk_token_echo(0).'&amp;unassigned=1&amp;confirm=Y">'.$hesklang['ycto'].'</a> | ' .
			'<a href="admin_ticket.php?track='.$ticket['trackid'].'">'.$hesklang['ncto'].'</a>',
			$_SERVER['PHP_SELF'], 'NOTICE'
		);
	}
}

if ($ticket['owner'] == $owner) {
    hesk_process_messages(sprintf($hesklang['taat'],$row['name']),'admin_ticket.php?track='.$trackingID.'&Refresh='.rand(10000,99999),'NOTICE');
}

/* Assigning to self? */
if ($can_assign_others || ($owner == $_SESSION['id'] && $can_assign_self))
{
    $assignedby = intval(hesk_SESSION('id'));
    if ($assignedby > 0)
    {
        $assignedby = ',`assignedby`=' . $assignedby;
    }
    else
    {
         $assignedby = '';
    }

	$revision = sprintf($hesklang['thist2'],hesk_date(),addslashes($row['name']).' ('.$row['user'].')',addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
	$res = hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `owner`={$owner} {$assignedby}, `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') WHERE `trackid`='".hesk_dbEscape($trackingID)."'");

    if ($owner != $_SESSION['id'] && !hesk_checkPermission('can_view_ass_others',0))
    {
    	$_SERVER['PHP_SELF']='admin_main.php';
    }
}
else
{
	hesk_error($hesklang['no_permission']);
}

$ticket['owner'] = $owner;
$customers = hesk_get_customers_for_ticket($ticket['id']);
$customer_emails = array_map(function($customer) { return $customer['email']; }, $customers);
$customer_names = array_map(function($customer) { return $customer['name']; }, $customers);

/* --> Prepare message */

// 1. Generate the array with ticket info that can be used in emails
$info = array(
'email'			=> implode(';', $customer_emails),
'category'		=> $ticket['category'],
'priority'		=> $ticket['priority'],
'owner'			=> $ticket['owner'],
'collaborators' => hesk_getTicketsCollaboratorIDs($ticket['id']),
'trackid'		=> $ticket['trackid'],
'status'		=> $ticket['status'],
'name'			=> implode(';', $customer_names),
'subject'		=> $ticket['subject'],
'message'		=> $ticket['message'],
'message_html'  => $ticket['message_html'],
'attachments'	=> $ticket['attachments'],
'dt'			=> hesk_date($ticket['dt'], true),
'lastchange'	=> hesk_date($ticket['lastchange'], true),
'due_date'      => hesk_format_due_date($ticket['due_date']),
'id'			=> $ticket['id'],
'time_worked'   => $ticket['time_worked'],
'last_reply_by' => hesk_getReplierNameArray($ticket),
);

// 2. Add custom fields to the array
foreach ($hesk_settings['custom_fields'] as $k => $v)
{
	$info[$k] = $v['use'] ? $ticket[$k] : '';
}

// 3. Make sure all values are properly formatted for email
$ticket = hesk_ticketToPlain($info, 1, 0);

/* Notify the new owner? */
if ($ticket['owner'] != intval($_SESSION['id']))
{
	hesk_notifyAssignedStaff(false, 'ticket_assigned_to_you', 'notify_assigned', false);
}

$tmp = ($owner == $_SESSION['id']) ? $hesklang['tasy'] : $hesklang['taso'];
hesk_process_messages($tmp,$_SERVER['PHP_SELF'],'SUCCESS');

banned_emails.php
wget 'https://lists2.roe3.org/hesk/admin/banned_emails.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
hesk_checkPermission('can_ban_emails');
$can_unban = hesk_checkPermission('can_unban_emails', 0);

// Define required constants
define('LOAD_TABS',1);

// What should we do?
if ( $action = hesk_REQUEST('a') )
{
	if ( defined('HESK_DEMO') ) {hesk_process_messages($hesklang['ddemo'], 'banned_emails.php', 'NOTICE');}
	elseif ($action == 'ban')   {ban_email();}
	elseif ($action == 'unban' && $can_unban) {unban_email();}
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
hesk_handle_messages();
?>

<div class="main__content tools">
    <h2>
        <?php echo $hesklang['banemail']; ?>
        <div class="tooltype right out-close">
            <svg class="icon icon-info">
                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
            </svg>
            <div class="tooltype__content">
                <div class="tooltype__wrapper">
                    <?php echo $hesklang['banemail_intro']; ?>
                </div>
            </div>
        </div>
    </h2>
    <form action="banned_emails.php" method="post" name="form1" aria-label="<?php echo $hesklang['banemail']; ?>">
        <div class="tools__add-mail form">
            <div class="form-group">
                <input type="text" name="email" class="form-control" maxlength="255" aria-label="<?php echo $hesklang['bananemail'];?>" placeholder="<?php echo htmlspecialchars($hesklang['bananemail']); ?>" autofocus>
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
                <input type="hidden" name="a" value="ban" />
                <button type="submit" class="btn btn--blue-border" ripple="ripple"><?php echo $hesklang['savebanemail']; ?></button>
            </div>
            <div class="mail--examples"><?php echo $hesklang['banex']; ?> john@example.com, @example.com</div>
        </div>
    </form>
    <?php
    // Get banned emails from database
    $res = hesk_dbQuery('SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'banned_emails` ORDER BY `email` ASC');
    $num = hesk_dbNumRows($res);
    ?>
    <div class="table-wrapper email">
        <table id="default-table" class="table sindu-table">
            <thead>
            <tr>
                <th><?php echo $hesklang['email']; ?></th>
                <th><?php echo $hesklang['banby']; ?></th>
                <th><?php echo $hesklang['date']; ?></th>
                <?php if ($can_unban): ?>
                    <th><?php echo $hesklang['opt']; ?></th>
                <?php endif; ?>
            </tr>
            </thead>
            <tbody>
            <?php if ($num < 1): ?>
            <tr>
                <td colspan="<?php echo $can_unban ? 4 : 3; ?>"><?php echo $hesklang['no_banemails']; ?></td>
            </tr>
            <?php
            else:
                // List of staff
                if ( ! isset($admins) )
                {
                    $admins = array();
                    $res2 = hesk_dbQuery("SELECT `id`,`name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users`");
                    while ($row=hesk_dbFetchAssoc($res2))
                    {
                        $admins[$row['id']]=$row['name'];
                    }
                }

                while ($ban = hesk_dbFetchAssoc($res)):
                    $table_row = '';
                    if (isset($_SESSION['ban_email']['id']) && $ban['id'] == $_SESSION['ban_email']['id'])
                    {
                        $table_row = 'class="ticket-new"';
                        unset($_SESSION['ban_email']['id']);
                    }
                ?>
                <tr <?php echo $table_row; ?>>
                    <td><?php echo $ban['email']; ?></td>
                    <td><?php echo isset($admins[$ban['banned_by']]) ? $admins[$ban['banned_by']] : $hesklang['e_udel']; ?></td>
                    <td><?php echo hesk_date($ban['dt']); ?></td>
                    <?php if ($can_unban): ?>
                    <td class="unban">
                        <?php $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                            $hesklang['delban_confirm'],
                            'banned_emails.php?a=unban&amp;id='. $ban['id'] .'&amp;token='. hesk_token_echo(0)); ?>
                        <a title="<?php echo $hesklang['delban']; ?>" href="javascript:" data-modal="[data-modal-id='<?php echo $modal_id; ?>']">
                            <?php echo $hesklang['delban']; ?>
                        </a>
                    </td>
                    <?php endif; ?>
                </tr>
                <?php endwhile;
                endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/

function ban_email()
{
	global $hesk_settings, $hesklang;

	// A security check
	hesk_token_check();

	// Get the email
	$email = hesk_emailCleanup( strtolower( hesk_input( hesk_REQUEST('email') ) ) );

	// Nothing entered?
	if ( ! strlen($email) )
	{
    	hesk_process_messages($hesklang['enterbanemail'],'banned_emails.php');
	}

	// Only allow one email to be entered
	$email = ($index = strpos($email, ',')) ? substr($email, 0,  $index) : $email;
	$email = ($index = strpos($email, ';')) ? substr($email, 0,  $index) : $email;

    // We don't need *@ to ban domains, remove the star if present
    if (strpos($email, '*@') === 0) {
        $email = ltrim($email, '*');
    }

	// Validate email address
	$hesk_settings['multi_eml'] = 0;

	if ( ! hesk_validateEmail($email, '', 0) && ! verify_email_domain($email) )
	{
		hesk_process_messages($hesklang['validbanemail'],'banned_emails.php');
	}

	// Redirect either to banned emails or ticket page from now on
	$redirect_to = ($trackingID = hesk_cleanID()) ? 'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999) : 'banned_emails.php';

	// Prevent duplicate rows
	if ( $_SESSION['ban_email']['id'] = hesk_isBannedEmail($email) )
	{
    	hesk_process_messages( sprintf($hesklang['emailbanexists'], $email) ,$redirect_to,'NOTICE');
	}

	// Insert the email address into database
	hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."banned_emails` (`email`,`banned_by`) VALUES ('".hesk_dbEscape($email)."','".intval($_SESSION['id'])."')");

	// Remember email that got banned
	$_SESSION['ban_email']['id'] = hesk_dbInsertID();

	// Show success
    hesk_process_messages( sprintf($hesklang['email_banned'], $email) ,$redirect_to,'SUCCESS');

} // End ban_email()


function unban_email()
{
	global $hesk_settings, $hesklang;

	// A security check
	hesk_token_check();

	// Delete from bans
	hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."banned_emails` WHERE `id`=" . intval( hesk_GET('id') ) );

	// Redirect either to banned emails or ticket page from now on
	$redirect_to = ($trackingID = hesk_cleanID()) ? 'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999) : 'banned_emails.php';

	// Show success
    hesk_process_messages($hesklang['email_unbanned'],$redirect_to,'SUCCESS');

} // End unban_email()


function verify_email_domain($domain)
{
    // Does it start with an @?
	$atIndex = strrpos($domain, "@");
	if ($atIndex !== 0)
	{
		return false;
	}

	// Get the domain and domain length
	$domain = substr($domain, 1);
	$domainLen = strlen($domain);

    // Check domain part length
	if ($domainLen < 1 || $domainLen > 254)
	{
		return false;
	}

    // Check domain part characters
	if ( ! preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain) )
	{
		return false;
	}

	// Domain part mustn't have two consecutive dots
	if ( strpos($domain, '..') !== false )
	{
		return false;
	}

	// All OK
	return true;

} // END verify_email_domain()

?>
banned_ips.php
wget 'https://lists2.roe3.org/hesk/admin/banned_ips.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
hesk_checkPermission('can_ban_ips');
$can_unban = hesk_checkPermission('can_unban_ips', 0);

// Define required constants
define('LOAD_TABS',1);

// What should we do?
if ( $action = hesk_REQUEST('a') )
{
	if ( defined('HESK_DEMO') ) {hesk_process_messages($hesklang['ddemo'], 'banned_ips.php', 'NOTICE');}
	elseif ($action == 'ban')   {ban_ip();}
	elseif ($action == 'unban' && $can_unban) {unban_ip();}
	elseif ($action == 'unbantemp' && $can_unban) {unban_temp_ip();}
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
hesk_handle_messages();
?>
<div class="main__content tools">
    <h2>
        <?php echo $hesklang['banip']; ?>
        <div class="tooltype right out-close">
            <svg class="icon icon-info">
                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
            </svg>
            <div class="tooltype__content">
                <div class="tooltype__wrapper">
                    <?php echo $hesklang['banip_intro']; ?>
                </div>
            </div>
        </div>
    </h2>
    <form action="banned_ips.php" method="post" name="form1">
        <div class="tools__add-mail form">
            <div class="form-group">
                <input type="text" name="ip" maxlength="255" placeholder="<?php echo $hesklang['bananip']; ?>" class="form-control" autofocus aria-label="<?php echo $hesklang['banip']; ?>">
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
                <input type="hidden" name="a" value="ban" />
                <button type="submit" class="btn btn--blue-border" ripple="ripple"><?php echo $hesklang['savebanip']; ?></button>
            </div>
            <div class="mail--examples"><?php echo $hesklang['banex']; ?></div>
            <ul style="margin-left: 10px">
                <li>123.0.0.0</li>
                <li>123.0.0.1 - 123.0.0.53</li>
                <li>123.0.0.0/24</li>
                <li>123.0.*.*</li>
            </ul>
        </div>
    </form>
    <?php
    // Get login failures
    $res = hesk_dbQuery("SELECT `ip`, TIMESTAMPDIFF(MINUTE, NOW(), DATE_ADD(`last_attempt`, INTERVAL ".intval($hesk_settings['attempt_banmin'])." MINUTE) ) AS `minutes` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."logins` WHERE `number` >= ".intval($hesk_settings['attempt_limit'])." AND `last_attempt` > (NOW() -  INTERVAL ".intval($hesk_settings['attempt_banmin'])." MINUTE)");
    $num = hesk_dbNumRows($res);

    if ($num > 0):
    ?>
    <h3><?php echo $hesklang['iptemp']; ?></h3>
    <div class="table-wrapper ips">
        <table id="temporary-bans-table" class="table sindu-table">
            <thead>
            <tr>
                <th><?php echo $hesklang['ip']; ?></th>
                <th><?php echo $hesklang['m2e']; ?></th>
                <?php if ($can_unban): ?>
                    <th><?php echo $hesklang['opt']; ?></th>
                <?php endif; ?>
            </tr>
            </thead>
            <tbody>
            <?php while ($ban = hesk_dbFetchAssoc($res)): ?>
	        <tr>
	            <td><?php echo $ban['ip']; ?></td>
	            <td><?php echo $ban['minutes']; ?></td>
                <?php if ($can_unban): ?>
                <td>
                    <a href="banned_ips.php?a=ban&amp;ip=<?php echo urlencode($ban['ip']); ?>&amp;token=<?php hesk_token_echo(); ?>"><?php echo $hesklang['ippermban']; ?></a>
                    <a href="banned_ips.php?a=unbantemp&amp;ip=<?php echo urlencode($ban['ip']); ?>&amp;token=<?php hesk_token_echo(); ?>"><?php echo $hesklang['delban']; ?></a>
                </td>
                <?php endif; ?>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
    <h3><?php echo $hesklang['ipperm']; ?></h3>
    <div class="table-wrapper ips">
        <table id="default-table" class="table sindu-table">
            <thead>
            <tr>
                <th><?php echo $hesklang['ip']; ?></th>
                <th><?php echo $hesklang['iprange']; ?></th>
                <th><?php echo $hesklang['banby']; ?></th>
                <th><?php echo $hesklang['date']; ?></th>
                <?php if ($can_unban): ?>
                <th><?php echo $hesklang['opt']; ?></th>
                <?php endif; ?>
            </tr>
            </thead>
            <tbody>
            <?php
            // Get banned ips from database
            $res = hesk_dbQuery('SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'banned_ips` ORDER BY `ip_from` ASC');
            $num = hesk_dbNumRows($res);

            if ($num < 1):
            ?>
            <tr>
                <td colspan="<?php echo $can_unban ? 5 : 4; ?>"><?php echo $hesklang['no_banips']; ?></td>
            </tr>
            <?php
            else:
                // List of staff
                if ( ! isset($admins) )
                {
                    $admins = array();
                    $res2 = hesk_dbQuery("SELECT `id`,`name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users`");
                    while ($row=hesk_dbFetchAssoc($res2))
                    {
                        $admins[$row['id']]=$row['name'];
                    }
                }

                $i = 1;

                while ($ban = hesk_dbFetchAssoc($res)):
                    $table_row = '';
                    if (isset($_SESSION['ban_ip']['id']) && $ban['id'] == $_SESSION['ban_ip']['id'])
                    {
                        $table_row = 'class="ticket-new"';
                        unset($_SESSION['ban_ip']['id']);
                    }
            ?>
                <tr <?php echo $table_row; ?>>
                    <td><?php echo $ban['ip_display']; ?></td>
                    <td><?php echo $ban['ip_to'] == $ban['ip_from'] ? long2ip($ban['ip_to']) : long2ip($ban['ip_from']) . ' - ' . long2ip($ban['ip_to']); ?></td>
                    <td><?php echo isset($admins[$ban['banned_by']]) ? $admins[$ban['banned_by']] : $hesklang['e_udel']; ?></td>
                    <td><?php echo hesk_date($ban['dt']); ?></td>
                    <?php if ($can_unban): ?>
                        <td class="unban">
                            <?php $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                                $hesklang['delban_confirm'],
                                'banned_ips.php?a=unban&amp;id='. $ban['id'] .'&amp;token='. hesk_token_echo(0)); ?>
                            <a href="javascript:" data-modal="[data-modal-id='<?php echo $modal_id; ?>']">
                                <?php echo $hesklang['delban']; ?>
                            </a>
                        </td>
                    <?php endif; ?>
                </tr>
            <?php
                endwhile;
            endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/

function ban_ip()
{
	global $hesk_settings, $hesklang;

	// A security check
	hesk_token_check();

	// Get the ip
	$ip = preg_replace('/[^0-9\.\-\/\*]/', '', hesk_REQUEST('ip') );
	$ip_display = str_replace('-', ' - ', $ip);

	// Nothing entered?
	if ( ! strlen($ip) )
	{
    	hesk_process_messages($hesklang['enterbanip'],'banned_ips.php');
	}

	// Convert asterisk to ranges
	if ( strpos($ip, '*') !== false )
	{
		$ip = str_replace('*', '0', $ip) . '-' . str_replace('*', '255', $ip);
	}

	$ip_regex = '(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])';

	// Is this a single IP address?
	if ( preg_match('/^'.$ip_regex.'$/', $ip) )
	{
    	$ip_from = ip2long($ip);
		$ip_to   = $ip_from;
	}
    // Is this an IP range?
	elseif ( preg_match('/^'.$ip_regex.'\-'.$ip_regex.'$/', $ip) )
	{
    	list($ip_from, $ip_to) = explode('-', $ip);
		$ip_from = ip2long($ip_from);
		$ip_to   = ip2long($ip_to);
	}
    // Is this an IP with CIDR?
	elseif ( preg_match('/^'.$ip_regex.'\/([0-9]{1,2})$/', $ip, $matches) && $matches[4] >= 0 && $matches[4] <= 32)
	{
    	list($ip_from, $ip_to) = hesk_cidr_to_range($ip);
	}
	// Not a valid input
	else
	{
    	hesk_process_messages($hesklang['validbanip'],'banned_ips.php');
	}

    if ($ip_from === false || $ip_to === false)
    {
        hesk_process_messages($hesklang['validbanip'],'banned_ips.php');
    }

	// Make sure we have valid ranges
	if ($ip_from < 0)
	{
		$ip_from += 4294967296;
	}
	elseif ($ip_from > 4294967296)
	{
    	$ip_from = 4294967296;
	}
	if ($ip_to < 0)
	{
		$ip_to += 4294967296;
	}
	elseif ($ip_to > 4294967296)
	{
    	$ip_to = 4294967296;
	}

	// Make sure $ip_to is not lower that $ip_from
	if ($ip_to < $ip_from)
	{
		$tmp    = $ip_to;
    	$ip_to   = $ip_from;
		$ip_from = $tmp;
	}

	// Is this IP address already banned?
	$res = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."banned_ips` WHERE {$ip_from} BETWEEN `ip_from` AND `ip_to` AND {$ip_to} BETWEEN `ip_from` AND `ip_to` LIMIT 1");
	if ( hesk_dbNumRows($res) == 1 )
	{
		$_SESSION['ban_ip']['id'] = hesk_dbResult($res);
		$hesklang['ipbanexists'] = ($ip_to == $ip_from) ? sprintf($hesklang['ipbanexists'], long2ip($ip_to) ) : sprintf($hesklang['iprbanexists'], long2ip($ip_from).' - '.long2ip($ip_to) );
    	hesk_process_messages($hesklang['ipbanexists'],'banned_ips.php','NOTICE');
	}

	// Delete any duplicate banned IP or ranges that are within the new banned range
	hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."banned_ips` WHERE `ip_from` >= {$ip_from} AND `ip_to` <= {$ip_to}");

	// Delete temporary bans from logins table
	if ($ip_to == $ip_from)
	{
		hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."logins` WHERE `ip`='".hesk_dbEscape($ip_display)."'");
	}

	// Redirect either to banned ips or ticket page from now on
	$redirect_to = ($trackingID = hesk_cleanID()) ? 'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999) : 'banned_ips.php';

	// Insert the ip address into database
	hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."banned_ips` (`ip_from`,`ip_to`,`ip_display`,`banned_by`) VALUES ({$ip_from}, {$ip_to},'".hesk_dbEscape($ip_display)."','".intval($_SESSION['id'])."')");

	// Remember ip that got banned
	$_SESSION['ban_ip']['id'] = hesk_dbInsertID();

    // Generate success message
	$hesklang['ip_banned'] = ($ip_to == $ip_from) ? sprintf($hesklang['ip_banned'], long2ip($ip_to) ) : sprintf($hesklang['ip_rbanned'], long2ip($ip_from).' - '.long2ip($ip_to) );

	// Show success
    hesk_process_messages( sprintf($hesklang['ip_banned'], $ip) ,$redirect_to,'SUCCESS');

} // End ban_ip()


function unban_temp_ip()
{
	global $hesk_settings, $hesklang;

	// A security check
	hesk_token_check();

	// Get the ip
	$ip = preg_replace('/[^0-9\.\-\/\*]/', '', hesk_REQUEST('ip') );

	// Delete from bans
	hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."logins` WHERE `ip`='" . hesk_dbEscape($ip) . "'");

	// Show success
    hesk_process_messages($hesklang['ip_tempun'],'banned_ips.php','SUCCESS');

} // End unban_temp_ip()


function unban_ip()
{
	global $hesk_settings, $hesklang;

	// A security check
	hesk_token_check();

	// Delete from bans
	hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."banned_ips` WHERE `id`=" . intval( hesk_GET('id') ) );

	// Redirect either to banned ips or ticket page from now on
	$redirect_to = ($trackingID = hesk_cleanID()) ? 'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999) : 'banned_ips.php';

	// Show success
    hesk_process_messages($hesklang['ip_unbanned'],$redirect_to,'SUCCESS');

} // End unban_ip()


function hesk_cidr_to_range($cidr)
{
	$range = array();
	$cidr = explode('/', $cidr);
	$range[0] = (ip2long($cidr[0])) & ((-1 << (32 - (int)$cidr[1])));
	$range[1] = (ip2long($cidr[0])) + pow(2, (32 - (int)$cidr[1])) - 1;
	return $range;
} // END hesk_cidr_to_range()

?>
change_status.php
wget 'https://lists2.roe3.org/hesk/admin/change_status.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
hesk_checkPermission('can_view_tickets');

/* A security check */
hesk_token_check();

/* Ticket ID */
$trackingID = hesk_cleanID() or die($hesklang['int_error'].': '.$hesklang['no_trackID']);
hesk_verifyStaffTicketAccess($trackingID);

// Load statuses
require_once(HESK_PATH . 'inc/statuses.inc.php');

/* New status */
$status = intval( hesk_REQUEST('s') );
if ( ! isset($hesk_settings['statuses'][$status]))
{
	hesk_process_messages($hesklang['instat'],'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999),'NOTICE');
}

// We need can_reply_tickets permission unless we are closing a ticket
if ($status != 3)
{
    hesk_checkPermission('can_reply_tickets');
}

$locked = 0;

// Is the new status same as old status?
if (hesk_get_ticket_status_from_DB($trackingID) == $status) {
    hesk_process_messages($hesklang['noch'],'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999),'NOTICE');
}

if ($status == 3) // Closed
{
    if ( ! hesk_checkPermission('can_resolve', 0))
    {
        hesk_process_messages($hesklang['noauth_resolve'],'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999),'NOTICE');
    }

	$action = $hesklang['ticket_been'] . ' ' . $hesklang['closed'];
    $revision = sprintf($hesklang['thist3'],hesk_date(),addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');

    if ($hesk_settings['custopen'] != 1)
    {
    	$locked = 1;
    }

    // If customer notifications are off, we need to check if the tickets has collaborators for potential notification
    if ( ! $hesk_settings['notify_closed']) {
        $result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `trackid`='".hesk_dbEscape($trackingID)."' LIMIT 1");
        if (hesk_dbNumRows($result) != 1) {
            hesk_error($hesklang['ticket_not_found']);
        }
        $ticket = hesk_dbFetchAssoc($result);
        $ticket['collaborators'] = hesk_getTicketsCollaboratorIDs($ticket['id']);
    }

	// Notify customer of closed ticket?
	if ($hesk_settings['notify_closed'] || ! empty( $ticket['collaborators']))
	{
        // Get ticket info
        if ( ! isset($ticket)) {
            $result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `trackid`='".hesk_dbEscape($trackingID)."' LIMIT 1");
            if (hesk_dbNumRows($result) != 1) {
                hesk_error($hesklang['ticket_not_found']);
            }
            $ticket = hesk_dbFetchAssoc($result);
            $ticket['collaborators'] = hesk_getTicketsCollaboratorIDs($ticket['id']);
        }

		$ticket['dt'] = hesk_date($ticket['dt'], true);
		$ticket['lastchange'] = hesk_date($ticket['lastchange'], true);
        $ticket['due_date'] = hesk_format_due_date($ticket['due_date']);

        require_once(HESK_PATH . 'inc/customer_accounts.inc.php');
        $customers = hesk_get_customers_for_ticket($ticket['id']);
        $customer_emails = array_map(function($customer) { return $customer['email']; }, $customers);
        $customer_names = array_map(function($customer) { return $customer['name']; }, $customers);
        
        $ticket['email'] = implode(';', $customer_emails);
        $ticket['name'] = implode(';', $customer_names);
        $ticket['last_reply_by'] = hesk_getReplierNameArray($ticket);
		$ticket = hesk_ticketToPlain($ticket, 1, 0);

		// Notify customer
		require(HESK_PATH . 'inc/email_functions.inc.php');

        if ($hesk_settings['notify_closed']) {
            hesk_notifyCustomer('ticket_closed');
        }

        if (count($ticket['collaborators'])) {
            hesk_notifyAssignedStaff(false, 'collaborator_resolved', 'notify_collaborator_resolved', 'notify_collaborator_resolved', array($_SESSION['id']));
        }
	}

	// Log who marked the ticket resolved
	$closedby_sql = ' , `closedat`=NOW(), `closedby`='.intval($_SESSION['id']).' ';
}
elseif ($status != 0)
{
    $status_name = hesk_get_status_name($status);
	$action = sprintf($hesklang['tsst'], $status_name);
    $revision = sprintf($hesklang['thist9'],hesk_date(),addslashes($status_name),addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');

	// Ticket is not resolved
	$closedby_sql = ' , `closedat`=NULL, `closedby`=NULL ';
}
else // Opened
{
	$action = $hesklang['ticket_been'] . ' ' . $hesklang['opened'];
    $revision = sprintf($hesklang['thist4'],hesk_date(),addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');

	// Ticket is not resolved
	$closedby_sql = ' , `closedat`=NULL, `closedby`=NULL ';
}

hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `status`='{$status}', `locked`='{$locked}' $closedby_sql , `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') WHERE `trackid`='".hesk_dbEscape($trackingID)."'");

if (hesk_dbAffectedRows() != 1)
{
	hesk_error("$hesklang[int_error]: $hesklang[trackID_not_found].");
}

hesk_process_messages($action,'admin_ticket.php?track='.$trackingID.'&Refresh='.rand(10000,99999),'SUCCESS');
collaborator.php
wget 'https://lists2.roe3.org/hesk/admin/collaborator.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();
require(HESK_PATH . 'inc/email_functions.inc.php');

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

$can_assign_others = hesk_checkPermission('can_assign_others',0);
if ($can_assign_others)
{
    $can_assign_self = TRUE;
}
else
{
    $can_assign_self = hesk_checkPermission('can_assign_self',0);
}

/* A security check */
hesk_token_check();

if ( ! $can_assign_others) {
    hesk_error($hesklang['no_permission']);
}

// Find ticket ID
$trackingID = hesk_cleanID() or die($hesklang['int_error'].': '.$hesklang['no_trackID']);
$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `trackid`='".hesk_dbEscape($trackingID)."' LIMIT 1");
if (hesk_dbNumRows($res) != 1) {
    hesk_error($hesklang['ticket_not_found']);
}
$ticket = hesk_dbFetchAssoc($res);
hesk_verifyStaffTicketAccess($trackingID, $ticket);

$collaborator = empty($_REQUEST['collaborator']) ? 0 : 1;
$_SERVER['PHP_SELF'] = 'admin_ticket.php?track='.$trackingID.'&Refresh='.rand(10000,99999);

$user = intval(hesk_REQUEST('user'));

if (empty($user)) {
    hesk_process_messages($hesklang['no_valid_id'],$_SERVER['PHP_SELF']);
}

// Verify the user has access to the ticket category
$res = hesk_dbQuery("SELECT `id`,`user`,`name`,`email`,`isadmin`,`language`,`categories`,`notify_collaborator_added` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id`='{$user}' AND `active` = 1 LIMIT 1");
$row = hesk_dbFetchAssoc($res);
if ( ! $row)
{
    hesk_process_messages($hesklang['no_valid_id'], $_SERVER['PHP_SELF']);
}
if ( ! $row['isadmin'])
{
    $row['categories']= hesk_getCategoriesForUser($row['id']);
    if (!in_array($ticket['category'],$row['categories']))
    {
        hesk_error($hesklang['unoa']);
    }
}

if ($collaborator) {
    // ADD AS A COLLABORATOR
    hesk_dbQuery("
        INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_collaborator` (`ticket_id`, `user_id`)
        SELECT ".intval($ticket['id']).", {$user}
        WHERE NOT EXISTS (
            SELECT 1
            FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_collaborator`
            WHERE `ticket_id`=".intval($ticket['id'])." AND `user_id`={$user}
        )
    " );

    if ( ! hesk_dbAffectedRows()) {
        hesk_process_messages($hesklang['user_collaborator_added'],$_SERVER['PHP_SELF'],'SUCCESS');
    }

    $revision = sprintf($hesklang['thist24'], hesk_date(), addslashes($row['name']).' ('.$row['user'].')', addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `history`=CONCAT(`history`,'" . hesk_dbEscape($revision) . "') WHERE `id`=" . intval($ticket['id']));

    if ($user != intval($_SESSION['id']) && $row['notify_collaborator_added']) {
        $customers = hesk_get_customers_for_ticket($ticket['id']);
        $customer_emails = array_map(function($customer) { return $customer['email']; }, $customers);
        $customer_names = array_map(function($customer) { return $customer['name']; }, $customers);

        /* --> Prepare message */

        // 1. Generate the array with ticket info that can be used in emails
        $info = array(
        'email'         => implode(';', $customer_emails),
        'category'      => $ticket['category'],
        'priority'      => $ticket['priority'],
        'owner'         => $ticket['owner'],
        'collaborators' => hesk_getTicketsCollaboratorIDs($ticket['id']),
        'trackid'       => $ticket['trackid'],
        'status'        => $ticket['status'],
        'name'          => implode(';', $customer_names),
        'subject'       => $ticket['subject'],
        'message'       => $ticket['message'],
        'message_html'  => $ticket['message_html'],
        'attachments'   => $ticket['attachments'],
        'dt'            => hesk_date($ticket['dt'], true),
        'lastchange'    => hesk_date($ticket['lastchange'], true),
        'due_date'      => hesk_format_due_date($ticket['due_date']),
        'id'            => $ticket['id'],
        'time_worked'   => $ticket['time_worked'],
        'last_reply_by' => hesk_getReplierNameArray($ticket),
        );

        // 2. Add custom fields to the array
        foreach ($hesk_settings['custom_fields'] as $k => $v)
        {
            $info[$k] = $v['use'] ? $ticket[$k] : '';
        }

        // 3. Make sure all values are properly formatted for email
        $ticket = hesk_ticketToPlain($info, 1, 0);

        hesk_notifyAssignedStaff($row, 'collaborator_added', 'notify_collaborator_added', false);
    }

    hesk_process_messages($hesklang['user_collaborator_added'],$_SERVER['PHP_SELF'],'SUCCESS');
} else {
    // REMOVE COLLABORATOR
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_collaborator` WHERE `ticket_id`={$ticket['id']} AND `user_id`={$user}");

    $revision = sprintf($hesklang['thist25'], hesk_date(), addslashes($row['name']).' ('.$row['user'].')', addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `history`=CONCAT(`history`,'" . hesk_dbEscape($revision) . "') WHERE `id`=" . intval($ticket['id']));

    if ($user == $_SESSION['id']) {
        hesk_process_messages($hesklang['not_collaborating'],$_SERVER['PHP_SELF'],'SUCCESS');
    } else {
        hesk_process_messages($hesklang['user_collaborator_removed'],$_SERVER['PHP_SELF'],'SUCCESS');
    }
}
custom_fields.php
wget 'https://lists2.roe3.org/hesk/admin/custom_fields.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

define('LOAD_TABS',1);
define('CALENDAR',1);

// Get all the req files and functions
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/setup_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_man_settings');

// Load custom fields
require_once(HESK_PATH . 'inc/custom_fields.inc.php');

// List of categories
$hesk_settings['categories'] = array();
$res = hesk_dbQuery("SELECT `id`, `name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` ORDER BY `cat_order` ASC");
while ($row=hesk_dbFetchAssoc($res))
{
	$hesk_settings['categories'][$row['id']] = $row['name'];
}

// What should we do?
if ( $action = hesk_REQUEST('a') )
{
	if ($action == 'edit_cf') {edit_cf();}
	elseif ( defined('HESK_DEMO') ) {hesk_process_messages($hesklang['ddemo'], 'custom_fields.php', 'NOTICE');}
	elseif ($action == 'new_cf') {new_cf();}
	elseif ($action == 'save_cf') {save_cf();}
	elseif ($action == 'order_cf') {order_cf();}
	elseif ($action == 'remove_cf') {remove_cf();}
}

// Print header
require_once(HESK_PATH . 'inc/header.inc.php');

// Print main manage users page
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
if (!hesk_SESSION(array('new_cf','errors'))) {
    hesk_handle_messages();
}

// Did we reach the custom fields limit?
if ($hesk_settings['num_custom_fields'] >= 100 && $action !== 'edit_cf')
{
    hesk_show_info($hesklang['cf_limit_all']);
}

$hesk_settings['datepicker']['#dmin']['position'] = 'left top';
$hesk_settings['datepicker']['#dmax']['position'] = 'left bottom';
?>

<div class="main__content tools">
    <section class="tools__between-head wider">
        <h2>
            <?php echo $hesklang['tab_4']; ?>
            <?php echo '(' . $hesk_settings['num_custom_fields'] . '/100)'; ?>
            <div class="tooltype right out-close">
                <svg class="icon icon-info">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                </svg>
                <div class="tooltype__content">
                    <div class="tooltype__wrapper">
                        <?php echo $hesklang['cf_intro']; ?>
                    </div>
                </div>
            </div>
        </h2>
        <?php if ($hesk_settings['num_custom_fields'] < 100 && $action !== 'edit_cf'): ?>
        <div class="btn btn--blue-border" ripple="ripple" data-action="create-custom-field">
            <?php echo $hesklang['new_cf']; ?>
        </div>
        <?php endif; ?>
    </section>
    <div class="table-wrapper custom-field">
        <div class="table">
            <table id="default-table" class="table sindu-table">
                <thead>
                <tr>
                    <th><?php echo $hesklang['id']; ?></th>
                    <th><?php echo $hesklang['custom_n']; ?></th>
                    <th><?php echo $hesklang['s_type']; ?></th>
                    <th><?php echo $hesklang['visibility']; ?></th>
                    <th><?php echo $hesklang['custom_r']; ?></th>
                    <th><?php echo $hesklang['category']; ?></th>
                    <th aria-label="Actions"></th>
                </tr>
                </thead>
                <tbody>
                <?php if ($hesk_settings['num_custom_fields'] < 1): ?>
                <tr>
                    <td colspan="7">
                        <?php echo $hesklang['no_cf']; ?>
                    </td>
                </tr>
                <?php
                endif;

                $num_before = 0;
                $num_after = 0;

                foreach ($hesk_settings['custom_fields'] as $tmp_id => $cf) {
                    if ($cf['place']) {
                        $num_after++;
                    } else {
                        $num_before++;
                    }
                }

                $k = 1;
                $first_before_custom_field = true;
                $first_after_custom_field = true;
                $hide_up = false;

                foreach ($hesk_settings['custom_fields'] as $tmp_id => $cf) {
                    $tmp_id = intval(str_replace('custom', '', $tmp_id));

                    if ($hide_up)
                    {
                        $hide_up = false;
                    }

                    if ($first_before_custom_field && $cf['place'] == 0) {
                        ?>
                        <tr class="title">
                            <td colspan="7"><?php echo $hesklang['place_before']; ?></td>
                        </tr>
                        <?php
                        $first_before_custom_field = false;
                    } elseif ($first_after_custom_field && $cf['place'] == 1) {
                        ?>
                        <tr class="title">
                            <td colspan="7"><?php echo $hesklang['place_after']; ?></td>
                        </tr>
                        <?php
                        $after = false;
                        $first_after_custom_field = false;
                        $hide_up = true;
                    }

                    $cf['type'] = hesk_custom_field_type($cf['type']);

                    $cf['use'] = ($cf['use'] == 1) ? $hesklang['cf_public'] : $hesklang['cf_private'];

                    $cf['req'] = ($cf['req'] == 0) ? $hesklang['no'] : ($cf['req'] == 2 ? $hesklang['yes'] : $hesklang['cf_cust']);

                    $cf['category'] = count($cf['category']) ? $hesklang['cf_cat'] : $hesklang['cf_all'];

                    $table_row = '';
                    if (isset($_SESSION['cford']) && $_SESSION['cford'] == $tmp_id) {
                        $table_row = 'class="ticket-new"';
                        unset($_SESSION['cford']);
                    }

                    ?>
                    <tr <?php echo $table_row; ?>>
                        <td><?php echo $tmp_id; ?></td>
                        <td><?php echo $cf['name']; ?></td>
                        <td><?php echo $cf['type']; ?></td>
                        <td><?php echo $cf['use']; ?></td>
                        <td><?php echo $cf['req']; ?></td>
                        <td><?php echo $cf['category']; ?></td>
                        <td class="nowrap buttons">
                            <?php $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                                $hesklang['del_cf'],
                                'custom_fields.php?a=remove_cf&amp;id='. $tmp_id .'&amp;token='. hesk_token_echo(0)); ?>
                            <p>
                                <?php
                                if ($hesk_settings['num_custom_fields'] == 2 && $num_before == 1)
                                {
                                    // Special case, don't print anything
                                }
                                elseif ($hesk_settings['num_custom_fields'] > 1)
                                {
                                    if (($num_before == 1 && $cf['place'] == 0) || ($num_after == 1 && $cf['place'] == 1))
                                    {
                                        // Only 1 custom fields in this place, don't print anything
                                        ?>
                                        <a href="#" style="visibility: hidden">
                                            <svg class="icon icon-chevron-up">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                            </svg>
                                        </a>
                                        <a href="#" style="visibility: hidden"
                                           title="<?php echo $hesklang['move_dn']; ?>">
                                            <svg class="icon icon-chevron-down">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                            </svg>
                                        </a>
                                        <?php
                                    }
                                    elseif ($k == 1 || $hide_up)
                                    {
                                        ?>
                                        <a href="#" style="visibility: hidden" aria-label="<?php echo $hesklang['move_up']; ?>">
                                            <svg class="icon icon-chevron-up">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                            </svg>
                                        </a>
                                        <a class="tooltip" href="custom_fields.php?a=order_cf&amp;id=<?php echo $tmp_id; ?>&amp;move=15&amp;token=<?php hesk_token_echo(); ?>"
                                           title="<?php echo $hesklang['move_dn']; ?>">
                                            <svg class="icon icon-chevron-down">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                            </svg>
                                        </a>
                                        <?php
                                    }
                                    elseif ($k == $hesk_settings['num_custom_fields'] || $k == $num_before)
                                    {
                                        ?>
                                        <a class="tooltip" href="custom_fields.php?a=order_cf&amp;id=<?php echo $tmp_id; ?>&amp;move=-15&amp;token=<?php hesk_token_echo(); ?>"
                                           title="<?php echo $hesklang['move_up']; ?>">
                                            <svg class="icon icon-chevron-up">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                            </svg>
                                        </a>
                                        <a href="#" style="visibility: hidden"
                                           title="<?php echo $hesklang['move_dn']; ?>">
                                            <svg class="icon icon-chevron-down">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                            </svg>
                                        </a>
                                        <?php
                                    }
                                    else
                                    {
                                        ?>
                                        <a class="tooltip" href="custom_fields.php?a=order_cf&amp;id=<?php echo $tmp_id; ?>&amp;move=-15&amp;token=<?php hesk_token_echo(); ?>"
                                           title="<?php echo $hesklang['move_up']; ?>">
                                            <svg class="icon icon-chevron-up">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                            </svg>
                                        </a>
                                        <a class="tooltip" href="custom_fields.php?a=order_cf&amp;id=<?php echo $tmp_id; ?>&amp;move=15&amp;token=<?php hesk_token_echo(); ?>"
                                           title="<?php echo $hesklang['move_dn']; ?>">
                                            <svg class="icon icon-chevron-down">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                            </svg>
                                        </a>
                                        <?php
                                    }
                                }
                                ?>
                                <a href="custom_fields.php?a=edit_cf&amp;id=<?php echo $tmp_id; ?>"
                                   title="<?php echo $hesklang['edit']; ?>"
                                   class="edit tooltip">
                                    <svg class="icon icon-edit-ticket">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-edit-ticket"></use>
                                    </svg>
                                </a>
                                <a href="javascript:"
                                   data-modal="[data-modal-id='<?php echo $modal_id; ?>']"
                                   title="<?php echo $hesklang['delete']; ?>"
                                   class="delete tooltip">
                                    <svg class="icon icon-delete">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-delete"></use>
                                    </svg>
                                </a>
                            </p>
                        </td>
                    </tr>
                    <?php
                    $k++;
                }
                ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<form action="custom_fields.php" method="post" name="form1" class="form right-bar create-custom-field <?php echo hesk_SESSION(array('new_cf','errors')) ? 'invalid' : ''; ?>"
      <?php if ($action === 'edit_cf' || hesk_SESSION(array('new_cf','errors'))) { ?>style="display: block"<?php } ?> aria-label="<?php echo $hesklang['edit_cf']; ?>">
    <div class="right-bar__body form">
        <h3>
            <a href="<?php echo $action === 'edit_cf' ? 'custom_fields.php' : 'javascript:' ?>">
                <svg class="icon icon-back">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                </svg>
                <span><?php echo hesk_SESSION('edit_cf') ? $hesklang['edit_cf'] : $hesklang['new_cf']; ?></span>
            </a>
        </h3>
        <?php
        if (hesk_SESSION(array('new_cf','errors'))) {
            hesk_handle_messages();
        }
        ?>

        <h4><?php echo $hesklang['custom_n']; ?></h4>
        <section class="item--section">
            <?php
            $names = hesk_SESSION(array('new_cf','names'));
            $errors = hesk_SESSION(array('new_cf','errors'));
            $errors = is_array($errors) ? $errors : array();

            if ($hesk_settings['can_sel_lang'] && count($hesk_settings['languages']) > 1) {
                foreach ($hesk_settings['languages'] as $lang => $info): ?>
                    <div class="form-group">
                        <label for="lang_<?php echo $lang; ?>"><?php echo $lang; ?></label>
                        <input type="text" id="lang_<?php echo $lang; ?>" name="name[<?php echo $lang; ?>]" class="form-control <?php echo in_array('name', $errors) ? 'isError' : ''; ?>"
                               value="<?php echo (isset($names[$lang]) ? $names[$lang] : ''); ?>">
                    </div>
                <?php
                endforeach;
            } else { ?>
                <div class="form-group">
                    <label for="sel_lang"><?php echo $hesk_settings['language']; ?></label>
                    <input type="text" id="sel_lang" name="name[<?php echo $hesk_settings['language']; ?>]" class="form-control <?php echo in_array('name', $errors) ? 'isError' : ''; ?>"
                           value="<?php echo isset($names[$hesk_settings['language']]) ? $names[$hesk_settings['language']] : (is_array($names) ? reset($names) : ''); ?>" />
                </div>
            <?php } ?>
            <div class="form-select">
                <label for="s_type"><?php echo $hesklang['s_type']; ?></label>
                <div class="dropdown-select center out-close">
                    <select id="s_type" name="type" onchange="hesk_setType(this.value);">
                        <?php $type = hesk_SESSION(array('new_cf','type'), 'text'); ?>
                        <option value="text"     <?php if ($type == 'text') {echo 'selected';} ?> ><?php echo $hesklang['stf']; ?></option>
                        <option value="textarea" <?php if ($type == 'textarea') {echo 'selected';} ?> ><?php echo $hesklang['stb']; ?></option>
                        <option value="radio"    <?php if ($type == 'radio') {echo 'selected';} ?> ><?php echo $hesklang['srb']; ?></option>
                        <option value="select"   <?php if ($type == 'select') {echo 'selected';} ?> ><?php echo $hesklang['ssb']; ?></option>
                        <option value="checkbox" <?php if ($type == 'checkbox') {echo 'selected';} ?> ><?php echo $hesklang['scb']; ?></option>
                        <option value="date"     <?php if ($type == 'date') {echo 'selected';} ?> ><?php echo $hesklang['date']; ?></option>
                        <option value="email"    <?php if ($type == 'email') {echo 'selected';} ?> ><?php echo $hesklang['email']; ?></option>
                        <option value="hidden"   <?php if ($type == 'hidden') {echo 'selected';} ?> ><?php echo $hesklang['sch']; ?></option>
                    </select>
                </div>
            </div>
            <?php
            $value = hesk_SESSION(array('new_cf','value'));

            if (is_string($value))
            {
                $value = json_decode($value, true);
            }
            ?>
            <div id="text" style="display:<?php echo ($type == 'text') ? 'block' : 'none' ?>">
                <div class="form-group">
                    <label for="max_length"><?php echo $hesklang['custom_l']; ?></label>
                    <input type="text" id="max_length" name="max_length" value="<?php echo isset($value['max_length']) ? intval($value['max_length']) : '255'; ?>" class="form-control">
                </div>
                <div class="form-group">
                    <label for="default_value"><?php echo $hesklang['defw']; ?></label>
                    <input type="text" class="form-control" id="default_value" name="default_value" value="<?php echo isset($value['default_value']) ? $value['default_value'] : ''; ?>">
                </div>
            </div>
            <div id="textarea" style="display:<?php echo ($type == 'textarea') ? 'block' : 'none' ?>">
                <div class="form-group">
                    <label for="rows"><?php echo $hesklang['rows']; ?></label>
                    <input type="text" class="form-control" id="rows" name="rows" value="<?php echo isset($value['rows']) ? intval($value['rows']) : '12'; ?>">
                </div>
                <div class="form-group">
                    <label for="cols"><?php echo $hesklang['cols']; ?></label>
                    <input type="text" class="form-control" id="cols" name="cols" value="<?php echo isset($value['cols']) ? intval($value['cols']) : '60'; ?>">
                </div>
            </div>
            <div id="radio" style="display:<?php echo ($type == 'radio') ? 'block' : 'none' ?>">
                <?php echo $hesklang['opt2']; ?>
                <div class="category-create__autoassign">
                    <label class="switch-checkbox">
                        <input value="1" name="no_default" type="checkbox" id="no_default" <?php if (!empty($value['no_default'])) {echo 'checked';} ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                        <span><?php echo $hesklang['rcheck']; ?></span>
                    </label>
                </div>
                <div class="form-group">
                    <textarea name="radio_options"
                              class="form-control <?php echo in_array('radio_options', $errors) ? 'isError' : ''; ?>"
                              rows="8"
                              cols="40"
                              aria-label="<?php echo $hesklang['opt']; ?>"
                              style="height: inherit;"><?php echo (isset($value['radio_options']) && is_array($value['radio_options'])) ? implode("\n", $value['radio_options']) : ''; ?></textarea>
                </div>
            </div>
            <div id="select" style="display:<?php echo ($type == 'select') ? 'block' : 'none' ?>">
                <p><?php echo $hesklang['opt3']; ?></p>
                <div class="category-create__autoassign">
                    <label class="switch-checkbox">
                        <input value="1" name="show_select" type="checkbox" id="show_select" <?php if ( ! empty($value['show_select'])) {echo 'checked';} ?>>
                        <div class="switch-checkbox__bullet">
                            <i>
                                <svg class="icon icon-close">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                </svg>
                                <svg class="icon icon-tick">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                                </svg>
                            </i>
                        </div>
                        <span><?php echo $hesklang['show_select']; ?></span>
                    </label>
                </div>
                <div class="form-group">
                    <textarea name="select_options"
                              class="form-control <?php echo in_array('select_options', $errors) ? 'isError' : ''; ?>"
                              style="height: inherit"
                              rows="6"
                              aria-label="<?php echo $hesklang['opt']; ?>
                              cols="40"><?php echo isset($value['select_options']) && is_array($value['select_options']) ? implode("\n", $value['select_options']) : ''; ?></textarea>
                </div>

                <h4><?php echo $hesklang['custom_is_searchable']; ?></h4>
                <section class="item--section">
                    <?php $is_searchable = (!empty($value['is_searchable'])) ? $value['is_searchable'] : 0; ?>
                    <div class="radio-custom">
                        <input type="radio" name="is_searchable" id="is_searchable0" value="0" <?php if ($is_searchable == 0) {echo 'checked';} ?>>
                        <label for="is_searchable0"><?php echo $hesklang['no']; ?></label>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" name="is_searchable" id="is_searchable1" value="1" <?php if ($is_searchable == 1) {echo 'checked';} ?>>
                        <label for="is_searchable1"><?php echo $hesklang['yes_via_autocomplete']; ?></label>
                    </div>
                </section>
            </div>
            <div id="checkbox" style="display:<?php echo ($type == 'checkbox') ? 'block' : 'none' ?>">
                <p><?php echo $hesklang['opt4']; ?></p>
                <div class="form-group">
                    <textarea name="checkbox_options"
                              class="form-control <?php echo in_array('checkbox_options', $errors) ? 'isError' : ''; ?>"
                              style="height: inherit"
                              rows="6"
                              aria-label="<?php echo $hesklang['opt']; ?>
                              cols="40"><?php echo isset($value['checkbox_options']) && is_array($value['checkbox_options']) ? implode("\n", $value['checkbox_options']) : ''; ?></textarea>
                </div>
            </div>
            <div id="date" style="display:<?php echo ($type == 'date') ? 'block' : 'none' ?>">
                <div class="form-group">
                    <?php
                    // min date
                    $dmin = isset($value['dmin']) ? $value['dmin'] : '';

                    // Defaults
                    $dmin_pm = '+';
                    $dmin_num = 1;
                    $dmin_type = 'day';

                    // Minimum date is in "+1 day" format
                    if (preg_match("/^([+-]{1})(\d+) (day|week|month|year)$/", $dmin, $matches))
                    {
                        $dmin = '';
                        $dmin_rf = 2;
                        $dmin_pm = $matches[1];
                        $dmin_num = $matches[2];
                        $dmin_type = $matches[3];
                    }
                    // Minimum date is in "MM/DD/YYYY" format
                    elseif (preg_match("/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/", $dmin))
                    {
                        try {
                            $date = new DateTime($dmin . ' t00:00:00');
                            $dmin = hesk_datepicker_format_date($date->getTimestamp());
                            $hesk_settings['datepicker']['#dmin']['timestamp'] = $date->getTimestamp();
                            $dmin_rf = 1;
                        } catch(Exception $e) {
                            $dmin = '';
                            $dmin_rf = 0;
                        }
                    }
                    else
                    {
                        $dmin = '';
                        $dmin_rf = 0;
                    }
                    ?>
                    <label><?php echo $hesklang['dmin']; ?></label>
                    <div class="radio-custom">
                        <input type="radio" name="dmin_rf" id="dmin_rf0" value="0" <?php if ($dmin_rf == 0) {echo 'checked';} ?>>
                        <label for="dmin_rf0"><?php echo $hesklang['d_any']; ?></label>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" name="dmin_rf" id="dmin_rf1" value="1" <?php if ($dmin_rf == 1) {echo 'checked';} ?>>
                        <label for="dmin_rf1"><?php echo $hesklang['d_fixed']; ?></label>
                        <section class="param calendar" style="margin-left: 10px;">
                            <div class="calendar--button">
                                <button type="button" onclick="document.getElementById('dmin_rf1').checked = true" aria-label="<?php echo $hesklang['dmin']; ?>">
                                    <svg class="icon icon-calendar">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-calendar"></use>
                                    </svg>
                                </button>
                                <input name="dmin"
                                       id="dmin"
                                       aria-label="<?php echo $hesklang['dmin']; ?>"
                                    <?php if ($dmin) {echo 'value="'.$dmin.'"';} ?>
                                       type="text" class="datepicker <?php echo in_array('date_range', $errors) ? 'isError' : ''; ?>">
                            </div>
                            <div class="calendar--value" <?php echo ($dmin ? 'style="display: block"' : ''); ?>>
                                <span><?php echo $dmin; ?></span>
                                <i class="close">
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                </i>
                            </div>
                        </section>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" name="dmin_rf" id="dmin_rf2" value="2" <?php if ($dmin_rf == 2) {echo 'checked';} ?>>
                        <label for="dmin_rf2"><?php echo $hesklang['d_relative']; ?></label>
                        <div class="dropdown-select center out-close" style="margin-left: 5px;">
                            <select class="form-control" name="dmin_pm" onclick="document.getElementById('dmin_rf2').checked = true" onchange="document.getElementById('dmin_rf2').checked = true">
                                <option value="+" <?php if ($dmin_pm == '+') {echo 'selected';} ?>>+</option>
                                <option value="-" <?php if ($dmin_pm == '-') {echo 'selected';} ?>>-</option>
                            </select>
                        </div>
                        <input type="text" class="form-control" style="height: inherit; width: inherit; margin-left: 5px; margin-right: 5px;"
                               name="dmin_num" value="<?php echo $dmin_num; ?>"
                               aria-label="<?php echo $hesklang['d_relative'];?>"
                               onclick="document.getElementById('dmin_rf2').checked = true" onchange="document.getElementById('dmin_rf2').checked = true">
                        <div class="dropdown-select center out-close">
                            <select name="dmin_type" onclick="document.getElementById('dmin_rf2').checked = true" onchange="document.getElementById('dmin_rf2').checked = true">
                                <option value="day"   <?php if ($dmin_type == 'day') {echo 'selected';} ?>><?php echo $hesklang['d_day']; ?></option>
                                <option value="week"  <?php if ($dmin_type == 'week') {echo 'selected';} ?>><?php echo $hesklang['d_week']; ?></option>
                                <option value="month" <?php if ($dmin_type == 'month') {echo 'selected';} ?>><?php echo $hesklang['d_month']; ?></option>
                                <option value="year"  <?php if ($dmin_type == 'year') {echo 'selected';} ?>><?php echo $hesklang['d_year']; ?></option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <?php
                    // max date
                    $dmax = isset($value['dmax']) ? $value['dmax'] : '';

                    // Defaults
                    $dmax_pm = '+';
                    $dmax_num = 1;
                    $dmax_type = 'day';

                    // Maximum date is in "+1 day" format
                    if (preg_match("/^([+-]{1})(\d+) (day|week|month|year)$/", $dmax, $matches))
                    {
                        $dmax = '';
                        $dmax_rf = 2;
                        $dmax_pm = $matches[1];
                        $dmax_num = $matches[2];
                        $dmax_type = $matches[3];
                    }
                    // Maximum date is in "MM/DD/YYYY" format
                    elseif (preg_match("/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/", $dmax))
                    {
                        try {
                            $date = new DateTime($dmax . ' t00:00:00');
                            $dmax = hesk_datepicker_format_date($date->getTimestamp());
                            $hesk_settings['datepicker']['#dmax']['timestamp'] = $date->getTimestamp();
                            $dmax_rf = 1;
                        } catch(Exception $e) {
                            $dmax = '';
                            $dmax_rf = 0;
                        }
                    }
                    else
                    {
                        $dmax = '';
                        $dmax_rf = 0;
                    }
                    ?>
                    <label><?php echo $hesklang['dmax']; ?></label>
                    <div class="radio-custom">
                        <input type="radio" name="dmax_rf" id="dmax_rf0" value="0" <?php if ($dmax_rf == 0) {echo 'checked';} ?>>
                        <label for="dmax_rf0"><?php echo $hesklang['d_any']; ?></label>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" name="dmax_rf" id="dmax_rf1" value="1" <?php if ($dmax_rf == 1) {echo 'checked';} ?>>
                        <label for="dmax_rf1"><?php echo $hesklang['d_fixed']; ?></label>
                        <section class="param calendar" style="margin-left: 10px;">
                            <div class="calendar--button">
                                <button type="button" onclick="document.getElementById('dmax_rf1').checked = true" aria-label="<?php echo $hesklang['dmax']; ?>">
                                    <svg class="icon icon-calendar">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-calendar"></use>
                                    </svg>
                                </button>
                                <input name="dmax"
                                       id="dmax"
                                       aria-label="<?php echo $hesklang['dmax']; ?>"
                                    <?php if ($dmax) {echo 'value="'.$dmax.'"';} ?>
                                       type="text" class="datepicker <?php echo in_array('date_range', $errors) ? 'isError' : ''; ?>">
                            </div>
                            <div class="calendar--value" <?php echo ($dmax ? 'style="display: block"' : ''); ?>>
                                <span><?php echo $dmax; ?></span>
                                <i class="close">
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                </i>
                            </div>
                        </section>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" name="dmax_rf" id="dmax_rf2" value="2" <?php if ($dmax_rf == 2) {echo 'checked';} ?>>
                        <label for="dmax_rf2"><?php echo $hesklang['d_relative']; ?></label>
                        <div class="dropdown-select center out-close" style="margin-left: 5px;">
                            <select class="form-control" name="dmax_pm" onclick="document.getElementById('dmax_rf2').checked = true" onchange="document.getElementById('dmax_rf2').checked = true">
                                <option value="+" <?php if ($dmax_pm == '+') {echo 'selected';} ?>>+</option>
                                <option value="-" <?php if ($dmax_pm == '-') {echo 'selected';} ?>>-</option>
                            </select>
                        </div>
                        <input type="text" class="form-control" style="height: inherit; width: inherit; margin-left: 5px; margin-right: 5px;"
                               name="dmax_num" value="<?php echo $dmax_num; ?>"
                               aria-label="<?php echo $hesklang['d_relative'];?>"
                               onclick="document.getElementById('dmax_rf2').checked = true" onchange="document.getElementById('dmax_rf2').checked = true">
                        <div class="dropdown-select center out-close">
                            <select name="dmax_type" onclick="document.getElementById('dmax_rf2').checked = true" onchange="document.getElementById('dmax_rf2').checked = true">
                                <option value="day"   <?php if ($dmax_type == 'day') {echo 'selected';} ?>><?php echo $hesklang['d_day']; ?></option>
                                <option value="week"  <?php if ($dmax_type == 'week') {echo 'selected';} ?>><?php echo $hesklang['d_week']; ?></option>
                                <option value="month" <?php if ($dmax_type == 'month') {echo 'selected';} ?>><?php echo $hesklang['d_month']; ?></option>
                                <option value="year"  <?php if ($dmax_type == 'year') {echo 'selected';} ?>><?php echo $hesklang['d_year']; ?></option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label><?php echo $hesklang['d_format']; ?></label>
                    <?php
                    $date_format = isset($value['date_format']) ? $value['date_format'] : 'F j, Y';

                    $default_formats = array(
                        'm/d/Y',
                        'd/m/Y',
                        'm-d-Y',
                        'd-m-Y',
                        'd.m.Y',
                        'M j Y',
                        'j M Y',
                        'j M y',
                        'F j, Y',
                    );

                    $time = mktime(0, 0, 0, 12, 30, date('Y'));

                    foreach ($default_formats as $format): ?>
                        <div class="radio-custom">
                            <input type="radio" name="date_format" id="format_<?php echo $format; ?>" value="<?php echo $format; ?>" <?php echo $date_format == $format ? 'checked' : ''; ?>>
                            <label for="format_<?php echo $format; ?>"><?php echo date($format, $time); ?></label>
                        </div>
                    <?php endforeach; ?>
                    <div class="radio-custom">
                        <input type="radio" name="date_format" value="custom" id="d_custom" <?php if (!in_array($date_format, $default_formats)) {echo 'checked';} ?>>
                        <label for="d_custom"><?php echo $hesklang['d_custom']; ?></label>
                        <input type="text"
                               class="form-control"
                               name="date_format_custom"
                               style="height: inherit; width: inherit; margin-left: 5px;"
                               value="<?php echo $date_format; ?>"
                               aria-label="<?php echo $hesklang['d_custom']; ?>"
                               onclick="document.getElementById('d_custom').checked = true" onchange="document.getElementById('d_custom').checked = true">
                    </div>
                </div>
                <p><?php echo $hesklang['d_ci']; ?></p>
            </div>
            <div id="email" style="display:<?php echo ($type == 'email') ? 'block' : 'none' ?>">
                <div class="form-group">
                    <label><?php echo $hesklang['meml3']; ?></label>
                    <?php $email_multi = empty($value['multiple']) ? 0 : 1; ?>
                    <div class="radio-custom">
                        <input type="radio" name="email_multi" id="email_multi0" value="0" <?php if ($email_multi == 0) {echo 'checked';} ?>>
                        <label for="email_multi0"><?php echo $hesklang['no']; ?></label>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" name="email_multi" id="email_multi1" value="1" <?php if ($email_multi == 1) {echo 'checked';} ?>>
                        <label for="email_multi1"><?php echo $hesklang['yes']; ?></label>
                    </div>
                </div>
            </div>
            <div id="hidden" style="display:<?php echo ($type == 'hidden') ? 'block' : 'none' ?>">
                <p><?php echo $hesklang['hidf']; ?></p>
                <div class="form-group">
                    <label><?php echo $hesklang['custom_l']; ?></label>
                    <input type="text" class="form-control" name="hidden_max_length"
                           value="<?php echo isset($value['max_length']) ? intval($value['max_length']) : '255'; ?>" aria-label="<?php echo $hesklang['custom_l']; ?>">
                </div>
                <div class="form-group">
                    <label><?php echo $hesklang['defw']; ?></label>
                    <input type="text" class="form-control" name="hidden_default_value"
                           value="<?php echo isset($value['default_value']) ? $value['default_value'] : ''; ?>" aria-label="<?php echo $hesklang['defw']; ?>">
                </div>
            </div>
        </section>
        <h4><?php echo $hesklang['visibility']; ?></h4>
        <section class="item--section">
            <?php $use = hesk_SESSION(array('new_cf','use'), 1); ?>
            <div class="radio-custom">
                <input type="radio" name="use" id="use1" value="1" onchange="hesk_setRadioOptions();" <?php if ($use == 1) {echo 'checked';} ?>>
                <label for="use1"><?php echo $hesklang['cf_public']; ?></label>
            </div>
            <div class="radio-custom">
                <input type="radio" name="use" id="use2" value="2" onchange="hesk_setRadioOptions();" <?php if ($use == 2) {echo 'checked';} ?>>
                <label for="use2"><?php echo $hesklang['cf_private']; ?></label>
            </div>
        </section>
        <h4><?php echo $hesklang['custom_r']; ?></h4>
        <section class="item--section">
            <?php $req = hesk_SESSION(array('new_cf','req'), 0); ?>
            <div class="radio-custom">
                <input type="radio" name="req" id="req0" value="0" <?php if ($req == 0) {echo 'checked';} ?>>
                <label for="req0"><?php echo $hesklang['no']; ?></label>
            </div>
            <div class="radio-custom">
                <input type="radio" name="req" id="req2" value="2" <?php if ($req == 2) {echo 'checked';} ?>>
                <label for="req2"><?php echo $hesklang['yes']; ?></label>
            </div>
            <div class="radio-custom" id="req_customers" style="display:<?php echo ($use == 2) ? 'none' : 'inline'; ?>">
                <input type="radio" name="req" id="req1" value="1" <?php if ($req == 1) {echo 'checked';} ?>>
                <label for="req1"><?php echo $hesklang['cf_cust']; ?></label>
            </div>
        </section>
        <h4><?php echo $hesklang['custom_place']; ?></h4>
        <section class="item--section">
            <?php $place = hesk_SESSION(array('new_cf','place')) ? 1 : 0; ?>
            <div class="radio-custom">
                <input type="radio" name="place" value="0" id="place0" <?php if ($place == 0) {echo 'checked';} ?>>
                <label for="place0"><?php echo $hesklang['place_before']; ?></label>
            </div>
            <div class="radio-custom">
                <input type="radio" name="place" value="1" id="place1" <?php if ($place == 1) {echo 'checked';} ?>>
                <label for="place1"><?php echo $hesklang['place_after']; ?></label>
            </div>
        </section>
        <h4><?php echo $hesklang['category']; ?></h4>
        <section class="item--section">
            <?php $category = hesk_SESSION(array('new_cf','category')) ? 1 : 0; ?>
            <div class="radio-custom">
                <input type="radio" name="category" id="category0" value="0" onchange="hesk_setRadioOptions();" <?php if ($category == 0) {echo 'checked';} ?>>
                <label for="category0"><?php echo $hesklang['cf_all']; ?></label>
            </div>
            <div class="radio-custom">
                <input type="radio" name="category" id="category1" value="1" onchange="hesk_setRadioOptions();" <?php if ($category == 1) {echo 'checked';} ?>>
                <label for="category1"><?php echo $hesklang['cf_cat']; ?></label>
            </div>
            <div id="selcat" style="display:<?php echo $category ? 'block' : 'none'; ?>">
                <select class="multiple form-control <?php echo in_array('categories', $errors) ? 'isError' : ''; ?>"
                        name="categories[]" multiple="multiple" size="10" aria-label="<?php echo $hesklang['allowed_cat']; ?>">
                    <?php
                    $categories = hesk_SESSION(array('new_cf','categories'));
                    $categories = is_array($categories) ? $categories : array();

                    foreach ($hesk_settings['categories'] as $cat_id => $cat_name)
                    {
                        echo '<option value="'.$cat_id.'"'.(in_array($cat_id, $categories) ? ' selected="selected"' : '').'>'.$cat_name.'</option>';
                    }
                    ?>
                </select>
                <?php echo $hesklang['cf_ctrl']; ?>
            </div>
        </section>
        <div class="right-bar__footer">
            <?php if (isset($_SESSION['edit_cf'])): ?>
                <input type="hidden" name="a" value="save_cf" />
                <input type="hidden" name="id" value="<?php echo intval($_SESSION['new_cf']['id']); ?>">
            <?php else: ?>
                <input type="hidden" name="a" value="new_cf">
            <?php endif; ?>
            <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
            <button class="btn btn-full" type="submit" ripple="ripple"><?php echo $hesklang['cf_save']; ?></button>
        </div>
    </div>
</form>

<script type="text/javascript"><!--
function hesk_toggleLayer(nr,setto) {
	if (document.all)
		document.all[nr].style.display = setto;
	else if (document.getElementById)
		document.getElementById(nr).style.display = setto;
}

function hesk_setType(myType) {
	var divs = new Array("text", "textarea", "radio", "select", "checkbox", "date", "email", "hidden");
	var index;
	var setTo;

	for (index = 0; index < divs.length; ++index) {
		setTo = (myType == divs[index] + "") ? 'block' : 'none';
		hesk_toggleLayer(divs[index], setTo);
	}
}

function hesk_setRadioOptions() {
	if(document.getElementById('use1').checked) {
		hesk_toggleLayer('req_customers', 'inline');
	} else {
		hesk_toggleLayer('req_customers', 'none');
		if(document.getElementById('req1').checked) {
			document.getElementById('req0').checked = true;
		}
	}

	if(document.getElementById('category1').checked) {
		hesk_toggleLayer('selcat', 'block');
	} else {
		hesk_toggleLayer('selcat', 'none');
	}
}
//-->
</script>
<?php
hesk_cleanSessionVars( array('new_cf', 'edit_cf') );

require_once(HESK_PATH . 'inc/footer.inc.php');
exit();

/*** START FUNCTIONS ***/

function save_cf()
{
	global $hesk_settings, $hesklang;
	global $hesk_error_buffer;

	// A security check
	hesk_token_check('POST');

	// Get custom field ID
	$id = intval( hesk_POST('id') ) or hesk_error($hesklang['cf_e_id']);

	// Validate inputs
	if (($cf = cf_validate()) == false)
	{
		$_SESSION['edit_cf'] = true;
		$_SESSION['new_cf']['id'] = $id;

		$tmp = '';
		foreach ($hesk_error_buffer as $error)
		{
			$tmp .= "<li>$error</li>\n";
		}
		$hesk_error_buffer = $tmp;

		$hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
		hesk_process_messages($hesk_error_buffer,'custom_fields.php');
	}

	// Add custom field data into database
	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_fields` SET
	`use`      = '{$cf['use']}',
	`place`    = '{$cf['place']}',
	`type`     = '{$cf['type']}',
	`req`      = '{$cf['req']}',
	`category` = ".(count($cf['categories']) ? "'".json_encode($cf['categories'])."'" : 'NULL').",
	`name`     = '".hesk_dbEscape($cf['names'])."',
	`value`    = ".(strlen($cf['value']) ? "'".hesk_dbEscape($cf['value'])."'" : 'NULL')."
	WHERE `id`={$id}");

	// Clear cache
	hesk_purge_cache('cf');

	// Show success
	$_SESSION['cford'] = $id;
	hesk_process_messages($hesklang['cf_mdf'],'custom_fields.php','SUCCESS');

} // End save_cf()


function edit_cf()
{
	global $hesk_settings, $hesklang;

	// Get custom field ID
	$id = intval( hesk_GET('id') ) or hesk_error($hesklang['cf_e_id']);

	// Get details from the database
	$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_fields` WHERE `id`={$id} LIMIT 1");
	if ( hesk_dbNumRows($res) != 1 )
	{
		hesk_error($hesklang['cf_not_found']);
	}
	$cf = hesk_dbFetchAssoc($res);

	$cf['names'] = json_decode($cf['name'], true);
	unset($cf['name']);

	if (isset($cf['category']) && strlen($cf['category']))
	{
		$cf['categories'] = json_decode($cf['category'], true);
		$cf['category'] = 1;
	}
	else
	{
		$cf['categories'] = array();
		$cf['category'] = 0;
	}

	$_SESSION['new_cf'] = $cf;
	$_SESSION['edit_cf'] = true;

} // End edit_cf()


function order_cf()
{
	global $hesk_settings, $hesklang;

	// A security check
	hesk_token_check();

	// Get ID and move parameters
	$id    = intval( hesk_GET('id') ) or hesk_error($hesklang['cf_e_id']);
	$move  = intval( hesk_GET('move') );
	$_SESSION['cford'] = $id;

	// Update article details
	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_fields` SET `order`=`order`+".intval($move)." WHERE `id`={$id}");

	// Update order of all custom fields
	update_cf_order();

	// Clear cache
	hesk_purge_cache('cf');

	// Finish
	header('Location: custom_fields.php');
	exit();

} // End order_cf()


function update_cf_order()
{
	global $hesk_settings, $hesklang;

	// Get list of current custom fields
	$res = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_fields` WHERE `use` IN ('1','2') ORDER BY `place` ASC, `order` ASC");

	// Update database
	$i = 10;
	while ( $cf = hesk_dbFetchAssoc($res) )
	{
		hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_fields` SET `order`=".intval($i)." WHERE `id`='".intval($cf['id'])."'");
		$i += 10;
	}

	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_fields` SET `order`=1000 WHERE `use`='0'");

	return true;

} // END update_cf_order()


function remove_cf()
{
	global $hesk_settings, $hesklang;

	// A security check
	hesk_token_check();

	// Get ID
	$id = intval( hesk_GET('id') ) or hesk_error($hesklang['cf_e_id']);

	// Reset the custom field
	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_fields` SET `use`='0', `place`='0', `type`='text', `req`='0', `category`=NULL, `name`='', `value`=NULL, `order`=1000 WHERE `id`={$id}");

	// Were we successful?
	if ( hesk_dbAffectedRows() == 1 )
	{
		// Update order
		update_cf_order();

		// Clear cache
		hesk_purge_cache('cf');

		// Delete custom field data from tickets
		hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `custom{$id}`='', `lastchange`=`lastchange` WHERE `custom{$id}`!=''");

		// Show success message
		hesk_process_messages($hesklang['cf_deleted'],'./custom_fields.php','SUCCESS');
	}
	else
	{
		hesk_process_messages($hesklang['cf_not_found'],'./custom_fields.php');
	}

} // End remove_cf()


function cf_validate()
{
	global $hesk_settings, $hesklang;
	global $hesk_error_buffer;

	$hesk_error_buffer = array();
	$errors = array();

	// Get names
	$cf['names'] = hesk_POST_array('name');

	// Make sure only valid names pass
	foreach ($cf['names'] as $key => $name)
	{
		if ( ! isset($hesk_settings['languages'][$key]))
		{
			unset($cf['names'][$key]);
		}
		else
		{
			$name = is_array($name) ? '' : hesk_input($name, 0, 0, HESK_SLASH);

			if (strlen($name) < 1)
			{
				unset($cf['names'][$key]);
			}
			else
			{
				$cf['names'][$key] = stripslashes($name);
			}
		}
	}

	// No name entered?
	if ( ! count($cf['names']))
	{
		$hesk_error_buffer[] = $hesklang['err_custname'];
		$errors[] = 'name';
	}

	// Get type and values
	$cf['type'] = hesk_POST('type');
	switch ($cf['type'])
	{
		case 'textarea':
			$cf['rows'] = hesk_checkMinMax(intval(hesk_POST('rows')), 1, 100, 12);
			$cf['cols'] = hesk_checkMinMax(intval(hesk_POST('cols')), 1, 500, 60);
			$cf['value'] = array('rows' => $cf['rows'], 'cols' => $cf['cols']);
			break;

		case 'radio':
			$cf['radio_options'] = stripslashes(hesk_input(hesk_POST('radio_options'), 0, 0, HESK_SLASH));

			$options = preg_split("/\\r\\n|\\r|\\n/", $cf['radio_options']);

			$no_default = hesk_POST('no_default') ? 1 : 0;

			$cf['value'] = array('radio_options' => $options, 'no_default' => $no_default);

			if (count($options) < 2)
			{
				$hesk_error_buffer[] = $hesklang['atl2'];
                $errors[] = 'radio_options';
			}

			break;

		case 'select':
			$cf['select_options'] = stripslashes(hesk_input(hesk_POST('select_options'), 0, 0, HESK_SLASH));

			$options = preg_split("/\\r\\n|\\r|\\n/", $cf['select_options']);

			$show_select = hesk_POST('show_select') ? 1 : 0;
			$is_searchable = hesk_POST('is_searchable') ? 1 : 0;

			$cf['value'] = array('show_select' => $show_select, 'is_searchable' => $is_searchable, 'select_options' => $options);

			if (count($options) < 2)
			{
				$hesk_error_buffer[] = $hesklang['atl2'];
                $errors[] = 'select_options';
			}

			break;

		case 'checkbox':
			$cf['checkbox_options'] = stripslashes(hesk_input(hesk_POST('checkbox_options'), 0, 0, HESK_SLASH));

			$options = preg_split("/\\r\\n|\\r|\\n/", $cf['checkbox_options']);

			$cf['value'] = array('checkbox_options' => $options);

			if ( ! isset($options[0]) || strlen($options[0]) < 1)
			{
				$hesk_error_buffer[] = $hesklang['atl1'];
                $errors[] = 'checkbox_options';
			}

			break;

		case 'date':
        	$cf['dmin'] = '';
            $cf['dmax'] = '';

            // Minimum date
            $dmin_rf = hesk_POST('dmin_rf');

            if ($dmin_rf == 1)
            {
            	$dmin = hesk_POST('dmin');

                if ($date = hesk_datepicker_get_date($dmin))
                {
                    $dmin = $date->format('m/d/Y');
                	$cf['dmin'] = $dmin;
                }
            }
            elseif ($dmin_rf == 2)
            {
				$dmin_pm = hesk_POST('dmin_pm') == '+' ? '+' : '-';
				$dmin_num = intval(hesk_POST('dmin_num', 0));
				$dmin_type = hesk_POST('dmin_type');
                if ( ! in_array($dmin_type, array('day', 'week', 'month', 'year')))
                {
                	$dmin_type = 'day';
                }

                $cf['dmin'] = $dmin_pm . $dmin_num . ' ' . $dmin_type;
            }

			// Maximum date
            $dmax_rf = hesk_POST('dmax_rf');

            if ($dmax_rf == 1)
            {
            	$dmax = hesk_POST('dmax');

                if ($date = hesk_datepicker_get_date($dmax))
                {
                    $dmax = $date->format('m/d/Y');
                	$cf['dmax'] = $dmax;
                }
            }
            elseif ($dmax_rf == 2)
            {
				$dmax_pm = hesk_POST('dmax_pm') == '+' ? '+' : '-';
				$dmax_num = intval(hesk_POST('dmax_num', 0));
				$dmax_type = hesk_POST('dmax_type');
                if ( ! in_array($dmax_type, array('day', 'week', 'month', 'year')))
                {
                	$dmax_type = 'day';
                }

                $cf['dmax'] = $dmax_pm . $dmax_num . ' ' . $dmax_type;
            }

            // Minimum date should not be higher than maximum date
            if (strlen($cf['dmin']) && strlen($cf['dmax']))
            {
				if (strtotime($cf['dmin']) > strtotime($cf['dmax']))
				{
					$hesk_error_buffer[] = $hesklang['d_mm'];
                    $errors[] = 'date_range';
				}
            }

            // Date format
            $date_format = hesk_POST('date_format');
            if ($date_format == 'custom')
            {
            	$date_format = hesk_POST('date_format_custom');
            }

            $cf['date_format'] = preg_replace('/[^a-zA-Z0-9 \/\.\_+\-,;:#(){}\[\]\'@*]/', '', $date_format);

            $cf['value'] = array('dmin' => $cf['dmin'], 'dmax' => $cf['dmax'], 'date_format' => $cf['date_format']);

			break;

		case 'email':
			$cf['email_multi'] = hesk_POST('email_multi') ? 1 : 0;
			$cf['value'] = array('multiple' => $cf['email_multi']);
			break;

		case 'hidden':
			$cf['hidden_max_length'] = hesk_checkMinMax(intval(hesk_POST('hidden_max_length')), 1, 10000, 255);
			$cf['hidden_default_value'] = stripslashes(hesk_input(hesk_POST('hidden_default_value'), 0, 0, HESK_SLASH));
			$cf['value'] = array('max_length' => $cf['hidden_max_length'], 'default_value' => $cf['hidden_default_value']);
			break;

		default:
			$cf['type'] = 'text';
			$cf['max_length'] = hesk_checkMinMax(intval(hesk_POST('max_length')), 1, 10000, 255);
			$cf['default_value'] = stripslashes(hesk_input(hesk_POST('default_value'), 0, 0, HESK_SLASH));
			$cf['value'] = array('max_length' => $cf['max_length'], 'default_value' => $cf['default_value']);

	}

	// Enable
	$cf['use'] = hesk_POST('use') == 2 ? 2 : 1;

	// req
	$cf['req'] = hesk_POST('req');
	$cf['req'] = $cf['req'] == 2 ? 2 : ($cf['req'] == 1 ? 1 : 0);

	// Private fields cannot be req for customers
	if ($cf['use'] == 2 && $cf['req'] == 1)
	{
		$cf['req'] = 0;
	}

	// Located above or below "Message"?
	$cf['place'] = hesk_POST('place') ? 1 : 0;

	// Get allowed categories
	if (hesk_POST('category'))
	{
		$cf['category'] = 1;
		$cf['categories'] = hesk_POST_array('categories');

		foreach ($cf['categories'] as $key => $cat_id)
		{
			if ( ! isset($hesk_settings['categories'][$cat_id]) )
			{
				unset($cf['categories'][$key]);
			}
		}

		if ( ! count($cf['categories']))
		{
			$hesk_error_buffer[] = $hesklang['cf_nocat'];
            $errors[] = 'categories';
		}
	}
	else
	{
		$cf['category'] = 0;
		$cf['categories'] = array();
	}

	// Any errors?
	if (count($hesk_error_buffer))
	{
		$_SESSION['new_cf'] = $cf;
		$_SESSION['new_cf']['errors'] = $errors;
		return false;
	}

	$cf['names'] = addslashes(json_encode($cf['names']));
	$cf['value'] = $cf['type'] == 'date' ? json_encode($cf['value']) : addslashes(json_encode($cf['value']));

	return $cf;
} // END cf_validate()


function new_cf()
{
	global $hesk_settings, $hesklang;
	global $hesk_error_buffer;

	// A security check
	hesk_token_check('POST');

	// Validate inputs
	if (($cf = cf_validate()) == false)
	{
		$tmp = '';
		foreach ($hesk_error_buffer as $error)
		{
			$tmp .= "<li>$error</li>\n";
		}
		$hesk_error_buffer = $tmp;

		$hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
		hesk_process_messages($hesk_error_buffer,'custom_fields.php');
	}

	// Get the lowest available custom field ID
	$res = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_fields` WHERE `use`='0' ORDER BY `id` ASC LIMIT 1");
	$row = hesk_dbFetchRow($res);
	$_SESSION['cford'] = intval($row[0]);

	// Insert custom field into database
	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_fields` SET
	`use`      = '{$cf['use']}',
	`place`    = '{$cf['place']}',
	`type`     = '{$cf['type']}',
	`req`      = '{$cf['req']}',
	`category` = ".(count($cf['categories']) ? "'".json_encode($cf['categories'])."'" : 'NULL').",
	`name`     = '".hesk_dbEscape($cf['names'])."',
	`value`    = ".(strlen($cf['value']) ? "'".hesk_dbEscape($cf['value'])."'" : 'NULL').",
	`order`    = 990
	WHERE `id`={$_SESSION['cford']}");

	// Update order
	update_cf_order();

	// Clear cache
	hesk_purge_cache('cf');

	// Show success
	hesk_process_messages($hesklang['cf_added'],'custom_fields.php','SUCCESS');

} // End new_cf()
custom_priorities.php
wget 'https://lists2.roe3.org/hesk/admin/custom_priorities.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

define('LOAD_TABS',1);

// Get all the req files and functions
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/setup_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_man_settings');

// Load priorities
require_once(HESK_PATH . 'inc/priorities.inc.php');

// What should we do?
if ( $action = hesk_REQUEST('a') )
{
    if ($action == 'edit_priority') {edit_priority();}
    elseif ( defined('HESK_DEMO') ) {hesk_process_messages($hesklang['ddemo'], 'custom_priorities.php', 'NOTICE');}
    elseif ($action == 'new_priority') {new_priority();}
    elseif ($action == 'save_priority') {save_priority();}
    elseif ($action == 'remove_priority') {remove_priority();}
    elseif ($action == 'sort_priority'){sort_priority();}
}

// Print header
require_once(HESK_PATH . 'inc/header.inc.php');

// Print main manage users page
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
if (!hesk_SESSION('edit_priority') && !hesk_SESSION(array('new_priority','errors'))) {
    hesk_handle_messages();
}

// Number of custom priorities
$hesk_settings['num_custom_priorities'] = count($hesk_settings['priorities']) - 4;

$reached_priority_limit = $hesk_settings['num_custom_priorities'] >= 100;

// Did we reach the custom priorities limit?
if ($reached_priority_limit && $action !== 'edit_priority') {
    hesk_show_info($hesklang['priority_limit']);
}

?>
<div class='custom_ajax_msg'></div>
<div class="main__content tools">
    <section class="tools__between-head">
        <h2>
            <?php echo $hesklang['priorities']; ?>
            <div class="tooltype right out-close">
                <svg class="icon icon-info">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                </svg>
                <div class="tooltype__content">
                    <div class="tooltype__wrapper">
                        <?php echo $hesklang['priority_intro']; ?>
                    </div>
                </div>
            </div>
        </h2>
        <?php if (!$reached_priority_limit && $action !== 'edit_priority'): ?>
        <div class="btn btn--blue-border" ripple="ripple" data-action="create-custom-status">
            <?php echo $hesklang['new_priority']; ?>
        </div>
        <?php endif; ?>
    </section>
    <div class="table-wrapper status">
        <div class="table">
            <table id="default-table" class="table sindu-table">
                <thead>
                <tr>
                    <th><?php echo $hesklang['id']; ?></th>
                    <th><?php echo $hesklang['priority_title']; ?></th>
                    <th><?php echo $hesklang['csscl']; ?></th>
                    <th><?php echo $hesklang['tickets']; ?></th>
                    <th><?php echo $hesklang['selected_by_customer']; ?></th>
                    <th aria-label="Action"></th>
                </tr>
                </thead>
                <tbody id="priority_sort">
                <?php
                // Number of tickets per priority
                $tickets_all = array();

                if ($_SESSION['isadmin']) {
                    $res = hesk_dbQuery('SELECT COUNT(*) AS `cnt`, `priority` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'tickets` GROUP BY `priority`');
                } else {
                    $res = hesk_dbQuery("SELECT COUNT(*) AS `cnt`, `priority`
                                        FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` AS `ticket`
                                        LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_collaborator` AS `w` ON (`ticket`.`id` = `w`.`ticket_id` AND `w`.`user_id` = ".intval($_SESSION['id']).")
                                        WHERE
                                        (
                                            `w`.`user_id`=".intval($_SESSION['id'])."
                                            OR
                                            (".hesk_myOwnership().")
                                        )
                                        AND ".hesk_myCategories()."
                                        GROUP BY `priority`");
                }

                while ($tmp = hesk_dbFetchAssoc($res)) {
                    $tickets_all[$tmp['priority']] = $tmp['cnt'];
                }

                $is_custom = false;

                $i = 1;

                foreach ($hesk_settings['priorities'] as $tmp_id => $priority) {
                    $p_color = $priority['color'];
                    $priority['span'] = isset($priority['class']) ? '<span class="' . $priority['class'] . '">' : '<span style="color: ' . $priority['color'] . '">';
                    $priority['color'] = isset($priority['class']) ? $priority['span'] . '.' . $priority['class'] . '</span>' : $priority['span'] . $priority['color'] . '</span>';
                    $priority['tickets'] = isset($tickets_all[$tmp_id]) ? $tickets_all[$tmp_id] : 0;
                    $priority['can_customers_select'] = ! isset($priority['can_customers_select']) ? '' : ($priority['can_customers_select'] == 1 ? $hesklang['yes'] : $hesklang['no']);
                    $icon_style = 'border-top-color:'.$p_color.';border-left-color:'.$p_color.';border-bottom-color:'.$p_color.';';
                    if (!$is_custom && $tmp_id > 1) {
                        $is_custom = true;
                    }

                    $table_row = '';
                    if (isset($_SESSION['priority_ord']) && $_SESSION['priority_ord'] == $priority['id']) {
                        $table_row = 'class="ticket-new"';
                        unset($_SESSION['priority_ord']);
                    }
                    ?>
                    <tr <?php echo $table_row; ?> data-id="<?php echo $priority['id']; ?>">
                        <td><?php echo $priority['id']; ?></td>
                        <td class="td-flex"><div class="priority_img" style=<?php echo $icon_style; ?>></div> <p class="p-title"><?php echo $priority['name']; ?></p></td>
                        <td><?php echo $priority['color']; ?></td>
                        <td><a class="tooltip" href="show_tickets.php?<?php echo 'p'.$tmp_id.'=1'; ?>&amp;s_all=1&amp;s_my=1&amp;s_ot=1&amp;s_un=1" alt="<?php echo $hesklang['list_tkt_priority']; ?>" title="<?php echo $hesklang['list_tkt_priority']; ?>"><?php echo $priority['tickets']; ?></a></td>
                        <td><?php echo $priority['can_customers_select']; ?></td>
                        <td class="nowrap buttons">
                            <?php $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                                $hesklang['confirm_delete_priority'],
                                'custom_priorities.php?a=remove_priority&amp;id='. $priority['id'] .'&amp;token='. hesk_token_echo(0)); ?>
                            <p>
                                <a href="custom_priorities.php?a=edit_priority&amp;id=<?php echo $priority['id']; ?>" class="edit tooltip" title="<?php echo $hesklang['edit']; ?>">
                                    <svg class="icon icon-edit-ticket">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-edit-ticket"></use>
                                    </svg>
                                </a>
                                <a href="javascript:;" class="icon icon-drag-drop tooltip row_sort" title="<?php echo $hesklang['click_to_enable_drag_drop']; ?>">
                                    <svg class="icon icon-drag-drop">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg?#icon-drag-drop"></use>
                                    </svg>
                                </a>
                                <?php 
                                
                                if ($tmp_id == 0 || $priority['tickets'] > 0):
                                    $priority_del_txt = ($tmp_id == 0) ? $hesklang['deletion_priority_restricted']:$hesklang['priority_not_empty'];
                                ?>
                                    <a onclick="alert('<?php echo hesk_makeJsString($priority_del_txt); ?>');"
                                       class="delete tooltip not-allowed"
                                       title="<?php echo $priority_del_txt; ?>">
                                        <svg class="icon icon-delete">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-delete"></use>
                                        </svg>
                                    </a>
                                <?php else: ?>
                                    <a class="delete tooltip" title="<?php echo $hesklang['delete']; ?>" href="javascript:" data-modal="[data-modal-id='<?php echo $modal_id; ?>']">
                                        <svg class="icon icon-delete">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-delete"></use>
                                        </svg>
                                    </a>
                                <?php
                            endif;
                            ?>
                            </p>
                        </td>
                    </tr>
                    <?php
                } // End foreach
                ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<script type="text/javascript" src="<?php echo HESK_PATH; ?>inc/jscolor/jscolor.min.js"></script>
<script type="text/javascript">
    function hesk_preview(jscolor) {
        document.getElementById('color_preview').style.color = "#" + jscolor;
    }
</script>
<script src="<?php echo HESK_PATH; ?>js/jquery-ui.js?<?php echo $hesk_settings['hesk_version']; ?>"></script>
<script type="text/javascript">
    $(function() {
        $('body').on('mouseover','.row_sort',function(){
            $( "#priority_sort" ).sortable({
                placeholder: "ui-state-highlight",
                cancel: ".ui-state-disabled",
                update: function( event, ui ) {
                    updatePriorityOrder();
                }
            });
            $( "#priority_sort" ).disableSelection();
        });
    });
    
    function updatePriorityOrder() {
        var priority_sort_data = [];
        var object_data = [];
        var j = 1;
        $('tbody#priority_sort tr').each(function() {
            if($(this).attr("data-id") > 0){
                priority_sort_data.push({id:$(this).attr("data-id"),priority_order:j});
                j++;
            }
        });
        var data = {
            'a':'sort_priority',
            'priority_order': JSON.stringify(priority_sort_data),
            'token':'<?php hesk_token_echo(); ?>'
        }
        $.ajax({
            type: 'POST',
            url: 'custom_priorities.php',
            data: data,
            cache: false,
            success: function(data){
                var result = JSON.parse(data);
                if(result.status=='SUCCESS'){
                    $('.notice-flash').remove();
                    $('.custom_ajax_msg').html('');
                    $('.custom_ajax_msg').html(result.message);
                    $( "#priority_sort" ).sortable("destroy");
                    //$('tr').addClass('ui-state-disabled');
                }
            }
        });
    }
</script>
<div class="right-bar create-status" <?php echo hesk_SESSION('edit_priority') || hesk_SESSION(array('new_priority','errors')) ? 'style="display: block"' : ''; ?>>
    <form action="custom_priorities.php" method="post" name="form1" class="form <?php echo hesk_SESSION(array('new_priority','errors')) ? 'invalid' : ''; ?>" aria-label="<?php echo $hesklang['edit_priority']; ?>">
        <div class="right-bar__body form">
            <h3>
                <a href="<?php echo hesk_SESSION('edit_priority') ? 'custom_priorities.php' : 'javascript:'; ?>">
                    <svg class="icon icon-back">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                    </svg>
                    <span><?php echo hesk_SESSION('edit_priority') ? $hesklang['edit_priority'] : $hesklang['new_priority']; ?></span>
                </a>
            </h3>
            <?php
            /* This will handle error, success and notice messages */
            if (hesk_SESSION(array('new_priority', 'errors'))) {
                echo '<div style="margin: -24px -24px 10px -16px;">';
                hesk_handle_messages();
                echo '</div>';
            }

            $names = hesk_SESSION(array('new_priority','names'));
            $id = hesk_SESSION(array('new_priority','id'));

            $errors = hesk_SESSION(array('new_priority','errors'));
            $errors = is_array($errors) ? $errors : array();
            
            if ($hesk_settings['can_sel_lang'] && count($hesk_settings['languages']) > 1) {
                echo '<h4>' . $hesklang['priority_title'] . '</h4>';
                foreach ($hesk_settings['languages'] as $lang => $info) {
                    
                    $lang_value = '';
                    if(isset($id) && $id !=''){
                        if((!isset($names[$lang]) && $id < 4) || (isset($names[$lang]) && strtolower($names[$lang]) == "null"  && $id < 4)){
                            hesk_setLanguage($lang);

                            //Check for default priority name is NULL
                            switch ($id) {
                                case 0:
                                    $lang_value = $hesklang['critical'];
                                    break;
                                case 1:
                                    $lang_value = $hesklang['high'];
                                    break;
                                case 2:
                                    $lang_value = $hesklang['medium'];
                                    break;
                                case 3:
                                    $lang_value = $hesklang['low'];
                                    break;    
                                default:
                                    $lang_value = '';
                            }
                        }else{
                            $lang_value = isset($names[$lang]) ? $names[$lang] : '';
                        }
                    }
                    ?>
                    <div class="form-group">
                        <label for="lang_<?php echo $lang; ?>"><?php echo $lang; ?></label>
                        <input type="text" class="form-control <?php echo in_array('names', $errors) ? 'isError' : ''; ?>" id="lang_<?php echo $lang; ?>" name="name[<?php echo $lang; ?>]" value="<?php echo $lang_value; ?>">
                    </div>
                <?php }
            } else { 
                    $lang = $hesk_settings['language'];
                    $lang_value = '';
                    if(isset($id) && $id !=''){
                        if((!isset($names[$lang]) && $id < 4) || (isset($names[$lang]) && strtolower($names[$lang]) == "null"  && $id < 4)){
                            //Check for default priority name is NULL
                            switch ($id) {
                                case 0:
                                    $lang_value = $hesklang['critical'];
                                    break;
                                case 1:
                                    $lang_value = $hesklang['high'];
                                    break;
                                case 2:
                                    $lang_value = $hesklang['medium'];
                                    break;
                                case 3:
                                    $lang_value = $hesklang['low'];
                                    break;    
                                default:
                                    $lang_value = '';
                            }
                        }else{
                            $lang_value = isset($names[$lang]) ? $names[$lang] : '';
                        }
                    }
                ?>
                <div class="form-group">
                    <label for="p_title"><?php echo $hesklang['priority_title']; ?></label>
                    <input type="text" class="form-control <?php echo in_array('names', $errors) ? 'isError' : ''; ?>" id="p_title" name="name[<?php echo $lang; ?>]"
                           value="<?php echo $lang_value; ?>">
                </div>
            <?php }
            hesk_resetLanguage();
            ?>
            <div class="form-group color">
                <?php $color = hesk_validate_color_hex(hesk_SESSION(array('new_priority','color'))); ?>
                <label for="p_color"><?php echo $hesklang['color']; ?></label>
                <input type="text" class="form-control jscolor {hash:true, uppercase:false, onFineChange:'hesk_preview(this)'}" id="p_color" name="color" value="<?php echo $color; ?>">
                <span id="color_preview" style="color:<?php echo $color; ?>"><?php echo $hesklang['clr_view']; ?></span>
            </div>
            <div class="form-switcher">
                <?php $can_customers_select = hesk_SESSION(array('new_priority','can_customers_select'), 0); ?>
                <label class="switch-checkbox">
                    <input type="checkbox" name="can_customers_select" <?php if ($can_customers_select) {echo 'checked';} ?>>
                    <div class="switch-checkbox__bullet">
                        <i>
                            <svg class="icon icon-close">
                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                            </svg>
                            <svg class="icon icon-tick">
                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                            </svg>
                        </i>
                    </div>
                    <span><?php echo $hesklang['can_customers_select_it']; ?></span>
                </label>
            </div>
            <?php if (isset($_SESSION['edit_priority'])): ?>
                <input type="hidden" name="a" value="save_priority">
                <input type="hidden" name="id" value="<?php echo intval($_SESSION['new_priority']['id']); ?>">
            <?php else: ?>
                <input type="hidden" name="a" value="new_priority">
            <?php endif; ?>
            <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
            <button type="submit" class="btn btn-full save" ripple="ripple"><?php echo $hesklang['status_save']; ?></button>
        </div>
    </form>
</div>
<?php

hesk_cleanSessionVars( array('new_priority', 'edit_priority') );

require_once(HESK_PATH . 'inc/footer.inc.php');

exit();


/*** START FUNCTIONS ***/


function save_priority()
{
    global $hesk_settings, $hesklang;
    global $hesk_error_buffer;

    // A security check
    hesk_token_check('POST');

    // Get custom priority ID
    $id = intval( hesk_POST('id') );
    if ($id < 0) {
         hesk_error($hesklang['priority_e_id']);
    }

    // Validate inputs
    if (($priority = priority_validate()) == false)
    {
        $_SESSION['edit_priority'] = true;
        $_SESSION['new_priority']['id'] = $id;

        $tmp = '';
        foreach ($hesk_error_buffer as $error)
        {
            $tmp .= "<li>$error</li>\n";
        }
        $hesk_error_buffer = $tmp;

        $hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
        hesk_process_messages($hesk_error_buffer,'custom_priorities.php');
    }

    // Remove # from color
    $color = str_replace('#', '', $priority['color']);

    // Add custom priority data into database
    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_priorities` SET
    `name` = '".hesk_dbEscape($priority['names'])."',
    `color` = '{$color}',
    `can_customers_select` = '{$priority['can_customers_select']}'
    WHERE `id`={$id}");

    // Clear cache
    hesk_purge_cache('priority');

    // Show success
    $_SESSION['priority_ord'] = $id;
    hesk_process_messages($hesklang['priority_mdf'],'custom_priorities.php','SUCCESS');

} // End save_priority()


function edit_priority()
{
    global $hesk_settings, $hesklang;

    // Get custom priority ID
    $id = intval( hesk_GET('id') );
    if ($id < 0) {
        hesk_error($hesklang['priority_e_id']);
    }

    // Get details from the database
    $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_priorities` WHERE `id`={$id} LIMIT 1");
    if ( hesk_dbNumRows($res) != 1 )
    {
        hesk_error($hesklang['priority_not_found']);
    }
    $priority = hesk_dbFetchAssoc($res);

    $priority['names'] = json_decode($priority['name'], true);

    unset($priority['name']);

    $priority['color'] = '#'.$priority['color'];
    
    $_SESSION['new_priority'] = $priority;
    $_SESSION['edit_priority'] = true;

} // End edit_priority()


function update_priority_order()
{
    global $hesk_settings, $hesklang;

    // Get list of current custom priorities
    $res = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_priorities` ORDER BY `priority_order` ASC");

    // Update database
    $i = 1;
    while ( $priority = hesk_dbFetchAssoc($res) )
    {
        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_priorities` SET `priority_order`=".intval($i)." WHERE `id`='".intval($priority['id'])."'");
        $i++;
    }

    return true;

} // END update_priority_order()


function remove_priority()
{
    global $hesk_settings, $hesklang;

    // A security check
    hesk_token_check();

    // Get ID
    $id = intval( hesk_GET('id') ) or hesk_error($hesklang['priority_e_id']);

    // Any tickets with this priority?
    $res = hesk_dbQuery("SELECT COUNT(*) AS `cnt`, `priority` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `priority` = {$id}");
    if (hesk_dbResult($res) > 0)
    {
        hesk_process_messages($hesklang['priority_not_empty'],'./custom_priorities.php');
    }

    // Reset the custom priority
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_priorities` WHERE `id`={$id}");

    // Were we successful?
    if ( hesk_dbAffectedRows() == 1 )
    {
        // Update order
        update_priority_order();
        
        // Clear cache
        hesk_purge_cache('priority');

        // Show success message
        hesk_process_messages($hesklang['priority_deleted'],'./custom_priorities.php','SUCCESS');
    }
    else
    {
        hesk_process_messages($hesklang['priority_not_found'],'./custom_priorities.php');
    }

} // End remove_priority()


function priority_validate()
{
    global $hesk_settings, $hesklang;
    global $hesk_error_buffer;

    $hesk_error_buffer = array();

    // Get names
    $priority['names'] = hesk_POST_array('name');

    // Make sure only valid names pass
    foreach ($priority['names'] as $key => $name)
    {
        if ( ! isset($hesk_settings['languages'][$key]))
        {
            unset($priority['names'][$key]);
        }
        else
        {
            $name = is_array($name) ? '' : hesk_input($name, 0, 0, HESK_SLASH);

            if (strlen($name) < 1)
            {
                unset($priority['names'][$key]);
            }
            else
            {
                $priority['names'][$key] = stripslashes($name);
            }
        }
    }

    // No name entered?
    $errors = array();
    if ( ! count($priority['names']))
    {
        $hesk_error_buffer[] = $hesklang['err_priority'];
        $errors[] = 'names';
    }

    // Color
    $priority['color'] = hesk_validate_color_hex(hesk_POST('color'));

    // Can customers change it?
    $priority['can_customers_select'] = hesk_POST('can_customers_select') ? 1 : 0;

    // Any errors?
    if (count($hesk_error_buffer))
    {
        $_SESSION['new_priority'] = $priority;
        $_SESSION['new_priority']['errors'] = $errors;
        return false;
    }

    $priority['names'] = addslashes(json_encode($priority['names']));
   
    return $priority;
} // END priority_validate()


function new_priority()
{
    global $hesk_settings, $hesklang;
    global $hesk_error_buffer;

    // A security check
    hesk_token_check('POST');

    // Validate inputs
    if (($priority = priority_validate()) == false)
    {
        $tmp = '';
        foreach ($hesk_error_buffer as $error)
        {
            $tmp .= "<li>$error</li>\n";
        }
        $hesk_error_buffer = $tmp;

        $hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
        hesk_process_messages($hesk_error_buffer,'custom_priorities.php');
    }

    // The lowest currently used ID
    $res = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_priorities` ORDER BY `id` DESC LIMIT 1");
    $lowest_id = hesk_dbResult($res);
    $next_id = $lowest_id + 1;

    // Did we reach priority limit?
    if ($next_id > 255) {
        hesk_process_messages($hesklang['priority_limit'],'custom_priorities.php');
    }

    // Remove # from color
    $color = str_replace('#', '', $priority['color']);

    // Insert custom priority into database
    hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_priorities` (`id`, `name`, `color`, `can_customers_select`, `priority_order`) VALUES ({$next_id}, '".hesk_dbEscape($priority['names'])."', '{$color}', '{$priority['can_customers_select']}', 990)");

    // Update order
    update_priority_order();

    // Clear cache
    hesk_purge_cache('priority');

    $_SESSION['priority_ord'] = $next_id;

    // Show success
    hesk_process_messages($hesklang['priority_added'],'custom_priorities.php','SUCCESS');

} // End new_priority()

//Sort Priority Order
function sort_priority()
{
    global $hesk_settings, $hesklang;

    // A security check
    hesk_token_check('POST');

    $priority['priority_order'] = json_decode(hesk_POST('priority_order'), true);

    if ( ! is_array($priority['priority_order']) )
    {
        hesk_error($hesklang['invalid_action']);
    }

    $priority_cases = array();
    $priority_ids = array();

    // Add each valid update to the CASE statement
    foreach ($priority['priority_order'] as $update)
    {
        $id = isset($update['id']) ? intval($update['id']) : 0;
        $priority_order = isset($update['priority_order']) ? intval($update['priority_order']) : 0;

        if ($id < 1 || $priority_order < 1 || ! isset($hesk_settings['priorities'][$id]))
        {
            continue;
        }

        $priority_cases[] = "WHEN {$id} THEN {$priority_order}";
        $priority_ids[] = $id;
    }

    if (count($priority_ids) < 1)
    {
        hesk_error($hesklang['invalid_action']);
    }

    $priority_ids = array_unique($priority_ids);

    // Update priority order
    $q = "UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_priorities` SET `priority_order` = CASE `id` ".implode(' ', $priority_cases)." END WHERE `id` IN (".implode(',', $priority_ids).")";
    hesk_dbQuery($q);

    // Show success
    $array = [];
    $array['status'] = 'SUCCESS';
    $array['redirect'] = HESK_PATH.'custom_priorities.php';
    $html = '<div class="main__content notice-flash ">';
    $html .= '<div role="status" class="notification green">';
    $html .= '<b>'.$hesklang['success'].': </b>'.$hesklang['reordered_message'].'</div>';
    $html .= '</div>';
    $array['message'] = $html;
    echo json_encode($array);

    // Clear cache
    hesk_purge_cache('priority');

    exit();
} // End sort_priority()


function hesk_validate_color_hex($hex, $def = '#000000')
{
    $hex = strtolower($hex);
    return preg_match('/^\#[a-f0-9]{6}$/', $hex) ? $hex : $def;
} // END hesk_validate_color_hex()


function hesk_get_text_color($bg_color)
{
    // Get RGB values
    list($r, $g, $b) = sscanf($bg_color, "#%02x%02x%02x");

    // Is Black a good text color?
    if (hesk_color_diff($r, $g, $b, 0, 0, 0) >= 500)
    {
        return '#000000';
    }

    // Use white instead
    return '#ffffff';
} // END hesk_get_text_color()


function hesk_color_diff($R1,$G1,$B1,$R2,$G2,$B2)
{
    return max($R1,$R2) - min($R1,$R2) +
           max($G1,$G2) - min($G1,$G2) +
           max($B1,$B2) - min($B1,$B2);
} // END hesk_color_diff()
custom_statuses.php
wget 'https://lists2.roe3.org/hesk/admin/custom_statuses.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

define('LOAD_TABS',1);

// Get all the req files and functions
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/setup_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_man_settings');

// Load statuses
require_once(HESK_PATH . 'inc/statuses.inc.php');

// What should we do?
if ( $action = hesk_REQUEST('a') )
{
	if ($action == 'edit_status') {edit_status();}
	elseif ( defined('HESK_DEMO') ) {hesk_process_messages($hesklang['ddemo'], 'custom_statuses.php', 'NOTICE');}
	elseif ($action == 'new_status') {new_status();}
	elseif ($action == 'save_status') {save_status();}
	elseif ($action == 'remove_status') {remove_status();}
}

// Print header
require_once(HESK_PATH . 'inc/header.inc.php');

// Print main manage users page
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
if (!hesk_SESSION('edit_status') && !hesk_SESSION(array('new_status','errors'))) {
    hesk_handle_messages();
}


// Number of custom statuses
$hesk_settings['num_custom_statuses'] = count($hesk_settings['statuses']) - 6;

$reached_status_limit = $hesk_settings['num_custom_statuses'] >= 100;

// Did we reach the custom statuses limit?
if ($reached_status_limit && $action !== 'edit_status') {
    hesk_show_info($hesklang['status_limit']);
}

?>
<div class="main__content tools">
    <section class="tools__between-head">
        <h2>
            <?php echo $hesklang['statuses']; ?>
            <div class="tooltype right out-close">
                <svg class="icon icon-info">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                </svg>
                <div class="tooltype__content">
                    <div class="tooltype__wrapper">
                        <?php echo $hesklang['statuses_intro']; ?>
                    </div>
                </div>
            </div>
        </h2>
        <?php if (!$reached_status_limit && $action !== 'edit_status'): ?>
        <div class="btn btn--blue-border" ripple="ripple" data-action="create-custom-status">
            <?php echo $hesklang['new_status']; ?>
        </div>
        <?php endif; ?>
    </section>
    <div class="table-wrapper status">
        <div class="table">
            <table id="default-table" class="table sindu-table">
                <thead>
                <tr>
                    <th><?php echo $hesklang['status']; ?></th>
                    <th><?php echo $hesklang['csscl']; ?></th>
                    <th><?php echo $hesklang['tickets']; ?></th>
                    <th><?php echo $hesklang['cbc']; ?></th>
                    <th aria-label="Actions"></th>
                </tr>
                </thead>
                <tbody>
                <tr class="title">
                    <td colspan="5"><?php echo $hesklang['status_hesk']; ?></td>
                </tr>
                <?php
                // Number of tickets per status
                $tickets_all = array();

                if ($_SESSION['isadmin']) {
                    $res = hesk_dbQuery('SELECT COUNT(*) AS `cnt`, `status` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'tickets` GROUP BY `status`');
                } else {
                    $res = hesk_dbQuery("SELECT COUNT(*) AS `cnt`, `status`
                                        FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` AS `ticket`
                                        LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_collaborator` AS `w` ON (`ticket`.`id` = `w`.`ticket_id` AND `w`.`user_id` = ".intval($_SESSION['id']).")
                                        WHERE
                                        (
                                            `w`.`user_id`=".intval($_SESSION['id'])."
                                            OR
                                            (".hesk_myOwnership().")
                                        )
                                        AND ".hesk_myCategories()."
                                        GROUP BY `status`");
                }

                while ($tmp = hesk_dbFetchAssoc($res)) {
                    $tickets_all[$tmp['status']] = $tmp['cnt'];
                }

                $is_custom = false;

                $i = 1;

                foreach ($hesk_settings['statuses'] as $tmp_id => $status) {
                    $status['span'] = isset($status['class']) ? '<span class="' . $status['class'] . '">' : '<span style="color: ' . $status['color'] . '">';
                    $status['color'] = isset($status['class']) ? $status['span'] . '.' . $status['class'] . '</span>' : $status['span'] . $status['color'] . '</span>';
                    $status['tickets'] = isset($tickets_all[$tmp_id]) ? $tickets_all[$tmp_id] : 0;
                    $status['can_customers_change'] = ! isset($status['can_customers_change']) ? '' : ($status['can_customers_change'] == 1 ? $hesklang['yes'] : $hesklang['no']);

                    if (!$is_custom && $tmp_id > 5) {
                        $is_custom = true;
                        echo '
        <tr class="title">
        <td colspan="5">' . $hesklang['status_custom'] . '</td>
        </tr>
        ';
                    }

                    $table_row = '';
                    if (isset($_SESSION['statusord']) && $_SESSION['statusord'] == $tmp_id) {
                        $table_row = 'class="ticket-new"';
                        unset($_SESSION['statusord']);
                    }
                    ?>
                    <tr <?php echo $table_row; ?>>
                        <td><?php echo $status['name']; ?></td>
                        <td><?php echo $status['color']; ?></td>
                        <td><a class="tooltip" href="show_tickets.php?<?php echo 's'.$tmp_id.'=1'; ?>&amp;s_my=1&amp;s_ot=1&amp;s_un=1" alt="<?php echo $hesklang['list_tkt_status']; ?>" title="<?php echo $hesklang['list_tkt_status']; ?>"><?php echo $status['tickets']; ?></a></td>
                        <td><?php echo $status['can_customers_change']; ?></td>
                        <td class="nowrap buttons">
                            <?php $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                                $hesklang['confirm_delete_status'],
                                'custom_statuses.php?a=remove_status&amp;id='. $tmp_id .'&amp;token='. hesk_token_echo(0)); ?>
                            <p>
                            <?php if ($is_custom): ?>
                                <a href="custom_statuses.php?a=edit_status&amp;id=<?php echo $tmp_id; ?>" class="edit tooltip" title="<?php echo $hesklang['edit']; ?>">
                                    <svg class="icon icon-edit-ticket">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-edit-ticket"></use>
                                    </svg>
                                </a>
                                <?php if ($status['tickets'] > 0): ?>
                                    <a onclick="alert('<?php echo hesk_makeJsString($hesklang['status_not_empty']); ?>');"
                                       class="delete tooltip not-allowed"
                                       title="<?php echo $hesklang['status_not_empty']; ?>">
                                        <svg class="icon icon-delete">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-delete"></use>
                                        </svg>
                                    </a>
                                <?php else: ?>
                                    <a class="delete tooltip" title="<?php echo $hesklang['delete']; ?>" href="javascript:" data-modal="[data-modal-id='<?php echo $modal_id; ?>']">
                                        <svg class="icon icon-delete">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-delete"></use>
                                        </svg>
                                    </a>
                                <?php
                                endif;
                            endif;
                            ?>
                            </p>
                        </td>
                    </tr>
                    <?php
                } // End foreach

                if ($hesk_settings['num_custom_statuses'] == 0):
                ?>
                    <tr class="title">
                        <td colspan="5"><?php echo $hesklang['status_custom']; ?></td>
                    </tr>
                    <tr>
                        <td colspan="5"><?php echo $hesklang['status_custom_none']; ?></td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<script type="text/javascript" src="<?php echo HESK_PATH; ?>inc/jscolor/jscolor.min.js"></script>
<script type="text/javascript">
    function hesk_preview(jscolor) {
        document.getElementById('color_preview').style.color = "#" + jscolor;
    }
</script>
<div class="right-bar create-status" <?php echo hesk_SESSION('edit_status') || hesk_SESSION(array('new_status','errors')) ? 'style="display: block"' : ''; ?>>
    <form action="custom_statuses.php" method="post" name="form1" class="form <?php echo hesk_SESSION(array('new_status','errors')) ? 'invalid' : ''; ?>" aria-label="<?php echo $hesklang['edit_status']; ?>">
        <div class="right-bar__body form">
            <h3>
                <a href="<?php echo hesk_SESSION('edit_status') ? 'custom_statuses.php' : 'javascript:'; ?>">
                    <svg class="icon icon-back">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                    </svg>
                    <span><?php echo hesk_SESSION('edit_status') ? $hesklang['edit_status'] : $hesklang['new_status']; ?></span>
                </a>
            </h3>
            <?php
            /* This will handle error, success and notice messages */
            if (hesk_SESSION(array('new_status', 'errors'))) {
                echo '<div style="margin: -24px -24px 10px -16px;">';
                hesk_handle_messages();
                echo '</div>';
            }

            $names = hesk_SESSION(array('new_status','names'));
            $errors = hesk_SESSION(array('new_status','errors'));
            $errors = is_array($errors) ? $errors : array();

            if ($hesk_settings['can_sel_lang'] && count($hesk_settings['languages']) > 1) {
                echo '<h4>' . $hesklang['status'] . '</h4>';
                foreach ($hesk_settings['languages'] as $lang => $info) { ?>
                    <div class="form-group">
                        <label for="lang_<?php echo $lang; ?>"><?php echo $lang; ?></label>
                        <input type="text" class="form-control <?php echo in_array('names', $errors) ? 'isError' : ''; ?>" id="lang_<?php echo $lang; ?>" name="name[<?php echo $lang; ?>]" value="<?php echo (isset($names[$lang]) ? $names[$lang] : ''); ?>">
                    </div>
                <?php }
            } else { ?>
                <div class="form-group">
                    <label for="lang"><?php echo $hesklang['status']; ?></label>
                    <input type="text" class="form-control <?php echo in_array('names', $errors) ? 'isError' : ''; ?>" id="lang" name="name[<?php echo $hesk_settings['language']; ?>]"
                           value="<?php echo isset($names[$hesk_settings['language']]) ? $names[$hesk_settings['language']] : ''; ?>">
                </div>
            <?php } ?>
            <div class="form-group color">
                <?php $color = hesk_validate_color_hex(hesk_SESSION(array('new_status','color'))); ?>
                <label for="color"><?php echo $hesklang['color']; ?></label>
                <input type="text" class="form-control jscolor {hash:true, uppercase:false, onFineChange:'hesk_preview(this)'}" id="color" name="color" value="<?php echo $color; ?>">
                <span id="color_preview" style="color:<?php echo $color; ?>"><?php echo $hesklang['clr_view']; ?></span>
            </div>
            <div class="form-switcher">
                <?php $can_customers_change = hesk_SESSION(array('new_status','can_customers_change'), 0); ?>
                <label class="switch-checkbox">
                    <input type="checkbox" name="can_customers_change" <?php if ($can_customers_change) {echo 'checked';} ?>>
                    <div class="switch-checkbox__bullet">
                        <i>
                            <svg class="icon icon-close">
                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                            </svg>
                            <svg class="icon icon-tick">
                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                            </svg>
                        </i>
                    </div>
                    <span><?php echo $hesklang['ccc']; ?></span>
                </label>
            </div>
            <?php if (isset($_SESSION['edit_status'])): ?>
                <input type="hidden" name="a" value="save_status">
                <input type="hidden" name="id" value="<?php echo intval($_SESSION['new_status']['id']); ?>">
            <?php else: ?>
                <input type="hidden" name="a" value="new_status">
            <?php endif; ?>
            <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
            <button type="submit" class="btn btn-full save" ripple="ripple"><?php echo $hesklang['status_save']; ?></button>
        </div>
    </form>
</div>
<?php

hesk_cleanSessionVars( array('new_status', 'edit_status') );

require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/


function save_status()
{
	global $hesk_settings, $hesklang;
	global $hesk_error_buffer;

	// A security check
	hesk_token_check('POST');

	// Get custom status ID
	$id = intval( hesk_POST('id') ) or hesk_error($hesklang['status_e_id']);

	// Validate inputs
	if (($status = status_validate()) == false)
	{
		$_SESSION['edit_status'] = true;
		$_SESSION['new_status']['id'] = $id;

		$tmp = '';
		foreach ($hesk_error_buffer as $error)
		{
			$tmp .= "<li>$error</li>\n";
		}
		$hesk_error_buffer = $tmp;

		$hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
		hesk_process_messages($hesk_error_buffer,'custom_statuses.php');
	}

    // Remove # from color
    $color = str_replace('#', '', $status['color']);

	// Add custom status data into database
	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_statuses` SET
	`name` = '".hesk_dbEscape($status['names'])."',
	`color` = '{$color}',
	`can_customers_change` = '{$status['can_customers_change']}'
	WHERE `id`={$id}");

	// Clear cache
	hesk_purge_cache('status');

	// Show success
	$_SESSION['statusord'] = $id;
	hesk_process_messages($hesklang['status_mdf'],'custom_statuses.php','SUCCESS');

} // End save_status()


function edit_status()
{
	global $hesk_settings, $hesklang;

	// Get custom status ID
	$id = intval( hesk_GET('id') ) or hesk_error($hesklang['status_e_id']);

	// Get details from the database
	$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_statuses` WHERE `id`={$id} LIMIT 1");
	if ( hesk_dbNumRows($res) != 1 )
	{
		hesk_error($hesklang['status_not_found']);
	}
	$status = hesk_dbFetchAssoc($res);

	$status['names'] = json_decode($status['name'], true);
	unset($status['name']);

    $status['color'] = '#'.$status['color'];

	$_SESSION['new_status'] = $status;
	$_SESSION['edit_status'] = true;

} // End edit_status()


function update_status_order()
{
	global $hesk_settings, $hesklang;

	// Get list of current custom statuses
	$res = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_statuses` ORDER BY `order` ASC");

	// Update database
	$i = 10;
	while ( $status = hesk_dbFetchAssoc($res) )
	{
		hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_statuses` SET `order`=".intval($i)." WHERE `id`='".intval($status['id'])."'");
		$i += 10;
	}

	return true;

} // END update_status_order()


function remove_status()
{
	global $hesk_settings, $hesklang;

	// A security check
	hesk_token_check();

	// Get ID
	$id = intval( hesk_GET('id') ) or hesk_error($hesklang['status_e_id']);

    // Any tickets with this status?
    $res = hesk_dbQuery("SELECT COUNT(*) AS `cnt`, `status` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `status` = {$id}");
    if (hesk_dbResult($res) > 0)
    {
        hesk_process_messages($hesklang['status_not_empty'],'./custom_statuses.php');
    }

	// Reset the custom status
	hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_statuses` WHERE `id`={$id}");

	// Were we successful?
	if ( hesk_dbAffectedRows() == 1 )
	{
		// Update order
		update_status_order();

		// Clear cache
		hesk_purge_cache('status');

		// Show success message
		hesk_process_messages($hesklang['status_deleted'],'./custom_statuses.php','SUCCESS');
	}
	else
	{
		hesk_process_messages($hesklang['status_not_found'],'./custom_statuses.php');
	}

} // End remove_status()


function status_validate()
{
	global $hesk_settings, $hesklang;
	global $hesk_error_buffer;

	$hesk_error_buffer = array();

	// Get names
	$status['names'] = hesk_POST_array('name');

	// Make sure only valid names pass
	foreach ($status['names'] as $key => $name)
	{
		if ( ! isset($hesk_settings['languages'][$key]))
		{
			unset($status['names'][$key]);
		}
		else
		{
			$name = is_array($name) ? '' : hesk_input($name, 0, 0, HESK_SLASH);

			if (strlen($name) < 1)
			{
				unset($status['names'][$key]);
			}
			else
			{
				$status['names'][$key] = stripslashes($name);
			}
		}
	}

	// No name entered?
    $errors = array();
	if ( ! count($status['names']))
	{
		$hesk_error_buffer[] = $hesklang['err_status'];
		$errors[] = 'names';
	}

	// Color
	$status['color'] = hesk_validate_color_hex(hesk_POST('color'));

	// Can customers change it?
	$status['can_customers_change'] = hesk_POST('can_customers_change') ? 1 : 0;

	// Any errors?
	if (count($hesk_error_buffer))
	{
		$_SESSION['new_status'] = $status;
		$_SESSION['new_status']['errors'] = $errors;
		return false;
	}

	$status['names'] = addslashes(json_encode($status['names']));

	return $status;
} // END status_validate()


function new_status()
{
	global $hesk_settings, $hesklang;
	global $hesk_error_buffer;

	// A security check
	hesk_token_check('POST');

	// Validate inputs
	if (($status = status_validate()) == false)
	{
		$tmp = '';
		foreach ($hesk_error_buffer as $error)
		{
			$tmp .= "<li>$error</li>\n";
		}
		$hesk_error_buffer = $tmp;

		$hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
		hesk_process_messages($hesk_error_buffer,'custom_statuses.php');
	}

    // Did we reach status limit?
    if (count($hesk_settings['statuses']) >= 100)
    {
        hesk_process_messages($hesklang['status_limit'],'custom_statuses.php');
    }

    // Lowest available ID for custom statuses is 6
    $next_id = 6;

	// Any existing statuses?
    if (count($hesk_settings['statuses']) > 6)
    {
        // The lowest currently used ID
        $res = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_statuses` ORDER BY `id` ASC LIMIT 1");
        $lowest_id = hesk_dbResult($res);

        if ($lowest_id > 6)
        {
            $next_id = 6;
        }
        else
        {
            // Minimum next ID
          	$res = hesk_dbQuery("
                  SELECT MIN(`t1`.`id` + 1) FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_statuses` AS `t1`
                      LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_statuses` AS `t2`
                           ON `t1`.`id` + 1 = `t2`.`id`
                  WHERE `t2`.`id` IS NULL"
            );
            $next_id = hesk_dbResult($res);
        }
    }

    // Remove # from color
    $color = str_replace('#', '', $status['color']);

	// Insert custom status into database
	hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_statuses` (`id`, `name`, `color`, `can_customers_change`, `order`) VALUES (".intval($next_id).", '".hesk_dbEscape($status['names'])."', '{$color}', '{$status['can_customers_change']}', 990)");

	// Update order
	update_status_order();

	// Clear cache
	hesk_purge_cache('status');

    $_SESSION['statusord'] = $next_id;

	// Show success
	hesk_process_messages($hesklang['status_added'],'custom_statuses.php','SUCCESS');

} // End new_status()


function hesk_validate_color_hex($hex, $def = '#000000')
{
    $hex = strtolower($hex);
    return preg_match('/^\#[a-f0-9]{6}$/', $hex) ? $hex : $def;
} // END hesk_validate_color_hex()


function hesk_get_text_color($bg_color)
{
    // Get RGB values
    list($r, $g, $b) = sscanf($bg_color, "#%02x%02x%02x");

    // Is Black a good text color?
    if (hesk_color_diff($r, $g, $b, 0, 0, 0) >= 500)
    {
        return '#000000';
    }

    // Use white instead
    return '#ffffff';
} // END hesk_get_text_color()


function hesk_color_diff($R1,$G1,$B1,$R2,$G2,$B2)
{
    return max($R1,$R2) - min($R1,$R2) +
           max($G1,$G2) - min($G1,$G2) +
           max($B1,$B2) - min($B1,$B2);
} // END hesk_color_diff()
delete_tickets.php
wget 'https://lists2.roe3.org/hesk/admin/delete_tickets.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
define('TEMPLATE_PATH', HESK_PATH . "theme/{$hesk_settings['site_theme']}/");
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require_once(HESK_PATH . 'inc/customer_accounts.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Load priorities
require_once(HESK_PATH . 'inc/priorities.inc.php');

/* Set correct return URL */
if (isset($_SERVER['HTTP_REFERER']))
{
	$url = hesk_input($_SERVER['HTTP_REFERER']);
    $url = str_replace('&amp;','&',$url);
	if ($tmp = strstr($url,'show_tickets.php'))
    {
    	$referer = $tmp;
    }
	elseif ($tmp = strstr($url,'find_tickets.php'))
    {
    	$referer = $tmp;
    }
    elseif ($tmp = strstr($url,'admin_main.php'))
    {
    	$referer = $tmp;
    }
    else
    {
    	$referer = 'admin_main.php';
    }
}
else
{
	$referer = 'admin_main.php';
}

/* Is this a delete ticket request from within a ticket ("delete" icon)? */
if ( isset($_GET['delete_ticket']) )
{
    /* Check permissions for this feature */
	hesk_checkPermission('can_del_tickets');

	/* A security check */
	hesk_token_check();

	// Tracking ID
	$trackingID = hesk_cleanID() or die($hesklang['int_error'].': '.$hesklang['no_trackID']);

	/* Get ticket info */
	$result = hesk_dbQuery("SELECT `id`,`trackid`,`category`,`owner`,`assignedby` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `trackid`='".hesk_dbEscape($trackingID)."' LIMIT 1");
	if (hesk_dbNumRows($result) != 1)
	{
		hesk_error($hesklang['ticket_not_found']);
	}
	$ticket = hesk_dbFetchAssoc($result);

	/* Is this user allowed to access this ticket? */
	hesk_verifyStaffTicketAccess($ticket['trackid'], $ticket);

	hesk_fullyDeleteTicket($ticket['id'], $ticket['trackid']);

    hesk_process_messages(sprintf($hesklang['num_tickets_deleted'],1),$referer,'SUCCESS');
}


/* This is a request from ticket list. Must be POST and id must be an array */
if ( ! isset($_POST['id']) || ! is_array($_POST['id']) )
{
	hesk_process_messages($hesklang['no_selected'], $referer, 'NOTICE');
}
/* If not, then needs an action (a) POST variable set */
elseif ( ! isset($_POST['a']) )
{
	hesk_process_messages($hesklang['invalid_action'], $referer);
}

$i=0;

// Assign tickets to
if ( isset($_POST['action-type']) && $_POST['action-type'] == 'assi')
{
	hesk_token_check('POST');

	if ( ! isset($_POST['owner']) || $_POST['owner'] == '')
	{
		hesk_process_messages($hesklang['assign_no'], $referer, 'NOTICE');
	}

	$end_message = array();
	$num_assigned = 0;

	// Permissions
	$can_assign_others = hesk_checkPermission('can_assign_others',0);
	if ($can_assign_others)
	{
		$can_assign_self = TRUE;
	}
	else
	{
		$can_assign_self = hesk_checkPermission('can_assign_self',0);
	}

	$owner = intval( hesk_POST('owner') );

    // Make sure this staff member is allowed to perform the requested assignment action.
    if ($owner == -1)
    {
        if ( ! $can_assign_others && ! $can_assign_self)
        {
            hesk_error($hesklang['no_permission']);
        }
    }
    elseif ( ! $can_assign_others && ($owner != intval($_SESSION['id']) || ! $can_assign_self))
    {
        hesk_error($hesklang['no_permission']);
    }

	if ($owner == -1)
	{
		foreach ($_POST['id'] as $this_id)
		{
			if ( is_array($this_id) )
			{
				continue;
			}

			$this_id = intval($this_id) or hesk_error($hesklang['id_not_valid']);

			$result = hesk_dbQuery("SELECT `id`,`trackid`,`category`,`owner`,`assignedby` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`={$this_id} LIMIT 1");
			if (hesk_dbNumRows($result) != 1)
			{
				continue;
			}
			$ticket = hesk_dbFetchAssoc($result);
			hesk_verifyStaffTicketAccess($ticket['trackid'], $ticket);

            if ( ! $can_assign_others && intval($ticket['owner']) != intval($_SESSION['id']))
            {
                $end_message[] = $ticket['trackid'] . ' error: ' . $hesklang['no_permission'];
                $i++;
                continue;
            }

			$revision = sprintf($hesklang['thist2'],hesk_date(),'<i>'.$hesklang['unas'].'</i>',addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
			$res = hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `owner`=0 , `assignedby`=NULL , `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') WHERE `id`={$this_id} LIMIT 1");

			$end_message[] = sprintf($hesklang['assign_2'], $this_id);
            $num_assigned++;
			$i++;
		}

        if ($num_assigned == $i)
        {
            hesk_process_messages($hesklang['assign_1'],$referer,'SUCCESS');
        }

        hesk_process_messages(sprintf($hesklang['assign_log'], $num_assigned, ($i - $num_assigned), implode("\n", $end_message)),$referer,($num_assigned == 0) ? 'ERROR' : 'NOTICE');
	}

	$res = hesk_dbQuery("SELECT `id`,`user`,`name`,`email`,`isadmin`,`categories`,`notify_assigned` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id`='{$owner}' AND `active` = 1 LIMIT 1");
	$owner_data = hesk_dbFetchAssoc($res);
	if ( ! $owner_data)
	{
		hesk_process_messages($hesklang['no_valid_id'], $referer);
	}

	if ( ! $owner_data['isadmin'])
	{
		$owner_data['categories'] = hesk_getCategoriesForUser($owner);
	}

	require(HESK_PATH . 'inc/email_functions.inc.php');

	foreach ($_POST['id'] as $this_id)
	{
		if ( is_array($this_id) )
		{
			continue;
		}

		$this_id = intval($this_id) or hesk_error($hesklang['id_not_valid']);

		$result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`={$this_id} LIMIT 1");
		if (hesk_dbNumRows($result) != 1)
		{
			continue;
		}
		$ticket = hesk_dbFetchAssoc($result);
		hesk_verifyStaffTicketAccess($ticket['trackid'], $ticket);

		if ( $ticket['owner'] == $owner )
		{
			$end_message[] = sprintf($hesklang['assign_3'], $ticket['trackid'], $owner_data['name']);
			$i++;
			continue;
		}
		if ( $owner_data['isadmin'] || in_array($ticket['category'],$owner_data['categories']))
		{
			$revision = sprintf($hesklang['thist2'],hesk_date(),addslashes($owner_data['name']).' ('.$owner_data['user'].')',addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
			hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `owner`={$owner} , `assignedby`=".intval($_SESSION['id']).", `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') WHERE `id`={$this_id} LIMIT 1");

			$end_message[] = sprintf($hesklang['assign_4'], $ticket['trackid'], $owner_data['name']);
			$num_assigned++;

			$ticket['owner'] = $owner;
			$customers = hesk_get_customers_for_ticket($ticket['id']);
			$customer_names = array_map(function($customer) { return $customer['name']; }, $customers);
			$first_name = empty($customer_names) ? '' : $customer_names[0];
			$customer_emails = array_map(function($customer) { return $customer['email']; }, $customers);

            /* --> Prepare message */

            // 1. Generate the array with ticket info that can be used in emails
            $info = array(
            'email'			=> implode(';', $customer_emails),
            'category'		=> $ticket['category'],
            'priority'		=> $ticket['priority'],
            'owner'			=> $ticket['owner'],
            'trackid'		=> $ticket['trackid'],
            'status'		=> $ticket['status'],
            'name'			=> implode(',', $customer_names),
            'subject'		=> $ticket['subject'],
            'message'		=> $ticket['message'],
            'message_html'  => $ticket['message_html'],
            'attachments'	=> $ticket['attachments'],
            'dt'			=> hesk_date($ticket['dt'], true),
            'lastchange'	=> hesk_date($ticket['lastchange'], true),
            'due_date'      => hesk_format_due_date($ticket['due_date']),
            'id'			=> $ticket['id'],
            'time_worked'   => $ticket['time_worked'],
            'last_reply_by' => hesk_getReplierNameArray($ticket),
            );

            // 2. Add custom fields to the array
            foreach ($hesk_settings['custom_fields'] as $k => $v)
            {
                $info[$k] = $v['use'] ? $ticket[$k] : '';
            }

            // 3. Make sure all values are properly formatted for email
            $ticket = hesk_ticketToPlain($info, 1, 0);

            /* Notify the new owner? */
            if ($ticket['owner'] != intval($_SESSION['id']))
            {
                hesk_notifyAssignedStaff(false, 'ticket_assigned_to_you', 'notify_assigned', false);
            }
		}
		else
		{
        	$end_message[] = sprintf($hesklang['assign_5'], $ticket['trackid'], $owner_data['name']);
		}

		$i++;
	}

	hesk_process_messages(sprintf($hesklang['assign_log'], $num_assigned, ($i - $num_assigned), implode("\n", $end_message)),$referer,($num_assigned == 0) ? 'ERROR' : ($num_assigned < $i ? 'NOTICE' : 'SUCCESS'));
}

// Change priority
if ( is_numeric($_POST['a']) && $_POST['action-type'] == 'bulk')
{
	// A security check
	hesk_token_check('POST');

    // Check permissions for this feature
    hesk_checkPermission('can_reply_tickets');

	// Priority info
	$priority = $_POST['a'];
    if ( ! isset($hesk_settings['priorities'][$priority])) {
        hesk_error($hesklang['priority_e_id']);
    }

	foreach ($_POST['id'] as $this_id)
	{
		if ( is_array($this_id) )
		{
			continue;
		}

		$this_id = intval($this_id) or hesk_error($hesklang['id_not_valid']);
		$result = hesk_dbQuery("SELECT `id`,`trackid`,`category`,`owner`,`assignedby`,`priority` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`={$this_id} LIMIT 1");
		if (hesk_dbNumRows($result) != 1)
		{
			continue;
		}
		$ticket = hesk_dbFetchAssoc($result);
		hesk_verifyStaffTicketAccess($ticket['trackid'], $ticket);

		if ($ticket['priority'] == $priority)
		{
			continue;
		}

		$revision = sprintf($hesklang['thist8'],hesk_date(),$hesk_settings['priorities'][$priority]['name'],addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
		hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `priority`='{$priority}', `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') WHERE `id`={$this_id}");

		$i++;
	}

	hesk_process_messages($hesklang['pri_set_to'].' '.$hesk_settings['priorities'][$priority]['name'],$referer,'SUCCESS');
}
/* DELETE */
elseif ($_POST['a']=='delete')
{
    /* Check permissions for this feature */
	hesk_checkPermission('can_del_tickets');

	/* A security check */
	hesk_token_check('POST');

    foreach ($_POST['id'] as $this_id)
    {
    	if ( is_array($this_id) )
        {
        	continue;
        }

        $this_id = intval($this_id) or hesk_error($hesklang['id_not_valid']);
        $result = hesk_dbQuery("SELECT `id`,`trackid`,`category`,`owner`,`assignedby` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`='".intval($this_id)."' LIMIT 1");
		if (hesk_dbNumRows($result) != 1)
		{
			continue;
		}
        $ticket = hesk_dbFetchAssoc($result);

        hesk_verifyStaffTicketAccess($ticket['trackid'], $ticket);

        hesk_fullyDeleteTicket($ticket['id'], $ticket['trackid']);
        $i++;
    }

    hesk_process_messages(sprintf($hesklang['num_tickets_deleted'],$i),$referer,'SUCCESS');
}
/* MERGE TICKETS */
elseif ($_POST['a']=='merge')
{
    /* Check permissions for this feature */
	hesk_checkPermission('can_merge_tickets');

	/* A security check */
	hesk_token_check('POST');

	/* Sort IDs, tickets will be merged to the lowest ID */
    sort($_POST['id'], SORT_NUMERIC);

    /* Select lowest ID as the target ticket */
    $merge_into = array_shift($_POST['id']);

    /* Verify access to all tickets being merged */
    $merge_ids = array_merge(array($merge_into), $_POST['id']);
    foreach ($merge_ids as $this_id)
    {
        if ( is_array($this_id) )
        {
            continue;
        }

        $this_id = intval($this_id) or hesk_error($hesklang['id_not_valid']);
        $result = hesk_dbQuery("SELECT `id`,`trackid`,`category`,`owner`,`assignedby` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`={$this_id} LIMIT 1");
        if (hesk_dbNumRows($result) != 1)
        {
            continue;
        }
        $ticket = hesk_dbFetchAssoc($result);
        hesk_verifyStaffTicketAccess($ticket['trackid'], $ticket);
    }

	/* Merge tickets or throw an error */
	if ( hesk_mergeTickets( $_POST['id'] , $merge_into ) )
    {
		hesk_process_messages($hesklang['merged'],$referer,'SUCCESS');
    }
    else
    {
    	$hesklang['merge_err'] .= ' ' . $_SESSION['error'];
        hesk_cleanSessionVars($_SESSION['error']);
    	hesk_process_messages($hesklang['merge_err'],$referer);
    }
}
/* TAG/UNTAG TICKETS */
elseif ($_POST['a']=='tag' || $_POST['a']=='untag')
{
    /* Check permissions for this feature */
	hesk_checkPermission('can_add_archive');

	/* A security check */
	hesk_token_check('POST');

    if ($_POST['a']=='tag')
    {
    	$archived = 1;
        $action = $hesklang['num_tickets_tag'];
    }
    else
    {
		$archived = 0;
        $action = $hesklang['num_tickets_untag'];
    }

    foreach ($_POST['id'] as $this_id)
    {
    	if ( is_array($this_id) )
        {
        	continue;
        }

        $this_id = intval($this_id) or hesk_error($hesklang['id_not_valid']);
        $result = hesk_dbQuery("SELECT `id`,`trackid`,`category`,`owner`,`assignedby` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`='".intval($this_id)."' LIMIT 1");
		if (hesk_dbNumRows($result) != 1)
		{
			continue;
		}
        $ticket = hesk_dbFetchAssoc($result);

        hesk_verifyStaffTicketAccess($ticket['trackid'], $ticket);

        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `archive`='$archived' WHERE `id`='".intval($this_id)."'");
        $i++;
    }

    hesk_process_messages(sprintf($action,$i),$referer,'SUCCESS');
}
/* EXPORT */
elseif ($_POST['a']=='export')
{
    /* Check permissions for this feature */
    hesk_checkPermission('can_export');

    /* A security check */
    hesk_token_check('POST');

    if (defined('HESK_DEMO')) {
        hesk_process_messages($hesklang['ddemo'], 'admin_main.php', 'NOTICE');
    }

    $ids_to_export = array();

    foreach ($_POST['id'] as $this_id)
    {
        if ( is_array($this_id) )
        {
            continue;
        }

        $ids_to_export[] = intval($this_id) or hesk_error($hesklang['id_not_valid']);
        $i++;
    }

    if ($i < 1)
    {
        hesk_process_messages($hesklang['no_selected'], $referer, 'NOTICE');
    }

    // Start SQL statement for selecting tickets
    $sql = "SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id` IN (".implode(',', $ids_to_export).") ";
    $sql .= " AND " . hesk_myCategories();
    $sql .= " AND " . hesk_myOwnership();

    require_once(HESK_PATH . 'inc/custom_fields.inc.php');
    require_once(HESK_PATH . 'inc/statuses.inc.php');
    require(HESK_PATH . 'inc/export_functions.inc.php');

    list($success_msg, $tickets_exported) = hesk_export_to_XML($sql, true);

    if ($tickets_exported > 0)
    {
        hesk_process_messages($success_msg,$referer,'SUCCESS');
    }
    else
    {
        hesk_process_messages($hesklang['n2ex'],$referer,'NOTICE');
    }
}
/* ANONYMIZE */
elseif ($_POST['a']=='anonymize')
{
    /* Check permissions for this feature */
    hesk_checkPermission('can_privacy');

    /* A security check */
    hesk_token_check('POST');

    if (defined('HESK_DEMO')) {
        hesk_process_messages($hesklang['ddemo'], 'admin_main.php', 'NOTICE');
    }    

    require(HESK_PATH . 'inc/privacy_functions.inc.php');

    foreach ($_POST['id'] as $this_id)
    {
        if ( is_array($this_id) )
        {
            continue;
        }

        $this_id = intval($this_id) or hesk_error($hesklang['id_not_valid']);
        $result = hesk_dbQuery("SELECT `id`,`trackid`,`category`,`owner`,`assignedby` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`='".intval($this_id)."' AND ".hesk_myOwnership()." LIMIT 1");
        if (hesk_dbNumRows($result) != 1)
        {
            continue;
        }
        $ticket = hesk_dbFetchAssoc($result);

        hesk_verifyStaffTicketAccess($ticket['trackid'], $ticket);

        hesk_anonymizeTicket(null, null, true);
        $i++;
    }

    hesk_process_messages(sprintf($hesklang['num_tickets_anon'],$i),$referer,'SUCCESS');
}
/* PRINT */
elseif ($_POST['a']=='print')
{
    /* Check permissions for this feature */
	hesk_checkPermission('can_view_tickets');

	/* A security check */
	hesk_token_check('POST');

    // Load custom fields
    require_once(HESK_PATH . 'inc/custom_fields.inc.php');

    // Load statuses
    require_once(HESK_PATH . 'inc/statuses.inc.php');

	// List of staff
	if (!isset($admins))
	{
		$admins = array();
		$res2 = hesk_dbQuery("SELECT `id`,`name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` ORDER BY `id` ASC");
		while ($row=hesk_dbFetchAssoc($res2))
		{
			$admins[$row['id']]=$row['name'];
		}
	}

	// List of categories
	$hesk_settings['categories'] = array();
	$res2 = hesk_dbQuery('SELECT `id`, `name` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'categories` WHERE ' . hesk_myCategories('id') . ' ORDER BY `cat_order` ASC');
	while ($row=hesk_dbFetchAssoc($res2))
	{
		$hesk_settings['categories'][$row['id']] = $row['name'];
	}

    // Print page head
    header('Content-Type: text/html; charset=utf-8');

	$tickets = array();
    // Loop through ticket IDs and print them
    foreach ($_POST['id'] as $this_id)
    {
        if ( is_array($this_id) ) {
            continue;
        }

        $this_id = intval($this_id) or hesk_error($hesklang['id_not_valid']);
        $result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`='".intval($this_id)."' LIMIT 1");
        if (hesk_dbNumRows($result) != 1)
        {
            continue;
        }
        $ticket = hesk_dbFetchAssoc($result);

        // Check that we have proper permissions to view this ticket
        hesk_verifyStaffTicketAccess($ticket['trackid'], $ticket);

        // All good, continue...
        $customers = hesk_get_customers_for_ticket($ticket['id']);

        // Demo mode
        if ( defined('HESK_DEMO') )
        {
            foreach ($customers as $customer) {
                $customer['email'] = 'hidden@demo.com';
            }
            $ticket['ip']	 = '127.0.0.1';
        }

        $category['name'] = isset($hesk_settings['categories'][$ticket['category']]) ? $hesk_settings['categories'][$ticket['category']] : $hesklang['catd'];

        // Get replies
        $res  = hesk_dbQuery("SELECT `replies`.*, `reply_customer`.`name` AS `customer_name`, `reply_staff`.`name` AS `staff_name` 
            FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` AS `replies`
            LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` AS `reply_customer`
                ON `replies`.`customer_id` = `reply_customer`.`id`
            LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."users` AS `reply_staff`
                ON `replies`.`staffid` = `reply_staff`.`id`
            WHERE `replyto`='{$ticket['id']}' ORDER BY `replies`.`id` ASC");

        $replies = [];
        while ($row = hesk_dbFetchAssoc($res)) {
            if (intval($row['staffid']) > 0) {
                $row['name'] = $row['staff_name'];
            } else {
                $row['name'] = $row['customer_name'];
            }
            $replies[] = $row;
        }

        // Get notes
        $notes = array();
        $res2 = hesk_dbQuery("SELECT t1.*, t2.`name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."notes` AS t1 LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."users` AS t2 ON t1.`who` = t2.`id` WHERE `ticket`='{$ticket['id']}' ORDER BY t1.`id`");
        while ($note = hesk_dbFetchAssoc($res2))
        {
            $notes[] = $note;
        }

        $ticket['notes'] = $notes;
        $ticket['replies'] = $replies;
        $ticket['categoryName'] = $category['name'];
        $ticket['customers'] = $customers;
        $tickets[] = $ticket;
    }

	// Print tickets
	require(HESK_PATH . 'inc/print_template.inc.php');
	flush();

    exit();
}
/* Linked Selected Tickets */
elseif ($_POST['a'] == 'link_tickets') {

    // Check permissions for this feature
    hesk_checkPermission('can_link_tickets');

    // A security check
    hesk_token_check('POST');

    $ticket_ids = $_POST['id'];

    // Need at least two tickets to link
    if (count($ticket_ids) < 2) {
        hesk_process_messages($hesklang['at_least_two_more'], $referer, 'NOTICE');
    }

    // Verify access to all tickets being linked
    foreach ($ticket_ids as $ticket_id)
    {
        if (is_array($ticket_id))
        {
            continue;
        }

        $ticket_id = intval($ticket_id) or hesk_error($hesklang['id_not_valid']);
        $result = hesk_dbQuery("SELECT `id`,`trackid`,`category`,`owner`,`assignedby` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`={$ticket_id} LIMIT 1");
        if (hesk_dbNumRows($result) != 1)
        {
            continue;
        }
        $ticket = hesk_dbFetchAssoc($result);
        hesk_verifyStaffTicketAccess($ticket['trackid'], $ticket);
    }

    $link_created = 0;
    $link_already_exists = 0;

    // Loop through all combinations and insert links
    foreach ($ticket_ids as $ticket_id) {
        if (is_array($ticket_id)) {
            continue;
        }

        if (count($ticket_ids) < 2) {
            continue;
        }

        $ticket_id = intval($ticket_id) or hesk_error($hesklang['id_not_valid']);

        // Get ticket tracking ID for the log
        $result = hesk_dbQuery("SELECT `trackid` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`={$ticket_id}");
        $ticket_track_id = hesk_dbResult($result) or hesk_error($hesklang['id_not_valid']);

        foreach ($ticket_ids as $linked_ticket_id) {
            if (is_array($linked_ticket_id)) {
                continue;
            }

            $linked_ticket_id = intval($linked_ticket_id) or hesk_error($hesklang['id_not_valid']);

            // Prevent self linking
            if ($ticket_id === $linked_ticket_id) {
                continue;
            }

            // Check for linked data in table
            $result = hesk_dbQuery("SELECT COUNT(*) FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."linked_tickets` WHERE (`ticket_id1` = {$ticket_id} AND `ticket_id2` = {$linked_ticket_id}) OR (`ticket_id1` = {$linked_ticket_id} AND `ticket_id2` = {$ticket_id})");
            $already_linked = hesk_dbResult($result);

            if (empty($already_linked)) {
                // Get linked ticket tracking ID for the log
                $result = hesk_dbQuery("SELECT `trackid` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`={$linked_ticket_id}");
                $linked_ticket_track_id = hesk_dbResult($result) or hesk_error($hesklang['id_not_valid']);

                // Insert ticket relation into database
                hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."linked_tickets` (`ticket_id1`, `ticket_id2`, `dt_created`) VALUES ('".hesk_dbEscape($ticket_id)."', '".hesk_dbEscape($linked_ticket_id)."',NOW())");

                // Update insert history log
                $link_ticket_log = sprintf($hesklang['link_history'], hesk_date(), $linked_ticket_track_id, addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');;
                hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `history`=CONCAT(`history`,'".hesk_dbEscape($link_ticket_log)."') WHERE `id`='".intval($ticket_id)."'");

                $link_created++;
            } else {
                $link_already_exists++;
            }
        }

        // No need for duplicate checks with this $ticket_id, remove it
        if (($key = array_search($ticket_id, $ticket_ids)) !== false) {
            unset($ticket_ids[$key]);
        }
    }
    hesk_process_messages(sprintf($hesklang['selected_link_success'], $link_created, $link_already_exists), $referer, 'SUCCESS');
}
/* JUST CLOSE */
else
{
    /* Check permissions for this feature */
	hesk_checkPermission('can_view_tickets');
    hesk_checkPermission('can_resolve');

	/* A security check */
	hesk_token_check('POST');

    $revision = sprintf($hesklang['thist3'],hesk_date(),addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');

	foreach ($_POST['id'] as $this_id)
	{
    	if ( is_array($this_id) )
        {
        	continue;
        }

		$this_id = intval($this_id) or hesk_error($hesklang['id_not_valid']);

        $result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`='".intval($this_id)."' LIMIT 1");
        if (hesk_dbNumRows($result) != 1)
        {
            continue;
        }
        $ticket = hesk_dbFetchAssoc($result);

        hesk_verifyStaffTicketAccess($ticket['trackid'], $ticket);

		hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `status`='3', `closedat`=NOW(), `closedby`=".intval($_SESSION['id']).", `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') WHERE `id`='".intval($this_id)."'");
		$i++;

        $ticket['collaborators'] = hesk_getTicketsCollaboratorIDs($ticket['id']);

		// Notify customer of closed ticket?
		if ($hesk_settings['notify_closed'] || count($ticket['collaborators']))
		{
            require_once(HESK_PATH . 'inc/email_functions.inc.php');

			$ticket['dt'] = hesk_date($ticket['dt'], true);
			$ticket['lastchange'] = hesk_date($ticket['lastchange'], true);
            $ticket['due_date'] = hesk_format_due_date($ticket['due_date']);

            $customers = hesk_get_customers_for_ticket($ticket['id']);
            $customer_emails = array_map(function($customer) { return $customer['email']; }, $customers);
            $customer_names = array_map(function($customer) { return $customer['name']; }, $customers);

            $ticket['email'] = implode(';', $customer_emails);
            $ticket['name'] = implode(';', $customer_names);
            $ticket['last_reply_by'] = hesk_getReplierNameArray($ticket);

			$ticket = hesk_ticketToPlain($ticket, 1, 0);

            if ($hesk_settings['notify_closed']) {
                hesk_notifyCustomer('ticket_closed');
            }

            if (count($ticket['collaborators'])) {
                hesk_notifyAssignedStaff(false, 'collaborator_resolved', 'notify_collaborator_resolved', 'notify_collaborator_resolved', array($_SESSION['id']));
            }
		}
	}

    hesk_process_messages(sprintf($hesklang['num_tickets_closed'],$i),$referer,'SUCCESS');
}
download_attachment.php
wget 'https://lists2.roe3.org/hesk/admin/download_attachment.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

// Get all the required files and functions
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_isLoggedIn();

// Knowledgebase attachments
if ( isset($_GET['kb_att']) )
{
	if ( ! $hesk_settings['kb_enable']) {
		hesk_error($hesklang['kbdis']);
	}

	// Attachment ID
	$att_id = intval( hesk_GET('kb_att') ) or hesk_error($hesklang['id_not_valid']);

	// Connect to database
	hesk_dbConnect();

	// Get attachment info
	$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_attachments` WHERE `att_id`='{$att_id}' LIMIT 1");
	if (hesk_dbNumRows($res) != 1)
	{
		hesk_error($hesklang['id_not_valid'].' (att_id)');
	}
	$file = hesk_dbFetchAssoc($res);

    // Is this person allowed access to this attachment?
	$res = hesk_dbQuery("SELECT `t1`.`type` as `cat_type`, `t2`.`type` as `art_type`
						FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` AS `t2`
                        JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` AS `t1`
                        ON `t2`.`catid` = `t1`.`id`
                        WHERE (`t2`.`attachments` LIKE '{$att_id}#%' OR `t2`.`attachments` LIKE '%,{$att_id}#%' )
                        LIMIT 1");

    // If no attachment found, throw an error
	if (hesk_dbNumRows($res) != 1)
	{
		hesk_error($hesklang['id_not_valid'].' (no_art)');
	}
	$row = hesk_dbFetchAssoc($res);

    // Private or draft article or category?
    if ($row['cat_type'] || $row['art_type'])
    {
		if ($row['art_type'] == 2)
		{
			// Need permission to manage KB to access draft attachments
			require(HESK_PATH . 'inc/admin_functions.inc.php');
			hesk_checkPermission('can_man_kb');
		}
    }
}

// Ticket attachments
else
{
	// Attachmend ID and ticket tracking ID
    $att_id = intval( hesk_GET('att_id', 0) ) or die($hesklang['id_not_valid']);
	$tic_id = hesk_cleanID() or die("$hesklang[int_error]: $hesklang[no_trackID]");

	// Connect to database
	hesk_dbConnect();

	// Get attachment info
	$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."attachments` WHERE `att_id`='{$att_id}' LIMIT 1");
	if (hesk_dbNumRows($res) != 1)
	{
		hesk_error($hesklang['id_not_valid'].' (att_id)');
	}
	$file = hesk_dbFetchAssoc($res);

	// Is ticket ID valid for this attachment?
	if ($file['ticket_id'] != $tic_id)
	{
	    hesk_error($hesklang['trackID_not_found']);
	}

    // Is this staff member allowed to access this ticket?
    hesk_verifyStaffTicketAccess($tic_id);
}

// Path of the file on the server
$realpath = HESK_PATH . $hesk_settings['attach_dir'] . '/' . $file['saved_name'];

// Perhaps the file has been deleted?
if ( ! file_exists($realpath))
{
	hesk_error($hesklang['attdel']);
}

// Send the file as an attachment to prevent malicious code from executing
header("Pragma: "); # To fix a bug in IE when running https
header("Cache-Control: "); # To fix a bug in IE when running https
hesk_sendFileDownloadHeaders($file['real_name'], $file['size']);

// For larger files use chunks, smaller ones can be read all at once
$chunksize = 1048576; // = 1024 * 1024 (1 Mb)
if ($file['size'] > $chunksize)
{
	$handle = fopen($realpath, 'rb');
	$buffer = '';
	while ( ! feof($handle))
    {
        set_time_limit(300);
		$buffer = fread($handle, $chunksize);
		echo $buffer;
		flush();
	}
	fclose($handle);
}
else
{
	readfile($realpath);
}

exit();
edit_note.php
wget 'https://lists2.roe3.org/hesk/admin/edit_note.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
hesk_checkPermission('can_view_tickets');

// Ticket ID
$trackingID = hesk_cleanID() or die($hesklang['int_error'].': '.$hesklang['no_trackID']);

// Note ID
$noteID = intval( hesk_REQUEST('note') ) or die($hesklang['int_error'].': '.$hesklang['mis_note']);

// Get ticket info and verify access
$ticket = hesk_verifyStaffTicketAccess($trackingID);

// Get note info
$result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."notes` WHERE `id`={$noteID}");
if (hesk_dbNumRows($result) != 1)
{
	hesk_error($hesklang['no_note']);
}
$note = hesk_dbFetchAssoc($result);

// Make sure the note matches the ticket and the user has permission to edit it
if ($note['ticket'] != $ticket['id'] || ( ! hesk_checkPermission('can_del_notes',0) && $note['who'] != $_SESSION['id']) )
{
	hesk_error($hesklang['perm_deny']);
}

// Save changes?
if (isset($_POST['save']))
{
	// A security check
	hesk_token_check('POST');

	// Get message
	$tmpvar['message'] = nl2br( hesk_makeURL( hesk_input( hesk_POST('message') ) ) );

	// If we have message or attachments do the update
	if ( strlen($tmpvar['message']) || strlen($note['attachments']) )
	{
		hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."notes` SET `message`='".hesk_dbEscape($tmpvar['message'])."' WHERE `id`={$noteID}");
		hesk_process_messages($hesklang['ednote2'],'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999),'SUCCESS');
	}
	// If not, delete the note
	else
	{
		hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."notes` WHERE `id`={$noteID}");
		header('Location: admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999));
		exit();
	}
}

$note['message'] = hesk_msgToPlain($note['message'],0,0);

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print admin navigation */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');
?>
<div class="main__content categories">
    <div class="table-wrap">
        <h3 style="font-size: 1.3rem; margin-top: 10px"><?php echo $hesklang['ednote']; ?></h3>
        <form method="post" action="edit_note.php" name="form1" class="form" aria-label="<?php echo $hesklang['ednote']; ?>">
            <div class="form-group">
                <label for="edit_message"><?php echo $hesklang['message']; ?></label>
                <textarea style="height: inherit" name="message" class="form-control" rows="12" cols="60"><?php echo $note['message']; ?></textarea>
            </div>
            <div class="form-group">
                <input type="hidden" name="save" value="1" /><input type="hidden" name="track" value="<?php echo $trackingID; ?>">
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                <input type="hidden" name="note" value="<?php echo $noteID; ?>">
                <button type="submit" class="btn btn-full"><?php echo $hesklang['save_changes']; ?></button>
            </div>
        </form>
    </div>
</div>

<p style="text-align:center"><a href="javascript:history.go(-1)"><?php echo $hesklang['back']; ?></a></p>

<p>&nbsp;</p>

<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();
?>
edit_post.php
wget 'https://lists2.roe3.org/hesk/admin/edit_post.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();
require(HESK_PATH . 'inc/posting_functions.inc.php');
require(HESK_PATH . 'inc/customer_accounts.inc.php');

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
hesk_checkPermission('can_view_tickets');
hesk_checkPermission('can_edit_tickets');

/* Ticket ID */
$trackingID = hesk_cleanID() or die($hesklang['int_error'].': '.$hesklang['no_trackID']);

// Load custom fields
require_once(HESK_PATH . 'inc/custom_fields.inc.php');

// Load calendar JS and CSS
define('CALENDAR',1);
define('ATTACHMENTS',1);

if ($hesk_settings['staff_ticket_formatting'] == 2) {
    define('WYSIWYG',1);
}

$hesk_settings['datepicker'] = array();
$is_reply = 0;
$tmpvar = array();

if (!isset($_SESSION['iserror']))
{
	$_SESSION['iserror'] = array();
}

/* Get ticket info */
$result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `trackid`='".hesk_dbEscape($trackingID)."' LIMIT 1");
if (hesk_dbNumRows($result) != 1)
{
	hesk_error($hesklang['ticket_not_found']);
}
$ticket = hesk_dbFetchAssoc($result);

$customers = hesk_get_customers_for_ticket($ticket['id']);

// Demo mode
if ( defined('HESK_DEMO') )
{
	foreach ($customers as $customer) {
        $customer['email'] = 'hidden@demo.com';
    }
}

/* Is this user allowed to view and edit this ticket? */
hesk_verifyStaffTicketAccess($trackingID, $ticket);

if ( hesk_isREQUEST('reply') )
{
	$tmpvar['id'] = intval( hesk_REQUEST('reply') ) or die($hesklang['id_not_valid']);

	$result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` WHERE `id`='{$tmpvar['id']}' AND `replyto`='".intval($ticket['id'])."' LIMIT 1");
	if (hesk_dbNumRows($result) != 1)
    {
    	hesk_error($hesklang['id_not_valid']);
    }
    $reply = hesk_dbFetchAssoc($result);
    $ticket['message'] = $reply['message'];
    $ticket['message_html'] = $reply['message_html'];
    $is_reply = 1;
}

// Count number of existing attachments for this post
$number_of_attachments = $is_reply ? hesk_countAttachments($reply['attachments']) : hesk_countAttachments($ticket['attachments']);

if (isset($_POST['save']))
{
	/* A security check */
	hesk_token_check('POST');

	$hesk_error_buffer = array();

    // Add attachments?
    $use_legacy_attachments = hesk_POST('use-legacy-attachments', 0);
    if ($hesk_settings['attachments']['use'] && $number_of_attachments < $hesk_settings['attachments']['max_number'])
    {
        require(HESK_PATH . 'inc/attachments.inc.php');
        $attachments = array();

        if ($use_legacy_attachments) {
            for ($i = $number_of_attachments + 1; $i <= $hesk_settings['attachments']['max_number']; $i++) {
                $att = hesk_uploadFile($i);
                if ($att !== false && !empty($att)) {
                    $attachments[$i] = $att;
                }
            }
        } else {
            // The user used the new drag-and-drop system.
            $temp_attachment_ids = hesk_POST_array('attachments');
            foreach ($temp_attachment_ids as $temp_attachment_id) {
                $temp_attachment = hesk_getTemporaryAttachment($temp_attachment_id);

                if ($temp_attachment !== null) {
                    $attachments[] = $temp_attachment;
                }
            }
        }
    }
    $myattachments = '';

    if ($is_reply)
    {
		$tmpvar['message'] = hesk_input( hesk_POST('message') ) or $hesk_error_buffer[]=$hesklang['enter_message'];
        $tmpvar['message_html'] = $tmpvar['message'];
        if ($hesk_settings['staff_ticket_formatting'] == 2) {
            // Decode the message we encoded earlier
            $tmpvar['message_html'] = hesk_html_entity_decode($tmpvar['message_html']);

            // Clean the HTML code and set the plaintext version
            require(HESK_PATH . 'inc/htmlpurifier/HeskHTMLPurifier.php');
            require(HESK_PATH . 'inc/html2text/html2text.php');
            $purifier = new HeskHTMLPurifier($hesk_settings['cache_dir']);
            $tmpvar['message_html'] = $purifier->heskPurify($tmpvar['message_html']);

            $tmpvar['message'] = convert_html_to_text($tmpvar['message_html']);
            $tmpvar['message'] = fix_newlines($tmpvar['message']);

            // Prepare plain message for storage as HTML
            $tmpvar['message'] = hesk_htmlspecialchars($tmpvar['message']);
            $tmpvar['message'] = nl2br($tmpvar['message']);
        } else {
            // `message` already contains a HTML friendly version. May as well just re-use it
            $tmpvar['message'] = hesk_makeURL($tmpvar['message']);
            $tmpvar['message'] = nl2br($tmpvar['message']);
            $tmpvar['message_html'] = $tmpvar['message'];
        }


        if (count($hesk_error_buffer))
	    {
            // Remove any successfully uploaded attachments
            if ($hesk_settings['attachments']['use'] && isset($attachments))
            {
                if ($use_legacy_attachments) {
                    hesk_removeAttachments($attachments);
                } else {
                    $_SESSION['edit_attachments'] = $attachments;
                }

            }

	    	$myerror = '<ul>';
		    foreach ($hesk_error_buffer as $error)
		    {
		        $myerror .= "<li>$error</li>\n";
		    }
	        $myerror .= '</ul>';
	    	hesk_error($myerror);
	    }

        if ($hesk_settings['attachments']['use'] && !empty($attachments))
        {
            if (!$use_legacy_attachments) {
                $attachments = hesk_migrateTempAttachments($attachments, $trackingID);
            }

            foreach ($attachments as $myatt)
            {
                hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."attachments` (`ticket_id`,`saved_name`,`real_name`,`size`) VALUES ('".hesk_dbEscape($trackingID)."','".hesk_dbEscape($myatt['saved_name'])."','".hesk_dbEscape($myatt['real_name'])."','".intval($myatt['size'])."')");
                $myattachments .= hesk_dbInsertID() . '#' . $myatt['real_name'] .',';
            }
        }

        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` SET `message`='".hesk_dbEscape($tmpvar['message'])."', `message_html`='".hesk_dbEscape($tmpvar['message_html'])."', `attachments`=CONCAT(`attachments`, '".hesk_dbEscape($myattachments)."') WHERE `id`='".intval($tmpvar['id'])."' AND `replyto`='".intval($ticket['id'])."'");
    }
    else
    {
        $tmpvar['customer_id'] = hesk_POST('customer_id') or $hesk_error_buffer[]=$hesklang['customer_required'];
        $tmpvar['follower_ids'] = hesk_POST_array('follower_id');

        // Set Ticket Language
        if (($tmpvar['set_language'] = hesk_input( hesk_POST('set_language') ))) {
            $language_SQL = "`language`='".hesk_dbEscape($tmpvar['set_language'])."',";
        } else {
            $language_SQL = '';
        }

		$tmpvar['subject'] = hesk_input( hesk_POST('subject') ) or $hesk_error_buffer[]=$hesklang['enter_ticket_subject'];
		$tmpvar['message'] = hesk_input( hesk_POST('message') );
        $tmpvar['message_html'] = $tmpvar['message'];
        if ($hesk_settings['require_message'] == 1 && $tmpvar['message'] == '')
        {
            $hesk_error_buffer[] = $hesklang['enter_message'];
        }
        if ($hesk_settings['staff_ticket_formatting'] == 2) {
            // Decode the message we encoded earlier
            $tmpvar['message_html'] = hesk_html_entity_decode($tmpvar['message_html']);

            // Clean the HTML code and set the plaintext version
            require(HESK_PATH . 'inc/htmlpurifier/HeskHTMLPurifier.php');
            require(HESK_PATH . 'inc/html2text/html2text.php');
            $purifier = new HeskHTMLPurifier($hesk_settings['cache_dir']);
            $tmpvar['message_html'] = $purifier->heskPurify($tmpvar['message_html']);

            $tmpvar['message'] = convert_html_to_text($tmpvar['message_html']);
            $tmpvar['message'] = fix_newlines($tmpvar['message']);

            // Prepare plain message for storage as HTML
            $tmpvar['message'] = hesk_htmlspecialchars($tmpvar['message']);
            $tmpvar['message'] = nl2br($tmpvar['message']);
        } else {
            // `message` already contains a HTML friendly version. May as well just re-use it
            $tmpvar['message'] = hesk_makeURL($tmpvar['message']);
            $tmpvar['message'] = nl2br($tmpvar['message']);
            $tmpvar['message_html'] = $tmpvar['message'];
        }

        // Custom fields
        foreach ($hesk_settings['custom_fields'] as $k=>$v)
        {
            if ($v['use'])
            {
                // Don't overwrite existing not used fields, but don't require them either if not required by category
                if ( ! hesk_is_custom_field_in_category($k, $ticket['category'])) {
                    $v['req'] = 0;
                }

                if ($v['type'] == 'checkbox')
                {
                    $tmpvar[$k]='';

                    if (isset($_POST[$k]) && is_array($_POST[$k]))
                    {
                        foreach ($_POST[$k] as $myCB)
                        {
                            $tmpvar[$k] .= ( is_array($myCB) ? '' : hesk_input($myCB) ) . '<br />';;
                        }
                        $tmpvar[$k]=substr($tmpvar[$k],0,-6);
                    }
                    else
                    {
                        if ($v['req'] == 2)
                        {
                            $hesk_error_buffer[$k]=$hesklang['fill_all'].': '.$v['name'];
                        }
                        $_POST[$k] = '';
                    }
                }
                elseif ($v['type'] == 'date')
                {
                    $tmpvar[$k] = hesk_POST($k);
                    $_SESSION["as_$k"] = '';

                    if ($date = hesk_datepicker_get_date($tmpvar[$k], false, 'UTC'))
                    {
                        $_SESSION["as_$k"] = $tmpvar[$k];

                        $date->setTime(0, 0);
                        $dmin = strlen($v['value']['dmin']) ? new DateTime($v['value']['dmin'] . ' t00:00:00 UTC') : false;
                        $dmax = strlen($v['value']['dmax']) ? new DateTime($v['value']['dmax'] . ' t00:00:00 UTC') : false;

                        if ($dmin && $dmin->format('Y-m-d') > $date->format('Y-m-d'))
                        {
                            $hesk_error_buffer[$k] = sprintf($hesklang['d_emin'], $v['name'], hesk_translate_date_string($dmin->format($hesk_settings['format_datepicker_php'])));
                        }
                        elseif ($dmax && $dmax->format('Y-m-d') < $date->format('Y-m-d'))
                        {
                            $hesk_error_buffer[$k] = sprintf($hesklang['d_emax'], $v['name'], hesk_translate_date_string($dmax->format($hesk_settings['format_datepicker_php'])));
                        }
                        else
                        {
                            $tmpvar[$k] = $date->getTimestamp();
                        }
                    }
                    else
                    {
                        $tmpvar[$k] = '';

                        if ($v['req'] == 2)
                        {
                            $hesk_error_buffer[$k]=$hesklang['fill_all'].': '.$v['name'];
                        }
                    }
                }
                elseif ($v['type'] == 'email')
                {
                    $tmp = $hesk_settings['multi_eml'];
                    $hesk_settings['multi_eml'] = $v['value']['multiple'];
                    $tmpvar[$k] = hesk_validateEmail( hesk_POST($k), 'ERR', 0);
                    $hesk_settings['multi_eml'] = $tmp;

                    if ($tmpvar[$k] != '')
                    {
                        $_SESSION["as_$k"] = hesk_input($tmpvar[$k]);
                    }
                    else
                    {
                        $_SESSION["as_$k"] = '';

                        if ($v['req'] == 2)
                        {
                            $hesk_error_buffer[$k] = $v['value']['multiple'] ? sprintf($hesklang['cf_noem'], $v['name']) : sprintf($hesklang['cf_noe'], $v['name']);
                        }
                    }
                }
                elseif ($v['req'] == 2)
                {
                    $tmpvar[$k]=hesk_makeURL(nl2br(hesk_input( hesk_POST($k) )));
                    if ($tmpvar[$k] == '')
                    {
                        $hesk_error_buffer[$k]=$hesklang['fill_all'].': '.$v['name'];
                    }
                }
                else
                {
                    $tmpvar[$k]=hesk_makeURL(nl2br(hesk_input(hesk_POST($k))));
                }
            }
            else
            {
                $tmpvar[$k] = '';
            }
        }

	    if (count($hesk_error_buffer))
	    {
            // Remove any successfully uploaded attachments
            if ($hesk_settings['attachments']['use'] && isset($attachments))
            {
                if ($use_legacy_attachments) {
                    hesk_removeAttachments($attachments);
                } else {
                    $_SESSION['edit_attachments'] = $attachments;
                }
            }

	    	$myerror = '<ul>';
		    foreach ($hesk_error_buffer as $error)
		    {
		        $myerror .= "<li>$error</li>\n";
		    }
	        $myerror .= '</ul>';
	    	hesk_error($myerror);
	    }

        if ($hesk_settings['attachments']['use'] && !empty($attachments))
        {
            if (!$use_legacy_attachments) {
                $attachments = hesk_migrateTempAttachments($attachments, $trackingID);
            }

            foreach ($attachments as $myatt)
            {
                hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."attachments` (`ticket_id`,`saved_name`,`real_name`,`size`) VALUES ('".hesk_dbEscape($trackingID)."','".hesk_dbEscape($myatt['saved_name'])."','".hesk_dbEscape($myatt['real_name'])."','".intval($myatt['size'])."')");
                $myattachments .= hesk_dbInsertID() . '#' . $myatt['real_name'] .',';
            }
        }

		$custom_SQL = '';
		for ($i=1; $i<=100; $i++)
		{
			$custom_SQL .= '`custom'.$i.'`=' . (isset($tmpvar['custom'.$i]) ? "'".hesk_dbEscape($tmpvar['custom'.$i])."'" : "''") . ',';
		}
		$custom_SQL = rtrim($custom_SQL, ',');

		hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET
		`subject`='".hesk_dbEscape( hesk_mb_substr($tmpvar['subject'], 0, 255) )."',
		`message`='".hesk_dbEscape($tmpvar['message'])."',
		`message_html`='".hesk_dbEscape($tmpvar['message_html'])."',
        `attachments`=CONCAT(`attachments`, '".hesk_dbEscape($myattachments)."'),
        $language_SQL
		$custom_SQL
		WHERE `id`='".intval($ticket['id'])."'");

        hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_customer`
        WHERE `ticket_id` = ".intval($ticket['id']));

        hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_customer` (`ticket_id`, `customer_id`, `customer_type`)
                      VALUES (".intval($ticket['id']).", ".intval($tmpvar['customer_id']).", 'REQUESTER')");
        foreach ($tmpvar['follower_ids'] as $follower_id) {
            hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_customer` (`ticket_id`, `customer_id`, `customer_type`)
                          VALUES (".intval($ticket['id']).", ".intval($follower_id).", 'FOLLOWER')");
        }
    }

    unset($tmpvar);
    hesk_cleanSessionVars('tmpvar');

    hesk_process_messages($hesklang['edt2'],'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999),'SUCCESS');
}

$ticket['message'] = hesk_msgToPlain($ticket['message'],0,0);

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print admin navigation */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');
?>
<div class="main__content categories ticket-create">
    <div class="table-wrap">
        <h3 style="margin-bottom: 20px"><?php echo $hesklang['edtt']; ?></h3>
        <form method="post" class="form" action="edit_post.php" name="form1" enctype="multipart/form-data" aria-label="<?php echo $hesklang['edtt']; ?>">
            <?php
            /* If it's not a reply edit all the fields */
            if (!$is_reply)
            {
                $requester = null;
                foreach ($customers as $customer) {
                    if ($customer['customer_type'] === 'REQUESTER') {
                        $requester = $customer;
                        break;
                    }
                }

                if ($requester['name'] == '') {
                    $requester['name'] = ( ! empty($requester['email']) ? $requester['email'] : $hesklang['pde'] );
                }
                ?>
                <div class="form-group">
                    <label for="create_customer">
                        <?php echo $hesklang['customer']; ?> <span class="important">*</span><a href="javascript:" class='ml5' id="new-customer-link" data-modal="[data-modal-id='create-customer']">[<?php echo $hesklang['new_customer']; ?>]</a>
                    </label>
                    <select name="customer_id" id="create_customer" class="read-write" placeholder="<?php echo hesk_addslashes($hesklang['search_by_name_or_email']); ?>">
                        <?php if ($requester !== null): ?>
                            <option value="<?php echo $requester['id']; ?>" selected>
                                <?php echo $requester['email'] ? "{$requester['name']} <{$requester['email']}>" : $requester['name']; ?>
                            </option>
                        <?php endif; ?>
                    </select>
                </div>
                <?php
                $followers = array_filter($customers, function($customer) { return $customer['customer_type'] === 'FOLLOWER'; });
                if (count($followers) > 0 || $hesk_settings['multi_eml']):
                ?>
                <div class="form-group">
                    <label for="followers_input">
                        <?php echo $hesklang['followers']; ?> <a href="javascript:" class='ml5' id="new-follower-link" data-modal="[data-modal-id='create-customer']">[<?php echo $hesklang['new_follower']; ?>]</a>
                    </label>
                    <select name="follower_id[]" multiple id="followers_input" class="read-write" placeholder="<?php echo hesk_addslashes($hesklang['search_by_name_or_email']); ?>">
                        <?php foreach ($followers as $row) { ?>
                            <option value="<?php echo $row['id']; ?>" selected>
                                <?php echo $row['email'] ? "{$row['name']} &lt;{$row['email']}&gt;" : $row['name']; ?>
                            </option>
                        <?php } ?>
                    </select>
                </div>
                <?php endif; ?>
                <div class="form-group">
                    <label for="edit_subject"><?php echo $hesklang['subject']; ?>:</label>
                    <input type="text" class="form-control" id="edit_subject" name="subject" maxlength="70" value="<?php echo $ticket['subject'];?>">
                </div>
                <script>
                    hesk_loadNoResultsSelectizePlugin('<?php echo hesk_jsString($hesklang['no_results_found']); ?>');
                    var plugins = ['no_results'];
                    var createCustomerSelectize = $('#create_customer').selectize({
                        valueField: 'id',
                        labelField: 'displayName',
                        searchField: ['name','email'],
                        copyClassesToDropdown: true,
                        preload: true,
                        options: [],
                        loadThrottle: 300,
                        persist: false,
                        plugins: plugins,
                        load: function(query, callback) {
                            $.ajax({
                                url: 'ajax/search_customers.php?query=' + encodeURIComponent(query),
                                dataType: 'json',
                                success: function(data) {
                                    callback(data);
                                }
                            });
                        },

                        /* Using deconstruct (requires EMCA6, but it's required in a bunch of other code already, so shouldn't be an issue)
                        here to add a bunch of general functionality needed for the custom "Add Entry",
                        And passing only the necessary custom behaviour for this specific dropdown.
                        */
                        ...hesk_selectizeAddCustomAddEntryToDropdown(
                            {
                                newEntryTextPrefix: '<?php echo hesk_jsString($hesklang['add_customer']); ?>',
                                onAddEntryClickedFunction: function(selectizeInstance, selectizeSearchValue) {
                                // populate the customer input field with the selected search value (either name or email)
                                let nameValue = selectizeSearchValue;
                                    let emailValue = '';
                                    if (selectizeSearchValue.indexOf('@') > -1) {
                                        // if there's an @ part of search string, we simply assume it's an email
                                        nameValue = '';
                                        emailValue = selectizeSearchValue;
                                    }
                                    // simply reuse what new-customer-link already does for adding a new customer.
                                    $('#new-customer-link').trigger('click', { nameValue: nameValue, emailValue: emailValue });
                                }
                            }
                        )
                    });

                    var plugins = ['no_results'<?php echo $hesk_settings['multi_eml'] ? ",'remove_button'" : ''; ?>];
                    var createFollowerSelectize = $('#followers_input').selectize({
                        valueField: 'id',
                        labelField: 'displayName',
                        searchField: ['name','email'],
                        copyClassesToDropdown: true,
                        preload: true,
                        options: [],
                        loadThrottle: 300,
                        persist: false,
                        plugins: plugins,
                        load: function(query, callback) {
                            $.ajax({
                                url: 'ajax/search_customers.php?query=' + encodeURIComponent(query),
                                dataType: 'json',
                                success: function(data) {
                                    callback(data);
                                }
                            });
                        },

                        /* Using deconstruct (requires EMCA6, but it's required in a bunch of other code already, so shouldn't be an issue)
                        here to add a bunch of general functionality needed for the custom "Add Entry",
                        And passing only the necessary custom behaviour for this specific dropdown.
                        */

                        ...hesk_selectizeAddCustomAddEntryToDropdown(
                            {
                                newEntryTextPrefix: '<?php echo hesk_jsString($hesklang['add_follower']); ?>',
                                onAddEntryClickedFunction: function(selectizeInstance, selectizeSearchValue) {
                                    // populate the follower input field with the selected search value (either name or email)
                                    let nameValue = selectizeSearchValue;
                                    let emailValue = '';
                                    if (selectizeSearchValue.indexOf('@') > -1) {
                                        nameValue = '';
                                        emailValue = selectizeSearchValue;
                                    }
                                    // simply reuse what new-follower-link already does for adding a new customer.
                                    $('#new-follower-link').trigger('click', { nameValue: nameValue, emailValue: emailValue });
                                }
                            }
                        )
                    });
                </script>
                <?php
                foreach ($hesk_settings['custom_fields'] as $k=>$v) {
                    if ($v['use'] && $v['place']==0 && (strlen($ticket[$k]) || hesk_is_custom_field_in_category($k, $ticket['category'])) ) {
                        $k_value  = $ticket[$k];

                        if ($v['type'] == 'checkbox') {
                            $k_value = explode('<br />',$k_value);
                        }

                        $v['req'] = ($v['req']==2 && hesk_is_custom_field_in_category($k, $ticket['category'])) ? '<span class="important">*</span>' : '';

                        switch ($v['type']) {
                            /* Radio box */
                            case 'radio':
                                echo '
                                <div class="form-group">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>
                                    <div class="radio-list">';

                                        $cls = in_array($k,$_SESSION['iserror']) ? ' class="isError" ' : '';

                                        $index = 0;
                                        foreach ($v['value']['radio_options'] as $option)
                                        {
                                            if (strlen($k_value) == 0)
                                            {
                                                $k_value = $option;
                                                $checked = empty($v['value']['no_default']) ? 'checked' : '';
                                            }
                                            elseif ($k_value == $option)
                                            {
                                                $k_value = $option;
                                                $checked = 'checked';
                                            }
                                            else
                                            {
                                                $checked = '';
                                            }

                                            echo '
                                            <div class="radio-custom" style="margin-bottom: 5px">
                                                <input type="radio" id="edit_'.$k.$index.'" name="'.$k.'" value="'.$option.'" '.$checked.' '.$cls.'>
                                                <label for="edit_'.$k.$index.'">'.$option.'</label>
                                            </div>';
                                            $index++;
                                        }
                                    echo '</div>
                                </div>';
                                break;

                            /* Select drop-down box */
                            case 'select':

                                $cls = in_array($k,$_SESSION['iserror']) ? ' class="isError" ' : '';

                                echo '
                                <div class="form-group">
                                    <label for="edit_">'.$v['name:'].' '.$v['req'].'</label>
                                        <select name="'.$k.'" id="'.$k.'" '.$cls.'>';
                                        // Show "Click to select"?
                                        if ( ! empty($v['value']['show_select']))
                                        {
                                            echo '<option value="">'.$hesklang['select'].'</option>';
                                        }

                                        foreach ($v['value']['select_options'] as $option)
                                        {
                                            if ($k_value == trim($option))
                                            {
                                                $k_value = $option;
                                                $selected = 'selected';
                                            }
                                            else
                                            {
                                                $selected = '';
                                            }

                                            echo '<option '.$selected.'>'.$option.'</option>';
                                        }
                                        echo '</select>
                                </div>
                                <script>
                                    $(\'#'.$k.'\').selectize();
                                </script>
                                ';
                                break;

                            /* Checkbox */
                            case 'checkbox':
                                echo '
                                <div class="form-group">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>';

                                $cls = in_array($k,$_SESSION['iserror']) ? ' class="isError" ' : '';

                                $index = 0;
                                foreach ($v['value']['checkbox_options'] as $option)
                                {
                                    if (in_array($option,$k_value))
                                    {
                                        $checked = 'checked';
                                    }
                                    else
                                    {
                                        $checked = '';
                                    }

                                    echo '
                                    <div class="checkbox-custom">
                                        <input type="checkbox" id="edit_'.$k.$index.'" name="'.$k.'[]" value="'.$option.'" '.$checked.' '.$cls.'>
                                        <label for="edit_'.$k.$index.'"> '.$option.'</label>
                                    </div>';
                                    $index++;
                                }

                                echo '</div>';
                                break;

                            /* Large text box */
                            case 'textarea':
                                $cls = in_array($k,$_SESSION['iserror']) ? ' isError" ' : '';
                                $k_value = hesk_msgToPlain($k_value,0,0);

                                echo '
                                <div class="form-group">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>
                                    <textarea name="'.$k.'" class="form-control'.$cls.'" style="height: inherit" rows="'.intval($v['value']['rows']).'" cols="'.intval($v['value']['cols']).'" >'.$k_value.'</textarea>
                                </div>';
                                break;

                            // Date
                            case 'date':
                                $cls = in_array($k,$_SESSION['iserror']) ? 'isErrorStr' : '';
                                $datepicker_date = '';
                                if ($k_value != '') {
                                    $date = new DateTime('@' . $k_value);
                                    $datepicker_date = hesk_datepicker_format_date($date->getTimestamp(), 'UTC');
                                    $hesk_settings['datepicker']['#'.$k]['timestamp'] = $date->getTimestamp();
                                    $hesk_settings['datepicker']['#'.$k]['fromDB'] = true;
                                }

                                echo '
                                <section class="param calendar">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>
                                    <div class="calendar--button">
                                        <button type="button" aria-label="' . $hesklang['date'] . '">
                                            <svg class="icon icon-calendar">
                                                <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-calendar"></use>
                                            </svg>
                                        </button>
                                        <input name="'. $k .'" id="'. $k .'"
                                               value="'. $datepicker_date .'"
                                               type="text" class="datepicker">
                                    </div>
                                    <div class="calendar--value" '. ($datepicker_date ? 'style="display: block"' : '') . '>
                                        <span class="'. $cls .'"><i>'. $datepicker_date .'</i></span>
                                        <i class="close">
                                            <svg class="icon icon-close">
                                                <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-close"></use>
                                            </svg>
                                        </i>
                                    </div>
                                </section>';
                                break;

                            // Email
                            case 'email':
                                $cls = in_array($k,$_SESSION['iserror']) ? 'isError' : '';

                                $suggest = $hesk_settings['detect_typos'] ? 'onblur="Javascript:hesk_suggestEmail(\''.$k.'\', \''.$k.'_suggestions\', 0, 1'.($v['value']['multiple'] ? ',1' : '').')"' : '';

                                echo '
                                <div class="form-group">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>
                                    <input class="form-control '.$cls.'" type="'.($v['value']['multiple'] ? 'text' : 'email').'" name="'.$k.'" id="'.$k.'" value="'.$k_value.'" size="40" '.$suggest.'>
                                </div>
                                <div id="'.$k.'_suggestions"></div>';
                                break;

                            // Hidden
                            // Handle as text fields for staff

                            /* Default text input */
                            default:
                                $k_value = hesk_msgToPlain($k_value,0,0);

                                $cls = in_array($k,$_SESSION['iserror']) ? 'isError' : '';

                                echo '
                                <div class="form-group">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>
                                    <input class="form-control '.$cls.'" type="text" name="'.$k.'" size="40" maxlength="'.intval($v['value']['max_length']).'" value="'.$k_value.'">
                                </div>';
                        }
                    }
                }
                ?>
                <?php
            }
            ?>
            <div class="form-group">
                <label for="edit_message"><?php echo $hesklang['message']; ?>:</label>
                <textarea style="height: inherit" class="form-control" id="edit_message" name="message" rows="12" cols="60"><?php echo $hesk_settings['staff_ticket_formatting'] == 2 ? hesk_htmlspecialchars($ticket['message_html']) : $ticket['message']; ?></textarea>
            </div>

            <?php
            if ($hesk_settings['staff_ticket_formatting'] == 2) {
                hesk_tinymce_init('#edit_message');
            }

            if (!$is_reply)
            {
                foreach ($hesk_settings['custom_fields'] as $k=>$v) {
                    if ($v['use'] && $v['place'] && hesk_is_custom_field_in_category($k, $ticket['category']) ) {
                        $k_value  = $ticket[$k];

                        if ($v['type'] == 'checkbox') {
                            $k_value = explode('<br />',$k_value);
                        }

                        $v['req'] = $v['req']==2 ? '<span class="important">*</span>' : '';

                        switch ($v['type']) {
                            /* Radio box */
                            case 'radio':
                                echo '
                                <div class="form-group">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>
                                    <div class="radio-list">';

                                        $cls = in_array($k,$_SESSION['iserror']) ? ' class="isError" ' : '';

                                        $index = 0;
                                        foreach ($v['value']['radio_options'] as $option)
                                        {
                                            if (strlen($k_value) == 0)
                                            {
                                                $k_value = $option;
                                                $checked = empty($v['value']['no_default']) ? 'checked' : '';
                                            }
                                            elseif ($k_value == $option)
                                            {
                                                $k_value = $option;
                                                $checked = 'checked';
                                            }
                                            else
                                            {
                                                $checked = '';
                                            }

                                            echo '
                                            <div class="radio-custom" style="margin-bottom: 5px">
                                                <input type="radio" id="edit_'.$k.$index.'" name="'.$k.'" value="'.$option.'" '.$checked.' '.$cls.'>
                                                <label for="edit_'.$k.$index.'">'.$option.'</label>
                                            </div>';
                                            $index++;
                                        }
                                    echo '</div>
                                </div>';
                                break;

                            /* Select drop-down box */
                            case 'select':

                                $cls = in_array($k,$_SESSION['iserror']) ? ' class="isError" ' : '';

                                echo '
                                <div class="form-group">
                                    <label for="edit_">'.$v['name:'].' '.$v['req'].'</label>
                                        <select name="'.$k.'" id="'.$k.'" '.$cls.'>';
                                        // Show "Click to select"?
                                        if ( ! empty($v['value']['show_select']))
                                        {
                                            echo '<option value="">'.$hesklang['select'].'</option>';
                                        }

                                        foreach ($v['value']['select_options'] as $option)
                                        {
                                            if ($k_value == trim($option))
                                            {
                                                $k_value = $option;
                                                $selected = 'selected';
                                            }
                                            else
                                            {
                                                $selected = '';
                                            }

                                            echo '<option '.$selected.'>'.$option.'</option>';
                                        }
                                        echo '</select>
                                </div>
                                <script>
                                    $(\'#'.$k.'\').selectize();
                                </script>
                                ';
                                break;

                            /* Checkbox */
                            case 'checkbox':
                                echo '
                                <div class="form-group">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>';

                                $cls = in_array($k,$_SESSION['iserror']) ? ' class="isError" ' : '';

                                $index = 0;
                                foreach ($v['value']['checkbox_options'] as $option)
                                {
                                    if (in_array($option,$k_value))
                                    {
                                        $checked = 'checked';
                                    }
                                    else
                                    {
                                        $checked = '';
                                    }

                                    echo '
                                    <div class="checkbox-custom">
                                        <input type="checkbox" id="edit_'.$k.$index.'" name="'.$k.'[]" value="'.$option.'" '.$checked.' '.$cls.'>
                                        <label for="edit_'.$k.$index.'"> '.$option.'</label>
                                    </div>';
                                    $index++;
                                }

                                echo '</div>';
                                break;

                            /* Large text box */
                            case 'textarea':
                                $cls = in_array($k,$_SESSION['iserror']) ? ' isError" ' : '';
                                $k_value = hesk_msgToPlain($k_value,0,0);

                                echo '
                                <div class="form-group">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>
                                    <textarea name="'.$k.'" class="form-control'.$cls.'" style="height: inherit" rows="'.intval($v['value']['rows']).'" cols="'.intval($v['value']['cols']).'" >'.$k_value.'</textarea>
                                </div>';
                                break;

                            // Date
                            case 'date':
                                $cls = in_array($k,$_SESSION['iserror']) ? 'isErrorStr' : '';
                                $datepicker_date = '';
                                if ($k_value != '') {
                                    $date = new DateTime('@' . $k_value);
                                    $datepicker_date = hesk_datepicker_format_date($date->getTimestamp(), 'UTC');
                                    $hesk_settings['datepicker']['#'.$k]['timestamp'] = $date->getTimestamp();
                                    $hesk_settings['datepicker']['#'.$k]['fromDB'] = true;
                                }

                                echo '
                                <section class="param calendar">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>
                                    <div class="calendar--button">
                                        <button type="button" aria-label="' . $hesklang['date'] . '">
                                            <svg class="icon icon-calendar">
                                                <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-calendar"></use>
                                            </svg>
                                        </button>
                                        <input name="'. $k .'" id="'. $k .'"
                                               value="'. $datepicker_date .'"
                                               type="text" class="datepicker">
                                    </div>
                                    <div class="calendar--value" '. ($datepicker_date ? 'style="display: block"' : '') . '>
                                        <span class="'. $cls .'"><i>'. $datepicker_date .'</i></span>
                                        <i class="close">
                                            <svg class="icon icon-close">
                                                <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-close"></use>
                                            </svg>
                                        </i>
                                    </div>
                                </section>';
                                break;

                            // Email
                            case 'email':
                                $cls = in_array($k,$_SESSION['iserror']) ? 'isError' : '';

                                $suggest = $hesk_settings['detect_typos'] ? 'onblur="Javascript:hesk_suggestEmail(\''.$k.'\', \''.$k.'_suggestions\', 0, 1'.($v['value']['multiple'] ? ',1' : '').')"' : '';

                                echo '
                                <div class="form-group">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>
                                    <input class="form-control '.$cls.'" type="'.($v['value']['multiple'] ? 'text' : 'email').'" name="'.$k.'" id="'.$k.'" value="'.$k_value.'" size="40" '.$suggest.'>
                                </div>
                                <div id="'.$k.'_suggestions"></div>';
                                break;

                            // Hidden
                            // Handle as text fields for staff

                            /* Default text input */
                            default:
                                $k_value = hesk_msgToPlain($k_value,0,0);

                                $cls = in_array($k,$_SESSION['iserror']) ? 'isError' : '';

                                echo '
                                <div class="form-group">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>
                                    <input class="form-control '.$cls.'" type="text" name="'.$k.'" size="40" maxlength="'.intval($v['value']['max_length']).'" value="'.$k_value.'">
                                </div>';
                        }
                    }
                }
            } // End if not a reply

            // attachments
            if ($hesk_settings['attachments']['use'] && $number_of_attachments < $hesk_settings['attachments']['max_number'])
            {
                require_once(HESK_PATH . 'inc/attachments.inc.php');
                echo '<div class="form-group attachments">';
                echo '<label>' . $hesklang['attachments'] . ': (<a class="link" href="javascript:" onclick="hesk_window(\'../file_limits.php\',250,500);return false;">' . $hesklang['ful'] . '</a>)</label>';
                build_dropzone_markup(true, 'filedrop', $number_of_attachments + 1);
                display_dropzone_field(HESK_PATH . 'upload_attachment.php',
                    true,
                    'filedrop',
                    $hesk_settings['attachments']['max_number'] - $number_of_attachments);
                dropzone_display_existing_files(hesk_SESSION_array('edit_attachments'));
                echo '</div>';
            }
            ?>
            <input type="hidden" name="save" value="1">
            <input type="hidden" name="track" value="<?php echo $trackingID; ?>">
            <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
            <?php
            if ($is_reply)
            {
                ?>
                <input type="hidden" name="reply" value="<?php echo $tmpvar['id']; ?>" />
                <?php
            }

            if ($hesk_settings['can_sel_lang']) {
                ?>
                <div class="form-group">
                    <label for="set-language"><?php echo $hesklang['set_lang']; ?>:</label>
                    <select name="set_language" id="set-language">
                        <option value="0">----</option>
                        <?php
                        foreach ($hesk_settings['languages'] as $setting_lang_key => $setting_lang) {
                            if ( ! empty($ticket['language']) && $ticket['language'] === $setting_lang_key) {
                                echo '<option value="'.$setting_lang_key.'" selected="selected">'.$setting_lang_key.'</option>';
                            } else {
                                echo '<option value="'.$setting_lang_key.'">'.$setting_lang_key.'</option>';
                            }
                        }
                        ?>
                    </select>
                </div>
                <script>
                    $('#set-language').selectize();
                </script>
                <?php
            }
            ?>
            <button type="submit" class="btn btn-full" style="display: inline-flex">
                <?php echo $hesklang['save_changes']; ?>
            </button>
            <a href="javascript:history.go(-1)" class="btn btn--blue-border"><?php echo $hesklang['back']; ?></a>
        </form>
    </div>
</div>

<p style="text-align:center"></p>

<p>&nbsp;</p>

<?php 
    //Common include for the "Create Customer / Follower"
    require_once(HESK_PATH . 'inc/customer_modal.inc.php'); 
?>

<?php
hesk_cleanSessionVars('edit_attachments');
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


function hesk_countAttachments($attachments_string)
{
    if ( ! strlen($attachments_string) || strpos($attachments_string, ',') === false)
    {
        return 0;
    }

    $att = explode(',', substr($attachments_string, 0, -1));

    return count($att);

} // END hesk_countAttachments()
elevator.php
wget 'https://lists2.roe3.org/hesk/admin/elevator.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

use RobThree\Auth\TwoFactorAuth;

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/mfa_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

$mfa_enrollment = intval($_SESSION['mfa_enrollment']);
$skip_email = false;
$show_backup_code = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    hesk_token_check('POST');

    if (hesk_POST('a') === 'backup_email') {
        // Force email verification instead of authenticator code
        $mfa_enrollment = 1;
        $force_send_email = true;

        // Let's limit the "Send another email" to max 3
        if (isset($_SESSION['mfa_emails_sent'])) {
            if ($_SESSION['mfa_emails_sent'] >= 3) {
                hesk_forceLogout($hesklang['bf_int']);
            }
            $_SESSION['mfa_emails_sent']++;
        } else {
            $_SESSION['mfa_emails_sent'] = 1;
        }
    } elseif (hesk_POST('a') === 'verify') {
        $skip_email = true;
        $mfa_method = intval(hesk_POST('mfa-method'));
        if ($mfa_method === 0) {
            $pass = hesk_input( hesk_POST('verification-code') );
            if ( ! $pass) {
                $error = $hesklang['enter_pass'];
            } elseif (strlen($pass) > 64) {
                $error = $hesklang['pass_len'];
            } else {
                hesk_limitInternalBfAttempts();
                if (hesk_password_verify($pass, fetch_current_user_password())) {
                    handle_successful_elevation();
                } else {
                    $error = $hesklang['wrong_pass'];
                }
            }
            hesk_process_messages($error, 'NOREDIRECT');
        } else {
            hesk_limitInternalBfAttempts();
            if (($mfa_method === 1 && is_mfa_email_code_valid($_SESSION['id'], hesk_POST('verification-code'))) ||
                ($mfa_method === 2 && is_mfa_app_code_valid($_SESSION['id'], hesk_POST('verification-code')))) {
                handle_successful_elevation();
            } else {
                // Verification failed
                hesk_process_messages($hesklang['mfa_invalid_verification_code'], 'NOREDIRECT');
            }
        }
    } elseif (hesk_POST('a') === 'do_backup_code_verification') {
        $skip_email = true;
        hesk_limitInternalBfAttempts();
        if (verify_mfa_backup_code($_SESSION['id'], hesk_POST('backup-code'))) {
            handle_successful_elevation();
        } else {
            // Verification failed
            hesk_process_messages($hesklang['mfa_invalid_backup_code'], 'NOREDIRECT');
            $show_backup_code = true;
        }
    } else {
        // Invalid action, something strange is going on... Let's force logout
        hesk_forceLogout($hesklang['invalid_action']);
    }
}

$message = ''; //$hesklang['elevator_intro'] . '<br><br>';

if ($mfa_enrollment === 0) {
    $mfa_verify_option = 0;
    $message .= $hesklang['elevator_enter_password'];
} elseif ($mfa_enrollment === 1) {
    // Email
    $mfa_verify_option = 1;

    // Unless the "Send another email" link was clicked, don't send a new email until the old one is valid
    if (! $skip_email && empty($force_send_email) && isset($_SESSION['skip_mfa_emails_until']) && $_SESSION['skip_mfa_emails_until'] > date('Y-m-d H:i:s')) {
        $skip_email = true;
    }

    // Don't send a new email each time a verification fails
    if (! $skip_email) {
        $verification_code = generate_mfa_code();
        hash_and_store_mfa_verification_code($_SESSION['id'], $verification_code);
        send_mfa_email($_SESSION['name'], $_SESSION['email'], $verification_code);

        hesk_process_messages($hesklang['mfa_sent'], 'NOREDIRECT', 'INFO');

        // Don't send a new email until the old one is valid (with 15 min buffer) unless explicitly asked to
        $skip_mfa_emails_until = new DateTime();
        $skip_mfa_emails_until->add(new DateInterval('PT15M'));
        $_SESSION['skip_mfa_emails_until'] = $skip_mfa_emails_until->format('Y-m-d H:i:s');
    }

    $message .= $hesklang['mfa_verification_needed_email'];
} elseif ($mfa_enrollment === 2) {
    // Authenticator App
    $message .= $hesklang['mfa_verification_needed_auth_app'];
    $mfa_verify_option = 2;
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');
?>
<div class="main__content profile">
    <section class="mfa__head">
        <h2>
            <?php echo $hesklang['elevator_header']; ?>
        </h2>
    </section>
    <article class="profile__wrapper mfa">
        <?php hesk_handle_messages(); ?>

        <div id="mfa-verify"<?php if ($show_backup_code) { echo ' style="display: none"'; } ?>>

        <p><?php echo $message; ?></p>
        <form id="verify-form" class="form" action="elevator.php" method="post" aria-label="<?php echo $hesklang['mfa_verify']; ?>">
            <div class="form-group">
                <?php if ($mfa_verify_option === 0): ?>
                    <label for="regInputPassword"><?php echo $hesklang['pass']; ?></label>
                    <div class="input-group">
                        <input name="verification-code" id="regInputPassword" type="password" class="form-control">
                        <div class="input-group-append--icon passwordIsHidden">
                            <svg class="icon icon-eye-close">
                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-eye-close"></use>
                            </svg>
                        </div>
                    </div>
                <?php else: ?>
                    <label for="verify-input"><?php echo $hesklang['mfa_code']; ?></label>
                    <input name="verification-code" id="verify-input" type="text" class="form-control" maxlength="6" placeholder="000000" autocomplete="off">
                <?php endif; ?>
            </div>
            <button id="verify-submit" style="margin-top: 10px;" type="submit" class="btn btn-full" ripple="ripple"><?php echo $hesklang['mfa_verify']; ?></button>
            <input type="hidden" name="mfa-method" value="<?php echo $mfa_verify_option; ?>">
            <input type="hidden" name="a" value="verify">
            <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
        </form>

            <?php if ($mfa_verify_option === 1): ?>
                &nbsp;
                <form action="elevator.php" class="form" id="send-another-email-form" method="post" name="send-another-email-form" novalidate aria-label="<?php echo $hesklang['mfa_send_another_email']; ?>">
                    <button class="btn btn-link" type="submit">
                        <?php echo $hesklang['mfa_send_another_email']; ?>
                    </button>
                    <input type="hidden" name="a" value="backup_email">
                    <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                </form>
            <?php endif; ?>

            <?php if ($mfa_verify_option !== 0): ?>
                &nbsp;<br>
                <a href="javascript:hesk_toggleLayerDisplay('verify-another-way');hesk_toggleLayerDisplay('mfa-verify')">
                    <?php echo $hesklang['mfa_verify_another_way']; ?>
                </a>
            <?php endif; ?>

        </div>

        <?php if ($mfa_verify_option !== 0): ?>
            <div id="verify-another-way" style="display: <?php echo $show_backup_code ? 'block' : 'none'; ?>">
                <ul>
                    <?php if ($mfa_verify_option === 2): ?>
                        <li>
                            <div class="flex">
                                <div class="mfa-alt-icon" aria-hidden="true">
                                    <svg class="icon icon-mail">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-mail"></use>
                                    </svg>
                                </div>
                                <div class="mfa-alt-text">
                                    <form action="elevator.php" class="form" id="email-backup-form" method="post" name="email-backup-form" novalidate aria-label="<?php echo $hesklang['mfa_verify_another_way_email']; ?>">
                                        <button class="btn btn-link" type="submit">
                                            <?php echo sprintf($hesklang['mfa_verify_another_way_email'], hesk_maskEmailAddress($_SESSION['email'])); ?>
                                        </button>
                                        <input type="hidden" name="a" value="backup_email">
                                        <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                                    </form>
                                </div>
                            </div>
                        </li>
                    <?php endif; ?>
                    <li>
                        <div class="flex">
                            <div class="mfa-alt-icon" aria-hidden="true">
                                <svg class="icon icon-lock">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-lock"></use>
                                </svg>
                            </div>
                            <div class="mfa-alt-text">
                                <a href="javascript:hesk_toggleLayerDisplay('backup-code-field')"><?php echo $hesklang['mfa_verify_another_way_code']; ?></a>
                                <div id="backup-code-field" style="display: <?php echo $show_backup_code ? 'block' : 'none'; ?>">
                                    <form action="elevator.php" class="form" id="backup-form" method="post" name="backup-form" novalidate aria-label="<?php echo $hesklang['mfa_verify_another_way_code']; ?>">
                                        <div class="form-group">
                                            <label for="backupCode"><?php echo $hesklang['mfa_backup_code']; ?></label>
                                            <input type="text" class="form-control" id="backupCode" name="backup-code" minlength="8" maxlength="9" autocomplete="off">
                                        </div>
                                        <div class="form__submit mfa">
                                            <button class="btn btn-full" ripple="ripple" type="submit" id="backup-code-submit">
                                                <?php echo $hesklang['s']; ?>
                                            </button>
                                        </div>
                                        <input type="hidden" name="a" value="do_backup_code_verification">
                                        <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                                    </form>
                                </div>
                            </div>
                        </div>
                    </li>
                </ul>

                &nbsp;

                <p style="text-align: center">
                    <a href="javascript:hesk_toggleLayerDisplay('verify-another-way');hesk_toggleLayerDisplay('mfa-verify')">
                        <?php echo $hesklang['back']; ?>
                    </a>
                </p>
            </div>
        <?php endif; ?>
    </article>
</div>
<script>
    $('#verify-form').preventDoubleSubmission();
    $('#backup-form').preventDoubleSubmission();
    $('#verify-input').keyup(function() {
        if (this.value.length === 6) {
            $('#verify-form').submit();
        }
    });
    $('#backupCode').keyup(function() {
        if (this.value.length === 8 || this.value.length === 9) {
            $('#backup-form').submit();
        }
    });
    $('#verify-form').submit(function() {
        $('#verify-submit').attr('disabled', 'disabled')
            .addClass('disabled');
    });
    $('#backup-form').submit(function() {
        $('#backup-code-submit').attr('disabled', 'disabled')
            .addClass('disabled');
    });
</script>

<?php
require_once(HESK_PATH . 'inc/footer.inc.php');

function fetch_current_user_password() {
    global $hesk_settings, $hesklang;

    $res = hesk_dbQuery("SELECT `pass` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id` = ".intval($_SESSION['id'])." AND `active` = 1 LIMIT 1");
    if (hesk_dbNumRows($res) != 1) {
        hesk_forceLogout($hesklang['wrong_user']);
    }

    $row = hesk_dbFetchAssoc($res);

    return $row['pass'];
}

function handle_successful_elevation() {
    global $hesk_settings;

    hesk_session_regenerate_id();
    hesk_cleanBfAttempts();
    delete_mfa_codes($_SESSION['id']);
    hesk_cleanSessionVars('mfa_emails_sent');
    hesk_cleanSessionVars('skip_mfa_emails_until');

    $current_time = new DateTime();
    $interval_amount = $hesk_settings['elevator_duration'];
    if (in_array(substr($interval_amount, -1), array('M', 'H'))) {
        $interval_amount = 'T'.$interval_amount;
    }
    $elevation_expiration = $current_time->add(new DateInterval("P{$interval_amount}"));

    $_SESSION['elevated'] = $elevation_expiration;
    $elevator_target = hesk_SESSION('elevator_target', 'admin_main.php');
    unset($_SESSION['elevator_target']);
    header('Location: ' . $elevator_target);
    exit();
}

exit();
email_templates.php
wget 'https://lists2.roe3.org/hesk/admin/email_templates.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
hesk_checkPermission('can_email_tpl');

// Define required constants
define('LOAD_TABS',1);

// Get valid email templates
require(HESK_PATH . 'inc/email_functions.inc.php');
$emails = array_keys(hesk_validEmails());

// Which language are we editing?
if ($hesk_settings['can_sel_lang'])
{
    $hesk_settings['edit_language'] = hesk_REQUEST('edit_language');

    // If user closed the edit template modal without saving; remember the language used
    if (empty($hesk_settings['edit_language']) && ! empty($_SESSION['edit_language']))
    {
        $hesk_settings['edit_language'] = $_SESSION['edit_language'];
    }

    // If not a valid language, default to settings
	if ( ! isset($hesk_settings['languages'][$hesk_settings['edit_language']]) )
	{
		$hesk_settings['edit_language'] = $hesk_settings['language'];
	}
}
else
{
	$hesk_settings['edit_language'] = $hesk_settings['language'];
}
hesk_cleanSessionVars('edit_language');

// What should we do?
if ( $action = hesk_REQUEST('a') )
{
    if ($action == 'edit') {
        if (hesk_GET('t') == 'html') {
            define('WYSIWYG',1);
            define('HTML_EMAIL_TEMPLATE',1);
            define('STYLE_CODE',1);
        }
    }
	elseif ( defined('HESK_DEMO') ) {hesk_process_messages($hesklang['ddemo'], 'email_templates.php', 'NOTICE');}
	elseif ($action == 'save') {save_et();}
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
if ($action != 'edit') {
    hesk_handle_messages();
}

// Let's tell users that plain text email templates will be ignored if we auto-generate them from HTML templates
if ($hesk_settings['email_formatting'] == 0) {
    hesk_show_info(sprintf($hesklang['email_formatting_note'], $hesklang['settings'], $hesklang['tab_6'], $hesklang['email_formatting'], $hesklang['email_formatting_plaintext']) . '<br><br>' . $hesklang['email_formatting_note0'], ' ', false);
} elseif ($hesk_settings['email_formatting'] == 1) {
    hesk_show_info(sprintf($hesklang['email_formatting_note'], $hesklang['settings'], $hesklang['tab_6'], $hesklang['email_formatting'], $hesklang['email_formatting_html']) . '<br><br>' . $hesklang['email_formatting_note1'], ' ', false);
} elseif ($hesk_settings['email_formatting'] == 2) {
    hesk_show_info(sprintf($hesklang['email_formatting_note'], $hesklang['settings'], $hesklang['tab_6'], $hesklang['email_formatting'], $hesklang['email_formatting_html_and_plaintext_auto']) . '<br><br>' . $hesklang['email_formatting_note2'], ' ', false);
}
?>
<div class="main__content tools">
    <section class="tools__between-head fw">
        <h2>
            <?php echo $hesklang['et_title']; ?>
            <div class="tooltype right out-close">
                <svg class="icon icon-info">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                </svg>
                <div class="tooltype__content">
                    <div class="tooltype__wrapper">
                        <?php echo $hesklang['et_intro']; ?>
                    </div>
                </div>
            </div>
        </h2>
        <?php if ($hesk_settings['can_sel_lang'] && count($hesk_settings['languages']) > 1): ?>
            <form method="get" action="email_templates.php" aria-label="<?php echo $hesklang['set_lang']; ?>">
            <div class="dropdown-select center out-close">
                <select name="edit_language" onchange="this.form.submit()">
                <?php foreach ($hesk_settings['languages'] as $lang => $info): ?>
                    <option value="<?php echo $lang; ?>" <?php if ($lang === $hesk_settings['edit_language']): ?>selected<?php endif; ?>>
                        <?php echo $lang; ?>
                    </option>
                <?php endforeach; ?>
                </select>
            </div>
        </form>
        <?php endif; ?>
    </section>
    <div class="table-wrapper email-templates">
        <div class="table">
            <table id="default-table" class="table sindu-table">
                <thead>
                <tr>
                    <th><?php echo $hesklang['email_tpl_title']; ?></th>
                    <th><?php echo $hesklang['rdesc']; ?></th>
                    <th><?php echo $hesklang['ticket_formatting_plaintext']; ?></th>
                    <th><?php echo $hesklang['ticket_formatting_rich_text']; ?></th>
                </tr>
                </thead>
                <tbody>
                <tr class="no-background-color">
                    <td colspan="4"><strong><?php echo $hesklang['emails_to_customers']; ?></strong></td>
                </tr>
                <?php
                $all_files = true;
                $all_writable = true;
                foreach ($emails as $email):
                    $plaintext_eml_file = et_file_path($email, 'plaintext');
                    $html_eml_file = et_file_path($email, 'html');

                    if ($email == 'category_moved') {
                        echo '<tr class="no-background-color"><td colspan="4"><strong>'.$hesklang['emails_to_staff'].'</strong></td></tr>';
                    } elseif ($email == 'mfa_verification') {
                        echo '<tr class="no-background-color"><td colspan="4"><strong>'.$hesklang['emails_to_everyone'].'</strong></td></tr>';
                    }
                ?>
                <tr <?php if (hesk_SESSION('et_id') == $email) {echo 'class="ticket-new"'; unset($_SESSION['et_id']);} ?>>
                    <td><?php echo $email; ?>.txt</td>
                    <td><?php echo $hesklang['desc_'.$email]; ?></td>
                    <td class="buttons">
                        <?php
                        if (!file_exists($plaintext_eml_file)) {
                            $all_files = false;
                            echo '<span style="color:red">'.$hesklang['no_exists'].'</span>';
                        } elseif (!is_writable($plaintext_eml_file)) {
                            $all_writable = false;
                            echo '<span style="color:red">'.$hesklang['not_writable'].'</span>';
                        } else {
                            ?>
                            <a title="<?php echo $hesklang['edit']; ?>" href="email_templates.php?a=edit&amp;t=plaintext&amp;id=<?php echo $email; ?>&amp;edit_language=<?php echo urlencode($hesk_settings['edit_language']); ?>" class="edit tooltip">
                                <svg class="icon icon-edit-ticket">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-edit-ticket"></use>
                                </svg>
                            </a>
                            <?php
                        }
                        ?>
                    </td>
                    <td class="buttons">
                        <?php
                        if (!file_exists($html_eml_file)) {
                            $all_files = false;
                            echo '<span style="color:red">'.$hesklang['no_exists'].'</span>';
                        } elseif (!is_writable($html_eml_file)) {
                            $all_writable = false;
                            echo '<span style="color:red">'.$hesklang['not_writable'].'</span>';
                        } else {
                            ?>
                            <a title="<?php echo $hesklang['edit']; ?>" href="email_templates.php?a=edit&amp;t=html&amp;id=<?php echo $email; ?>&amp;edit_language=<?php echo urlencode($hesk_settings['edit_language']); ?>" class="edit tooltip">
                                <svg class="icon icon-edit-ticket">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-edit-ticket"></use>
                                </svg>
                            </a>
                            <?php
                        }
                        ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php
            // Any template missing?
            if (!$all_files)
            {
                hesk_show_error(sprintf($hesklang['etfm'], $hesk_settings['languages'][$hesk_settings['edit_language']]['folder'], $hesk_settings['languages'][$hesk_settings['edit_language']]['folder']));
            }

            // Any template not writable?
            if (!$all_writable)
            {
                hesk_show_error(sprintf($hesklang['etfw'], $hesk_settings['languages'][$hesk_settings['edit_language']]['folder'], $hesk_settings['languages'][$hesk_settings['edit_language']]['folder']));
            }
            ?>
        </div>
    </div>
</div>
<?php
// EDIT
if ($action == 'edit')
{
    // Get email ID
    $email = hesk_GET('id');

    // Get email type
    if (($type = hesk_GET('t')) != 'html') {
        $type = 'plaintext';
    }

    // Get file path
    $eml_file = et_file_path($email, $type);

    // Make sure the file exists and is writable
    if ( ! file_exists($eml_file))
    {
        hesk_error($hesklang['et_fm']);
    }
    elseif ( ! is_writable($eml_file))
    {
        hesk_error($hesklang['et_fw']);
    }

    // We need this to remember which language was being edited if the modal is closed without saving
    $_SESSION['edit_language'] = $hesk_settings['edit_language'];

    // Start the edit form
    ?>
    <script language="javascript" type="text/javascript"><!--

    function hesk_insertRichTag(tag) {
        var text_to_insert = '%%'+tag+'%%';
        <?php if ($type === 'html'): ?>
            tinymce.get("msg").execCommand('mceInsertContent', false, text_to_insert);
        <?php else: ?>
            hesk_insertAtCursor(document.getElementById('msg'), text_to_insert);
            document.getElementById('msg').focus();
        <?php endif; ?>
    }

    //-->
    </script>

    <div class="right-bar tools-email-template-edit" style="display: block">
        <div class="right-bar__body form">
            <h3>
                <a href="email_templates.php">
                    <svg class="icon icon-back">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                    </svg>
                    <span><?php echo $hesklang['edit_email_template']; ?></span>
                </a>
            </h3>
            <?php
            /* This will handle error, success and notice messages */
            echo '<div style="margin: -24px -24px 10px -16px;">';

            if (
                    ($type === 'html' && $hesk_settings['email_formatting'] === 0) ||
                    ($type === 'plaintext' && $hesk_settings['email_formatting'] === 1) ||
                    ($type === 'plaintext' && $hesk_settings['email_formatting'] === 2)
                ) {
                    hesk_show_notice(sprintf($hesklang['etnu'], $hesklang['settings'], $hesklang['tab_6'], $hesklang['email_formatting']), ' ', false);
            }

            hesk_handle_messages();
            echo '</div>';
            ?>
            <section class="param">
                <span><?php echo $hesklang['efile']; ?></span>
                <form method="get" action="email_templates.php" aria-label="<?php echo $hesklang['efile']; ?>">
                    <div class="dropdown-select center out-close">
                        <select name="id" onchange="this.form.submit()">
                            <?php
                            foreach ($emails as $email_tmp) {
                                $eml_file_tmp = et_file_path($email_tmp, $type);

                                if (!file_exists($eml_file_tmp) || !is_writable($eml_file_tmp)) {
                                    continue;
                                }

                                if ($email_tmp === $email) {
                                    echo '<option value="'.$email_tmp.'" selected>' . $hesklang['desc_'.$email_tmp].'</option>';
                                } else {
                                    echo '<option value="'.$email_tmp.'">' . $hesklang['desc_'.$email_tmp].'</option>';
                                }
                            }
                            ?>
                        </select>
                        <input type="hidden" name="t" value="<?php echo $type; ?>">
                        <input type="hidden" name="a" value="edit">
                        <input type="hidden" name="edit_language" value="<?php echo hesk_htmlspecialchars($hesk_settings['edit_language']); ?>">
                    </div>
                </form>
            </section>
            <?php if ($hesk_settings['can_sel_lang'] && count($hesk_settings['languages']) > 1): ?>
                <section class="param">
                    <form method="get" action="email_templates.php" aria-label="<?php echo $hesklang['lgs']; ?>">
                        <span><?php echo $hesklang['lgs']; ?></span>
                        <div class="dropdown-select center out-close">
                            <select name="edit_language" onchange="this.form.submit()">
                                <?php foreach ($hesk_settings['languages'] as $lang => $info): ?>
                                    <option value="<?php echo $lang; ?>" <?php if ($lang === $hesk_settings['edit_language']) { ?>selected<?php } ?>>
                                        <?php echo $lang; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <input type="hidden" name="t" value="<?php echo $type; ?>">
                            <input type="hidden" name="a" value="edit" />
                            <input type="hidden" name="id" value="<?php echo hesk_htmlspecialchars($email); ?>" />
                        </div>
                    </form>
                </section>
            <?php endif; ?>
            <form action="email_templates.php" method="post" name="form1" aria-label="<?php echo $hesklang['edit_email_template']; ?>">
                <div class="form-group">
                    <label for="message"><?php echo $hesklang['source'] . ': ' . substr($eml_file, 2); ?></label>
                    <span id="HeskMsg">
                        <textarea class="form-control" id="msg" name="msg" rows="35" cols="100"><?php echo hesk_htmlspecialchars(file_get_contents($eml_file)); ?></textarea>
                    </span>
                </div>
                <div class="template--tags">
                    <label><?php echo $hesklang['insert_special']; ?></label>
                    <div class="tag-list">
                        <?php if ($email == 'forgot_ticket_id'): ?>
                            <a href="javascript:" title="%%NAME%%" onclick="hesk_insertRichTag('NAME')">
                                <?php echo $hesklang['name']; ?>
                            </a>
                            <a href="javascript:" title="%%FIRST_NAME%%" onclick="hesk_insertRichTag('FIRST_NAME')">
                                <?php echo $hesklang['fname']; ?>
                            </a>
                            <a href="javascript:" title="%%NUM%%" onclick="hesk_insertRichTag('NUM')">
                                <?php echo $hesklang['et_num']; ?>
                            </a>
                            <a href="javascript:" title="%%LIST_TICKETS%%" onclick="hesk_insertRichTag('LIST_TICKETS')">
                                <?php echo $hesklang['et_list']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_TITLE%%" onclick="hesk_insertRichTag('SITE_TITLE')">
                                <?php echo $hesklang['wbst_title']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_URL%%" onclick="hesk_insertRichTag('SITE_URL')">
                                <?php echo $hesklang['wbst_url']; ?>
                            </a>
                        <?php elseif ($email == 'new_pm'): ?>
                            <a href="javascript:" title="%%NAME%%" onclick="hesk_insertRichTag('NAME')">
                                <?php echo $hesklang['staff_name']; ?>
                            </a>
                            <a href="javascript:" title="%%FIRST_NAME%%" onclick="hesk_insertRichTag('FIRST_NAME')">
                                <?php echo $hesklang['fname']; ?>
                            </a>
                            <a href="javascript:" title="%%SUBJECT%%" onclick="hesk_insertRichTag('SUBJECT')">
                                <?php echo $hesklang['subject']; ?>
                            </a>
                            <a href="javascript:" title="%%MESSAGE%%" onclick="hesk_insertRichTag('MESSAGE')">
                                <?php echo $hesklang['message']; ?>
                            </a>
                            <a href="javascript:" title="%%TRACK_URL%%" onclick="hesk_insertRichTag('TRACK_URL')">
                                <?php echo $hesklang['pm_url']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_TITLE%%" onclick="hesk_insertRichTag('SITE_TITLE')">
                                <?php echo $hesklang['wbst_title']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_URL%%" onclick="hesk_insertRichTag('SITE_URL')">
                                <?php echo $hesklang['wbst_url']; ?>
                            </a>
                        <?php elseif ($email == 'reset_password' || $email == 'customer_reset_password'): ?>
                            <a href="javascript:" title="%%NAME%%" onclick="hesk_insertRichTag('NAME')">
                                <?php echo $hesklang['name']; ?>
                            </a>
                            <a href="javascript:" title="%%FIRST_NAME%%" onclick="hesk_insertRichTag('FIRST_NAME')">
                                <?php echo $hesklang['fname']; ?>
                            </a>
                            <a href="javascript:" title="%%PASSWORD_RESET%%" onclick="hesk_insertRichTag('PASSWORD_RESET')">
                                <?php echo $hesklang['passr']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_TITLE%%" onclick="hesk_insertRichTag('SITE_TITLE')">
                                <?php echo $hesklang['wbst_title']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_URL%%" onclick="hesk_insertRichTag('SITE_URL')">
                                <?php echo $hesklang['wbst_url']; ?>
                            </a>
                        <?php elseif ($email == 'customer_verify_registration' || $email == 'customer_verify_new_email'): ?>
                            <a href="javascript:" title="%%NAME%%" onclick="hesk_insertRichTag('NAME')">
                                <?php echo $hesklang['name']; ?>
                            </a>
                            <a href="javascript:" title="%%FIRST_NAME%%" onclick="hesk_insertRichTag('FIRST_NAME')">
                                <?php echo $hesklang['fname']; ?>
                            </a>
                            <a href="javascript:" title="%%VERIFICATION_URL%%" onclick="hesk_insertRichTag('VERIFICATION_URL')">
                                <?php echo $hesklang['et_link_verify']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_TITLE%%" onclick="hesk_insertRichTag('SITE_TITLE')">
                                <?php echo $hesklang['wbst_title']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_URL%%" onclick="hesk_insertRichTag('SITE_URL')">
                                <?php echo $hesklang['wbst_url']; ?>
                            </a>
                        <?php elseif ($email == 'customer_approved'): ?>
                            <a href="javascript:" title="%%NAME%%" onclick="hesk_insertRichTag('NAME')">
                                <?php echo $hesklang['name']; ?>
                            </a>
                            <a href="javascript:" title="%%FIRST_NAME%%" onclick="hesk_insertRichTag('FIRST_NAME')">
                                <?php echo $hesklang['fname']; ?>
                            </a>
                            <a href="javascript:" title="%%CUSTOMER_LOGIN_URL%%" onclick="hesk_insertRichTag('CUSTOMER_LOGIN_URL')">
                                <?php echo $hesklang['et_cust_login']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_TITLE%%" onclick="hesk_insertRichTag('SITE_TITLE')">
                                <?php echo $hesklang['wbst_title']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_URL%%" onclick="hesk_insertRichTag('SITE_URL')">
                                <?php echo $hesklang['wbst_url']; ?>
                            </a>
                        <?php elseif ($email == 'customer_rejected'): ?>
                            <a href="javascript:" title="%%NAME%%" onclick="hesk_insertRichTag('NAME')">
                                <?php echo $hesklang['name']; ?>
                            </a>
                            <a href="javascript:" title="%%FIRST_NAME%%" onclick="hesk_insertRichTag('FIRST_NAME')">
                                <?php echo $hesklang['fname']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_TITLE%%" onclick="hesk_insertRichTag('SITE_TITLE')">
                                <?php echo $hesklang['wbst_title']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_URL%%" onclick="hesk_insertRichTag('SITE_URL')">
                                <?php echo $hesklang['wbst_url']; ?>
                            </a>
                        <?php elseif ($email == 'mfa_verification'): ?>
                            <a href="javascript:" title="%%NAME%%" onclick="hesk_insertRichTag('NAME')">
                                <?php echo $hesklang['name']; ?>
                            </a>
                            <a href="javascript:" title="%%FIRST_NAME%%" onclick="hesk_insertRichTag('FIRST_NAME')">
                                <?php echo $hesklang['fname']; ?>
                            </a>
                            <a href="javascript:" title="%%VERIFICATION_CODE%%" onclick="hesk_insertRichTag('VERIFICATION_CODE')">
                                <?php echo $hesklang['mfa_short']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_TITLE%%" onclick="hesk_insertRichTag('SITE_TITLE')">
                                <?php echo $hesklang['wbst_title']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_URL%%" onclick="hesk_insertRichTag('SITE_URL')">
                                <?php echo $hesklang['wbst_url']; ?>
                            </a>
                        <?php elseif ($email == 'new_customer_approval'): ?>
                            <a href="javascript:" title="%%NUM%%" onclick="hesk_insertRichTag('NUM')">
                                <?php echo $hesklang['et_num_customers']; ?>
                            </a>
                            <a href="javascript:" title="%%VERIFICATION_URL%%" onclick="hesk_insertRichTag('VERIFICATION_URL')">
                                <?php echo $hesklang['et_link_customers']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_TITLE%%" onclick="hesk_insertRichTag('SITE_TITLE')">
                                <?php echo $hesklang['wbst_title']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_URL%%" onclick="hesk_insertRichTag('SITE_URL')">
                                <?php echo $hesklang['wbst_url']; ?>
                            </a>
                        <?php elseif ($email === 'email_rejected_can_self_register' || $email === 'email_rejected_cannot_self_register'): ?>
                            <a href="javascript:" title="%%NAME%%" onclick="hesk_insertRichTag('NAME')">
                                <?php echo $hesklang['name']; ?>
                            </a>
                            <a href="javascript:" title="%%SUBJECT%%" onclick="hesk_insertRichTag('SUBJECT')">
                                <?php echo $hesklang['email_subject']; ?>
                            </a>
                            <a href="javascript:" title="%%CUSTOMER_REGISTER_URL%%" onclick="hesk_insertRichTag('CUSTOMER_REGISTER_URL')">
                                <?php echo $hesklang['register_url']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_TITLE%%" onclick="hesk_insertRichTag('SITE_TITLE')">
                                <?php echo $hesklang['wbst_title']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_URL%%" onclick="hesk_insertRichTag('SITE_URL')">
                                <?php echo $hesklang['wbst_url']; ?>
                            </a>
                        <?php else: ?>
                            <?php if ($email === 'new_note' || $email === 'collaborator_staff_reply'): ?>
                            <a href="javascript:" title="%%NAME%%" onclick="hesk_insertRichTag('NAME')">
                                <?php echo $hesklang['staff_name']; ?>
                            </a>
                            <?php endif; ?>
                            <a href="javascript:" title="%%REQUESTER%%" onclick="hesk_insertRichTag('REQUESTER')">
                                <?php echo $hesklang['email_tag_requester']; ?>
                            </a>
                            <a href="javascript:" title="%%REQUESTER_NAME%%" onclick="hesk_insertRichTag('REQUESTER_NAME')">
                                <?php echo $hesklang['email_tag_requester_name']; ?>
                            </a>
                            <a href="javascript:" title="%%REQUESTER_FIRST_NAME%%" onclick="hesk_insertRichTag('REQUESTER_FIRST_NAME')">
                                <?php echo $hesklang['email_tag_requester_first_name']; ?>
                            </a>
                            <a href="javascript:" title="%%REQUESTER_EMAIL%%" onclick="hesk_insertRichTag('REQUESTER_EMAIL')">
                                <?php echo $hesklang['email_tag_requester_email']; ?>
                            </a>
                            <a href="javascript:" title="%%FOLLOWERS%%" onclick="hesk_insertRichTag('FOLLOWERS')">
                                <?php echo $hesklang['email_tag_followers']; ?>
                            </a>
                            <a href="javascript:" title="%%FOLLOWER_NAMES%%" onclick="hesk_insertRichTag('FOLLOWER_NAMES')">
                                <?php echo $hesklang['email_tag_follower_names']; ?>
                            </a>
                            <a href="javascript:" title="%%FOLLOWER_EMAILS%%" onclick="hesk_insertRichTag('FOLLOWER_EMAILS')">
                                <?php echo $hesklang['email_tag_follower_emails']; ?>
                            </a>
                            <a href="javascript:" title="%%CATEGORY%%" onclick="hesk_insertRichTag('CATEGORY')">
                                <?php echo $hesklang['category']; ?>
                            </a>
                            <a href="javascript:" title="%%PRIORITY%%" onclick="hesk_insertRichTag('PRIORITY')">
                                <?php echo $hesklang['priority']; ?>
                            </a>
                            <a href="javascript:" title="%%STATUS%%" onclick="hesk_insertRichTag('STATUS')">
                                <?php echo $hesklang['status']; ?>
                            </a>
                            <a href="javascript:" title="%%SUBJECT%%" onclick="hesk_insertRichTag('SUBJECT')">
                                <?php echo $hesklang['subject']; ?>
                            </a>
                            <a href="javascript:" title="%%MESSAGE%%" onclick="hesk_insertRichTag('MESSAGE')">
                                <?php echo $hesklang['message']; ?>
                            </a>
                            <a href="javascript:" title="%%ATTACHMENTS%%" onclick="hesk_insertRichTag('ATTACHMENTS')">
                                <?php echo $hesklang['attachments']; ?>
                            </a>
                            <a href="javascript:" title="%%CREATED%%" onclick="hesk_insertRichTag('CREATED')">
                                <?php echo $hesklang['created_on']; ?>
                            </a>
                            <a href="javascript:" title="%%UPDATED%%" onclick="hesk_insertRichTag('UPDATED')">
                                <?php echo $hesklang['updated_on']; ?>
                            </a>
                            <a href="javascript:" title="%%OWNER%%" onclick="hesk_insertRichTag('OWNER')">
                                <?php echo $hesklang['owner']; ?>
                            </a>
                            <a href="javascript:" title="%%LAST_REPLY_BY%%" onclick="hesk_insertRichTag('LAST_REPLY_BY')">
                                <?php echo $hesklang['last_replier']; ?>
                            </a>
                            <a href="javascript:" title="%%TIME_WORKED%%" onclick="hesk_insertRichTag('TIME_WORKED')">
                                <?php echo $hesklang['ts']; ?>
                            </a>
                            <a href="javascript:" title="%%DUE_DATE%%" onclick="hesk_insertRichTag('DUE_DATE')">
                                <?php echo $hesklang['due_date']; ?>
                            </a>
                            <a href="javascript:" title="%%TRACK_ID%%" onclick="hesk_insertRichTag('TRACK_ID')">
                                <?php echo $hesklang['trackID']; ?>
                            </a>
                            <a href="javascript:" title="%%ID%%" onclick="hesk_insertRichTag('ID')">
                                <?php echo $hesklang['seqid']; ?>
                            </a>
                            <a href="javascript:" title="%%TRACK_URL%%" onclick="hesk_insertRichTag('TRACK_URL')">
                                <?php echo $hesklang['ticket_url']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_TITLE%%" onclick="hesk_insertRichTag('SITE_TITLE')">
                                <?php echo $hesklang['wbst_title']; ?>
                            </a>
                            <a href="javascript:" title="%%SITE_URL%%" onclick="hesk_insertRichTag('SITE_URL')">
                                <?php echo $hesklang['wbst_url']; ?>
                            </a>
                            <?php
                            foreach ($hesk_settings['custom_fields'] as $k=>$v)
                            {
                                if ($v['use'])
                                {
                                    echo '<a href="javascript:" title="%%'.strtoupper($k).'%%" onclick="hesk_insertRichTag(\''.strtoupper($k).'\')">'.$v['name'].'</a>';
                                }
                            }

                            // Add survey tag?
                            if ($email == 'survey') {
                                ?>
                                <a href="javascript:" title="%%SURVEY_URL%%" onclick="hesk_insertRichTag('SURVEY_URL')">
                                    <?php echo rtrim($hesklang['satisfaction']['url'], ":"); ?>
                                </a>
                                <?php
                            }

                        endif;
                        ?>
                    </div>
                </div>
                <div class="right-bar__footer">
                    <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
                    <input type="hidden" name="a" value="save" />
                    <input type="hidden" name="edit_language" value="<?php echo hesk_htmlspecialchars($hesk_settings['edit_language']); ?>" />
                    <input type="hidden" name="id" value="<?php echo $email; ?>" />
                    <input type="hidden" name="t" value="<?php echo $type; ?>">
                    <button type="submit" class="btn btn-full save" ripple="ripple"><?php echo $hesklang['et_save']; ?></button>
                </div>
            </form>
            <?php
            if (function_exists('hesk_tinymce_init')) {
                hesk_tinymce_init('#msg');
            }
            ?>
        </div>
    </div>
    <?php
} // END EDIT

require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/


function save_et()
{
	global $hesk_settings, $hesklang;

	// A security check
	hesk_token_check('POST');

	// Get email ID
	$email = hesk_POST('id');

    // Get email type
    if (($type = hesk_POST('t')) != 'html') {
        $type = 'plaintext';
    }

	// Get file path
    $eml_file = et_file_path($email, $type);

	// Make sure the file exists and is writable
	if ( ! file_exists($eml_file))
	{
   		hesk_error($hesklang['et_fm']);
	}
	elseif ( ! is_writable($eml_file))
	{
		hesk_error($hesklang['et_fw']);
	}

	// Get message
	$message = trim(hesk_POST('msg'));

    if ($type == 'html') {
        // Trick to save a href="tel:" type links
        $message = preg_replace('/href="(tel:%%CUSTOM(\d{1,2})%%)"/', 'href="X-HESK-TEL-$2"', $message);

        // Clean the HTML content
        require(HESK_PATH . 'inc/htmlpurifier/HeskHTMLPurifier.php');
        require(HESK_PATH . 'inc/html2text/html2text.php');
        $purifier = new HeskHTMLPurifier($hesk_settings['cache_dir']);
        $message = $purifier->heskPurify($message);

        // Restore a href="tel:" type links
        $message = preg_replace('/"X\-HESK\-TEL\-(\d{1,2})"/', '"tel:%%CUSTOM$1%%"', $message);

        // Make sure any Hesk emails tags are not URL-encoded
        $email_tags = array(
        'NAME',
        'FIRST_NAME',
        'SUBJECT',
        'TRACK_ID',
        'TRACK_URL',
        'SITE_TITLE',
        'SITE_URL',
        'CATEGORY',
        'PRIORITY',
        'OWNER',
        'STATUS',
        'EMAIL',
        'CREATED',
        'UPDATED',
        'DUE_DATE',
        'ID',
        'TIME_WORKED',
        'LAST_REPLY_BY',
        'FIRST_NAME',
        'ESCALATED_BY_RULE',
        'MESSAGE',
        'SURVEY_URL',
        'PASSWORD_RESET',
        'VERIFICATION_CODE',
        'VERIFICATION_URL',
        'CUSTOMER_LOGIN_URL',
        'CUSTOMER_REGISTER_URL',
        'NUM',
        'REQUESTER',
        'REQUESTER_NAME',
        'REQUESTER_FIRST_NAME',
        'REQUESTER_EMAIL',
        'FOLLOWERS',
        'FOLLOWER_NAMES',
        'FOLLOWER_EMAILS',
        'ATTACHMENTS',
        );

        for ($i = 1; $i <= 100; $i++) {
            $email_tags[] = 'CUSTOM' . $i;
        }

        $message = str_replace(
            array_map(function ($a) {return '%25%25' . $a . '%25%25';}, $email_tags),
            array_map(function ($a) {return '%%' . $a . '%%';}, $email_tags),
            $message
        );
    }

	// Do we need to remove backslashes from the message?
	if ( ! HESK_SLASH)
	{
    	$message = stripslashes($message);
	}

	// We won't accept an empty message
	if ( ! strlen($message))
	{
		hesk_process_messages($hesklang['et_empty'],'email_templates.php?a=edit&id=' . $email . '&t=' . $type . '&edit_language='.$hesk_settings['edit_language']);
	}

	// Save to the file
	file_put_contents($eml_file, $message);

	// Show success
    $_SESSION['et_id'] = $email;
    hesk_process_messages($hesklang['et_saved'],'email_templates.php?edit_language='.$hesk_settings['edit_language'],'SUCCESS');
} // End save_et()


function et_file_path($id, $type)
{
	global $hesk_settings, $hesklang, $emails;

	if ( ! is_string($id) || ! in_array($id, $emails, true))
	{
    	hesk_error($hesklang['inve']);
	}

	$folder = $type === 'plaintext' ? 'emails' : 'html_emails';

	return HESK_PATH . 'language/' . $hesk_settings['languages'][$hesk_settings['edit_language']]['folder'] . '/' . $folder . '/' . $id . '.txt';
} // END et_file_path()
export.php
wget 'https://lists2.roe3.org/hesk/admin/export.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */
define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/reporting_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_export');

// Just a delete file action?
$delete = hesk_GET('delete');
if (strlen($delete) && preg_match('/^hesk_export_[0-9_\-]+$/', $delete))
{
    hesk_token_check();
    hesk_unlink(HESK_PATH.$hesk_settings['cache_dir'].'/'.$delete.'.zip');
    hesk_process_messages($hesklang['fd'], hesk_verifyGoto(), 'SUCCESS');
}

// Load custom fields
require_once(HESK_PATH . 'inc/custom_fields.inc.php');

// Load priorities
require_once(HESK_PATH . 'inc/priorities.inc.php');

// Load statuses
require_once(HESK_PATH . 'inc/statuses.inc.php');

// Set default values
define('CALENDAR',1);
define('MAIN_PAGE',1);
define('LOAD_TABS',1);

$selected = array(
	'w'    => array(0=>'',1=>''),
	'time' => array(1=>'',2=>'',3=>'',4=>'',5=>'',6=>'',7=>'',8=>'',9=>'',10=>'',11=>'',12=>''),
);
$is_all_time = 0;

// Default this month to date
$hesk_settings['datepicker'] = array();

$df = new DateTime("first day of this month");
$date_from = $df->format('Y-m-d');
$hesk_settings['datepicker']['#datefrom']['timestamp'] = $df->getTimestamp();

$dt = new DateTime();
$date_to = $dt->format('Y-m-d');
$hesk_settings['datepicker']['#dateto']['timestamp'] = $dt->getTimestamp();

$input_datefrom = hesk_translate_date_string(date($hesk_settings['format_datepicker_php'], strtotime('last month')));
$input_dateto = hesk_translate_date_string(date($hesk_settings['format_datepicker_php']));

/* Date */
if (!empty($_GET['w']))
{
    $df = hesk_datepicker_get_date( hesk_GET('datefrom') );
    if ($df === false) {
        try {
            $df = new DateTime( hesk_GET('datefrom') );
            $date_from = $df->format('Y-m-d');
            $input_datefrom = hesk_translate_date_string($df->format($hesk_settings['format_datepicker_php']));
        } catch(Exception $e) {
            $date_from = date('Y-m-d', strtotime('last month') );
        }
    } else {
        $date_from = $df->format('Y-m-d');
        $input_datefrom = hesk_translate_date_string($df->format($hesk_settings['format_datepicker_php']));
    }

    $dt = hesk_datepicker_get_date( hesk_GET('dateto') );
    if ($dt === false) {
        try {
            $dt = new DateTime( hesk_GET('dateto') );
            $date_to = $dt->format('Y-m-d');
            $input_dateto = hesk_translate_date_string($dt->format($hesk_settings['format_datepicker_php']));
        } catch(Exception $e) {
            $date_to = date('Y-m-d');
        }
    } else {
        $date_to = $dt->format('Y-m-d');
        $input_dateto = hesk_translate_date_string($dt->format($hesk_settings['format_datepicker_php']));
    }

    if ($date_from > $date_to)
    {
        $tmp = $date_from;
        $tmp2 = $input_datefrom;

        $date_from = $date_to;
        $input_datefrom = $input_dateto;

        $date_to = $tmp;
        $input_dateto = $tmp2;

        $note_buffer = $hesklang['datetofrom'];

        $df2 = $df;
        $df = $dt;
        $dt = $df2;
        unset($df2);
    }

    if ($date_to > date('Y-m-d'))
    {
        $dt = new DateTime();
        $date_to = $dt->format('Y-m-d');
        $input_dateto = hesk_translate_date_string(date($hesk_settings['format_datepicker_php']));
    }

    if ($df instanceof DateTime) {
        $hesk_settings['datepicker']['#datefrom']['timestamp'] = $df->getTimestamp();
    } elseif (isset($hesk_settings['datepicker']['#datefrom']['timestamp'])) {
        unset($hesk_settings['datepicker']['#datefrom']['timestamp']);
    }
    if ($dt instanceof DateTime) {
        $hesk_settings['datepicker']['#dateto']['timestamp'] = $dt->getTimestamp();
    } elseif (isset($hesk_settings['datepicker']['#dateto']['timestamp'])) {
        unset($hesk_settings['datepicker']['#dateto']['timestamp']);
    }
	$selected['w'][1]='checked="checked"';
    $selected['time'][3]='selected="selected"';
}
else
{
	$selected['w'][0]='checked="checked"';
	$_GET['time'] = intval( hesk_GET('time', 3) );

    switch ($_GET['time'])
    {
    	case 1:
			/* Today */
			$date_from = date('Y-m-d');
			$date_to = $date_from;
			$selected['time'][1]='selected="selected"';
            $is_all_time = 1;
        break;

    	case 2:
			/* Yesterday */
			$date_from = date('Y-m-d',mktime(0, 0, 0, date("m"), date("d")-1, date("Y")));
			$date_to = $date_from;
			$selected['time'][2]='selected="selected"';
            $is_all_time = 1;
        break;

    	case 4:
			/* Last month */
			$date_from = date('Y-m-d',mktime(0, 0, 0, date("m")-1, 1, date("Y")));
			$date_to = date('Y-m-d',mktime(0, 0, 0, date("m"), 0, date("Y")));
			$selected['time'][4]='selected="selected"';
        break;

    	case 5:
			/* Last 30 days */
			$date_from = date('Y-m-d',mktime(0, 0, 0, date("m")-1, date("d"), date("Y")));
			$date_to = date('Y-m-d');
			$selected['time'][5]='selected="selected"';
        break;

    	case 6:
			/* This week */
			list($date_from,$date_to)=dateweek(0);
            $date_to = date('Y-m-d');
			$selected['time'][6]='selected="selected"';
        break;

    	case 7:
			/* Last week */
			list($date_from,$date_to)=dateweek(-1);
			$selected['time'][7]='selected="selected"';
        break;

    	case 8:
			/* This business week */
			list($date_from,$date_to)=dateweek(0,1);
            $date_to = date('Y-m-d');
			$selected['time'][8]='selected="selected"';
        break;

    	case 9:
			/* Last business week */
			list($date_from,$date_to)=dateweek(-1,1);
			$selected['time'][9]='selected="selected"';
        break;

    	case 10:
			/* This year */
			$date_from = date('Y').'-01-01';
			$date_to = date('Y-m-d');
			$selected['time'][10]='selected="selected"';
        break;

    	case 11:
			/* Last year */
			$date_from = date('Y')-1 . '-01-01';
			$date_to = date('Y')-1 . '-12-31';
			$selected['time'][11]='selected="selected"';
        break;

    	case 12:
			/* All time */
			$date_from = hesk_getOldestDate();
			$date_to = date('Y-m-d');
			$selected['time'][12]='selected="selected"';
            $is_all_time = 1;
        break;

        default:
        	$_GET['time'] = 3;
			$selected['time'][3]='selected="selected"';
    }

}

unset($tmp);

// Start SQL statement for selecting tickets
$sql = "SELECT `tickets`.*, `requester`.`name` AS `name`
    FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` AS `tickets`
    LEFT JOIN (
        SELECT DISTINCT `ticket_id`, `user_id`
        FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_collaborator`
    ) AS `w` ON (`tickets`.`id` = `w`.`ticket_id` AND `w`.`user_id` = ".intval($_SESSION['id']).")
    LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_customer` AS `ticket_to_customer`
        ON `tickets`.`id` = `ticket_to_customer`.`ticket_id`
        AND `ticket_to_customer`.`customer_type` = 'REQUESTER'
    LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` AS `requester`
        ON `ticket_to_customer`.`customer_id` = `requester`.`id` 
    WHERE ";

// Some default settings
$archive = array(1=>0,2=>0);
$s_my = array(1=>1,2=>1);
$s_ot = array(1=>1,2=>1);
$s_un = array(1=>1,2=>1);

// --> TICKET CATEGORY
$category = intval( hesk_GET('category', 0) );

// Make sure user has access to this category
if ($category && hesk_okCategory($category, 0) )
{
	$sql .= " `category`='{$category}' ";
}
// No category selected, show only allowed categories
else
{
	$sql .= hesk_myCategories();
}

// Show only tagged tickets?
if ( ! empty($_GET['archive']) )
{
	$archive[1]=1;
	$sql .= " AND `archive`='1' ";
}

// Ticket owner preferences
$fid = 1;
require(HESK_PATH . 'inc/assignment_search.inc.php');

// --> TICKET STATUS
$status = $hesk_settings['statuses'];

foreach ($status as $k => $v)
{
	if (empty($_GET['s'.$k]))
    {
    	unset($status[$k]);
    }
}

// How many statuses are we pulling out of the database?
$tmp = count($status);

// Do we need to search by status?
if ( $tmp < count($hesk_settings['statuses']) )
{
	// If no statuses selected, show all
	if ($tmp == 0)
	{
		$status = $hesk_settings['statuses'];
	}
	else
	{
		// Add to the SQL
		$sql .= " AND `status` IN ('" . implode("','", array_keys($status) ) . "') ";
	}
}

// --> TICKET PRIORITY
$possible_priority = hesk_possible_priorities();
$priority = $possible_priority;

foreach ($priority as $k => $v)
{
	if (empty($_GET['p'.$k]))
    {
    	unset($priority[$k]);
    }
}

// How many priorities are we pulling out of the database?
$tmp = count($priority);

// Create the SQL based on the number of priorities we need
if ($tmp == 0 || $tmp == count($possible_priority))
{
	// Nothing or all selected, no need to modify the SQL code
    $priority = $possible_priority;
}
else
{
	// A custom selection of priorities
	$sql .= " AND `priority` IN ('" . implode("','", array_keys($priority) ) . "') ";
}

// Prepare variables used in search and forms
require_once(HESK_PATH . 'inc/prepare_ticket_export.inc.php');

////////////////////////////////////////////////////////////////////////////////

// Can view tickets that are unassigned or assigned to others?
$can_view_ass_others = hesk_checkPermission('can_view_ass_others',0);
$can_view_unassigned = hesk_checkPermission('can_view_unassigned',0);

// Category options
$category_options = '';
$my_cat = array();
$res2 = hesk_dbQuery("SELECT `id`, `name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE " . hesk_myCategories('id') . " ORDER BY `cat_order` ASC");
while ($row=hesk_dbFetchAssoc($res2))
{
	$my_cat[$row['id']] = hesk_msgToPlain($row['name'], 1, 0);
	$row['name'] = (hesk_mb_strlen($row['name']) > 50) ? hesk_mb_substr($row['name'],0,50) . '...' : $row['name'];
	$cat_selected = ($row['id'] == $category) ? 'selected="selected"' : '';
	$category_options .= '<option value="'.$row['id'].'" '.$cat_selected.'>'.$row['name'].'</option>';
}

// Generate export file
if (isset($_GET['w'])) {
    hesk_token_check();

    if (defined('HESK_DEMO')) {
        hesk_process_messages($hesklang['ddemo'], 'export.php', 'NOTICE');
    } else {
        require_once(HESK_PATH . 'inc/export_functions.inc.php');
        list($success_msg, $tickets_exported) = hesk_export_to_XML($sql, false, $history, $replies);
    }
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
hesk_handle_messages();

// If an export was generated, show the link to download
if (isset($success_msg))
{
	if ($tickets_exported > 0)
	{
		hesk_show_success($success_msg);
	}
	else
	{
		hesk_show_notice($hesklang['n2ex']);
	}
}
?>
<div class="main__content reports">
    <h2>
        <?php echo $hesklang['export']; ?>
        <div class="tooltype right out-close">
            <svg class="icon icon-info">
                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
            </svg>
            <div class="tooltype__content">
                <div class="tooltype__wrapper">
                    <?php echo $hesklang['export_intro']; ?>
                </div>
            </div>
        </div>
    </h2>
    <form name="showt" action="export.php" method="get" aria-label="<?php echo $hesklang['export']; ?>">
        <div class="reports__range pl0">
            <h4><?php echo $hesklang['dtrg']; ?></h4>
            <div class="reports__range_form form">
                <div class="radio-list">
                    <div class="radio-custom">
                        <input type="radio" name="w" value="0" id="w0" <?php echo $selected['w'][0]; ?>>
                        <label for="w0" aria-label="<?php echo $hesklang['dtrg']; ?>">&nbsp;</label>
                        <div class="dropdown-select center out-close">
                            <select name="time" onclick="document.getElementById('w0').checked = true" onchange="document.getElementById('w0').checked = true" style="margin-top:5px;margin-bottom:5px;">
                                <option value="1" <?php echo $selected['time'][1]; ?>><?php echo $hesklang['r1']; ?> (<?php echo $hesklang['d'.date('w')]; ?>)</option>
                                <option value="2" <?php echo $selected['time'][2]; ?>><?php echo $hesklang['r2']; ?> (<?php echo $hesklang['d'.date('w',mktime(0, 0, 0, date('m'), date('d')-1, date('Y')))]; ?>)</option>
                                <option value="3" <?php echo $selected['time'][3]; ?>><?php echo $hesklang['r3']; ?> (<?php echo $hesklang['m'.date('n')]; ?>)</option>
                                <option value="4" <?php echo $selected['time'][4]; ?>><?php echo $hesklang['r4']; ?> (<?php echo $hesklang['m'.date('n',mktime(0, 0, 0, date('m')-1, 1, date('Y')))]; ?>)</option>
                                <option value="5" <?php echo $selected['time'][5]; ?>><?php echo $hesklang['r5']; ?></option>
                                <option value="6" <?php echo $selected['time'][6]; ?>><?php echo $hesklang['r6']; ?></option>
                                <option value="7" <?php echo $selected['time'][7]; ?>><?php echo $hesklang['r7']; ?></option>
                                <option value="8" <?php echo $selected['time'][8]; ?>><?php echo $hesklang['r8']; ?></option>
                                <option value="9" <?php echo $selected['time'][9]; ?>><?php echo $hesklang['r9']; ?></option>
                                <option value="10" <?php echo $selected['time'][10]; ?>><?php echo $hesklang['r10']; ?> (<?php echo date('Y'); ?>)</option>
                                <option value="11" <?php echo $selected['time'][11]; ?>><?php echo $hesklang['r11']; ?> (<?php echo date('Y',mktime(0, 0, 0, date('m'), date('d'), date('Y')-1)); ?>)</option>
                                <option value="12" <?php echo $selected['time'][12]; ?>><?php echo $hesklang['r12']; ?></option>
                            </select>
                        </div>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" name="w" value="1" id="w1" <?php echo $selected['w'][1]; ?>>
                        <label for="w1" aria-label="<?php echo $hesklang['cdr']; ?>">&nbsp;</label>
                        <?php echo $hesklang['from']; ?>
                        <section class="param calendar" style="margin-left: 10px; margin-right: 10px">
                            <div class="calendar--button">
                                <button type="button" onclick="document.getElementById('w1').checked = true" aria-label="<?php echo $hesklang['date'] . ' ' . $hesklang['from']; ?>">
                                    <svg class="icon icon-calendar">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-calendar"></use>
                                    </svg>
                                </button>
                                <input name="datefrom"
                                       id="datefrom"
                                    <?php if ($input_datefrom) {echo 'value="'.$input_datefrom.'"';} ?>
                                       type="text" class="datepicker" aria-label="<?php echo $hesklang['date'] . ' ' . $hesklang['from']; ?>">
                            </div>
                            <div class="calendar--value" <?php echo ($input_datefrom ? 'style="display: block"' : ''); ?>>
                                <span><?php echo $input_datefrom; ?></span>
                                <i class="close">
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                </i>
                            </div>
                        </section>
                        <?php echo $hesklang['to']; ?>
                        <section class="param calendar" style="margin-left: 10px;">
                            <div class="calendar--button">
                                <button type="button" onclick="document.getElementById('w1').checked = true" aria-label="<?php echo $hesklang['date'] . ' ' . $hesklang['to']; ?>">
                                    <svg class="icon icon-calendar">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-calendar"></use>
                                    </svg>
                                </button>
                                <input name="dateto"
                                       id="dateto"
                                    <?php if ($input_dateto) {echo 'value="'.$input_dateto.'"';} ?>
                                       type="text" class="datepicker" aria-label="<?php echo $hesklang['date'] . ' ' . $hesklang['to']; ?>">
                            </div>
                            <div class="calendar--value" <?php echo ($input_dateto ? 'style="display: block"' : ''); ?>>
                                <span><?php echo $input_dateto; ?></span>
                                <i class="close">
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                </i>
                            </div>
                        </section>
                    </div>
                </div>
            </div>
        </div>
        <section class="reports__checkbox">
            <h3><?php echo $hesklang['status']; ?></h3>
            <?php
            hesk_get_status_checkboxes($status);
            ?>
        </section>
        <section class="reports__checkbox">
            <h3><?php echo $hesklang['priority']; ?></h3>
            <?php
                hesk_get_priority_checkboxes($priority);
            ?>
        </section>
        <section class="reports__checkbox">
            <h3><?php echo $hesklang['assigned_to']; ?></h3>
            <div class="checkbox-custom">
                <input type="checkbox" name="s_my" id="s_my" value="1" <?php if ($s_my[1]) echo 'checked'; ?>>
                <label for="s_my"><?php echo $hesklang['s_my']; ?></label>
            </div>
            <?php
            if ($can_view_unassigned)
            {
                ?>
                <div class="checkbox-custom">
                    <input type="checkbox" name="s_un" id="s_un" value="1" <?php if ($s_un[1]) echo 'checked'; ?>>
                    <label for="s_un"><?php echo $hesklang['s_un']; ?></label>
                </div>
                <?php
            }

            if ($can_view_ass_others)
            {
                ?>
                <div class="checkbox-custom">
                    <input type="checkbox" name="s_ot" id="s_ot" value="1" <?php if ($s_ot[1]) echo 'checked'; ?>>
                    <label for="s_ot"><?php echo $hesklang['s_ot']; ?></label>
                </div>
                <?php
            }
            ?>
            <div class="checkbox-custom">
                <input type="checkbox" name="archive" id="archive" value="1" <?php if ($archive[1]) echo 'checked'; ?>>
                <label for="archive"><?php echo $hesklang['disp_only_archived']; ?></label>
            </div>
        </section>
        <section class="reports__checkbox">
            <h3><?php echo $hesklang['sort_by']; ?></h3>
            <div class="radio-list">
                <div class="radio-custom">
                    <input type="radio" name="sort" id="sort_priority" value="priority" <?php if ($sort == 'priority') {echo 'checked';} ?>>
                    <label for="sort_priority"><?php echo $hesklang['priority']; ?></label>
                </div>
                <div class="radio-custom">
                    <input type="radio" name="sort" id="sort_lastchange" value="lastchange" <?php if ($sort == 'lastchange') {echo 'checked';} ?>>
                    <label for="sort_lastchange"><?php echo $hesklang['last_update']; ?></label>
                </div>
                <div class="radio-custom">
                    <input type="radio" name="sort" id="sort_name" value="name" <?php if ($sort == 'name') {echo 'checked';} ?>>
                    <label for="sort_name"><?php echo $hesklang['name']; ?></label>
                </div>
                <div class="radio-custom">
                    <input type="radio" name="sort" id="sort_subject" value="subject" <?php if ($sort == 'subject') {echo 'checked';} ?>>
                    <label for="sort_subject"><?php echo $hesklang['subject']; ?></label>
                </div>
                <div class="radio-custom">
                    <input type="radio" name="sort" id="sort_status" value="status" <?php if ($sort == 'status') {echo 'checked';} ?>>
                    <label for="sort_status"><?php echo $hesklang['status']; ?></label>
                </div>
                <div class="radio-custom">
                    <input type="radio" name="sort" id="sort_id" value="id" <?php if ($sort == 'id') {echo 'checked';} ?>>
                    <label for="sort_id"><?php echo $hesklang['sequentially']; ?></label>
                </div>
            </div>
        </section>
        <section class="reports__checkbox">
            <h3><?php echo $hesklang['category']; ?></h3>
            <div class="dropdown-select center out-close">
                <select name="category">
                    <option value="0" ><?php echo $hesklang['any_cat']; ?></option>
                    <?php echo $category_options; ?>
                </select>
            </div>
        </section>
        <section class="reports__checkbox">
            <h3><?php echo $hesklang['order']; ?></h3>
            <div class="radio-list">
                <div class="radio-custom">
                    <input type="radio" name="asc" id="asc_1" value="1" <?php if ($asc) {echo 'checked';} ?>>
                    <label for="asc_1"><?php echo $hesklang['ascending']; ?></label>
                </div>
                <div class="radio-custom">
                    <input type="radio" name="asc" id="asc_0" value="0" <?php if (!$asc) {echo 'checked';} ?>>
                    <label for="asc_0"><?php echo $hesklang['descending']; ?></label>
                </div>
            </div>
        </section>
        <section class="reports__checkbox">
            <h3><?php echo $hesklang['opt']; ?></h3>
            <div class="checkbox-custom">
                <input type="checkbox" name="history" id="history" value="1" <?php if ($history) echo 'checked'; ?>>
                <label for="history"><?php echo $hesklang['ex_history']; ?></label>
            </div>
            <div class="checkbox-custom">
                <input type="checkbox" name="replies" id="replies" value="1" <?php if ($replies) echo 'checked'; ?>>
                <label for="replies"><?php echo $hesklang['ex_replies']; ?></label>
            </div>
        </section>
        <div class="reports__export">
            <input type="hidden" name="cot" value="1">
            <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
            <button class="btn btn-full" ripple="ripple" data-action="reports-export"><?php echo $hesklang['export_btn']; ?></button>
        </div>
    </form>
</div>

<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();
?>
export_ticket.php
wget 'https://lists2.roe3.org/hesk/admin/export_ticket.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/privacy_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_export');

// A security check
hesk_token_check();

// Tracking ID
$trackingID = hesk_cleanID() or die($hesklang['int_error'].': '.$hesklang['no_trackID']);

// Generate SQL for the ticket, make sure the user has access to it
$sql = "SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `trackid`='".hesk_dbEscape($trackingID)."' AND ";
$sql .= hesk_myCategories();
$sql .= " AND " . hesk_myOwnership();
$sql .= " LIMIT 1";

require_once(HESK_PATH . 'inc/custom_fields.inc.php');
require_once(HESK_PATH . 'inc/priorities.inc.php');
require_once(HESK_PATH . 'inc/statuses.inc.php');
require(HESK_PATH . 'inc/export_functions.inc.php');

list($success_msg, $tickets_exported) = hesk_export_to_XML($sql, true);

if ($tickets_exported == 1)
{
    hesk_process_messages($success_msg,'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999),'SUCCESS');
}

hesk_error($hesklang['n2ex']);
find_tickets.php
wget 'https://lists2.roe3.org/hesk/admin/find_tickets.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

define('CALENDAR',1);
define('AUTO_RELOAD',1);
$_SESSION['hide']['ticket_list'] = true;

/* Check permissions for this feature */
hesk_checkPermission('can_view_tickets');

$_SERVER['PHP_SELF'] = './admin_main.php';
$href = 'find_tickets.php';

// Load custom fields
require_once(HESK_PATH . 'inc/custom_fields.inc.php');

// Load priorities
require_once(HESK_PATH . 'inc/priorities.inc.php');

// Load statuses
require_once(HESK_PATH . 'inc/statuses.inc.php');

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print admin navigation */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');
?>
<div class="main__content tickets">
    <div style="margin-left: -16px; margin-right: -24px;">
        <?php

        /* This will handle error, success and notice messages */
        hesk_handle_messages();
        ?>
    </div>
<?php
// Is this a quick link?
$is_quick_link = hesk_GET('ql', false);

$sql_customer_count = "SELECT COUNT(1) FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_customer` AS `ticket_to_customer_names`
    INNER JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` `customer_names`
        ON `ticket_to_customer_names`.`customer_id` = `customer_names`.`id` 
    WHERE `ticket_id` = `ticket`.`id`";
$sql_email_count = "SELECT COUNT(1) FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_customer` AS `ticket_to_customer_emails`
    INNER JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` `customer_emails`
        ON `ticket_to_customer_emails`.`customer_id` = `customer_emails`.`id` 
    WHERE `ticket_id` = `ticket`.`id`
        AND COALESCE(`customer_emails`.`email`, '') <> ''";

// This SQL code will be used to retrieve results
$sql_final = "SELECT
`ticket`.`id` AS `id`,
`trackid`,
COALESCE(`customer`.`name`, '".hesk_dbEscape($hesklang['anon_name'])."') AS `name`,
COALESCE(`customer`.`email`, '".hesk_dbEscape($hesklang['anon_email'])."') AS `email`,
({$sql_customer_count}) AS `customer_count`,
({$sql_email_count}) AS `email_count`,
`category`,
`priority`,
`priority_order` AS `vv`,
`subject`,
LEFT(`message`, 400) AS `message`,
`dt`,
`lastchange`,
`firstreply`,
`closedat`,
`status`,
`openedby`,
`firstreplyby`,
`closedby`,
`ticket`.`replies`,
`staffreplies`,
`owner`,
`time_worked`,
`due_date`,
`lastreplier`,
`lastreplier_customer`.`name` AS `lastreplier_customername`,
`replierid`,
`archive`,
`locked`,
CASE WHEN `bookmarks`.`ticket_id` IS NOT NULL THEN 1 ELSE 0 END AS `is_bookmark`
";

foreach ($hesk_settings['custom_fields'] as $k=>$v)
{
	if ($v['use'])
	{
		$sql_final .= ", `".$k."`";
	}
}

$sql_final.= " FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` AS `ticket`
LEFT JOIN (
    SELECT DISTINCT `ticket_id`, `user_id`
    FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_collaborator`
    WHERE `user_id` = ".intval($_SESSION['id'])."
) AS `w` ON (`ticket`.`id` = `w`.`ticket_id`) ";

$sql_final.= "
LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` AS `customer`
    ON `customer`.`id` = (
        SELECT `customer_id`
        FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_customer` AS `ticket_to_customer`
        WHERE `ticket_id` = `ticket`.`id`
            AND `customer_type` = 'REQUESTER'
        LIMIT 1
    )
LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` AS `lastreplier_customer`
    ON `ticket`.`lastreplier` = '0'
    AND `lastreplier_customer`.`id` = (
        SELECT `customer_id` 
        FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` 
        WHERE `replyto` = `ticket`.`id`
            AND `customer_id` IS NOT NULL 
        ORDER BY `id` DESC 
        LIMIT 1)
LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."users` AS `lastreplier_staff`
    ON `ticket`.`lastreplier` <> '0'
    AND `ticket`.`replierid` = `lastreplier_staff`.`id`
LEFT JOIN (
    SELECT DISTINCT `ticket_id`, `user_id`
    FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."bookmarks`
    WHERE `user_id` = ".intval($_SESSION['id'])."
) AS `bookmarks` ON (`ticket`.`id` = `bookmarks`.`ticket_id`)
LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_priorities` AS `custom_priorities` ON `ticket`.`priority` = `custom_priorities`.`id`
WHERE ";

if ($is_quick_link == 'cbm') {
    $sql_final.= " `w`.`user_id`=".intval($_SESSION['id'])." AND ".hesk_myCategories()." ";
} else {
    $sql_final .= " ".hesk_myCategories()." AND ".hesk_myOwnership(1);
}

// This code will be used to count number of results for this specific search
$sql_count = " SELECT COUNT(DISTINCT `ticket`.`id`) AS `cnt`, `status`,
                      IF (`owner` = " . intval($_SESSION['id']) . ", 1, IF (`owner` = 0, 0, IF (`assignedby` = " . intval($_SESSION['id']) . ", 3, 2) ) ) AS `assigned_to`,
                      IF (`due_date` < NOW(), 2, IF (`due_date` BETWEEN NOW() AND (NOW() + INTERVAL ".intval($hesk_settings['due_soon'])." DAY), 1, 0) ) AS `due`,
                      CASE WHEN `bookmarks`.`ticket_id` IS NOT NULL THEN 1 ELSE 0 END AS `is_bookmark`,
                      CASE WHEN `w`.`user_id` IS NOT NULL THEN 1 ELSE 0 END AS `is_collaborator`
                FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` AS `ticket`
                LEFT JOIN (
                    SELECT DISTINCT `ticket_id`, `user_id`
                    FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_collaborator`
                    WHERE `user_id` = ".intval($_SESSION['id'])."
                ) AS `w` ON (`ticket`.`id` = `w`.`ticket_id`)
                LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` AS `customer`
                    ON `customer`.`id` = (
                        SELECT `customer_id`
                        FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_customer` AS `ticket_to_customer`
                        WHERE `ticket_id` = `ticket`.`id`
                            AND `customer_type` = 'REQUESTER'
                        LIMIT 1
                    )
                LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` AS `lastreplier_customer`
                    ON `ticket`.`lastreplier` = '0'
                    AND `lastreplier_customer`.`id` = (
                        SELECT `customer_id`
                        FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies`
                        WHERE `replyto` = `ticket`.`id`
                            AND `customer_id` IS NOT NULL
                        ORDER BY `id` DESC
                        LIMIT 1)
                LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."users` AS `lastreplier_staff`
                    ON `ticket`.`lastreplier` <> '0'
                    AND `ticket`.`lastreplier` = `lastreplier_staff`.`id`
                LEFT JOIN (
                    SELECT DISTINCT `ticket_id`, `user_id`
                    FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."bookmarks`
                    WHERE `user_id` = ".intval($_SESSION['id'])."
                ) AS `bookmarks` ON (`ticket`.`id` = `bookmarks`.`ticket_id`)
                WHERE ".hesk_myCategories()." AND ".hesk_myOwnership(1);

// This code will be used to count collaborated tickets for this specific search
$sql_collaborator = " SELECT COUNT(DISTINCT `ticket`.`id`) AS `cnt`
                FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` AS `ticket`
                LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_collaborator` AS `w` ON (`ticket`.`id` = `w`.`ticket_id` AND `w`.`user_id` = ".intval($_SESSION['id']).")
                LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` AS `customer`
                    ON `customer`.`id` = (
                        SELECT `customer_id`
                        FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_customer` AS `ticket_to_customer`
                        WHERE `ticket_id` = `ticket`.`id`
                            AND `customer_type` = 'REQUESTER'
                        LIMIT 1
                    )                
                WHERE `w`.`user_id`=".intval($_SESSION['id'])." AND ".hesk_myCategories();

// This is common SQL for both queries
$sql = "";

// Some default settings
$archive = array(1=>0,2=>0);
$s_my = array(1=>1,2=>1);
$s_ot = array(1=>1,2=>1);
$s_un = array(1=>1,2=>1);

// --> TICKET CATEGORY
if (isset($_GET['c']) && is_array($_GET['c'])) {
    $categories = [];
    foreach ($_GET['c'] as $category) {
        $category = intval($category);
        if ($category && hesk_okCategory($category, 0) ) {
            $categories[] = $category;
        }
    }
    if (count($categories)) {
        $sql .= " AND `category` IN (".implode(',', $categories).") ";
    }
} elseif (isset($_GET['category'])) {
    // Legacy, select a single category
    $category = intval( hesk_GET('category', 0) );
    $categories = array($category);
    if ($category && hesk_okCategory($category, 0) ) {
        $sql .= " AND `category`='{$category}' ";
    }
} else {
    $category = 0;
    $categories = [0];
}

// Show only tagged tickets?
if ( ! empty($_GET['archive']) )
{
	$archive[2]=1;
	$sql .= " AND `archive`='1' ";
}

$sql_count .= $sql;
$sql_collaborator .= $sql;

// Ticket owner preferences
$fid = 2;
require(HESK_PATH . 'inc/assignment_search.inc.php');

$hesk_error_buffer = '';
$no_query = 0;

// Search query
$q = hesk_input( hesk_GET('q', '') );

// No query entered?
if ( ! strlen($q) )
{
	$no_query = 1;
}

// What field are we searching in
$what = hesk_GET('what', '') or $hesk_error_buffer .= '<br />' . $hesklang['wsel'];

// Sequential ID supported?
if ($what == 'seqid' && ! $hesk_settings['sequential'])
{
	$what = 'trackid';
}

// Sequential ID must be numeric
if ($what == 'seqid' && strlen($q) && !is_numeric($q)) {
    $q = '';
    $no_query = 1;
    $hesk_error_buffer .= $hesklang['seq_id_numeric'];
    $hesklang['fsq'] = '';
}

// Setup SQL based on searching preferences
if ( ! $no_query)
{
    $sql_previous = $sql;
    $sql = " AND ";

	switch ($what)
	{
		case 'trackid':
		    $sql  .= " ( `trackid` = '".hesk_dbEscape($q)."' OR `merged` LIKE '%#".hesk_dbEscape($q)."#%' ) ";
		    break;
		case 'name':
            $sql .= "`ticket`.`id` IN (
                SELECT `ticket_id`
                FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_customer` AS `ticket_to_customer`
                INNER JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` AS `customer`
                    ON `ticket_to_customer`.`customer_id` = `customer`.`id`
                    AND `customer`.`name` LIKE '%".hesk_dbEscape( hesk_dbLike($q) )."%' COLLATE '" . hesk_dbCollate() . "'
            ) ";
		    //$sql  .= "`name` LIKE '%".hesk_dbEscape( hesk_dbLike($q) )."%' COLLATE '" . hesk_dbCollate() . "' ";
		    break;
		case 'email':
            $sql .= "`ticket`.`id` IN (
                SELECT `ticket_id`
                FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_customer` AS `ticket_to_customer`
                INNER JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` AS `customer`
                    ON `ticket_to_customer`.`customer_id` = `customer`.`id`
                    AND `customer`.`email` LIKE '%".hesk_dbEscape( hesk_dbLike($q) )."%'
            ) ";
			 break;
		case 'subject':
		    $sql  .= "`subject` LIKE '%".hesk_dbEscape( hesk_dbLike($q) )."%' COLLATE '" . hesk_dbCollate() . "' ";
		    break;
		case 'message':
		    $sql  .= " ( `message` LIKE '%".hesk_dbEscape( hesk_dbLike($q) )."%' COLLATE '" . hesk_dbCollate() . "'
            		OR
                    `ticket`.`id` IN (
            		SELECT DISTINCT `replyto`
                	FROM   `".hesk_dbEscape($hesk_settings['db_pfix'])."replies`
                	WHERE  `message` LIKE '%".hesk_dbEscape( hesk_dbLike($q) )."%' COLLATE '" . hesk_dbCollate() . "' )
                    )
                    ";
		    break;
		case 'seqid':
	        $sql  .= "`ticket`.`id` = '".intval($q)."' ";
			break;
        case 'customer':
            $sql  .= "`ticket`.`id` IN (
                SELECT `ticket_id`
                FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_customer`
                WHERE `customer_id` = '".intval($q)."'
            ) ";
            break;
		case 'notes':
		    $sql  .= "`ticket`.`id` IN (
            		SELECT DISTINCT `ticket`
                	FROM   `".hesk_dbEscape($hesk_settings['db_pfix'])."notes`
                	WHERE  `message` LIKE '%".hesk_dbEscape( hesk_dbLike($q) )."%' COLLATE '" . hesk_dbCollate() . "' )
                	";
		    break;
		case 'ip':
	         $sql  .= "`ip` LIKE '".preg_replace('/[^0-9\.\%]/', '', $q)."' ";
			 break;
		default:
	    	if (isset($hesk_settings['custom_fields'][$what]) && $hesk_settings['custom_fields'][$what]['use'])
	        {
	        	$sql .= "`".hesk_dbEscape($what)."` LIKE '%".hesk_dbEscape( hesk_dbLike($q) )."%' COLLATE '" . hesk_dbCollate() . "' ";
	        }
	        else
	        {
	        	$hesk_error_buffer .= '<br />' . $hesklang['invalid_search'];
	        }
	}

    $sql_count .= $sql;
    $sql_collaborator .= $sql;
    $sql = $sql_previous . $sql;
}
// Some fields can be searched for empty (or NULL) values
else
{
    $sql_previous = $sql;
    $sql = " AND ";

    switch ($what)
    {
        case 'email':
             $sql  .= " COALESCE(`customer`.`email`, '') = '' ";
             $no_query = 0;
             break;
        case 'message':
            $sql  .= " `message` = '' ";
            $no_query = 0;
            break;
        case 'ip':
             $sql  .= "`ip` = '' ";
             $no_query = 0;
             break;
        default:
            if (isset($hesk_settings['custom_fields'][$what]) && $hesk_settings['custom_fields'][$what]['use'])
            {
                $sql .= "(`".hesk_dbEscape($what)."` IS NULL OR `".hesk_dbEscape($what)."` = '') ";
                $no_query = 0;
            }
    }

    if ($no_query) {
        $hesk_error_buffer .= $hesklang['fsq'];
        $sql = "";
    }

    $sql_count .= $sql;
    $sql_collaborator .= $sql;
    $sql = $sql_previous . $sql;
}

// Owner
if ( $tmp = intval( hesk_GET('owner', 0) ) )
{
	$sql .= " AND `owner`={$tmp} ";
    $sql_count .= " AND `owner`={$tmp} ";
    $sql_collaborator .= " AND `owner`={$tmp} ";
	$owner_input = $tmp;
	$hesk_error_buffer = str_replace($hesklang['fsq'],'',$hesk_error_buffer);
}
else
{
	$owner_input = 0;
}

/* Date */
$date_input = hesk_GET('dt');
$formatted_search_date = hesk_datepicker_get_date($date_input);

if ($formatted_search_date !== false) {
    $hesk_settings['datepicker'] = array();
    $hesk_settings['datepicker']['#find-date']['timestamp'] = $formatted_search_date->getTimestamp();;

    $formatted_search_date = $formatted_search_date->format('Y-m-d');

    // This search is valid even if no query is entered
    if ($no_query) {
        $hesk_error_buffer = str_replace($hesklang['fsq'],'',$hesk_error_buffer);
    }

	$sql .= " AND `dt` BETWEEN '{$formatted_search_date} 00:00:00' AND '{$formatted_search_date} 23:59:59' ";
    $sql_count .= " AND `dt` BETWEEN '{$formatted_search_date} 00:00:00' AND '{$formatted_search_date} 23:59:59' ";
    $sql_collaborator .= " AND `dt` BETWEEN '{$formatted_search_date} 00:00:00' AND '{$formatted_search_date} 23:59:59' ";

} else {
    $formatted_search_date = '';
    $date_input = '';
}

/* Any errors? */
if (strlen($hesk_error_buffer))
{
	hesk_process_messages($hesk_error_buffer,'NOREDIRECT');
}

/* This will handle error, success and notice messages */
$handle = hesk_handle_messages();

// Due date
if ($is_quick_link == 'due')
{
    $sql .= " AND `status` != 3 AND `due_date` BETWEEN NOW() AND (NOW() + INTERVAL ".intval($hesk_settings['due_soon'])." DAY) ";
}
elseif ($is_quick_link == 'ovr')
{
    $sql .= " AND `status` != 3 AND `due_date` < NOW() ";
}
elseif ($is_quick_link == 'alo')
{
    $sql .= " AND `status` != 3 ";
    $sql_count .= " AND `status` != 3 ";
    $sql_collaborator .= " AND `status` != 3 ";
}
elseif ($is_quick_link == 'bm')
{
    $sql .= " AND `bookmarks`.`ticket_id` IS NOT NULL";
}

// Complete the required SQL queries
$sql = $sql_final . $sql;
$sql_count .= " GROUP BY `assigned_to`, `due`, `status`, `is_bookmark`, `is_collaborator` ";

// Strip extra slashes
$q = stripslashes($q);

/* Prepare variables used in search and forms */
require_once(HESK_PATH . 'inc/prepare_ticket_search.inc.php');

/* If there has been an error message skip searching for tickets */
if ($handle !== FALSE)
{
    $totals = array(
        'all' => 0,
        'open' => 0,
        'resolved' => 0,
        'filtered' => array(
            'all' => 0,
            'open' => 0,
            'assigned_to_me' => 0,
            'assigned_to_others' => 0,
            'assigned_to_others_by_me' => 0,
            'unassigned' => 0,
            'bookmarks' => 0,
            'due_soon' => 0,
            'overdue' => 0,
            'by_status' => array(),
            'collaborator' => 0,
            'collaborator_assigned_to_me' => 0,
            'collaborator_assigned_to_others' => 0,
            'collaborator_assigned_to_others_by_me' => 0,
            'collaborator_unassigned' => 0,
        ),
    );

    $can_view_unassigned = hesk_checkPermission('can_view_unassigned',0);
    $can_view_ass_others = hesk_checkPermission('can_view_ass_others',0);
    $can_view_ass_by = hesk_checkPermission('can_view_ass_by',0);

	require_once(HESK_PATH . 'inc/ticket_list.inc.php');
}

/* Clean unneeded session variables */
hesk_cleanSessionVars('hide');

/* Show the search form */
require_once(HESK_PATH . 'inc/show_search_form.inc.php');

/* Print footer */
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();
?>
generate_spam_question.php
wget 'https://lists2.roe3.org/hesk/admin/generate_spam_question.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/setup_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();
hesk_checkPermission('can_man_settings');

$spam_question = hesk_generate_SPAM_question();

header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

header('Content-type: text/plain; charset=utf-8');
?>
<div class="form-group">
    <h5></h5>
    <button style="margin-left: 24px" type="button" class="btn btn--blue-border" onclick="Javascript:hesk_rate('generate_spam_question.php','question')">
        <?php echo $hesklang['genq']; ?>
    </button>
</div>
<div class="form-group">
    <h5><span><?php echo $hesklang['q_q']; ?></span></h5>
    <textarea style="margin-left: 24px;" name="s_question_ask" class="form-control" rows="3" cols="40"><?php echo addslashes(hesk_htmlspecialchars($spam_question[0])); ?></textarea>
</div>
<div class="form-group">
    <h5><span><?php echo $hesklang['q_a']; ?></span></h5>
    <input class="form-control" type="text" name="s_question_ans" value="<?php echo addslashes(hesk_htmlspecialchars($spam_question[1])); ?>">
</div>
<?php
exit();
?>
import_customers.php
wget 'https://lists2.roe3.org/hesk/admin/import_customers.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');
define('LOAD_TABS',1);

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/privacy_functions.inc.php');
require(HESK_PATH . 'inc/manage_customers_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

if (defined('HESK_DEMO')) {
    hesk_process_messages($hesklang['ddemo'], 'manage_customers.php', 'NOTICE');
}

// Are customer accounts enabled?
if (empty($hesk_settings['customer_accounts'])) {
    hesk_error($hesklang['customer_accounts_disabled']);
}

// Check permissions for this feature
$can_man_customers = hesk_checkPermission('can_man_customers');

// This is a sensitive page, double-check user authentication
hesk_check_user_elevation('import_customers.php');

//-- We're utilizing the existing attachments functionality, but with a bunch of customizations.
require_once(HESK_PATH . 'inc/attachments.inc.php');

define('ATTACHMENTS', 1);
define('CSV', 1);
/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
if (!hesk_SESSION(array('userdata', 'errors'))) {
    hesk_handle_messages();
}
?>
<div class="main__content team">
    <section class="team__head">
        <h2>
            <?php echo $hesklang['import_customers']; ?>
            <div class="tooltype right out-close">
                <svg class="icon icon-info">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                </svg>
                <div class="tooltype__content">
                    <div class="tooltype__wrapper">
                        <?php echo $hesklang['import_customers_tip']; ?>
                    </div>
                </div>
            </div>
        </h2>
    </section>
    <div class="table-wrap import" data-step="1">
        <div class="import-steps">
            <ul class="step-bar">
                <li data-link="1" data-all="3"><?php echo $hesklang['import_customer_select_file']; ?></li>
                <li data-link="2" data-all="3"><?php echo $hesklang['import_customer_select_columns']; ?></li>
                <li data-link="3" data-all="3"><?php echo $hesklang['import_customer_upload_customers']; ?></li>
            </ul>
        </div>
        <div class="step-slider form">
            <div class="step-item step-1">
                <div>
                    <strong>1. <?php echo $hesklang['import_customer_step1_instructions']; ?></strong>
                    <ul>
                        <li><?php echo $hesklang['import_customer_upload_requirements_1']; ?></li>
                        <li><?php echo $hesklang['import_customer_upload_requirements_2']; ?></li>
                        <li><?php echo $hesklang['import_customer_upload_requirements_3']; ?><br><br></li>
                    </ul>
                </div>
                <div>
                    <strong><?php echo $hesklang['import_customer_sample']; ?></strong>
                    <ul>
                        <li><a href="samples/customer-import-CSV-example-US.csv"><?php echo $hesklang['import_customer_sample_1']; ?></a></li>
                        <li><a href="samples/customer-import-CSV-example-EU.csv"><?php echo $hesklang['import_customer_sample_2']; ?></a><br><br></li>
                    </ul>
                </div>
                <div class="form-group short">
                    <label for="separator-column"><strong>2. <?php echo $hesklang['import_customer_step1_separator']; ?></strong></label>
                    <input id="separator-column" type="text" class="form-control" value=",">
                </div>
                <div><strong>3. <?php echo $hesklang['import_customer_step1_note']; ?></strong></div>
                <div class="attachments" id="attachments-container">
                    <?php
                    build_dropzone_markup(true, 'upload_filedrop', 1, false);
                    ?>
                </div>
            </div>
            <div class="step-item step-2">
                <div><strong><?php echo $hesklang['file']; ?>: <span data-field="file-name"></span></strong></div>
                <div class="form-group">
                    <label for="name-column"><?php echo $hesklang['import_customer_column_name']; ?></label>
                    <select id="name-column" class="selectized">
                        <option value="-1"><?php echo $hesklang['select']; ?></option>
                    </select>
                    <div class="form-control__error"><?php echo $hesklang['import_customer_name_or_email_required']; ?></div>
                </div>
                <div class="form-group">
                    <label for="email-column"><?php echo $hesklang['import_customer_column_email']; ?></label>
                    <select id="email-column" class="selectized">
                        <option value="-1"><?php echo $hesklang['select']; ?></option>
                    </select>
                    <div class="form-control__error"><?php echo $hesklang['import_customer_name_or_email_required']; ?></div>
                </div>
                <div class="form-group">
                    <label for="password-column"><?php echo $hesklang['import_customer_column_pass']; ?></label>
                    <select id="password-column" class="selectized">
                        <option value="-1"><?php echo $hesklang['select']; ?></option>
                    </select>
                </div>
                <p><?php echo $hesklang['import_customer_step2_note']; ?></p>
                <div class="action-buttons">
                    <a href="import_customers.php" class="btn btn--blue-border"><?php echo $hesklang['wizard_back']; ?></a>
                    <button type="submit" class="btn btn-full next" ripple="ripple" data-submit-step="2"><?php echo $hesklang['wizard_next']; ?></button>
                </div>
            </div>
            <div class="step-item step-3">
                <div role="status" class="notification blue" id="step-3-pending">
                    <?php echo $hesklang['import_customer_step3_note']; ?>
                </div>
                <div role="alert" class="notification orange" id="step-3-partial-success" style="display: none">
                    <?php echo $hesklang['import_customer_step3_complete_some_failed']; ?>
                </div>
                <div role="status" class="notification green" id="step-3-total-success" style="display: none">
                    <?php echo $hesklang['import_customer_step3_complete']; ?>
                </div>
                <div class="upload-stats">
                    <div>
                        <p><?php echo $hesklang['import_customer_step3_successful_imports']; ?></p>
                        <p class="value"><span data-stat="successes">0</span></p>
                    </div>
                    <div>
                        <p><?php echo $hesklang['import_customer_step3_failed_imports']; ?></p>
                        <p class="value"><span data-stat="failures">0</span></p>
                    </div>
                    <div>
                        <p><?php echo $hesklang['import_customer_step3_progress']; ?></p>
                        <p class="value">
                            <span data-stat="finished-uploads">0</span>/<span data-stat="total-uploads">0</span>
                            (<span data-stat="percent-uploaded">0</span>%)
                        </p>
                    </div>
                </div>
                <table class="table sindu-table">
                    <thead>
                    <tr>
                        <th><?php echo $hesklang['name']; ?></th>
                        <th><?php echo $hesklang['email']; ?></th>
                        <th><?php echo $hesklang['status']; ?></th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php // Filled in via JS ?>
                    </tbody>
                </table>
                <template id="row-template">
                    <tr data-attr="index">
                        <td data-attr="name"></td>
                        <td data-attr="email"></td>
                        <td data-attr="status"></td>
                    </tr>
                </template>
            </div>
        </div>
    </div>
</div>
<script>
    const UPLOAD = {
        name: '',
        contents: '',
        columnIndexes: {
            name: -1,
            email: -1,
            password: -1,
        },
        successfulUploads: 0,
        failedUploads: 0,
        totalUploads: function() {
            return this.successfulUploads + this.failedUploads;
        },
        addColumnsToDropdowns: function() {
            const $selectizedDropdowns = $('.selectized');
            $.each($selectizedDropdowns, function(idx, dropdown) {
                let index = 0;
                for (const column of UPLOAD.getColumns()) {
                    const opt = document.createElement('option');
                    opt.value = (index++).toString();
                    opt.textContent = column;
                    dropdown.appendChild(opt);
                }
            });
            $selectizedDropdowns.selectize();
            $('.selectize-control:not(.read-write) .selectize-input input').prop('readonly', true);
        },
        getColumns: function() {
            return UPLOAD.contents[0];
        }
    };

    Dropzone.autoDiscover = false;
    const importDropzone = new Dropzone('#upload_filedrop', {
        url: '#',
        autoProcessQueue: false,
        dictDefaultMessage: '<?php echo hesk_makeJsString($hesklang['attachment_viewer_message']); ?>',
        clickable: '.dz-click-upload_filedrop',
        accept: function(file, done) {
            const reader = new FileReader();
            const dz = this;
            reader.addEventListener('loadend', function(event) {
                dz.emit('success', file);
                dz.emit('complete', file);

                UPLOAD.contents = $.csv.toArrays(reader.result, {
                    separator: $('#separator-column').val()
                });
                UPLOAD.name = file.name;
                goToStep2();
            });
            reader.readAsText(file);
        }
    });

    function goToStep2() {
        $('[data-step="1"]').attr('data-step', 2);
        $('.step-2').find('[data-field="file-name"]').text(UPLOAD.name);
        UPLOAD.addColumnsToDropdowns();
    }

    $('[data-submit-step="2"]').click(function() {
        const $formValidationErrors = $('.step-2').find('.form-control__error');
        $formValidationErrors.hide();
        const nameColumnIndex = parseInt($('#name-column').val(), 10);
        const emailColumnIndex = parseInt($('#email-column').val(), 10);
        if (nameColumnIndex === -1 && emailColumnIndex === -1) {
            $formValidationErrors.show();
        }

        UPLOAD.columnIndexes.name = nameColumnIndex;
        UPLOAD.columnIndexes.email = emailColumnIndex;
        UPLOAD.columnIndexes.password = parseInt($('#password-column').val(), 10);
        goToStep3();
    });

    function goToStep3() {
        $('[data-step="2"]').attr('data-step', 3);

        //-- Output all records to the table
        const rows = UPLOAD.contents.slice(1);
        document.querySelector('[data-stat="total-uploads"]').innerHTML = rows.length.toString();
        let index = 0
        for (const row of rows) {
            const template = document.querySelector('#row-template');

            if (UPLOAD.columnIndexes.name > -1) {
                template.content.querySelector('[data-attr="name"]').textContent = row[UPLOAD.columnIndexes.name];
            }
            if (UPLOAD.columnIndexes.email > -1) {
                template.content.querySelector('[data-attr="email"]').textContent = row[UPLOAD.columnIndexes.email];
            }
            template.content.querySelector('[data-attr="index"]').setAttribute('data-customer-index', index++);
            template.content.querySelector('[data-attr="status"]').textContent = '<?php echo hesk_makeJsString($hesklang['import_customer_step3_pending']); ?>';

            const clone = document.importNode(template.content, true);
            document.querySelector('.step-3 tbody').appendChild(clone);
        }

        // Index 0 = headers
        doUpload(1);
    }

    function doUpload(index) {
        if (index >= UPLOAD.contents.length) {
            document.querySelector('#step-3-pending').style.display = 'none';
            if (UPLOAD.failedUploads === 0) {
                document.querySelector('#step-3-total-success').style.display = 'block';
            } else {
                const warningAlert = document.querySelector('#step-3-partial-success');
                warningAlert.style.display = 'block';
                const existingText = warningAlert.innerHTML;
                warningAlert.innerHTML = existingText.replace('%s', UPLOAD.failedUploads);
            }
            return;
        }

        const record = UPLOAD.contents[index];
        const requestBody = {
            name: UPLOAD.columnIndexes.name > -1 ? record[UPLOAD.columnIndexes.name] : '',
            email: UPLOAD.columnIndexes.email > -1 ? record[UPLOAD.columnIndexes.email] : '',
            password: UPLOAD.columnIndexes.password > -1 ? record[UPLOAD.columnIndexes.password] : '',
            token: '<?php echo hesk_token_echo(0); ?>'
        };
        const customerStatus = document.querySelector('.step-3 [data-customer-index="'+ (index - 1) +'"] [data-attr="status"]');
        customerStatus.innerHTML = '<?php echo hesk_makeJsString($hesklang['import_customer_step3_importing']); ?>';

        $.ajax({
            url: 'ajax/create_customer.php',
            method: 'POST',
            data: requestBody,
            dataType: 'json',
            success: function(res) {
                customerStatus.innerHTML = '<?php echo hesk_makeJsString($hesklang['success']); ?>';
                customerStatus.classList.add('success');
                incrementSuccess();

                doUpload(index + 1);
            },
            error: function(err) {
                customerStatus.innerHTML = '<?php echo hesk_makeJsString($hesklang['error']) ?> - ';
                customerStatus.innerHTML += JSON.parse(err.responseText).message;
                customerStatus.classList.add('failed');
                incrementFailed();

                doUpload(index + 1);
            }
        });
    }

    function incrementSuccess() {
        UPLOAD.successfulUploads++;
        document.querySelector('[data-stat="successes"]').innerHTML = UPLOAD.successfulUploads;
        updateProgress();
    }

    function incrementFailed() {
        UPLOAD.failedUploads++;
        document.querySelector('[data-stat="failures"]').innerHTML = UPLOAD.failedUploads;
        updateProgress();
    }

    function updateProgress() {
        document.querySelector('[data-stat="finished-uploads"]').innerHTML = UPLOAD.totalUploads();

        document.querySelector('[data-stat="percent-uploaded"]').innerHTML =
            ((UPLOAD.totalUploads() / (UPLOAD.contents.length - 1)) * 100).toFixed(0);
    }
</script>
<?php

require_once(HESK_PATH . 'inc/footer.inc.php');
knowledgebase_private.php
wget 'https://lists2.roe3.org/hesk/admin/knowledgebase_private.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Is Knowledgebase enabled? */
if ( ! $hesk_settings['kb_enable'])
{
	hesk_error($hesklang['kbdis']);
}

/* Can this user manage Knowledgebase or just view it? */
$can_man_kb = hesk_checkPermission('can_man_kb',0);

require(HESK_PATH . 'inc/knowledgebase_functions.inc.php');

/* Any category ID set? */
$catid = intval( hesk_GET('category', 1) );
$artid = intval( hesk_GET('article', 0) );

if (isset($_GET['search']))
{
	$query = hesk_input( hesk_GET('search') );
}
else
{
	$query = 0;
}

$hesk_settings['kb_link'] = ($artid || $catid != 1 || $query) ? '<a href="knowledgebase_private.php" class="smaller">'.$hesklang['gopr'].'</a>' : ($can_man_kb ? $hesklang['gopr'] : '');

if ($hesk_settings['kb_search'] && $query)
{
    hesk_kb_search($query);
}
elseif ($artid)
{
	// Show drafts only to staff who can manage knowledgebase
	if ($can_man_kb)
	{
		$result = hesk_dbQuery("SELECT t1.*, t2.`name` AS `cat_name`, t2.`type` AS `cat_type`
		FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` AS `t1`
		LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` AS `t2` ON `t1`.`catid` = `t2`.`id`
		WHERE `t1`.`id` = '{$artid}'
		");
	}
	else
	{
		$result = hesk_dbQuery("SELECT t1.*, t2.`name` AS `cat_name`, t2.`type` AS `cat_type`
		FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` AS `t1`
		LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` AS `t2` ON `t1`.`catid` = `t2`.`id`
		WHERE `t1`.`id` = '{$artid}' AND `t1`.`type` IN ('0', '1')
		");
	}

    $article = hesk_dbFetchAssoc($result) or hesk_error($hesklang['kb_art_id']);
    $article['views_formatted'] = number_format($article['views'], 0, null, $hesklang['sep_1000']);
    $article['votes_formatted'] = number_format($article['votes'], 0, null, $hesklang['sep_1000']);
    if ($article['catid'] == 1)
    {
        $article['cat_name'] = $hesklang['kb_text'];
    }
    hesk_show_kb_article($artid);
}
else
{
	hesk_show_kb_category($catid);
}

require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/

function hesk_kb_header()
{
    // They may be unused here, but they're used down the line. Don't delete
	global $hesk_settings, $hesklang, $can_man_kb;

	/* Print admin navigation */
	require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

    hesk_kbSearchLarge(1);
} // END hesk_kb_header()


function hesk_kb_search($query)
{
	global $hesk_settings, $hesklang;

	/* Print header */
	require_once(HESK_PATH . 'inc/header.inc.php');
	hesk_kb_header();

	$res = hesk_dbQuery('SELECT t1.`id`, t1.`subject`, LEFT(`t1`.`content`, '.max(200, $hesk_settings['kb_substrart'] * 2).') AS `content`, t1.`rating` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_articles` AS t1 LEFT JOIN `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` AS t2 ON t1.`catid` = t2.`id` '." WHERE t1.`type` IN ('0','1') AND MATCH(`subject`,`content`,`keywords`) AGAINST ('".hesk_dbEscape($query)."') LIMIT ".intval($hesk_settings['kb_search_limit']));
    $num = hesk_dbNumRows($res);

    ?>



	<?php
	if ($num == 0)
	{
		hesk_show_info($hesklang['nosr']);
        hesk_show_kb_category(1,1);
	}
    else
    {
?>
<div class="main__content categories">
    <div class="table-wrap">
        <h3 style="font-size: 1.3rem"><?php echo $hesklang['sr']; ?> (<?php echo $num; ?>)</h3>
        <?php
        while ($article = hesk_dbFetchAssoc($res))
        {
            $txt = hesk_kbArticleContentPreview($article['content']);

            if ($hesk_settings['kb_rating'])
            {
                $alt = $article['rating'] ? sprintf($hesklang['kb_rated'], sprintf("%01.1f", $article['rating'])) : $hesklang['kb_not_rated'];
                $rat = hesk3_get_rating($article['rating']);
            }
            else
            {
                $rat = '';
            }

            echo '
                <div>
                    <div>
                        <svg class="icon icon-note" style="fill: #9c9c9c">
                            <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-note"></use>
                        </svg>
                        <a class="link" href="knowledgebase_private.php?article='.$article['id'].'">'.$article['subject'].'</a>
                        '.$rat.'
                    </div>  
                    <div>
                        <svg class="icon icon-note" style="visibility: hidden">
                            <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-note"></use>
                        </svg>
                        <span class="article_list">'.$txt.'</span>
                    </div>              
                </div>';
        }
        ?>
        <div style="padding-top: 20px">
            <a href="javascript:history.go(-1)">
                <svg class="icon icon-back" style="width: 20px">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                </svg>
                <?php echo $hesklang['back']; ?>
            </a>
        </div>
    </div>
</div>
    <?php
    } // END else

} // END hesk_kb_search()


function hesk_show_kb_article($artid)
{
	global $hesk_settings, $hesklang, $article, $can_man_kb;

    // We should style <code> elemenets here
    define('STYLE_CODE',1);
    define('TIMEAGO',1);

	// Print header
    $hesk_settings['tmp_title'] = $article['subject'];
	require_once(HESK_PATH . 'inc/header.inc.php');
	hesk_kb_header();

    // Update views by 1
	hesk_dbQuery('UPDATE `'.hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` SET `views`=`views`+1 WHERE `id`={$artid}");
    $article['views']++;
    $article['views_formatted'] = number_format($article['views'], 0, null, $hesklang['sep_1000']);
?>
    <div class="main__content knowledge article">
        <div class="article__detalies">
            <div class="article__detalies_head">
                <h3><?php echo $hesklang['ad']; ?></h3>
                <?php

                if ($article['catid']==1)
                {
                    $link = 'knowledgebase_private.php';
                }
                else
                {
                    $link = 'knowledgebase_private.php?category='.$article['catid'];
                }
                ?>
            </div>
            <ul class="article__detalies_list">
                <li>
                    <div class="name"><?php echo $hesklang['aid']; ?></div>
                    <div class="descr">
                        <?php echo $article['id']; ?>
                        <?php
                        if ($article['type'] == 0 && $article['cat_type'] != 1)
                        {
                            echo '<a href="' . $hesk_settings['hesk_url'] . '/knowledgebase.php?article=' . $article['id'] . '">' . $hesklang['public_link'] . '</a>';
                        }
                        ?>
                    </div>
                </li>
                <li>
                    <div class="name"><?php echo $hesklang['category']; ?></div>
                    <div class="descr">
                        <a style="margin-left: 0" href="<?php echo $link; ?>"><?php echo $article['cat_name']; ?></a>
                    </div>
                </li>
                <li>
                    <div class="name"><?php echo $hesklang['dta']; ?></div>
                    <div class="descr">
                        <time class="timeago tooltip" datetime="<?php echo date("c", strtotime($article['dt'])) ; ?>" title="<?php echo hesk_date($article['dt'], true); ?>"><?php echo hesk_date($article['dt'], true); ?></time>
                    </div>
                </li>
                <li>
                    <div class="name"><?php echo $hesklang['views']; ?></div>
                    <div class="descr"><?php echo $article['views_formatted']; ?></div>
                </li>
                <?php
                if ($hesk_settings['kb_rating']) {
                    ?>
                    <li>
                        <div class="name"><?php echo $hesklang['rating']; ?> (<?php echo $hesklang['votes']; ?>)</div>
                        <div class="descr">
                            <div class="rate"><?php echo hesk3_get_rating($article['rating']); ?> <span>(<?php echo $article['votes_formatted']; ?>)</span></div>
                        </div>
                    </li>
                    <?php
                }
                ?>
            </ul>
            <?php if ($can_man_kb) {
                ?>
                <div class="article__detalies_action">
                    <a href="manage_knowledgebase.php?a=edit_article&amp;id=<?php echo $artid; ?>" class="btn btn btn--blue-border" ripple="ripple"><?php echo $hesklang['kb_art_edit']; ?><div class="ripple--container"></div></a>
                </div>
                <?php
            }
            ?>
        </div>
        <div class="article__body">
            <?php
            if (!isset($_GET['back']))
            {
                ?>
                <div class="article__back">
                    <a href="javascript:history.go(-1)">
                        <svg class="icon icon-back">
                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                        </svg>
                        <?php echo $hesklang['back']; ?>
                    </a>
                </div>
                <?php
            }
            ?>
            <h2><?php echo $article['subject']; ?></h2>
            <div class="article__description browser-default">
                <?php echo $article['content']; ?>

            </div>
            <div class="article__attachments" style="margin-top: 20px">
                <?php
                if (!empty($article['attachments']))
                {
                    $att=explode(',',substr($article['attachments'], 0, -1));
                    foreach ($att as $myatt)
                    {
                        list($att_id, $att_name) = explode('#', $myatt);
                        echo '
                        <svg class="icon icon-attach" style="fill: #9c9c9c">
                            <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-attach"></use>
                        </svg>
                        <a class="link" href="download_attachment.php?kb_att='.$att_id.'" rel="nofollow">
                            '.$att_name.'
                        </a><br>';
                    }
                }
                ?>
            </div>
            <?php
            // Related articles
            if ($hesk_settings['kb_related'])
            {
                require(HESK_PATH . 'inc/mail/email_parser.php');

                $query = hesk_dbEscape( $article['subject'] . ' ' . convert_html_to_text($article['content']) );

                // Get relevant articles from the database
                $res = hesk_dbQuery("SELECT `id`, `subject`, MATCH(`subject`,`content`,`keywords`) AGAINST ('{$query}') AS `score` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `type` IN ('0','1') AND MATCH(`subject`,`content`,`keywords`) AGAINST ('{$query}') LIMIT ".intval($hesk_settings['kb_related']+1));

                // Array with related articles
                $related_articles = array();

                while ($related = hesk_dbFetchAssoc($res))
                {
                    // Get base match score from the first article
                    if ( ! isset($base_score) )
                    {
                        $base_score = $related['score'];
                    }

                    // Ignore this article
                    if ( $related['id'] == $artid )
                    {
                        continue;
                    }

                    // Stop when articles reach less than 10% of base score
                    if ($related['score'] / $base_score < 0.10)
                    {
                        break;
                    }

                    // This is a valid related article
                    $related_articles[$related['id']] = $related['subject'];
                }

                // Print related articles if we have any valid matches
                if ( count($related_articles) )
                {
                    echo '<div class="article__related">';
                    echo '<h4>'.$hesklang['relart'].'</h4>';
                    foreach ($related_articles as $id => $subject)
                    {
                        echo '<p><a href="knowledgebase_private.php?article='.$id.'">'.$subject.'</a></p>';
                    }
                    echo '</div>';
                }
            }
            ?>
        </div>
    </div>
    <?php
} // END hesk_show_kb_article()


function hesk_show_kb_category($catid, $is_search = 0) {
	global $hesk_settings, $hesklang;

    if ($is_search == 0)
    {
		/* Print header */
		require_once(HESK_PATH . 'inc/header.inc.php');
		hesk_kb_header();

		if ($catid == 1)
	    {
	    	echo '<span style="padding-left: 16px">' . $hesklang['priv'] . '</span>';
	    }
    }

	$res = hesk_dbQuery("SELECT `name`,`parent` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` WHERE `id`='".intval($catid)."' LIMIT 1");
    $thiscat = hesk_dbFetchAssoc($res) or hesk_error($hesklang['kb_cat_inv']);

	if ($thiscat['parent'])
	{
		$link = ($thiscat['parent'] == 1) ? 'knowledgebase_private.php' : 'knowledgebase_private.php?category='.$thiscat['parent'];
		echo '<span class="homepageh3" style="font-size: 1.4rem; padding-left: 16px">'.$hesklang['kb_cat'].': '.$thiscat['name'].'
        &nbsp;(<a style="display: inline" class="link" href="javascript:history.go(-1)">'.$hesklang['back'].'</a>)</span>
		';
	}

    ?>
    <div class="main__content knowledge">
        <h3 style="font-size: 1.3rem"><?php echo $hesklang['kb_cat_sub']; ?></h3>
        <div class="knowledge__tabs">
            <div class="knowledge__tabs_tab" style="display: flex">
    <?php

	$result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` WHERE `parent`='".intval($catid)."' ORDER BY `parent` ASC, `cat_order` ASC");
	if (hesk_dbNumRows($result) > 0)
	{
        $i = 1;

        while ($cat = hesk_dbFetchAssoc($result))
        {

            $private = ($cat['type'] == 1) ? ' *' : '';
            ?>
            <div class="knowledge__list">
                <div class="knowledge__list_item">
                    <div class="item--head">
                        <a class="link not-underlined" href="knowledgebase_private.php?category=<?php echo $cat['id']; ?>">
                            <h3>
                                <svg class="icon icon-knowledge" style="fill: #9c9c9c">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-knowledge"></use>
                                </svg>
                                <?php echo $cat['name'].$private; ?>
                            </h3>
                        </a>
                    </div>
                    <ul class="item--list">
                    <?php
                    if (!$hesk_settings['kb_numshow'] || (!$cat['articles'] && !$cat['articles_private'])) {
                        echo '<li><h5>'.$hesklang['noac'].'</h5></li>';
                    }

                    /* Print most popular/sticky articles */
                    if ($hesk_settings['kb_numshow'] && ($cat['articles'] || $cat['articles_private']))
                    {
                        $res = hesk_dbQuery("SELECT `id`,`subject`,`type` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `catid`='".intval($cat['id'])."' AND `type` IN ('0','1') ORDER BY `sticky` DESC, `views` DESC, `art_order` ASC LIMIT " . (intval($hesk_settings['kb_numshow']) + 1) );
                        $num = 1;
                        while ($art = hesk_dbFetchAssoc($res))
                        {
                            $private = ($art['type'] == 1) ? ' *' : '';
                            ?>
                            <li>
                                <h5>
                                    <a href="knowledgebase_private.php?article=<?php echo $art['id']; ?>" class="article">
                                        <svg class="icon icon-note">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-note"></use>
                                        </svg>
                                        <?php echo $art['subject']; ?>
                                        <?php echo $private; ?>
                                    </a>
                                </h5>
                            </li>
                            <?php

                            if ($num == $hesk_settings['kb_numshow'])
                            {
                                break;
                            }
                            else
                            {
                                $num++;
                            }
                        }
                        if (hesk_dbNumRows($res) > $hesk_settings['kb_numshow'])
                        {
                            echo '
                            <div class="all">
                                <a class="link" href="knowledgebase_private.php?category='. $cat['id'] .'">'.$hesklang['m'].'</a>
                            </div>
                            ';
                        }
                    }
                    ?>
                    </ul>
                </div>
            </div>
            <?php
        }
        ?>
	<?php
	} // END if NumRows > 0
	?>
        </div>
    </div>
    <div class="table-wrap" style="margin-top: 20px">
        <h3 style="font-size: 1.3rem"><?php echo $hesklang['ac']; ?></h3>
        <?php
        $res = hesk_dbQuery("SELECT `id`, `subject`, LEFT(`content`, ".max(200, $hesk_settings['kb_substrart'] * 2).") AS `content`, `rating`, `type` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `catid`='".intval($catid)."' AND `type` IN ('0','1') ORDER BY `sticky` DESC, `art_order` ASC");
        if (hesk_dbNumRows($res) == 0)
        {
            echo '<p><i>'.$hesklang['noac'].'</i></p>';
        }
        else
        {
            while ($article = hesk_dbFetchAssoc($res))
            {
                $private = ($article['type'] == 1) ? ' *' : '';

                $txt = hesk_kbArticleContentPreview($article['content']);

                echo '
				<div style="margin: 10px 0">
				    <svg class="icon icon-note" style="fill: #9c9c9c">
                        <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-note"></use>
                    </svg>
                    <a class="link" href="knowledgebase_private.php?article='.$article['id'].'">'.$article['subject'].'</a>'.$private.'
                    <br>
                    <svg class="icon icon-note" style="visibility: hidden">
                        <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-note"></use>
                    </svg>
                    <span class="article_list">'.$txt.'</span>
				</div>';
            }
        }
        ?>
    </div>
</div>
<?php
} // END hesk_show_kb_category()
?>
lock.php
wget 'https://lists2.roe3.org/hesk/admin/lock.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
hesk_checkPermission('can_view_tickets');
hesk_checkPermission('can_reply_tickets');
hesk_checkPermission('can_resolve');

/* A security check */
hesk_token_check();

/* Ticket ID */
$trackingID = hesk_cleanID() or die($hesklang['int_error'].': '.$hesklang['no_trackID']);
hesk_verifyStaffTicketAccess($trackingID);

/* New locked status */
if (empty($_GET['locked']))
{
	$status = 0;
	$tmp = $hesklang['tunlock'];
    $revision = sprintf($hesklang['thist6'],hesk_date(),addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
	$closedby_sql = ' , `closedat`=NULL, `closedby`=NULL ';
}
else
{
	$status = 1;
	$tmp = $hesklang['tlock'];
    $revision = sprintf($hesklang['thist5'],hesk_date(),addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
	$closedby_sql = ' , `closedat`=NOW(), `closedby`='.intval($_SESSION['id']).' ';

	// Notify customer of closed ticket?
	if ($hesk_settings['notify_closed'])
	{
		// Get ticket info
		$result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `trackid`='".hesk_dbEscape($trackingID)."' LIMIT 1");
		if (hesk_dbNumRows($result) != 1)
		{
			hesk_error($hesklang['ticket_not_found']);
		}
		$ticket = hesk_dbFetchAssoc($result);

		// Notify customer, but only if ticket is not already closed
		if ($ticket['status'] != 3)
		{
			require(HESK_PATH . 'inc/email_functions.inc.php');
            $customers = hesk_get_customers_for_ticket($ticket['id']);
            $customer_emails = array_map(function($customer) { return $customer['email']; }, $customers);
            $customer_names = array_map(function($customer) { return $customer['name']; }, $customers);
            $ticket['email'] = implode(';', $customer_emails);
            $ticket['name'] = implode(';', $customer_names);
			$ticket['dt'] = hesk_date($ticket['dt'], true);
			$ticket['lastchange'] = hesk_date($ticket['lastchange'], true);
            $ticket['due_date'] = hesk_format_due_date($ticket['due_date']);
            $ticket['last_reply_by'] = hesk_getReplierNameArray($ticket);
			hesk_notifyCustomer('ticket_closed');

            $ticket['collaborators'] = hesk_getTicketsCollaboratorIDs($ticket['id']);
            if (count($ticket['collaborators'])) {
                hesk_notifyAssignedStaff(false, 'collaborator_resolved', 'notify_collaborator_resolved', 'notify_collaborator_resolved', array($_SESSION['id']));
            }
		}
	}
}

/* Update database */
hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `status`='3',`locked`='{$status}' $closedby_sql , `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."')  WHERE `trackid`='".hesk_dbEscape($trackingID)."'");

/* Back to ticket page and show a success message */
hesk_process_messages($tmp,'admin_ticket.php?track='.$trackingID.'&Refresh='.rand(10000,99999),'SUCCESS');

mail.php
wget 'https://lists2.roe3.org/hesk/admin/mail.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();
require(HESK_PATH . 'inc/email_functions.inc.php');

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* List of staff */
$admins = array();
$res = hesk_dbQuery("SELECT `id`,`name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `active` = 1 ORDER BY `name` ASC");
while ($row=hesk_dbFetchAssoc($res))
{
	$admins[$row['id']]=$row['name'];
}

/* What folder are we in? */
$hesk_settings['mailtmp']['inbox']  = '
        <a href="mail.php">
            <li>
              <span>' . $hesklang['inbox'] . '</span>
            </li>
        </a>';
$hesk_settings['mailtmp']['outbox']  = '
        <a href="mail.php?folder=outbox">
            <li>
                  <span>' . $hesklang['outbox'] . '</span>
            </li>
        </a>';
$hesk_settings['mailtmp']['new']  = '
        <a href="mail.php?a=new" class="email--new">
            <svg class="icon icon-add">
              <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-add"></use>
            </svg>
            '.$hesklang['m_new'].'
        </a>';

/* Get action */
if ( $action = hesk_REQUEST('a') )
{
	if ( defined('HESK_DEMO') && $action != 'new' && $action != 'read' )
	{
		hesk_process_messages($hesklang['ddemo'], 'mail.php', 'NOTICE');
	}
}

/* Sub-page specific settings */
if (isset($_GET['folder']) && hesk_GET('folder') == 'outbox')
{
	$hesk_settings['mailtmp']['this']   = 'from';
	$hesk_settings['mailtmp']['other']  = 'to';
	$hesk_settings['mailtmp']['m_from'] = $hesklang['m_to'];
    $hesk_settings['mailtmp']['outbox']  = '
        <li class="current">
          <span>' . $hesklang['outbox'] . '</span>
        </li>';
    $hesk_settings['mailtmp']['folder'] = 'outbox';
}
elseif ($action == 'new')
{
	$hesk_settings['mailtmp']['new'] = '
        <a href="mail.php?a=new" class="email--new">
            <svg class="icon icon-add">
              <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-add"></use>
            </svg>
            '.$hesklang['m_new'].'
        </a>';
	$_SESSION['hide']['list'] = 1;

    /* Do we have a recipient selected? */
    if (!isset($_SESSION['mail']['to']) && isset($_GET['id']))
    {
    	$_SESSION['mail']['to'] = intval( hesk_GET('id') );
    }
}
else
{
	$hesk_settings['mailtmp']['this']   = 'to';
	$hesk_settings['mailtmp']['other']  = 'from';
	$hesk_settings['mailtmp']['m_from'] = $hesklang['m_from'];
    if ($action != 'read')
    {
        $hesk_settings['mailtmp']['inbox']  = '
            <li class="current">
              <span>' . $hesklang['inbox'] . '</span>
            </li>';
        $hesk_settings['mailtmp']['folder'] = '';
    }
}

/* What should we do? */
switch ($action)
{
	case 'send':
    	mail_send();
        break;
    case 'mark_read':
    	mail_mark_read();
        break;
    case 'mark_unread':
    	mail_mark_unread();
        break;
    case 'delete':
    	mail_delete();
        break;
}

if ($action == 'read') {
    show_message(false);
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
hesk_handle_messages();
?>

<script language="javascript" type="text/javascript"><!--
function confirm_delete()
{
	if (confirm('<?php echo addslashes($hesklang['delete_saved']); ?>')) {return true;}
	else {return false;}
}
//-->
</script>
<div class="main__content emails">
    <h2><?php echo $hesklang['m_h']; ?></h2>
    <div class="emails__head">
        <ul class="emails__head_tabs">
            <?php
            echo $hesk_settings['mailtmp']['inbox'] . $hesk_settings['mailtmp']['outbox'];
            ?>
        </ul>
        <?php echo $hesk_settings['mailtmp']['new']; ?>
    </div>
    <?php
    /* Show a message? */
    if ($action == 'read')
    {
        show_message();
    }

    /* Hide list of messages? */
    if (!isset($_SESSION['hide']['list']))
    {
        mail_list_messages();
    } // END hide list of messages

    /* Show new message form */
    show_new_form();
    ?>
</div>


<?php

/* Clean unneeded session variables */
hesk_cleanSessionVars('hide');
hesk_cleanSessionVars('mail');

require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/


function mail_delete()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check();

	$ids = mail_get_ids();

	if ($ids)
	{
		foreach ($ids as $id)
        {
        	/* If both correspondents deleted the mail remove it from database, otherwise mark as deleted by this user */
	        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."mail` SET `deletedby`='".intval($_SESSION['id'])."' WHERE `id`='".intval($id)."' AND (`to`='".intval($_SESSION['id'])."' OR `from`='".intval($_SESSION['id'])."') AND `deletedby`=0");

            if (hesk_dbAffectedRows() != 1)
            {
		        hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."mail` WHERE `id`='".intval($id)."' AND (`to`='".intval($_SESSION['id'])."' OR `from`='".intval($_SESSION['id'])."') AND `deletedby`!=0");
            }
        }

		hesk_process_messages($hesklang['smdl'],'NOREDIRECT','SUCCESS');
	}

    return true;
} // END mail_mark_unread()


function mail_mark_unread()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check();

	$ids = mail_get_ids();

	if ($ids)
	{
		foreach ($ids as $id)
        {
	        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."mail` SET `read`='0' WHERE `id`='".intval($id)."' AND `to`='".intval($_SESSION['id'])."'");
        }

		hesk_process_messages($hesklang['smmu'],'NOREDIRECT','SUCCESS');
	}

    return true;
} // END mail_mark_unread()


function mail_mark_read()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check('POST');

	$ids = mail_get_ids();

	if ($ids)
	{
		foreach ($ids as $id)
        {
	        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."mail` SET `read`='1' WHERE `id`='".intval($id)."' AND `to`='".intval($_SESSION['id'])."'");
        }

		hesk_process_messages($hesklang['smmr'],'NOREDIRECT','SUCCESS');
	}

    return true;
} // END mail_mark_read()


function mail_get_ids()
{
	global $hesk_settings, $hesklang;

	// Mail id as a query parameter?
	if ( $id = hesk_GET('id', false) )
	{
		return array($id);
	}
	// Mail id as a post array?
	elseif ( isset($_POST['id']) && is_array($_POST['id']) )
	{
		return array_map('intval', $_POST['id']);
	}
	// No valid ID parameter
	else
	{
		hesk_process_messages($hesklang['nms'],'NOREDIRECT','NOTICE');
		return false;
	}
    
} // END mail_get_ids()


function mail_send()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check('POST');

	$hesk_error_buffer = '';

	/* Recipient */
	$_SESSION['mail']['to'] = intval( hesk_POST('to') );

	/* Valid recipient? */
    if (empty($_SESSION['mail']['to']))
    {
		$hesk_error_buffer .= '<li>' . $hesklang['m_rec'] . '</li>';
    }
	elseif ($_SESSION['mail']['to'] == $_SESSION['id'])
	{
		$hesk_error_buffer .= '<li>' . $hesklang['m_inr'] . '</li>';
	}
	else
	{
		$res = hesk_dbQuery("SELECT `name`,`email`,`notify_pm` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id`='".intval($_SESSION['mail']['to'])."' AND `active` = 1 LIMIT 1");
		$num = hesk_dbNumRows($res);
		if (!$num)
		{
			$hesk_error_buffer .= '<li>' . $hesklang['m_inr'] . '</li>';
		}
        else
        {
        	$pm_recipient = hesk_dbFetchAssoc($res);
        }
	}

	/* Subject */
	$_SESSION['mail']['subject'] = hesk_input( hesk_POST('subject') ) or $hesk_error_buffer .= '<li>' . $hesklang['m_esu'] . '</li>';

	/* Message */
	$_SESSION['mail']['message'] = hesk_input( hesk_POST('message') ) or $hesk_error_buffer .= '<li>' . $hesklang['enter_message'] . '</li>';

	// Attach signature to the message?
	if ( ! empty($_POST['signature']))
	{
		$_SESSION['mail']['message'] .= "\n\n" . addslashes($_SESSION['signature']) . "\n";
	}

	/* Any errors? */
	if (strlen($hesk_error_buffer))
	{
    	$_SESSION['hide']['list'] = 1;
		$hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
		hesk_process_messages($hesk_error_buffer,'NOREDIRECT');
	}
    else
    {
		$_SESSION['mail']['message'] = hesk_makeURL($_SESSION['mail']['message']);
		$_SESSION['mail']['message'] = nl2br($_SESSION['mail']['message']);
        
		hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."mail` (`from`,`to`,`subject`,`message`,`dt`,`read`) VALUES ('".intval($_SESSION['id'])."','".intval($_SESSION['mail']['to'])."','".hesk_dbEscape($_SESSION['mail']['subject'])."','".hesk_dbEscape($_SESSION['mail']['message'])."',NOW(),'0')");

        /* Notify receiver via e-mail? */
        if (isset($pm_recipient) && $pm_recipient['notify_pm'])
        {
            $pm_id = hesk_dbInsertID();

            $pm = array(
				'name'		=> hesk_msgToPlain( addslashes($_SESSION['name']) ,1,1),
				'subject'	=> hesk_msgToPlain($_SESSION['mail']['subject'],1,1),
				'message'	=> hesk_msgToPlain($_SESSION['mail']['message'],1,1),
                'message_html' => $_SESSION['mail']['message'],
				'id'		=> $pm_id,
            );

			/* Format email subject and message for recipient */
			$subject = hesk_getEmailSubject('new_pm',$pm,0);
			list($message, $html_message) = hesk_getEmailMessage('new_pm',$pm,1,0);

			/* Send e-mail */
			hesk_mail($pm_recipient['email'], [], $subject, $message, $html_message);
        }

		unset($_SESSION['mail']);

		hesk_process_messages($hesklang['m_pms'],'./mail.php','SUCCESS');
    }
} // END mail_send()


function show_message($actually_show = true)
{
	global $hesk_settings, $hesklang, $admins;

		$id = intval( hesk_GET('id') );

		/* Get the message details */
		$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."mail` WHERE `id`='".intval($id)."' AND (`to`='".intval($_SESSION['id'])."' OR `from`='".intval($_SESSION['id'])."') AND `deletedby`!='".intval($_SESSION['id'])."' LIMIT 1");
		$num = hesk_dbNumRows($res);

	    if ($num)
	    {
	    	$pm = hesk_dbFetchAssoc($res);

	        /* Allowed to read the message? */
	        if ($pm['to'] == $_SESSION['id'])
	        {

			    if (!isset($_SESSION['mail']['subject']))
			    {
			    	$_SESSION['mail']['subject'] = $hesklang['m_re'] . ' ' . $pm['subject'];
			    }

			    if (!isset($_SESSION['mail']['to']))
			    {
			    	$_SESSION['mail']['to'] = $pm['from'];
			    }

	        }
	        elseif ($pm['from'] == $_SESSION['id'])
	        {

			    if (!isset($_SESSION['mail']['subject']))
			    {
			    	$_SESSION['mail']['subject'] = $hesklang['m_fwd'] . ' ' . $pm['subject'];
			    }

			    if (!isset($_SESSION['mail']['to']))
			    {
			    	$_SESSION['mail']['to'] = $pm['to'];
			    }

				$hesk_settings['mailtmp']['this']   = 'from';
				$hesk_settings['mailtmp']['other']  = 'to';
				$hesk_settings['mailtmp']['m_from'] = $hesklang['m_to'];
				$hesk_settings['mailtmp']['outbox'] = '<b>'.$hesklang['outbox'].'</b>';
				$hesk_settings['mailtmp']['inbox']  = '<a href="mail.php"><li><span>'.$hesklang['inbox'].'</span></li></a>';
				$hesk_settings['mailtmp']['outbox'] = '<a href="mail.php?folder=outbox"><li><span>'.$hesklang['outbox'].'</span></li></a>';

	        }
	        else
	        {
	        	hesk_process_messages($hesklang['m_ena'],'mail.php');
	        }

	        /* Mark as read */
	        if ($hesk_settings['mailtmp']['this'] == 'to' && !$pm['read'])
	        {
				$res = hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."mail` SET `read`='1' WHERE `id`='".intval($id)."'");
	        }

	        $pm['name'] = isset($admins[$pm[$hesk_settings['mailtmp']['other']]]) ? '<a href="mail.php?a=new&amp;id='.$pm[$hesk_settings['mailtmp']['other']].'">'.$admins[$pm[$hesk_settings['mailtmp']['other']]].'</a>' : (($pm['from'] == 9999) ? '<a href="https://www.hesk.com" target="_blank">HESK.com</a>' : $hesklang['e_udel']);
            $pm['dt'] = hesk_date($pm['dt'], true, true, true, $hesk_settings['format_timestamp']);

	        if ($actually_show) {
                ?>
                <div class="email__list_article">
                    <div class="email__list_descr">
                        <div class="head">
                            <button type="button" class="btn btn-empty btn-hide-article">
                                <svg class="icon icon-back">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                                </svg>
                            </button>
                            <div>
                                <h4><?php echo $pm['name']; ?></h4>
                                <h3><?php echo $pm['subject']; ?></h3>
                            </div>
                            <time><?php echo $pm['dt']; ?></time>
                        </div>
                        <div class="body browser-default">
                            <?php echo $pm['message']; ?>
                        </div>
                        <div class="form">
                            <?php
                            $folder = '&amp;folder=outbox';
                            if ($pm['to'] == $_SESSION['id']) {
                                echo '<a class="btn btn--blue-border" href="mail.php?a=mark_unread&amp;id=' . $id . '&amp;token=' . hesk_token_echo(0) . '">' . $hesklang['mau'] . '</a> ';
                                $folder = '';
                            }
                            echo '<a class="btn btn-full inline-flex next" ripple="ripple" href="mail.php?a=delete&amp;id=' . $id . '&amp;token=' . hesk_token_echo(0) . $folder . '" onclick="return hesk_confirmExecute(\'' . hesk_makeJsString($hesklang['delm']) . '?\');">' . $hesklang['delm'] . '</a>';
                            ?>
                        </div>
                    </div>
                </div>
                <?php
            }
	    } // END if $num
        else
        {
            hesk_process_messages($hesklang['m_ena'],'mail.php');
        }

		$_SESSION['hide']['list'] = 1;

} // END show_message()


function mail_list_messages()
{
	global $hesk_settings, $hesklang, $admins;

    $href = 'mail.php';
    $query = '';
    if ($hesk_settings['mailtmp']['folder'] == 'outbox')
    {
    	$query .= 'folder=outbox&amp;';
    }
    $query .= 'page=';

	$maxresults = 30;

	$tmp  = intval( hesk_GET('page', 1) );
	$page = ($tmp > 1) ? $tmp : 1;

	/* List of private messages */
	$res = hesk_dbQuery("SELECT COUNT(*) FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."mail` WHERE `".hesk_dbEscape($hesk_settings['mailtmp']['this'])."`='".intval($_SESSION['id'])."' AND `deletedby`!='".intval($_SESSION['id'])."'");
	$total = hesk_dbResult($res,0,0);

    if ($total > 0)
	{
        $pages = ceil($total/$maxresults) or $pages = 1;
        if ($page > $pages)
        {
            $page = $pages;
        }
        $limit_down = ($page * $maxresults) - $maxresults;

		// Get messages from the database
		$res = hesk_dbQuery("SELECT `id`, `from`, `to`, `subject`, `dt`, `read` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."mail` WHERE `".hesk_dbEscape($hesk_settings['mailtmp']['this'])."`='".intval($_SESSION['id'])."' AND `deletedby`!='".intval($_SESSION['id'])."' ORDER BY `id` DESC LIMIT ".intval($limit_down)." , ".intval($maxresults)." ");
		?>

		<form action="mail.php<?php if ($hesk_settings['mailtmp']['folder'] == 'outbox') {echo '?folder=outbox';} ?>" name="form1" method="post">
            <div style="margin: 16px">
                <table id="default-table" class="table sindu-table">
                    <thead>
                    <tr>
                        <th class="table__first_th sindu_handle" aria-label="<?php echo $hesklang['a_select']; ?>">
                            <div class="checkbox-custom">
                                <input type="checkbox" id="checkbox_selectall" name="checkall" value="2" onclick="hesk_changeAll(this)">
                                <label for="checkbox_selectall" aria-label="<?php echo $hesklang['a_select']; ?>"></label>
                            </div>
                        </th>
                        <th style="border: none"><?php echo $hesklang['m_sub']; ?></th>
                        <th><?php echo $hesk_settings['mailtmp']['m_from']; ?></th>
                        <th><?php echo $hesklang['date']; ?></th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php
                    while ($pm=hesk_dbFetchAssoc($res))
                    {
                        $pm['subject'] = '<a href="mail.php?a=read&amp;id='.$pm['id'].'">'.$pm['subject'].'</a>';
                        if ($hesk_settings['mailtmp']['this'] == 'to' && !$pm['read'])
                        {
                            $pm['subject'] = '<b>'.$pm['subject'].'</b>';
                        }
                        $pm['name'] = isset($admins[$pm[$hesk_settings['mailtmp']['other']]]) ? '<a href="mail.php?a=new&amp;id='.$pm[$hesk_settings['mailtmp']['other']].'">'.$admins[$pm[$hesk_settings['mailtmp']['other']]].'</a>' : (($pm['from'] == 9999) ? '<a href="https://www.hesk.com" target="_blank">HESK.com</a>' : $hesklang['e_udel']);
                        $pm['dt'] = hesk_date($pm['dt'], true, true, true, $hesk_settings['format_date']);
                        $css_class = !$pm['read'] && $pm['to'] == $_SESSION['id'] ? 'class="new"' : '';

                        echo <<<EOC
                <tr $css_class>
                <td class="table__first_td">
                    <div class="checkbox-custom">
                        <input type="checkbox" id="$pm[id]" name="id[]" value="$pm[id]">
                        <label for="$pm[id]" aria-label="$hesklang[select]"></label>
                      </div>
                </td>
                <td style="border: none">$pm[subject]</td>
                <td>$pm[name]</td>
                <td>$pm[dt]</td>
                </tr>
EOC;
                    } // End while
                    ?>
                    </tbody>
                </table>
                <?php

                $prev_page = ($page - 1 <= 0) ? 0 : $page - 1;
                $next_page = ($page + 1 > $pages) ? 0 : $page + 1;

                if ($pages > 1): ?>
                    <div class="pagination-wrap">
                        <div class="pagination">
                            <?php
                            /* List pages */
                            if ($pages >= 7)
                            {
                                if ($page > 2) { ?>
                                    <a href="<?php echo $href.'?'.$query.'1'; ?>" class="btn pagination__nav-btn">
                                        <svg class="icon icon-chevron-left">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-left"></use>
                                        </svg>
                                        <svg class="icon icon-chevron-left">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-left"></use>
                                        </svg>
                                        <span><?php echo $hesklang['pager_first']; ?></span>
                                    </a>
                                <?php }

                                if ($prev_page) { ?>
                                    <a href="<?php echo $href.'?'.$query.$prev_page; ?>" class="btn pagination__nav-btn">
                                        <svg class="icon icon-chevron-left">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-left"></use>
                                        </svg>
                                        <span><?php echo $hesklang['pager_previous']; ?></span>
                                    </a>
                                <?php }
                            }

                            echo '<ul class="pagination__list">';
                            for ($i=1; $i<=$pages; $i++)
                            {
                                if ($i <= ($page+5) && $i >= ($page-5))
                                {
                                    if ($i == $page) {
                                        echo '
                                <li class="pagination__item is-current">
                                    <a href="#" class="pagination__link">' . $i . '</a>
                                </li>';
                                    }
                                    else
                                    {
                                        echo '
                                <li class="pagination__item ">
                                    <a href="'.$href.'?'.$query.$i.'" class="pagination__link">' . $i . '</a>';
                                    }
                                }
                            }
                            echo '</ul>';

                            if ($pages >= 7) {
                                if ($next_page) { ?>
                                    <a href="<?php echo $href.'?'.$query.$next_page; ?>" class="btn pagination__nav-btn">
                                        <span><?php echo $hesklang['pager_next']; ?></span>
                                        <svg class="icon icon-chevron-right">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-right"></use>
                                        </svg>
                                    </a>
                                <?php }

                                if ($page < ($pages - 1)) { ?>
                                    <a href="<?php echo $href.'?'.$query.$pages; ?>" class="btn pagination__nav-btn">
                                        <span><?php echo $hesklang['pager_last']; ?></span>
                                        <svg class="icon icon-chevron-right">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-right"></use>
                                        </svg>
                                        <svg class="icon icon-chevron-right">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-right"></use>
                                        </svg>
                                    </a>
                                <?php }
                            }

                            echo '<br />&nbsp;
                                </div>
                            </div>
                            ';

                            endif; // end PAGES > 1
                            ?>

                <div class="actions" style="display: flex; margin-top: 16px;">
                    <select name="a" id="email-batch-process" autocomplete="off">
                        <?php
                        if ($hesk_settings['mailtmp']['this'] == 'to')
                        {
                            ?>
                            <option value="mark_read" selected="selected"><?php echo $hesklang['mo1']; ?></option>
                            <option value="mark_unread"><?php echo $hesklang['mo2']; ?></option>
                            <?php
                        }
                        ?>
                        <option value="delete"><?php echo $hesklang['mo3']; ?></option>
                    </select>
                    <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
                    <button style="margin-left: 5px" class="btn btn-full" ripple="ripple" type="submit" onclick="Javascript:if (document.form1.a.value=='delete') return hesk_confirmExecute('<?php echo hesk_makeJsString($hesklang['mo3']); ?>?');">
                        <?php echo $hesklang['execute']; ?>
                    </button>
                </div>
            </div>
		</form>
	    <?php
	} // END if total > 0
    else
    {
        hesk_show_info($hesklang['npm']);
    }

} // END mail_list_messages()


function show_new_form()
{
	global $hesk_settings, $hesklang, $admins;
	?>
    <h2 style="margin-top: 20px"><?php echo $hesklang['new_mail']; ?></h2>
    <div class="new-message">
        <form action="mail.php" method="post" name="form2" class="form" aria-label="<?php echo $hesklang['new_mail']; ?>">
            <div class="form-group">
                <label for="email-create-destination"><?php echo $hesklang['m_to']; ?></label>
                <select name="to" id="email-create-destination" autocomplete="off">
                    <option value="" selected="selected"><?php echo $hesklang['select']; ?></option>
                    <?php
                    foreach ($admins as $k=>$v) {
                        if ($k != $_SESSION['id']) {
                            if (isset($_SESSION['mail']) && $k == $_SESSION['mail']['to']) {
                                echo '<option value="'.$k.'" selected>'.$v.'</option>';
                            } else {
                                echo '<option value="'.$k.'">'.$v.'</option>';
                            }
                        }
                    }
                    ?>
                </select>
            </div>
            <div class="form-group">
                <label for="m_subject"><?php echo $hesklang['m_sub']; ?></label>
                <input type="text" class="form-control" name="subject" id="m_subject" maxlength="50"
                    <?php
                    if (isset($_SESSION['mail']['subject'])) {
                        echo ' value="'.stripslashes($_SESSION['mail']['subject']).'" ';
                    }
                    ?>
                >
            </div>
            <div class="form-group">
                <label for="m_message"><?php echo $hesklang['message']; ?></label>
                <textarea style="height: inherit" class="form-control" id="m_message" name="message" rows="15" cols="70"><?php
                    if (isset($_SESSION['mail']['message']))
                    {
                        echo stripslashes($_SESSION['mail']['message']);
                    }
                    ?></textarea>
            </div>
            <div class="checkbox-custom">
                <input type="checkbox" id="m_signature" name="signature" value="1" checked="checked" />
                <label for="m_signature"><?php echo $hesklang['attach_sign']; ?></label>&nbsp;(<a href="profile.php"><?php echo $hesklang['profile_settings']; ?></a>)
            </div>
            <div style="margin-top: 10px">
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
                <input type="hidden" name="a" value="send" />
                <button class="btn btn-full" type="submit"><?php echo $hesklang['m_send']; ?></button>
            </div>
        </form>
    </div>
    <?php
} // END show_new_form()
?>
manage_canned.php
wget 'https://lists2.roe3.org/hesk/admin/manage_canned.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
hesk_checkPermission('can_man_canned');

// Load custom fields
require_once(HESK_PATH . 'inc/custom_fields.inc.php');

// Define required constants
define('LOAD_TABS',1);

if ($hesk_settings['staff_ticket_formatting'] == 2) {
    define('WYSIWYG',1);
}

/* What should we do? */
if ( $action = hesk_REQUEST('a') )
{
	if ( defined('HESK_DEMO') )  {hesk_process_messages($hesklang['ddemo'], 'manage_canned.php', 'NOTICE');}
	elseif ($action == 'new')    {new_saved();}
	elseif ($action == 'edit')   {edit_saved();}
	elseif ($action == 'remove') {remove();}
	elseif ($action == 'order')  {order_saved();}
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');
?>
<script language="javascript" type="text/javascript"><!--
function confirm_delete()
{
if (confirm('<?php echo hesk_makeJsString($hesklang['delete_saved']); ?>')) {return true;}
else {return false;}
}

var heskManageTemplateSubmitting = false;
function hesk_disableTemplateSubmit(buttonID)
{
    if (heskManageTemplateSubmitting)
    {
        return false;
    }

    heskManageTemplateSubmitting = true;

    var button = document.getElementById(buttonID);
    if (button)
    {
        button.disabled = true;
        button.innerHTML = '<?php echo hesk_makeJsString($hesklang['please_wait']); ?>';
    }

    return true;
}

function hesk_insertRichTag(tag) {
    var text_to_insert = '%%'+tag+'%%';
    <?php if ($hesk_settings['staff_ticket_formatting'] == 2): ?>
        tinymce.get("canned_message").execCommand('mceInsertContent', false, text_to_insert);
    <?php else: ?>
        hesk_insertAtCursor(document.getElementById('canned_message'), text_to_insert);
        document.getElementById('canned_message').focus();
    <?php endif; ?>
}
//-->
</script>
<?php
/* This will handle error, success and notice messages */
if (!isset($_SESSION['canned']['what'])) {
    hesk_handle_messages();
}

// Get canned responses from database
$result = hesk_dbQuery('SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'std_replies` ORDER BY `reply_order` ASC');
$options='';
$javascript_messages='';
$javascript_titles='';

$i=1;
$j=0;
$num = hesk_dbNumRows($result);
?>
<div class="main__content templates">
    <section class="templates__head">
        <h2>
            <?php echo $hesklang['manage_saved']; ?>
            <div class="tooltype right out-close">
                <svg class="icon icon-info">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                </svg>
                <div class="tooltype__content">
                    <div class="tooltype__wrapper">
                        <?php echo $hesklang['manage_intro']; ?>
                    </div>
                </div>
            </div>
        </h2>
        <div class="btn btn--blue-border" ripple="ripple" data-action="create-template" onclick="displayAddTitle()"><?php echo $hesklang['canned_add']; ?></div>
    </section>
    <ul class="response__list">
        <?php if ($num < 1): ?>
            <li><h3><?php echo $hesklang['no_saved']; ?></h3></li>
        <?php
        endif;

        while ($mysaved=hesk_dbFetchAssoc($result))
        {
            $j++;

            $table_row = '';
            if (isset($_SESSION['canned']['selcat2']) && $mysaved['id'] == $_SESSION['canned']['selcat2']) {
                $table_row = 'class="ticket-new"';
                unset($_SESSION['canned']['selcat2']);
            }

            $options .= '<option value="'.$mysaved['id'].'"';
            $options .= (isset($_SESSION['canned']['id']) && $_SESSION['canned']['id'] == $mysaved['id']) ? ' selected="selected" ' : '';
            $options .= '>'.$mysaved['title'].'</option>';

            $message_text = $hesk_settings['staff_ticket_formatting'] == 2 ? $mysaved['message_html'] : $mysaved['message'];

            $javascript_messages.='myMsgTxt['.$mysaved['id'].']='.hesk_json_encode_for_js($message_text).";\n";
            $javascript_titles.='myTitle['.$mysaved['id'].']='.hesk_json_encode_for_js($mysaved['title']).";\n";

            echo '
	    <li '.$table_row.'>
	    <h3>'.$mysaved['title'].'</h3>
        ';

            if ($num > 1)
            {
                if ($j == 1)
                {
                    echo'
                    <a href="#" style="visibility: hidden">
                        <svg class="icon icon-chevron-down">
                            <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-chevron-down"></use>
                        </svg>
                    </a>
                    <a class="tooltip" title="'.$hesklang['move_dn'].'" href="manage_canned.php?a=order&amp;replyid='.$mysaved['id'].'&amp;move=15&amp;token='.hesk_token_echo(0).'">
                        <svg class="icon icon-chevron-down">
                            <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-chevron-down"></use>
                        </svg>
                    </a>';
                }
                elseif ($j == $num)
                {
                    echo'
                    <a class="tooltip" title="'.$hesklang['move_up'].'" href="manage_canned.php?a=order&amp;replyid='.$mysaved['id'].'&amp;move=-15&amp;token='.hesk_token_echo(0).'">
                        <svg class="icon icon-chevron-up">
                            <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-chevron-down"></use>
                        </svg>
                    </a>
                    <a href="#" style="visibility: hidden">
                        <svg class="icon icon-chevron-down">
                            <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-chevron-down"></use>
                        </svg>
                    </a>';
                }
                else
                {
                    echo'
                    <a class="tooltip" title="'.$hesklang['move_up'].'" href="manage_canned.php?a=order&amp;replyid='.$mysaved['id'].'&amp;move=-15&amp;token='.hesk_token_echo(0).'">
                        <svg class="icon icon-chevron-up">
                            <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-chevron-down"></use>
                        </svg>
                    </a>
                    <a class="tooltip" title="'.$hesklang['move_dn'].'" href="manage_canned.php?a=order&amp;replyid='.$mysaved['id'].'&amp;move=15&amp;token='.hesk_token_echo(0).'">
                        <svg class="icon icon-chevron-down">
                            <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-chevron-down"></use>
                        </svg>
                    </a>';
                }
            }
            else
            {
                echo '';
            }

            $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                $hesklang['delete_saved'],
                'manage_canned.php?a=remove&amp;id='.$mysaved['id'].'&amp;token='.hesk_token_echo(0));

            echo '
            <a class="tooltip" title="'.$hesklang['edit'].'" href="javascript:setMessage(' . $mysaved['id'] . ')">
                <svg class="icon icon-edit-ticket">
                    <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-edit-ticket"></use>
                </svg>
            </a>
            <a class="tooltip" title="'.$hesklang['remove'].'" href="javascript:" data-modal="[data-modal-id=\''.$modal_id.'\']">
                <svg class="icon icon-delete">
                    <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-delete"></use>
                </svg>
            </a>
	    </li>
		';
        } // End while
        ?>
    </ul>
</div>
<div class="right-bar template-create" <?php if (isset($_SESSION['canned']['what'])) { echo 'style="display: block"'; } ?>>
    <div class="right-bar__body template-create__body">
        <h3>
            <a href="javascript:">
                <svg class="icon icon-back">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                </svg>
                <span <?php if (isset($_SESSION['canned']['what']) && $_SESSION['canned']['what'] !== 'NEW') { echo 'style="display: none"'; } ?> id="add-title"><?php echo $hesklang['canned_add']; ?></span>
                <span <?php if (isset($_SESSION['canned']['what']) && $_SESSION['canned']['what'] !== 'EDIT') { echo 'style="display: none"'; } ?> id="edit-title"><?php echo $hesklang['canned_edit']; ?></span>
            </a>
        </h3>
        <div class="form">
            <?php
            /* This will handle error, success and notice messages */
            if (isset($_SESSION['canned']['what'])) {
                echo '<div style="margin: -24px -24px 10px -16px;">';
                hesk_handle_messages();
                echo '</div>';
            }

            $errors = hesk_SESSION(array('canned', 'errors'));
            $errors = is_array($errors) ? $errors : array();
            ?>
            <form action="manage_canned.php" method="post" name="form1" class="form <?php echo hesk_SESSION(array('canned', 'errors')) ? 'invalid' : ''; ?>" aria-label="<?php echo $hesklang['can_man_canned']; ?>" onsubmit="return hesk_disableTemplateSubmit('canned-submit');">
                <div class="form-group">
                    <label for="canned_title"><?php echo $hesklang['saved_title']; ?></label>
                    <span id="HeskTitle">
                        <input type="text" class="form-control <?php echo in_array('name', $errors) ? 'isError' : ''; ?>" id="canned_title" name="name" maxlength="50"
                            <?php if (isset($_SESSION['canned']['name'])) {echo ' value="'.stripslashes($_SESSION['canned']['name']).'" ';} ?>>
                    </span>
                </div>
                <div class="form-group">
                    <label for="canned_message"><?php echo $hesklang['message']; ?></label>
                    <span id="HeskMsg">
                        <textarea class="form-control <?php echo in_array('msg', $errors) ? 'isError' : ''; ?>" name="msg" rows="40" cols="70" id="canned_message" style="resize: vertical; transition: none;"><?php
                            if (isset($_SESSION['canned']['msg'])) {
                                echo stripslashes($_SESSION['canned']['msg']);
                            }
                            ?></textarea>
                    </span>
                    <?php
                        if ($hesk_settings['staff_ticket_formatting'] == 2) {
                            hesk_tinymce_init('#canned_message');
                        }
                    ?>
                </div>
                <div class="template--tags">
                    <label><?php echo $hesklang['insert_special']; ?></label>
                    <div class="tag-list">
                        <a href="javascript:" onclick="hesk_insertRichTag('HESK_ID')">
                            <?php echo $hesklang['seqid']; ?>
                        </a>
                        <a href="javascript:" onclick="hesk_insertRichTag('HESK_TRACK_ID')">
                            <?php echo $hesklang['trackID']; ?>
                        </a>
                        <a href="javascript:" onclick="hesk_insertRichTag('HESK_SUBJECT')">
                            <?php echo $hesklang['subject']; ?>
                        </a>
                        <a href="javascript:" onclick="hesk_insertRichTag('HESK_REQUESTER')">
                            <?php echo $hesklang['email_tag_requester']; ?>
                        </a>
                        <a href="javascript:" onclick="hesk_insertRichTag('HESK_REQUESTER_NAME')">
                            <?php echo $hesklang['email_tag_requester_name']; ?>
                        </a>
                        <a href="javascript:" onclick="hesk_insertRichTag('HESK_REQUESTER_FIRST_NAME')">
                            <?php echo $hesklang['email_tag_requester_first_name']; ?>
                        </a>
                        <a href="javascript:" onclick="hesk_insertRichTag('HESK_REQUESTER_EMAIL')">
                            <?php echo $hesklang['email_tag_requester_email']; ?>
                        </a>
                        <a href="javascript:" onclick="hesk_insertRichTag('HESK_FOLLOWERS')">
                            <?php echo $hesklang['email_tag_followers']; ?>
                        </a>
                        <a href="javascript:" onclick="hesk_insertRichTag('HESK_FOLLOWER_NAMES')">
                            <?php echo $hesklang['email_tag_follower_names']; ?>
                        </a>
                        <a href="javascript:" onclick="hesk_insertRichTag('HESK_FOLLOWER_EMAILS')">
                            <?php echo $hesklang['email_tag_follower_emails']; ?>
                        </a>
                        <a href="javascript:" onclick="hesk_insertRichTag('HESK_OWNER')">
                            <?php echo $hesklang['owner']; ?>
                        </a>
                        <a href="javascript:" onclick="hesk_insertRichTag('HESK_CATEGORY')">
                            <?php echo $hesklang['category']; ?>
                        </a>
                        <a href="javascript:" onclick="hesk_insertRichTag('HESK_DUE_DATE')">
                            <?php echo $hesklang['due_date']; ?>
                        </a>
                        <?php
                        foreach ($hesk_settings['custom_fields'] as $k=>$v) {
                            if ($v['use']) {
                                echo '<a href="javascript:" onclick="hesk_insertRichTag(\'HESK_'.$k.'\')">'.$v['name'].'</a>';
                            }
                        }
                        ?>
                    </div>
                </div>
                <div class="template--submit">
                    <?php if(isset($_SESSION['canned']['what']) && $_SESSION['canned']['what'] == 'EDIT'): ?>
                        <input type="hidden" name="a" value="edit">
                        <input type="hidden" name="saved_replies" value="<?php echo $_SESSION['canned']['id']; ?>">
                    <?php else: ?>
                        <input type="hidden" name="a" value="new">
                        <input type="hidden" name="saved_replies" value="0">
                    <?php endif; ?>
                    <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                    <button type="submit" class="btn btn-full" ripple="ripple" id="canned-submit"><?php echo $hesklang['save_reply']; ?></button>
                </div>
            </form>
        </div>
    </div>
</div>
<script language="javascript" type="text/javascript"><!--
var myMsgTxt = new Array();
myMsgTxt[0]='';
var myTitle = new Array();
myTitle[0]='';

<?php
echo $javascript_titles;
echo $javascript_messages;
?>

function heskDecodeHtmlEntities(value)
{
    var textarea = document.createElement('textarea');
    textarea.innerHTML = String(value).replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return textarea.value;
}

function setMessage(msgid) {
    if (document.getElementById) {
        <?php if ($hesk_settings['staff_ticket_formatting'] == 2): ?>
        tinymce.get("canned_message").setContent('');
        tinymce.get("canned_message").setContent(myMsgTxt[msgid]);
        <?php else: ?>
        document.getElementById('canned_message').value = heskDecodeHtmlEntities(myMsgTxt[msgid]);
        <?php endif; ?>
        document.getElementById('canned_title').value = heskDecodeHtmlEntities(myTitle[msgid]);
    } else {
        document.form1.msg.value=heskDecodeHtmlEntities(myMsgTxt[msgid]);
        document.form1.name.value=heskDecodeHtmlEntities(myTitle[msgid]);
    }

    document.form1.a.value = 'edit';
    document.form1.saved_replies.value = msgid;
    document.getElementById('add-title').style.display = 'none';
    document.getElementById('edit-title').style.display = 'block';
    document.getElementsByClassName('template-create')[0].style.display = 'block';
}

function displayAddTitle() {
    document.form1.msg.value = '';
    document.form1.name.value = '';
    document.form1.saved_replies.value = 0;
    document.form1.a.value = 'new';
    <?php if ($hesk_settings['staff_ticket_formatting'] == 2): ?>
    tinymce.get("canned_message").setContent('');
    <?php endif; ?>
    document.getElementById('add-title').style.display = 'block';
    document.getElementById('edit-title').style.display = 'none';
}
//-->
</script>
<?php

hesk_cleanSessionVars('canned');

require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/

function edit_saved()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check('POST');

    $hesk_error_buffer = '';
    $errors = array();

    $id = intval(hesk_POST('saved_replies'));
    if (!$id) {
        $hesk_error_buffer .= '<li>' . $hesklang['selcan'] . '</li>';
        $errors[] = 'saved_replies';
    }
	$savename = hesk_input( hesk_POST('name') );
    if (!$savename) {
        $hesk_error_buffer .= '<li>' . $hesklang['ent_saved_title'] . '</li>';
        $errors[] = 'name';
    }
	$msg = hesk_input( hesk_POST('msg') );
    if (!$msg) {
        $hesk_error_buffer .= '<li>' . $hesklang['ent_saved_msg'] . '</li>';
        $errors[] = 'msg';
    }

	// Avoid problems with utf-8 newline chars in Javascript code, detect and remove them
	$msg = preg_replace('/\R/u', "\r\n", $msg);
    
	$_SESSION['canned']['what'] = 'EDIT';
    $_SESSION['canned']['id'] = $id;
    $_SESSION['canned']['name'] = $savename;
    $_SESSION['canned']['msg'] = $msg;
    $_SESSION['canned']['errors'] = $errors;

    /* Any errors? */
    if (strlen($hesk_error_buffer))
    {
    	$hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
    	hesk_process_messages($hesk_error_buffer,'manage_canned.php?saved_replies='.$id);
    }

    if ($hesk_settings['staff_ticket_formatting'] == 2) {
        // Decode the message we encoded earlier
        $msg_html = hesk_html_entity_decode($msg);

        // Clean the HTML code and set the plaintext version
        require(HESK_PATH . 'inc/htmlpurifier/HeskHTMLPurifier.php');
        require(HESK_PATH . 'inc/html2text/html2text.php');
        $purifier = new HeskHTMLPurifier($hesk_settings['cache_dir']);
        $msg_html = $purifier->heskPurify($msg_html);

        $msg = convert_html_to_text($msg_html);
        $msg = fix_newlines($msg);
        // Replace regular newlines with \r\n to match regular plaintext storage... but then get rid of any accidental \r\r\n outputs
        $msg = str_replace("\n", "\r\n", $msg);
        $msg = str_replace("\r\r\n", "\r\n", $msg);

        // Re-encode the message
        $msg = hesk_htmlspecialchars($msg);
    } else {
        $msg_html = hesk_makeURL($msg);
        $msg_html = nl2br($msg_html);
    }

    $result = hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."std_replies` SET `title`='".hesk_dbEscape($savename)."',`message`='".hesk_dbEscape($msg)."', `message_html`='".hesk_dbEscape($msg_html)."' WHERE `id`='".intval($id)."'");
    $_SESSION['canned']['selcat2'] = $id;

	unset($_SESSION['canned']['what']);
    unset($_SESSION['canned']['id']);
    unset($_SESSION['canned']['name']);
    unset($_SESSION['canned']['msg']);
    unset($_SESSION['canned']['errors']);

    hesk_process_messages($hesklang['your_saved'],'manage_canned.php?saved_replies='.$id,'SUCCESS');
} // End edit_saved()


function new_saved()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check('POST');

    $hesk_error_buffer = '';
    $errors = array();
	$savename = hesk_input( hesk_POST('name') );
	if (!$savename) {
        $hesk_error_buffer .= '<li>' . $hesklang['ent_saved_title'] . '</li>';
	    $errors[] = 'name';
    }
	$msg = hesk_input( hesk_POST('msg') );
	if (!$msg) {
        $hesk_error_buffer .= '<li>' . $hesklang['ent_saved_msg'] . '</li>';
        $errors[] = 'msg';
    }

	// Avoid problems with utf-8 newline chars in Javascript code, detect and remove them
	$msg = preg_replace('/\R/u', "\r\n", $msg);

	$_SESSION['canned']['what'] = 'NEW';
    $_SESSION['canned']['name'] = $savename;
    $_SESSION['canned']['msg'] = $msg;
    $_SESSION['canned']['errors'] = $errors;

    /* Any errors? */
    if (strlen($hesk_error_buffer))
    {
    	$hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
    	hesk_process_messages($hesk_error_buffer,'manage_canned.php');
    }

    if ($hesk_settings['staff_ticket_formatting'] == 2) {
        // Decode the message we encoded earlier
        $msg_html = hesk_html_entity_decode($msg);

        // Clean the HTML code and set the plaintext version
        require(HESK_PATH . 'inc/htmlpurifier/HeskHTMLPurifier.php');
        require(HESK_PATH . 'inc/html2text/html2text.php');
        $purifier = new HeskHTMLPurifier($hesk_settings['cache_dir']);
        $msg_html = $purifier->heskPurify($msg_html);

        $msg = convert_html_to_text($msg_html);
        $msg = fix_newlines($msg);
        // Replace regular newlines with \r\n to match regular plaintext storage... but then get rid of any accidental \r\r\n outputs
        $msg = str_replace("\n", "\r\n", $msg);
        $msg = str_replace("\r\r\n", "\r\n", $msg);

        // Re-encode the message
        $msg = hesk_htmlspecialchars($msg);
    } else {
        $msg_html = hesk_makeURL($msg);
        $msg_html = nl2br($msg_html);
    }

    /* Get the latest reply_order */
	$result = hesk_dbQuery('SELECT `reply_order` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'std_replies` ORDER BY `reply_order` DESC LIMIT 1');
	$row = hesk_dbFetchRow($result);
    $my_order = isset($row[0]) ? intval($row[0]) + 10 : 10;

	hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."std_replies` (`title`,`message`,`message_html`,`reply_order`) VALUES ('".hesk_dbEscape($savename)."','".hesk_dbEscape($msg)."','".hesk_dbEscape($msg_html)."','".intval($my_order)."')");
    $_SESSION['canned']['selcat2'] = hesk_dbInsertID();

	unset($_SESSION['canned']['what']);
    unset($_SESSION['canned']['name']);
    unset($_SESSION['canned']['msg']);
    unset($_SESSION['canned']['errors']);

    hesk_process_messages($hesklang['your_saved'],'manage_canned.php','SUCCESS');
} // End new_saved()


function remove()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check();

	$mysaved = intval( hesk_GET('id') ) or hesk_error($hesklang['id_not_valid']);

	hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."std_replies` WHERE `id`='".intval($mysaved)."'");
	if (hesk_dbAffectedRows() != 1)
    {
    	hesk_error("$hesklang[int_error]: $hesklang[reply_not_found].");
    }

    hesk_process_messages($hesklang['saved_rem_full'],'manage_canned.php','SUCCESS');
} // End remove()


function order_saved()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check();

	$replyid = intval( hesk_GET('replyid') ) or hesk_error($hesklang['reply_move_id']);
    $_SESSION['canned']['selcat2'] = $replyid;

	$reply_move = intval( hesk_GET('move') );

	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."std_replies` SET `reply_order`=`reply_order`+".intval($reply_move)." WHERE `id`='".intval($replyid)."'");
	if (hesk_dbAffectedRows() != 1) {hesk_error("$hesklang[int_error]: $hesklang[reply_not_found].");}

	/* Update all category fields with new order */
	$result = hesk_dbQuery('SELECT `id` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'std_replies` ORDER BY `reply_order` ASC');

	$i = 10;
	while ($myreply=hesk_dbFetchAssoc($result))
	{
	    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."std_replies` SET `reply_order`=".intval($i)." WHERE `id`='".intval($myreply['id'])."'");
	    $i += 10;
	}

	header('Location: manage_canned.php');
	exit();
} // End order_saved()

?>
manage_categories.php
wget 'https://lists2.roe3.org/hesk/admin/manage_categories.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Load priorities
require_once(HESK_PATH . 'inc/priorities.inc.php');

/* Check permissions for this feature */
$can_man_cat = hesk_checkPermission('can_man_cat', 0);

/* What should we do? */
if ( $action = hesk_REQUEST('a') ) {
	if ( defined('HESK_DEMO') )  {hesk_process_messages($hesklang['ddemo'], 'manage_categories.php', 'NOTICE');}
    elseif ( ! $can_man_cat)         {hesk_process_messages($hesklang['no_permission'], 'manage_categories.php', 'NOTICE');}
	elseif ($action == 'remove')     {remove();}
	elseif ($action == 'order')      {order_cat();}
	elseif ($action == 'type')       {toggle_type();}
	elseif ($action == 'priority')   {change_priority();}
	elseif ($action == 'due-date')   {change_default_due_date();}
    elseif ($action == 'order_name') {order_categories_by_name();}
    elseif ($action == 'order_id')   {order_categories_by_id();}
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
if (!hesk_SESSION('error')) {
    hesk_handle_messages();
}
?>
<div class="main__content categories">
    <section class="categories__head">
        <h2>
            <?php echo $hesklang['menu_cat']; ?>
            <div class="tooltype right out-close">
                <svg class="icon icon-info">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                </svg>
                <div class="tooltype__content">
                    <div class="tooltype__wrapper">
                        <?php echo $hesklang['cat_intro']; ?>
                    </div>
                </div>
            </div>
        </h2>
        <?php if ($can_man_cat): ?>
        <a href="manage_category.php" class="btn btn btn--blue-border" ripple="ripple">
            <?php echo $hesklang['add_cat']; ?>
        </a>
        <?php endif; ?>
    </section>
    <div class="table-wrap">
        <div class="table">
            <table id="default-table" class="table sindu-table">
                <thead>
                <tr>
                    <th><?php echo $hesklang['id']; ?></th>
                    <th><?php echo $hesklang['cat_name']; ?></th>
                    <th>
                        <span><?php echo $hesklang['priority']; ?></span>
                        <?php if ($hesk_settings['cust_urgency']): ?>
                        <div class="tooltype right out-close">
                            <svg class="icon icon-info">
                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                            </svg>
                            <div class="tooltype__content">
                                <div class="tooltype__wrapper">
                                    <?php echo $hesklang['cat_pri_info'] . ' <a href="#">' . $hesklang['cpri'] . '</a>'; ?>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                    </th>
                    <th>
                        <span><?php echo $hesklang['not']; ?></span>
                    </th>
                    <th>
                        <span><?php echo $hesklang['cat_type']; ?></span>
                    </th>
                    <?php if ($hesk_settings['autoassign']): ?>
                    <th><?php echo $hesklang['aass']; ?></th>
                    <?php endif; ?>
                    <th class="due-date"><?php echo $hesklang['category_default_due_date'] ?></th>
                    <?php if ($can_man_cat): ?>
                    <th aria-label="Actions"></th>
                    <?php endif; ?>
                </tr>
                </thead>
                <tbody>
                <?php
                /* Get number of tickets per category */
                $tickets_all   = array();
                $tickets_total = 0;

                if ($can_man_cat) {
                    $res = hesk_dbQuery('SELECT COUNT(*) AS `cnt`, `category` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'tickets` WHERE ' . ( $can_man_cat ? '1' : hesk_myCategories('category') ) . ' GROUP BY `category`');
                } else {
                    $res = hesk_dbQuery("SELECT COUNT(*) AS `cnt`, `category` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` AS `ticket`
                                        LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_collaborator` AS `w` ON (`ticket`.`id` = `w`.`ticket_id` AND `w`.`user_id` = ".intval($_SESSION['id']).")
                                        WHERE
                                        (
                                            `w`.`user_id`=".intval($_SESSION['id'])."
                                            OR
                                            (".hesk_myOwnership().")
                                        )
                                        AND ".hesk_myCategories()."
                                        GROUP BY `category`");
                }
                while ($tmp = hesk_dbFetchAssoc($res))
                {
                    $tickets_all[$tmp['category']] = $tmp['cnt'];
                    $tickets_total += $tmp['cnt'];
                }

                /* Get list of categories */
                $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE " . ( $can_man_cat ? '1' : hesk_myCategories('id') ) . " ORDER BY `cat_order` ASC");
                $keyed_categories = array();
                $options='';

                $i=1;
                $j=0;
                $num = hesk_dbNumRows($res);

                while ($mycat=hesk_dbFetchAssoc($res)) {
                    $keyed_categories[$mycat['id']] = $mycat;
                }

                foreach ($keyed_categories as $id => $mycat) {
                    $j++;

                    $table_row = '';
                    if (isset($_SESSION['selcat2']) && $mycat['id'] == $_SESSION['selcat2'])
                    {
                        $table_row = 'class="ticket-new"';
                        unset($_SESSION['selcat2']);
                    }
                    else
                    {
                        $color = $i ? 'admin_white' : 'admin_gray';
                    }

                    $tmp   = $i ? 'White' : 'Blue';
                    $style = 'class="option'.$tmp.'OFF" onmouseover="this.className=\'option'.$tmp.'ON\'" onmouseout="this.className=\'option'.$tmp.'OFF\'"';
                    $i     = $i ? 0 : 1;

                    /* Number of tickets and graph width */
                    $all = isset($tickets_all[$mycat['id']]) ? $tickets_all[$mycat['id']] : 0;
                    $width_all = 0;
                    if ($tickets_total && $all)
                    {
                        $width_all  = round(($all / $tickets_total) * 100);
                    }

                    $options .= '<option value="'.$mycat['id'].'" ';
                    $options .= (isset($_SESSION['selcat']) && $mycat['id'] == $_SESSION['selcat']) ? ' selected="selected" ' : '';
                    $options .= '>'.$mycat['name'].'</option>';


                    ?>
                    <tr <?php echo $table_row; ?> data-category-id="<?php echo $mycat['id']; ?>" data-autoassign-enabled="<?php echo $mycat['autoassign'] ?>" data-autoassign-config="<?php echo hesk_stripslashes($mycat['autoassign_config']); ?>">
                        <td><?php echo $mycat['id']; ?></td>
                        <td>
                            <span class="category-name"><?php echo $mycat['name']; ?></span>
                        </td>
                        <?php
                            echo '<td><div class="td-flex">' . hesk_get_admin_ticket_priority_for_list($mycat['priority']) . '&nbsp;</div></td>';
                        ?>
                        <td>
                            <?php
                            $tickets_url = 'show_tickets.php?category='.$mycat['id'].'&amp;s_all=1&amp;s_my=1&amp;s_ot=1&amp;s_un=1';
                            ?>
                            <a class="tooltip" data-ztt_vertical_offset="0" href="<?php echo $tickets_url; ?>" title="<?php echo $hesklang['list_tickets_cat']; ?>">
                                <?php echo $all; ?>
                                (<?php echo $width_all; ?>%)
                            </a>
                        </td>
                        <td>
                            <?php echo $mycat['type'] == 0 ? $hesklang['cat_public'] : $hesklang['cat_private']; ?>
                        </td>
                        <?php if ($hesk_settings['autoassign']): ?>
                        <td class="assign">
                            <?php
                            if ($mycat['autoassign']) {
                                echo $hesklang['on'];
                            } else {
                                echo $hesklang['off'];
                            } ?>
                            <?php if (($display = hesk_getAutoAssignConfigDisplay($mycat['autoassign_config'])) !== '') { ?>
                                <div class="autoassign-config-display">
                                    (<?php echo $display; ?>)
                                </div>
                            <?php } ?>
                        </td>
                        <?php endif; ?>
                        <td class="due-date">
                            <?php if ($mycat['default_due_date_amount'] === null && $mycat['default_due_date_unit'] === null) {
                                echo $hesklang['none'];
                            } else {
                                echo $mycat['default_due_date_amount'] . ' ' . $hesklang["d_{$mycat['default_due_date_unit']}"];
                            } ?>
                        </td>
                        <?php if ($can_man_cat): ?>
                        <td class="nowrap generate">
                            <a class="tooltip" href="javascript:"
                               title="<?php echo $hesklang['geco']; ?>"
                               <?php echo $mycat['type'] == 1 ? 'style="visibility: hidden"' : '' ?>
                               data-action="generate-link"
                               data-link="<?php echo htmlspecialchars($hesk_settings['hesk_url']) . '/index.php?a=add&catid=' . intval($mycat['id']); ?>">
                                <svg class="icon icon-export">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-export"></use>
                                </svg>
                            </a>
                            <a class="tooltip" href="manage_category.php?id=<?php echo $mycat['id']; ?>"
                               title="<?php echo $hesklang['edit']; ?>">
                                <svg class="icon icon-edit-ticket">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-edit-ticket"></use>
                                </svg>
                            </a>
                            <?php
                            if ($num > 1) {
                                if ($j == 1) {
                                    ?>
                                    <a href="#" style="visibility: hidden"
                                       title="<?php echo $hesklang['move_up']; ?>" aria-label="<?php echo $hesklang['move_up']; ?>">
                                        <svg class="icon icon-chevron-up">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                        </svg>
                                    </a>
                                    <a class="tooltip" href="manage_categories.php?a=order&amp;catid=<?php echo $mycat['id']; ?>&amp;move=15&amp;token=<?php hesk_token_echo(); ?>"
                                       title="<?php echo $hesklang['move_dn']; ?>" aria-label="<?php echo $hesklang['move_dn']; ?>">
                                        <svg class="icon icon-chevron-down">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                        </svg>
                                    </a>
                                    <?php
                                    echo'';
                                } elseif ($j == $num) {
                                    ?>
                                    <a class="tooltip" href="manage_categories.php?a=order&amp;catid=<?php echo $mycat['id']; ?>&amp;move=-15&amp;token=<?php hesk_token_echo(); ?>"
                                       title="<?php echo $hesklang['move_up']; ?>" aria-label="<?php echo $hesklang['move_up']; ?>">
                                        <svg class="icon icon-chevron-up">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                        </svg>
                                    </a>
                                    <a href="#" style="visibility: hidden"
                                       title="<?php echo $hesklang['move_dn']; ?>" aria-label="<?php echo $hesklang['move_dn']; ?>">
                                        <svg class="icon icon-chevron-down">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                        </svg>
                                    </a>
                                    <?php
                                } else {
                                    ?>
                                    <a class="tooltip" href="manage_categories.php?a=order&amp;catid=<?php echo $mycat['id']; ?>&amp;move=-15&amp;token=<?php hesk_token_echo(); ?>"
                                       title="<?php echo $hesklang['move_up']; ?>" aria-label="<?php echo $hesklang['move_up']; ?>">
                                        <svg class="icon icon-chevron-up">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                        </svg>
                                    </a>
                                    <a class="tooltip" href="manage_categories.php?a=order&amp;catid=<?php echo $mycat['id']; ?>&amp;move=15&amp;token=<?php hesk_token_echo(); ?>"
                                       title="<?php echo $hesklang['move_dn']; ?>" aria-label="<?php echo $hesklang['move_dn']; ?>">
                                        <svg class="icon icon-chevron-down">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                        </svg>
                                    </a>
                                    <?php
                                }
                            }
                            ?>
                            <?php
                            if ($mycat['id'] != 1):
                                $modal_body = $hesklang['confirm_del_cat'];
                                if ($all > 0) {
                                    //-- $j - 2 because $j is 1-indexed and the first category can't be deleted
                                    $modal_body .= '<br><br>'.
                                        '<div><b>'.sprintf($hesklang['select_new_category'], $all).'</b></div>'.
                                        '<select id="targetCat'.($j - 2).'" name="modal-dropdown" onchange="hesk_updateDeleteCategoryUrl('.($j - 2).')" aria-label="Transfer tickets to category">';

                                    foreach ($keyed_categories as $potential_transfer_id => $dropdown_category) {
                                        //-- Don't allow transferring to self
                                        if ($potential_transfer_id === $id) {
                                            continue;
                                        }

                                        $modal_body .= '<option value="'.$potential_transfer_id.'"  aria-label="' . $dropdown_category['name'] . '">'.$dropdown_category['name'].'</option>';
                                    }
                                    $modal_body .= '</select>';
                                }
                                $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                                    $modal_body,
                                    'manage_categories.php?a=remove&catid='. $mycat['id'] .'&token='. hesk_token_echo(0).'&targetCategory=1');
                                ?>
                            <a class="tooltip delete" title="<?php echo $hesklang['delcat']; ?>" href="javascript:" data-modal="[data-modal-id='<?php echo $modal_id; ?>']">
                                <svg class="icon icon-delete">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-delete"></use>
                                </svg>
                            </a>
                            <?php
                            endif;
                            ?>
                        </td>
                        <?php endif; /* endif $can_man_cat */ ?>
                    </tr>
                <?php } ?>
                </tbody>
            </table>
        </div>
    </div>

    <br>
    <br>
    <?php if ($can_man_cat && count($keyed_categories) > 3): ?>
    <div>
        <section class="categories__head">
            <h2><?php echo $hesklang['tools']; ?></h2>
        </section>
        <div>
             <?php
                $m_body = $hesklang['warning_order_cat_by_name'];
                $m_body .= '<input type="hidden" name="a" value="order_name">
                <input type="hidden" name="token" value="'.hesk_token_echo(0).'">';

                $mid = hesk_generate_delete_modal([
                    'title' => $hesklang['confirm_ordering_title'],
                    'body' => $m_body,
                    'confirm_action' => 'manage_categories.php',
                    'use_form' => true,
                    'form_method' => 'GET',
                    'delete_text' => $hesklang['yes_title_case'],
                    'cancel_text' => $hesklang['no_title_case']
                ]);
            ?>
            <a href="javascript:" data-modal="[data-modal-id='<?php echo $mid; ?>']"
                title="<?php echo $hesklang['remove']; ?>"
                class="btn btn btn--blue-border">
                <?php echo $hesklang['order_cat_by_name']; ?>
            </a>
        </div>
        <br>
        <div>
             <?php
                $m_body = $hesklang['warning_order_cat_by_id'];
                $m_body .= '<input type="hidden" name="a" value="order_id">
                <input type="hidden" name="token" value="'.hesk_token_echo(0).'">';

                $mid = hesk_generate_delete_modal([
                    'title' => $hesklang['confirm_ordering_title'],
                    'body' => $m_body,
                    'confirm_action' => 'manage_categories.php',
                    'use_form' => true,
                    'form_method' => 'GET',
                    'delete_text' => $hesklang['yes_title_case'],
                    'cancel_text' => $hesklang['no_title_case']
                ]);
            ?>
            <a href="javascript:" data-modal="[data-modal-id='<?php echo $mid; ?>']"
                title="<?php echo $hesklang['remove']; ?>"
                class="btn btn btn--blue-border">
                <?php echo $hesklang['order_cat_by_id']; ?>
            </a>
        </div>
    </div>
    <br>
    <br>
    <?php endif; ?>

</div>
<div role="status" class="notification-flash green" data-type="link-generate-message">
    <i class="close">
        <svg class="icon icon-close">
            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
        </svg>
    </i>
    <div class="notification--title error-title"><?php echo $hesklang['genl_not_copied']; ?></div>
    <div class="notification--title"><?php echo $hesklang['genl']; ?></div>
    <div class="notification--text"><?php echo $hesklang['genl2']; ?></div>
</div>
<?php
hesk_cleanSessionVars('error');
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/
function remove()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check();

    $_SERVER['PHP_SELF'] = 'manage_categories.php';

	$mycat = intval( hesk_GET('catid') ) or hesk_error($hesklang['no_cat_id']);
	if ($mycat == 1)
    {
    	hesk_process_messages($hesklang['cant_del_default_cat'],$_SERVER['PHP_SELF']);
    }

	hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE `id`='".intval($mycat)."'");
	if (hesk_dbAffectedRows() != 1)
    {
    	hesk_error("$hesklang[int_error]: $hesklang[cat_not_found].");
    }

    $new_category = hesk_GET('targetCategory', 1);
    // Don't update resolved tickets "Last modified"
    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `category`=".intval($new_category).", `lastchange`=`lastchange` WHERE `category`='".intval($mycat)."' AND `status` = '3'");
    // For unresolved tickets, update the "Last modified"
	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `category`=".intval($new_category)." WHERE `category`='".intval($mycat)."'");

    hesk_process_messages($hesklang['cat_removed_db'],$_SERVER['PHP_SELF'],'SUCCESS');
} // End remove()


function order_cat()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check();

	$catid = intval( hesk_GET('catid') ) or hesk_error($hesklang['cat_move_id']);
	$_SESSION['selcat2'] = $catid;

	$cat_move=intval( hesk_GET('move') );

	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` SET `cat_order`=`cat_order`+".intval($cat_move)." WHERE `id`='".intval($catid)."'");
	if (hesk_dbAffectedRows() != 1)
    {
    	hesk_error("$hesklang[int_error]: $hesklang[cat_not_found].");
    }

	/* Update all category fields with new order */
	$res = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` ORDER BY `cat_order` ASC");

	$i = 10;
	while ($mycat=hesk_dbFetchAssoc($res))
	{
	    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` SET `cat_order`=".intval($i)." WHERE `id`='".intval($mycat['id'])."'");
	    $i += 10;
	}

    header('Location: manage_categories.php');
    exit();
} // End order_cat()


function order_categories_by_name() {
    global $hesk_settings, $hesklang;
    order_categories_by('name');
    hesk_process_messages($hesklang['success_order_cat_by_name'],$_SERVER['PHP_SELF'],'SUCCESS');
} // End order_categories_by_name()


function order_categories_by_id() {
    global $hesk_settings, $hesklang;
    order_categories_by('id');
    hesk_process_messages($hesklang['success_order_cat_by_id'],$_SERVER['PHP_SELF'],'SUCCESS');
} // End order_categories_by_id()


function order_categories_by($column='name') {
    global $hesk_settings, $hesklang;

    // A security check
    hesk_token_check();

    // Validate the column value
    $valid_columns = array('id', 'name');
    if ( ! in_array($column, $valid_columns)) {
        hesk_error($hesklang['invalid_action']);
    }

    // Get categories by asccending order to update order
    $result = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` ORDER BY `{$column}` ASC");

    // Sorted all category order field with category by name
    $i = 10;
    while ($cat = hesk_dbFetchAssoc($result)) {
        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` SET `cat_order`={$i} WHERE `id`='".intval($cat['id'])."'");
        $i += 10;
    }
} // End order_categories_by()

manage_category.php
wget 'https://lists2.roe3.org/hesk/admin/manage_category.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/setup_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Load priorities
require_once(HESK_PATH . 'inc/priorities.inc.php');

/* Check permissions for this feature */
hesk_checkPermission('can_man_cat');

// Populate default values for creation
$category = array(
    'id' => 0,
    'name' => '',
    'priority' => $hesk_settings['priorities'][array_keys($hesk_settings['priorities'])[0]]['id'],
    'autoassign' => $hesk_settings['autoassign'],
    'autoassign_config' => null,
    'type' => 0,
    'default_due_date_unit' => 'day',
    'default_due_date_amount' => ''
);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (defined('HESK_DEMO')) {
        hesk_process_messages($hesklang['ddemo'], 'manage_categories.php', 'NOTICE');
    }

    // Attempt to save. If problematic, we'll get back the form data entered.
    $category = try_save_category();
} elseif (hesk_REQUEST('id')) {
    // Fetch category information
    $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE `id` = ".intval(hesk_REQUEST('id')));
    if ($row = hesk_dbFetchAssoc($res)) {
        $category['id'] = $row['id'];
        $category['name'] = $row['name'];
        $category['priority'] = intval($row['priority']);
        $category['autoassign'] = intval($row['autoassign']);
        $category['autoassign_config'] = $row['autoassign_config'];
        $category['type'] = intval($row['type']);
        $category['default_due_date_amount'] = $row['default_due_date_amount'] ? intval($row['default_due_date_amount']) : '';
        $category['default_due_date_unit'] = $row['default_due_date_unit'];
    }

    // If we're still on ID 0, then the category ID passed in doesn't exist
    if ($category['id'] === 0) {
        hesk_process_messages($hesklang['cat_not_found'], 'manage_categories.php');
    }
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
if (hesk_SESSION('iserror')) {
    hesk_handle_messages();
}
?>
<div class="main__content categories category-create">
    <section class="categories__head">
        <h2>
            <?php echo $category['id'] !== 0 ? $hesklang['edit_category'] : $hesklang['create_category']; ?>
        </h2>
    </section>
    <div class="table-wrap">
        <form method="post" class="form <?php echo isset($_SESSION['iserror']) ? 'invalid' : ''; ?>" action="manage_category.php" name="create-form" aria-label="<?php echo $hesklang['edit_category']; ?>">
            <div class="form-group">
                <label for="name">
                    <?php echo $hesklang['cat_name']; ?>: <span class="important">*</span>
                </label>
                <input type="text"
                       name="name"
                       class="form-control"
                       id="name"
                       maxlength="100"
                       value="<?php echo $category['name']; ?>">
            </div>
            <div class="category-create__select">
                <span><?php echo $hesklang['def_pri']; ?></span>
                <div class="dropdown-select center out-close priority select-priority">
                    <select name="priority">
                        <?php 
                        foreach ($hesk_settings['priorities'] as $id => $priority):
                            $data_style ='border-top-color:'.$priority['color'].';border-left-color:'.$priority['color'].';border-bottom-color:'.$priority['color'].';';
                        ?>
                            <option value="<?php echo $priority['id']; ?>"
                                    <?php if (intval($priority['id']) == intval($category['priority'])): ?>selected<?php endif; ?> data-class="priority_img priority_dwn" data-style="<?php echo $data_style;?>">
                                <?php echo $priority['name']; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <?php if ($hesk_settings['autoassign']): ?>
            <div class="form-group">
                <label style="text-align: left"><?php echo $hesklang['aa_cat']; ?>:</label>
                <div class="radio-group">
                    <div class="radio-list">
                        <div class="radio-custom">
                            <input type="radio"
                                   id="autoassign_on_all"
                                   name="autoassign"
                                   value="1"
                                   onclick="hesk_toggleLayer('select-users-window','none')"
                                   <?php if ($category['autoassign'] === 1 && $category['autoassign_config'] === null): ?>checked<?php endif; ?>>
                            <label for="autoassign_on_all"><?php echo $hesklang['autoassign_on_all_users']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio"
                                   id="autoassign_on_some"
                                   name="autoassign"
                                   value="2"
                                   onclick="hesk_toggleLayer('select-users-window','block')"
                                   <?php if ($category['autoassign'] === 1 && $category['autoassign_config'] !== null): ?>checked<?php endif; ?>>
                            <label for="autoassign_on_some"><?php echo $hesklang['autoassign_on_select_users']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio"
                                   id="autoassign_off"
                                   name="autoassign"
                                   value="0"
                                   onclick="hesk_toggleLayer('select-users-window','none')"
                                   <?php if ($category['autoassign'] === 0): ?>checked<?php endif; ?>>
                            <label for="autoassign_off"><?php echo $hesklang['autoassign_off']; ?></label>
                        </div>
                    </div>
                </div>
            </div>
            <div id="select-users-window" style="display: <?php echo $category['autoassign'] === 1 && $category['autoassign_config'] !== null ? 'block' : 'none'; ?>">
                <hr>
                <div class="form-group">
                    <?php
                    $users_with_view_access = hesk_getUserIdsWithAccessToFeatureAndCategory('can_view_tickets');
                    $users_with_reply_access = hesk_getUserIdsWithAccessToFeatureAndCategory('can_reply_tickets');
                    $users_num = count(array_intersect($users_with_view_access, $users_with_reply_access));

                    $users_with_category_view_access = hesk_getUserIdsWithAccessToFeatureAndCategory('can_view_tickets', $category['id']);
                    $users_with_category_reply_access = hesk_getUserIdsWithAccessToFeatureAndCategory('can_reply_tickets', $category['id']);
                    $users_with_category_access = array_intersect($users_with_category_view_access, $users_with_category_reply_access);
                    $users_with_category_access_sql = count($users_with_category_access) ? implode(',', array_map('intval', $users_with_category_access)) : '0';
                    $users_res = hesk_dbQuery("SELECT `id`, `name`
                                                  FROM `" . hesk_dbEscape($hesk_settings['db_pfix']) . "users` AS `user`
                                                  WHERE `active` = 1
                                                  AND `id` IN ({$users_with_category_access_sql})
                                                  ORDER BY `name` ASC");
                    $users_found = hesk_dbNumRows($users_res);

                    if ($users_num > $users_found): ?>
                    <div class="notice-flash">
                        <div role="status" class="notification blue">
                            <?php echo sprintf($hesklang['ouwa'], $hesklang['team']); ?>
                        </div>
                    </div>
                    <?php endif;

                    echo '<label>'.$hesklang['autoassign_users'].':</label>';

                    if ($users_found > 19) {
                        // Only show search box if we have 20+ users
                    ?>
                    <div class="form-group">
                        <input type="text"
                               id="search-for-user"
                               class="form-control"
                               placeholder="<?php echo $hesklang['search_for_user']; ?>">
                    </div>
                    <?php } ?>
                    <div class="autoassign-users">
                        <?php
                        while ($user = hesk_dbFetchAssoc($users_res)) { ?>
                            <div class="checkbox-custom <?php if (user_is_involved_in_autoassign_config($user['id'], $category['autoassign_config'])): ?>checked<?php endif; ?>" data-name="<?php echo hesk_htmlspecialchars($user['name']); ?>">
                                <input type="checkbox"
                                       id="autoassign_user_<?php echo $user['id']; ?>"
                                       name="autoassign_user[]"
                                       value="<?php echo $user['id']; ?>"
                                       <?php if (user_is_involved_in_autoassign_config($user['id'], $category['autoassign_config'])): ?>checked<?php endif; ?>>
                                <label for="autoassign_user_<?php echo $user['id']; ?>"><?php echo $user['name']; ?></label>
                            </div>
                        <?php } ?>
                        <p id="search-no-results" style="display: none"><span role="alert"><?php echo $hesklang['no_results_found']; ?></span></p>
                    </div>
                    <a href="javascript:" id="select-all"><?php echo $hesklang['a_select']; ?></a>
                    &nbsp;
                    <a href="javascript:" id="deselect-all"><?php echo $hesklang['a_deselect']; ?></a>
                </div>
                <div class="form-group">
                    <div class="radio-group">
                        <div class="radio-list" style="text-align: left">
                            <div class="radio-custom">
                                <input type="radio"
                                       id="autoassign_user_include"
                                       name="autoassign_user_operator"
                                       value="="
                                       <?php if ($category['autoassign_config'] === null || (is_string($category['autoassign_config']) && substr($category['autoassign_config'], 0, 1) === '=')): ?>checked<?php endif; ?>>
                                <label for="autoassign_user_include"><?php echo $hesklang['autoassign_selected_include']; ?></label>
                            </div>
                            <div class="radio-custom">
                                <input type="radio"
                                       id="autoassign_user_exclude"
                                       name="autoassign_user_operator"
                                       value="!"
                                       <?php if (is_string($category['autoassign_config']) && substr($category['autoassign_config'], 0, 1) === '!'): ?>checked<?php endif; ?>>
                                <label for="autoassign_user_exclude"><?php echo $hesklang['autoassign_selected_exclude']; ?></label>
                            </div>
                        </div>
                    </div>
                </div>
                <hr>
            </div>
            <?php endif; ?>
            <div class="category-create__select">
                <span><?php echo $hesklang['cat_type']; ?>:</span>
                <div class="dropdown-select center out-close">
                    <select name="type">
                        <option value="0" <?php if ($category['type'] === 0): ?>selected<?php endif; ?>>
                            <?php echo $hesklang['cat_public']; ?>
                        </option>
                        <option value="1" <?php if ($category['type'] === 1): ?>selected<?php endif; ?>>
                            <?php echo $hesklang['cat_private']; ?>
                        </option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label style="text-align: left" for="due-date-amount"><?php echo $hesklang['category_default_due_date']; ?>:</label>
                <input type="text"
                       class="form-control"
                       id="due-date-amount"
                       name="due-date-amount"
                       style="width:100px; margin-left:6px; margin-right:6px"
                       value="<?php echo $category['default_due_date_amount']; ?>">
                <div class="dropdown-select center out-close" id="id1">
                    <select name="due-date-unit" id="due-date-unit" class="form-control selectized">
                        <option value="day" <?php if ($category['default_due_date_unit'] === 'day'): ?>selected<?php endif; ?>>
                            <?php echo $hesklang['d_day']; ?>
                        </option>
                        <option value="week" <?php if ($category['default_due_date_unit'] === 'week'): ?>selected<?php endif; ?>>
                            <?php echo $hesklang['d_week']; ?>
                        </option>
                        <option value="month" <?php if ($category['default_due_date_unit'] === 'month'): ?>selected<?php endif; ?>>
                            <?php echo $hesklang['d_month']; ?>
                        </option>
                        <option value="year" <?php if ($category['default_due_date_unit'] === 'year'): ?>selected<?php endif; ?>>
                            <?php echo $hesklang['d_year']; ?>
                        </option>
                    </select>
                </div>
                <div><?php echo $hesklang['category_leave_blank_for_no_default_due_date']; ?></div>
            </div>
            <input type="hidden" name="id" value="<?php echo $category['id']; ?>">
            <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
            <button class="btn btn-full" type="submit" ripple="ripple"><?php echo $hesklang['create_cat']; ?></button>
        </form>
    </div>
</div>

<script type="text/javascript"><!--

function hesk_toggleLayer(nr,setto) {
    if (document.all)
        document.all[nr].style.display = setto;
    else if (document.getElementById)
        document.getElementById(nr).style.display = setto;
}

$(document).ready(function() {
    $('#select-all').click(function() {
        $('.checkbox-custom[data-name]').each(function() {
            clickCheckbox($(this), true);
        });
    });

    function clickCheckbox($el, shouldBeChecked) {
        if ($el.hasClass('checked') !== shouldBeChecked) {
            $el.find('input').click();
        }
    }

    $('#deselect-all').click(function() {
        $('.checkbox-custom[data-name]').each(function() {
            clickCheckbox($(this), false);
        });
    });

    $('#search-for-user').keyup(function() {
        var criteria = $(this).val().toLowerCase();
        var foundResult = false;

        $('.checkbox-custom[data-name]').each(function() {
            if ($(this).attr('data-name').toLowerCase().indexOf(criteria) === -1) {
                $(this).hide();
            } else {
                foundResult = true;
                $(this).show();
            }
        });

        if (foundResult) {
            $('#search-no-results').hide();
        } else {
            $('#search-no-results').show();
        }
    });
})
//-->
</script>
<?php
hesk_cleanSessionVars('iserror');
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/
function user_is_involved_in_autoassign_config($user_id, $autoassign_config) {
    if ($autoassign_config === null || $autoassign_config === '') {
        return false;
    }

    if (!preg_match('/([!=])?\((.+)\)/', $autoassign_config, $matches) || !isset($matches[2])) {
        return false;
    }

    return in_array($user_id, explode(',', $matches[2]));
}


function try_save_category()
{
    global $hesk_settings, $hesklang, $priorities;

    /* A security check */
    hesk_token_check('POST');

    /* Options */
    $category = array();
    $category['id'] = intval(hesk_POST('id'));

    $category['autoassign'] = intval(hesk_checkMinMax(hesk_POST('autoassign'), 0, 2, $hesk_settings['autoassign']));
    $category['autoassign_config'] = null;
    if ($category['autoassign'] === 2) {
        // Handle inclusions/exclusions
        $autoassign_setup = get_autoassign_state($category['id'],
            intval($category['autoassign']),
            hesk_POST('autoassign_user_operator'),
            hesk_POST_array('autoassign_user'));

        $category['autoassign'] = $autoassign_setup['autoassign'];
        $category['autoassign_config'] = $autoassign_setup['autoassign_config'];
    }

    $category['type'] = hesk_POST('type') === '1' ? 1 : 0;

    // Default priority
    $category['priority'] = hesk_get_valid_priority_id(hesk_POST('priority'));

    // Default due date
    $category['default_due_date_amount'] = intval(hesk_POST('due-date-amount', -1));
    if ($category['default_due_date_amount'] < 1) {
        $category['default_due_date_amount'] = '';
    }

    $category['default_due_date_unit'] = get_valid_date_unit(hesk_POST('due-date-unit'));

    /* Category name */
    $category['name'] = hesk_input(hesk_POST('name'));

    if ($category['name'] === '') {
        $_SESSION['iserror'] = 1;
        hesk_process_messages($hesklang['enter_cat_name'], 'NOREDIRECT');
    }

    if ($category['id'] === 0) {
        /* Do we already have a category with this name? */
        $res = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE `name` LIKE '".hesk_dbEscape( hesk_dbLike($category['name']) )."' LIMIT 1");
        if (hesk_dbNumRows($res) != 0)
        {
            hesk_process_messages($hesklang['cndupl'], 'NOREDIRECT');
        }
    }

    // Do we have errors? If so, just return the category to the page.
    if (isset($_SESSION['iserror'])) {
        return $category;
    }

    /* Get the latest cat_order */
    $res = hesk_dbQuery("SELECT `cat_order` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` ORDER BY `cat_order` DESC LIMIT 1");
    $row = hesk_dbFetchRow($res);
    $my_order = isset($row[0]) ? intval($row[0]) + 10 : 10;

    // Prepare autoassign config for saving
    $sql_friendly_autoassign_config = $category['autoassign_config'] === null ? 'NULL' : "'".hesk_dbEscape($category['autoassign_config'])."'";
    $sql_friendly_due_date_amount = $category['default_due_date_amount'] === '' ? 'NULL' : $category['default_due_date_amount'];
    $sql_friendly_due_date_unit = $sql_friendly_due_date_amount === 'NULL' ? 'NULL' : "'".hesk_dbEscape($category['default_due_date_unit'])."'";
    if ($category['id'] === 0) {
        hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` (`name`,`cat_order`,`autoassign`,
                      `autoassign_config`,`type`, `priority`,`default_due_date_amount`,`default_due_date_unit`)
                    VALUES ('".hesk_dbEscape($category['name'])."',
                            '".intval($my_order)."',
                            '".intval($category['autoassign'])."',
                            ".$sql_friendly_autoassign_config.",
                            '".intval($category['type'])."',
                            '".intval($category['priority'])."',
                            ".$sql_friendly_due_date_amount.",
                            ".$sql_friendly_due_date_unit.")");
        $_SESSION['selcat2'] = hesk_dbInsertID();
    } else {
        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."categories`
                      SET `name` = '".hesk_dbEscape($category['name'])."',
                          `autoassign` = '".intval($category['autoassign'])."',
                          `autoassign_config` = {$sql_friendly_autoassign_config},
                          `type` = '".intval($category['type'])."',
                          `priority` = '".intval($category['priority'])."',
                          `default_due_date_amount` = {$sql_friendly_due_date_amount},
                          `default_due_date_unit` = {$sql_friendly_due_date_unit}
                      WHERE `id` = ".intval($category['id']));
        $_SESSION['selcat2'] = $category['id'];
    }

    hesk_cleanSessionVars('iserror');

    $success_language_key = $category['id'] === 0 ? 'cat_name_added' : 'cat_edited';
    hesk_process_messages(sprintf($hesklang[$success_language_key],'<i>'.stripslashes($category['name']).'</i>'),'manage_categories.php','SUCCESS');
    exit();
} // End new_cat()


function get_autoassign_state($id, $autoassign_setting, $autoassign_user_operator, $autoassign_users) {
    /*
     * 1 -> On, All
     * 2 -> On, Some
     * 3 -> Off
     */
    // "On - All Users" or "On - Some Users" with 0 users being excluded
    if ($autoassign_setting === 1 ||
        ($autoassign_setting === 2 &&
            $autoassign_user_operator === '!' &&
            count($autoassign_users) === 0)) {
        $autoassign = 1;
        $autoassign_config = null;
    } elseif ($autoassign_setting === 2 && count($autoassign_users) !== 0) {
        // "On - Some Users" with at least one user selected. Otherwise it'll be treated as "On - All Users" above if 0 exclusions, or "Off" if 0 inclusions
        $autoassign = 1;
        $autoassign_config = build_autoassign_config($id, $autoassign_users, $autoassign_user_operator);

        // All excluded == off
        // All included == on - all users
        if ($autoassign_config === 'ALL_EXCLUDED') {
            $autoassign = 0;
            $autoassign_config = null;
        } elseif ($autoassign_config === 'ALL_INCLUDED') {
            $autoassign_config = null;
        }
    } else {
        $autoassign = 0;
        $autoassign_config = null;
    }

    return array(
        'autoassign' => $autoassign,
        'autoassign_config' => $autoassign_config
    );
} // End update_autoassign()

function build_autoassign_config($catid, $selected_users, $operator) {
    global $hesk_settings;

    // Make sure the entered operator is valid
    $operator = $operator === '=' ? '=' : '!';
    $formatted_users = array();
    $valid_users = array_intersect(
        hesk_getUserIdsWithAccessToFeatureAndCategory('can_view_tickets', $catid),
        hesk_getUserIdsWithAccessToFeatureAndCategory('can_reply_tickets', $catid)
    );

    foreach ($selected_users as $selected_user)
    {
        $selected_user = intval($selected_user);

        if (in_array($selected_user, $valid_users))
        {
            $formatted_users[] = $selected_user;
        }
    }

    $formatted_users = array_unique($formatted_users);

    // Make sure we're not including/excluding the entire list of possible users, as we can simplify
    if (count($valid_users) === count($formatted_users)) {
        return $operator === '=' ? 'ALL_INCLUDED' : 'ALL_EXCLUDED';
    }


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


    return "{$operator}({$formatted_users})";
} // End build_autoassign_config()

function get_valid_date_unit($unit) {
    switch ($unit) {
        case 'week':
            return 'week';
            break;
        case 'month':
            return 'month';
            break;
        case 'year':
            return 'year';
            break;
        default:
            return 'day';
    }
} // END get_valid_date_unit()
?>
manage_customers.php
wget 'https://lists2.roe3.org/hesk/admin/manage_customers.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');
define('LOAD_TABS',1);

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/privacy_functions.inc.php');
require(HESK_PATH . 'inc/manage_customers_functions.inc.php');
require(HESK_PATH . 'inc/customer_accounts.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
$can_man_customers = hesk_checkPermission('can_man_customers', false);
$can_edit_tickets = hesk_checkPermission('can_edit_tickets', false);
$can_view_customers = hesk_checkPermission('can_view_customers', false);
$can_merge_customers = hesk_checkPermission('can_merge_customers', false);

if ($can_man_customers || (!$hesk_settings['customer_accounts'] && $can_edit_tickets && ! empty(hesk_REQUEST('a')))) {
    $elevation_target = !isset($_GET['track']) ?
        'manage_customers.php' :
        'manage_customers.php?a=edit&track='.hesk_cleanID().'&id='.hesk_GET('id');
    hesk_check_user_elevation($elevation_target);
} else {
    hesk_checkPermission('can_view_customers');
}

/* Set default values */
$default_userdata = array(
    'name' => '',
    'email' => '',
    'cleanpass' => ''
);

/* Use any set values, default otherwise */
foreach ($default_userdata as $k => $v)
{
    if ( ! isset($_SESSION['userdata'][$k]) )
    {
        $_SESSION['userdata'][$k] = $v;
    }
}

$_SESSION['userdata'] = hesk_stripArray($_SESSION['userdata']);

/* What should we do? */
if ( $action = hesk_REQUEST('a') )
{
    if ($hesk_settings['customer_accounts']) {
        // Check permission again - required manage users permission for all actions
        hesk_checkPermission('can_man_customers');

        if ($action == 'reset_form')
        {
            $_SESSION['edit_userdata'] = TRUE;
            header('Location: ./manage_customers.php');
        }
        elseif ($action == 'edit')       {edit_user();}
        elseif ( defined('HESK_DEMO') )  {hesk_process_messages($hesklang['ddemo'], 'manage_customers.php', 'NOTICE');}
        elseif ($action == 'new')        {new_user();}
        elseif ($action == 'save')       {update_user();}
        elseif ($action == 'remove')     {remove();}
        elseif ($action == 'resetmfa')   {reset_mfa();}
        elseif ($action === 'approve')   {approve_registration();}
        elseif ($action === 'reject')    {reject_registration();}
        elseif ($action === 'delete')    {delete_registration();}
        elseif ($action === 'bulk')      {handle_bulk_action();}
        elseif ($action === 'resend_verification_email') {resend_verification_email();}
        else 							 {hesk_error($hesklang['invalid_action']);}
    } else {
        // When customer accounts disabled, we can only edit customers here
        if ( ! $can_man_customers) {
            hesk_checkPermission('can_edit_tickets');
        }
        if ($action === 'edit') {edit_user();}
        elseif ( defined('HESK_DEMO') )  {hesk_process_messages($hesklang['ddemo'], 'manage_customers.php', 'NOTICE');}
        elseif ($action == 'save')       {update_user();}
        elseif ($action == 'remove')     {remove();}
        else 							 {hesk_error($hesklang['invalid_action']);}
    }
} else {
    /* If one came from the Edit page make sure we reset user values */
    if (isset($_SESSION['save_userdata']))
    {
        $_SESSION['userdata'] = $default_userdata;
        $_SESSION['save_customer_search'] = true;
        unset($_SESSION['save_userdata']);
    }
    if (isset($_SESSION['edit_userdata']))
    {
        $_SESSION['save_customer_search'] = true;
        $_SESSION['userdata'] = $default_userdata;
        unset($_SESSION['edit_userdata']);
    }

    // Clear the saved search unless we're told to keep it
    if (!isset($_SESSION['save_customer_search'])) {
        unset($_SESSION['saved_customer_search']);
    } else {
        unset($_SESSION['save_customer_search']);
    }
    $saved_search = hesk_SESSION_array('saved_customer_search');

    /* Print header */
    require_once(HESK_PATH . 'inc/header.inc.php');

    /* Print main manage users page */
    require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

    /* This will handle error, success and notice messages */
    if (!hesk_SESSION(array('userdata', 'errors'))) {
        hesk_handle_messages();
    }

    // If POP3 fetching is active, no customer should have the same email address
    if ($hesk_settings['pop3'] && hesk_validateEmail($hesk_settings['pop3_user'], 'ERR', 0))
    {
        $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` WHERE `email` LIKE '".hesk_dbEscape($hesk_settings['pop3_user'])."'");

        if ($myuser = hesk_dbFetchAssoc($res))
        {
            hesk_show_notice(sprintf($hesklang['pop3_warning'], $myuser['name'], $hesk_settings['pop3_user']) . "<br /><br />" . $hesklang['fetch_warning'], $hesklang['warn']);
        }
    }

    // If IMAP fetching is active, no user should have the same email address
    if ($hesk_settings['imap'] && hesk_validateEmail($hesk_settings['imap_user'], 'ERR', 0))
    {
        $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` WHERE `email` LIKE '".hesk_dbEscape($hesk_settings['imap_user'])."'");

        if ($myuser = hesk_dbFetchAssoc($res))
        {
            hesk_show_notice(sprintf($hesklang['imap_warning'], $myuser['name'], $hesk_settings['imap_user']) . "<br /><br />" . $hesklang['fetch_warning'], $hesklang['warn']);
        }
    }

    $approval_res = hesk_dbQuery("SELECT 1 FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` WHERE `verified` = 2");
    $pending_approval_count = hesk_dbNumRows($approval_res);
    if($pending_approval_count > 0) {
        hesk_show_notice(sprintf($hesklang['customer_manage_approvals'], $pending_approval_count));
    }
?>
<div class="main__content team">
    <section class="team__head">
        <h2>
            <?php echo $hesklang['customers']; ?>
            <div class="tooltype right out-close">
                <svg class="icon icon-info">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                </svg>
                <div class="tooltype__content">
                    <div class="tooltype__wrapper">
                        <?php echo $hesklang['customers_intro']; ?>
                    </div>
                </div>
            </div>
        </h2>
        <?php if ($hesk_settings['customer_accounts'] && $can_man_customers): ?>
        <div class="buttons">
            <button class="btn btn btn--blue-border" ripple="ripple" data-action="team-create"><?php echo $hesklang['new_customer']; ?></button>
            <a href="import_customers.php" class="btn btn btn--blue-border" ripple="ripple"><?php echo $hesklang['import_customers']; ?></a>
        </div>
        <?php endif; ?>
    </section>

    <?php
    // START check if we have any customers in the database
    $res = hesk_dbQuery("SELECT EXISTS (SELECT 1 FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers`)");
    if ( ! hesk_dbResult($res)):
        hesk_show_notice(
            $hesklang['no_customers'] . '<br><br>' .
            (
                $hesk_settings['customer_accounts'] ?
                $hesklang['no_customers_enabled'] . ($can_man_customers ? '<br><br>' . $hesklang['no_customers_enabled2'] : '') :
                $hesklang['no_customers_disabled']
            ), ' ', false
        );
    else:
    ?>

    <?php
    $search_name = isset($saved_search['search_name']) ? $saved_search['search_name'] : hesk_REQUEST('search_name');
    $url_name = urlencode($search_name);
    $search_email = isset($saved_search['search_email']) ? $saved_search['search_email'] : hesk_REQUEST('search_email');
    $url_email = urlencode($search_email);

    $pagesizes = [10, 25, 50, 100, 250, 500];
    $search_pagesize = isset($saved_search['search_pagesize']) ? intval($saved_search['search_pagesize']) : intval(hesk_REQUEST('search_pagesize', 20));
    if ( ! in_array($search_pagesize, $pagesizes, true)) {
        $search_pagesize = 20;
    }

    $search_pagenumber = isset($saved_search['search_pagenumber']) ? intval($saved_search['search_pagenumber']) : intval(hesk_REQUEST('search_pagenumber', 1));
    if ($search_pagenumber < 1) {
        $search_pagenumber = 1;
    }

    $search_sort_column = isset($saved_search['search_sort_column']) ? $saved_search['search_sort_column'] : hesk_REQUEST('search_sort_column', 'id');
    if ( ! in_array($search_sort_column, ['id', 'name', 'email', 'tickets'], true)) {
        $search_sort_column = 'name';
    }
    $url_sort_column = urlencode($search_sort_column);

    $search_sort_direction = isset($saved_search['search_sort_direction']) ? $saved_search['search_sort_direction'] : hesk_REQUEST('search_sort_direction', 'DESC');
    $search_sort_direction = $search_sort_direction === 'ASC' ? 'ASC' : 'DESC';
    $url_sort_direction = urlencode($search_sort_direction);

    $query_url = "manage_customers.php?search_name={$url_name}&search_email={$url_email}&search_pagesize={$search_pagesize}&search_sort_column={$url_sort_column}&search_sort_direction={$url_sort_direction}";
    $sort_query_url = $query_url . "&search_pagenumber={$search_pagenumber}";
    ?>
    <form action="manage_customers.php" method="get" name="form1"
          aria-label="<?php echo $hesklang['search_customers']; ?>">
        <div class="table-wrap customers__search">
            <h3><?php echo $hesklang['search_customers']; ?></h3>
            <div class="customers__search_form form">
                <div class="filters">
                    <div class="form-group">
                        <label for="search_name">
                            <?php echo $hesklang['name']; ?>:
                        </label>
                        <input type="text" id="search_name"
                               value="<?php echo stripslashes(hesk_input($search_name)); ?>"
                               name="search_name"
                               class="form-control">
                    </div>
                    <div class="form-group">
                        <label for="search_email">
                            <?php echo $hesklang['email']; ?>:
                        </label>
                        <input type="text" id="search_email"
                               value="<?php echo stripslashes(hesk_input($search_email)); ?>"
                               name="search_email"
                               class="form-control">
                    </div>
                    <div class="form-group">
                        <label for="search_pagesize">
                            <?php echo $hesklang['page_size']; ?>:
                        </label>
                        <select id="search_pagesize" name="search_pagesize">
                            <?php foreach ($pagesizes as $pagesize): ?>
                            <option value="<?php echo $pagesize; ?>" <?php echo $pagesize === $search_pagesize ? 'selected' : '' ?>>
                                <?php echo $pagesize; ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <script>$('#search_pagesize').selectize();</script>
                    </div>
                </div>
                <button type="submit" class="btn btn-full"><?php echo $hesklang['search']; ?></button>
            </div>
        </div>
        <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
    </form>
    <?php if ($can_man_customers || $can_view_customers): ?>
    <?php
    $offset = ($search_pagenumber - 1) * $search_pagesize;

    $where_clause = 'WHERE 1=1 ';
    if ($search_name) {
        $where_clause .= "AND `hc`.`name` LIKE '%".hesk_dbEscape(hesk_dbLike($search_name))."%' ";
    }
    if ($search_email) {
        $where_clause .= "AND `hc`.`email` LIKE '%".hesk_dbEscape(hesk_dbLike($search_email))."%'";
    }
    $count_res = hesk_dbQuery("SELECT COUNT(1) AS `cnt` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` AS `hc`
                    {$where_clause}");
    $total_count = 0;
    if ($row = hesk_dbFetchAssoc($count_res)) {
        $_SESSION['saved_customer_search'] = [
            'search_name' => $search_name,
            'search_email' => $search_email,
            'search_pagesize' => $search_pagesize,
            'search_pagenumber' => $search_pagenumber,
            'search_sort_column' => $search_sort_column,
            'search_sort_direction' => $search_sort_direction
        ];
        $total_count = intval($row['cnt']);
    }

    $res = hesk_dbQuery("SELECT `hc`.*, COUNT(CASE WHEN htc.customer_type = 'REQUESTER' THEN 1 END) AS `tickets`, COUNT(CASE WHEN htc.customer_type = 'FOLLOWER' THEN 1 END) AS `following`
                    FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` AS `hc`
                    LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_customer` AS `htc` ON `hc`.`id` = `htc`.`customer_id`
                    {$where_clause}
                    GROUP BY `hc`.`id`, `hc`.`name`, `hc`.`email`
                    ORDER BY CASE WHEN `hc`.`verified` = 2 THEN 0 ELSE 1 END ASC, `{$search_sort_column}` {$search_sort_direction}
                    LIMIT {$search_pagesize} OFFSET {$offset}");
    $customers = [];
    while ($customer = hesk_dbFetchAssoc($res)) {
        $customers[$customer['id']] = $customer;
    }
    $customer_ids = count($customers) > 0 ?
        array_map(function($customer) { return intval($customer['id']); }, $customers) :
        [-1];

    $pending_delete_modal_ids = [];
    $verified_delete_modal_ids = [];
    $pending_customers = [];
    $verified_customers = [];

    foreach ($customers as $customer) {
        if ($can_man_customers) {
            $modal_body = $hesklang['sure_remove_customer']."<br>".$hesklang['sure_remove_customer_additional_note']."<br>";

            // What to do with tickets opened by this customer?
            if (isset($customer['tickets']) && $customer['tickets'] > 0) {
                $modal_body .= '<br><div role="alert" class="notification orange" style="margin-bottom: 5px">';
                $modal_body .= sprintf($hesklang['deleting_customer_tickets'], $customer['tickets']);
                $modal_body .= '</div>';
                $modal_body .= '
                                <div class="radio-center">
                                    <div class="radio-list">
                                        <div class="radio-custom">
                                            <input type="radio" id="delete-method-retain-'.$customer['id'].'" name="delete-method" value="retain" checked>
                                            <label for="delete-method-retain-'.$customer['id'].'">
                                                <strong>'. $hesklang['deleting_customer_retain_tickets2'] .'</strong><br>
                                            </label>
                                        </div>
                                        <div class="radio-custom">
                                            <input type="radio" id="delete-method-anonymize-'.$customer['id'].'" name="delete-method" value="anonymize">
                                            <label for="delete-method-anonymize-'.$customer['id'].'">
                                                <strong>'. $hesklang['deleting_customer_anonymize_tickets2'] .'</strong><br>
                                            </label>
                                        </div>
                                        <div class="radio-custom">
                                            <input type="radio" id="delete-method-delete-'.$customer['id'].'" name="delete-method" value="delete">
                                            <label for="delete-method-delete-'.$customer['id'].'">
                                                <strong>'. $hesklang['deleting_customer_delete_tickets2'] .'</strong><br>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                                ';
            }

            // Tickets folowed by this customer:
            if (isset($customer['following']) && $customer['following'] > 0) {
                $modal_body .= '<br><div role="status" class="notification blue" style="margin-bottom: 5px">';
                $modal_body .= sprintf($hesklang['deleting_customer_follower'], $customer['following']);
                $modal_body .= '</div>';
            }

            $modal_body .= '<input type="hidden" name="a" value="remove">
                            <input type="hidden" name="id" value="'.$customer['id'].'">
                            <input type="hidden" name="token" value="'.hesk_token_echo(0).'">';

            $modal_id = hesk_generate_delete_modal([
                'title' => $hesklang['confirm_deletion'],
                'body' => $modal_body,
                'confirm_action' => 'manage_customers.php',
                'use_form' => true,
                'form_method' => 'GET'
            ]);
            if (intval($customer['verified']) === 2) {
                $pending_delete_modal_ids[$customer['id']] = $modal_id;
            } else {
                $verified_delete_modal_ids[$customer['id']] = $modal_id;
            }
        }

        if (intval($customer['verified']) === 2) {
            $pending_customers[] = $customer;
        } else {
            $verified_customers[] = $customer;
        }
    }

    $confirm_modal_body = $hesklang['confirm_merge_text']."<br>".$hesklang['confirm_merge_additional_text']."<br>";

    $confirm_modal_id = hesk_generate_delete_modal([
        'title' => $hesklang['confirm_merge'],
        'body' => $confirm_modal_body,
        'confirm_action' => 'manage_customers.php',
        'use_form' => false,
        'form_method' => 'POST',
        'delete_text' => $hesklang['yes_title_case'],
        'cancel_text' => $hesklang['no_title_case'],
        'custom_class' => 'merge_customers'
    ]);

    endif;
    ?>
    <?php if (($can_man_customers || $can_view_customers) && count($pending_customers)>0): ?>
    <form action="manage_customers.php" method="post" name="customersTable" aria-label="<?php echo $hesklang['customers_pending_approval']; ?>">
        <h3 class="cus_label"><?php echo $hesklang['customers_pending_approval']; ?></h3>
        <input type="hidden" name="a" value="bulk">
        <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
        <section class="team__head bulk-actions" id="bulk-buttons">
            <div class="buttons">
                <?php if ($pending_approval_count > 0 && $can_man_customers): ?>
                    <button class="btn btn--blue-border" type="submit" name="bulk_approve"><?php echo $hesklang['customer_manage_bulk_approve']; ?></button>
                    <button class="btn btn--blue-border" type="submit" name="bulk_reject"><?php echo $hesklang['customer_manage_bulk_reject']; ?></button>
                    <button class="btn btn--blue-border" type="submit" name="bulk_delete"><?php echo $hesklang['customer_manage_bulk_delete']; ?></button>
                <?php endif; ?>
            </div>
        </section>
        <?php hesk_render_customer_table($pending_customers,$can_man_customers,$can_merge_customers,$pending_approval_count,$pending_delete_modal_ids,$search_sort_column,$search_sort_direction,$sort_query_url,$url_sort_column,'pending'); ?>
    </form>
    <?php endif; ?>

    <?php if (($can_man_customers || $can_view_customers) && count($verified_customers)>0): ?>
        <?php
        $cls = '';
        if($search_pagesize <= count($pending_customers)){
            $cls = 'd_hide';
        }
        ?>
        <form action="manage_customers.php" method="post" name="customersTable" id="activeCustomersTable" class='<?php echo $cls;?>' aria-label="<?php echo $hesklang['existing_customers']; ?>">
            <h3 class="cus_label"><?php echo $hesklang['existing_customers']; ?></h3>
            <input type="hidden" name="a" value="bulk">
            <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
            <section class="team__head bulk-actions" id="bulk-buttons">
                <div class="buttons">
                    <?php if ($can_man_customers && $can_merge_customers && $hesk_settings['customer_accounts'] > 0): ?>
                        <input type="hidden" name="merge_customers" value="">
                        <button type="button" data-modal="[data-modal-id='<?php echo $confirm_modal_id; ?>']"
                            title="<?php echo $hesklang['merge_selected_customers']; ?>"
                            class="btn btn--blue-border tooltip">
                            <?php echo $hesklang['merge_selected_customers']; ?>
                        </button>
                    <?php endif; ?>
                </div>
            </section>

            <?php hesk_render_customer_table($verified_customers,$can_man_customers,$can_merge_customers,$pending_approval_count,$verified_delete_modal_ids,$search_sort_column, $search_sort_direction,$sort_query_url,$url_sort_column,'active'); ?>
        </form>
    <?php endif; ?>
    <?php
    $total_pages = intval($total_count / $search_pagesize);
    if ($total_count % $search_pagesize !== 0) {
        $total_pages++;
    }
    hesk_output_pager($total_count, $total_pages, $search_pagenumber, $query_url, 'search_pagenumber');
    ?>

    <?php
    endif; // END check if we have any customers in the database
    ?>
</div>

<?php if ($can_man_customers || $can_merge_customers): ?>
<script>
function toggleCheckboxes(id) {
    // Find the master checkbox
    var master = document.getElementById(id);
    if (!master) return;

    // Find the form/table this master belongs to
    var form = master.closest("form");
    if (!form) return;

    // Clear selections in other forms
    document.querySelectorAll('form').forEach(f => {
        if (f !== form && f.querySelector('.customer-checkbox')) {
            f.querySelectorAll('.customer-checkbox').forEach(cb => cb.checked = false);
            const otherMaster = f.querySelector("input[id^='customer_checkall_']");
            if (otherMaster) otherMaster.checked = false;
            const otherBulk = f.querySelector('.bulk-actions');
            //if (otherBulk) otherBulk.style.display = 'none';
        }
    });

    // Apply master checkbox state to row checkboxes
    form.querySelectorAll('.customer-checkbox').forEach(cb => cb.checked = master.checked);

    updateBulkButtonState(form);
}

function updateBulkButtonState(elem) {
    let form = null;

    if (elem) {
        form = elem.closest('form');
    }
    if (!form) return;

    // If a row checkbox was checked then clear selections in all other forms
    if (elem.classList && elem.classList.contains('customer-checkbox') && elem.checked) {
        document.querySelectorAll('form').forEach(f => {
            if (f !== form && f.querySelector('.customer-checkbox')) {
                f.querySelectorAll('.customer-checkbox').forEach(cb => cb.checked = false);
                const otherMaster = f.querySelector("input[id^='customer_checkall_']");
                if (otherMaster) otherMaster.checked = false;
                const otherBulk = f.querySelector('.bulk-actions');
                //if (otherBulk) otherBulk.style.display = 'none';
            }
        });
    }

    // Now update current form state
    const rowCheckboxes = form.querySelectorAll('.customer-checkbox');
    const checkedCount = form.querySelectorAll('.customer-checkbox:checked').length;

    // Sync master checkbox state
    const master = form.querySelector("input[id^='customer_checkall_']");
    if (master) {
        master.checked = (rowCheckboxes.length > 0 && checkedCount === rowCheckboxes.length);
    }

    // Show/hide bulk actions
    const bulk = form.querySelector('.bulk-actions');
    /*
    if (bulk) {
        bulk.style.display = (checkedCount > 0) ? 'flex' : 'none';
    }
    */
}


$('body').on('click','.merge_customers',function(e){
    e.preventDefault();
    $('#activeCustomersTable').submit();
});

</script>
<?php endif; ?>

<?php if ($can_man_customers): ?>
<div class="right-bar team-create customer" <?php echo hesk_SESSION(array('userdata','errors')) ? 'style="display: block"' : ''; ?>>
    <div class="right-bar__body form" data-step="1">
        <h3>
            <a href="manage_customers.php?a=reset_form">
                <svg class="icon icon-back">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                </svg>
                <span><?php echo $hesklang['add_user']; ?></span>
            </a>
        </h3>
        <?php
        if (hesk_SESSION(array('userdata', 'errors'))) {
            hesk_handle_messages();
        }
        ?>
        <form name="form1" method="post" action="manage_customers.php" class="form <?php echo hesk_SESSION(array('userdata','errors')) ? 'invalid' : ''; ?>" aria-label="<?php echo $hesklang['can_man_customers']; ?>">
            <?php hesk_customer_tab('userdata'); ?>

            <!-- Submit -->
            <div class="right-bar__footer">
                <input type="hidden" name="a" value="new">
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                <button type="submit" class="btn btn-full save" data-action="save" ripple="ripple"><?php echo $hesklang['create_user']; ?></button>
            </div>
        </form>
    </div>
</div>
<script>
function pwToggle(pwId, eyeClosedId, eyeOpenId, pw, stars) {
    var pwEl = document.getElementById(pwId);
    var eyeClosed = document.getElementById(eyeClosedId);
    var eyeOpen = document.getElementById(eyeOpenId);

    var visible = pwEl.textContent === pw;

    pwEl.textContent = visible ? stars : pw;
    eyeClosed.style.display = visible ? '' : 'none';
    eyeOpen.style.display   = visible ? 'none' : '';
}
</script>
<?php
endif;
unset($_SESSION['seluser']);

require_once(HESK_PATH . 'inc/footer.inc.php');
exit();

} // End else


/*** START FUNCTIONS ***/


function compare_user_permissions($compare_id, $compare_isadmin = null, $compare_categories = null, $compare_features = null)
{
	global $hesk_settings;

    /* Comparing myself? */
    if ($compare_id == $_SESSION['id'])
    {
    	return true;
    }

    /* Admins have full access, no need to compare */
	if ($_SESSION['isadmin'])
    {
    	return true;
    }
    elseif ($compare_isadmin)
    {
    	return false;
    }

    // Do we need to get data from the database?
    if ($compare_categories === null)
    {
        $res = hesk_dbQuery("SELECT `isadmin`, `categories`, `heskprivileges` AS `features` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id`='".intval($compare_id)."' LIMIT 1");
        $row = hesk_dbFetchAssoc($res);

        // If this user is an admin and we're not - no need to check further
        if ($row['isadmin'])
        {
            return false;
        }

        $compare_features = explode(',', $row['features']);
        $compare_categories = explode(',', $row['categories']);
    }

	/* Compare categories */
    foreach ($compare_categories as $catid)
    {
    	if ( ! array_key_exists($catid, $hesk_settings['categories']) )
        {
        	return false;
        }
    }

	/* Compare features */
    foreach ($compare_features as $feature)
    {
    	if ( ! in_array($feature, $hesk_settings['features']) )
        {
        	return false;
        }
    }

    return true;

} // END compare_user_permissions()


function edit_user()
{
	global $hesk_settings, $hesklang, $default_userdata;

	$id = intval( hesk_GET('id') ) or hesk_error("$hesklang[int_error]: $hesklang[no_valid_id]");
    $trackingID = hesk_cleanID();
    $return_url = $trackingID ? "admin_ticket.php?track={$trackingID}" : 'manage_customers.php';

    $_SESSION['edit_userdata'] = TRUE;

    if ( ! isset($_SESSION['save_userdata']))
    {
		$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` WHERE `id`= {$id} LIMIT 1");
    	$_SESSION['userdata'] = hesk_dbFetchAssoc($res);

        if (defined('HESK_DEMO')) {
            $_SESSION['userdata']['email'] = 'hidden@demo.com';
        }

        /* Store original username for display until changes are saved successfully */
        $_SESSION['original_user'] = $_SESSION['userdata']['email'];
        $_SESSION['userdata']['cleanpass'] = '';
    }

    /* Print header */
	require_once(HESK_PATH . 'inc/header.inc.php');

	/* Print main manage users page */
	require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');
	?>
    <div class="right-bar team-create customer" style="display: block">
        <div class="right-bar__body form" data-step="1">
            <h3>
                <a href="<?php echo $return_url; ?>">
                    <svg class="icon icon-back">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                    </svg>
                    <span><?php echo $hesklang['editing_user'].' '.$_SESSION['original_user']; ?></span>
                </a>
            </h3>
            <?php
            if (hesk_SESSION(array('userdata', 'errors'))) {
                hesk_handle_messages();
            }
            ?>
            <form name="form1" method="post" action="manage_customers.php" class="form <?php echo hesk_SESSION(array('userdata','errors')) ? 'invalid' : ''; ?>" aria-label="<?php echo $hesklang['can_man_customers']; ?>">
                <?php hesk_customer_tab('userdata', intval($_SESSION['userdata']['verified']) === 1); ?>

                <!-- Submit -->
                <div class="right-bar__footer">
                    <input type="hidden" name="a" value="save">
                    <input type="hidden" name="userid" value="<?php echo $id; ?>" />
                    <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                    <input type="hidden" name="track" value="<?php echo $trackingID; ?>">
                    <button type="submit" class="btn btn-full save" data-action="save" ripple="ripple"><?php echo $hesklang['save_changes']; ?></button>
                </div>
            </form>
        </div>
    </div>

	<?php
	require_once(HESK_PATH . 'inc/footer.inc.php');
	exit();
} // End edit_user()


function new_user()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check('POST');

	$myuser = hesk_validateUserInfo();

    // Check for duplicate emails. Don't care about registration state as the staff member can update an existing record
    if (strlen($myuser['email'])) {
        $result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` WHERE `email` = '".hesk_dbEscape($myuser['email'])."' LIMIT 1");
        if (hesk_dbNumRows($result) != 0) {
            hesk_process_messages($hesklang['customer_name_email_exists'],'manage_customers.php');
        }
    }

    $pass = $myuser['pass'] === null ? 'NULL' : "'".hesk_dbEscape($myuser['pass'])."'";

	hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` (
	`pass`,
	`name`,
	`email`,
	`language`,
	`verified`,
	`verification_token`,
	`mfa_enrollment`,
	`mfa_secret`
	) VALUES (
	".$pass.",
	'".hesk_dbEscape($myuser['name'])."',
	'".hesk_dbEscape($myuser['email'])."',
	NULL,
	".intval($myuser['verified']).",
	NULL,
	0,
	NULL
	)" );

    $_SESSION['seluser'] = [hesk_dbInsertID()];

    unset($_SESSION['userdata']);

    // No user password, show the success message
    if ($myuser['pass'] === null) {
        hesk_process_messages(sprintf($hesklang['user_added_success_no_pass'],$myuser['email']),'./manage_customers.php','SUCCESS');
    }

    // User with a password, show a success message with the password hidden
    $stars = str_repeat('*', strlen($myuser['cleanpass']));

    $passwordHtml = '
    <span id="pw_1" style="font-weight:bold">'.$stars.'</span>
    <span onclick="pwToggle(\'pw_1\', \'eyeClosed_1\', \'eyeOpen_1\', \''.$myuser['cleanpass'].'\', \''.$stars.'\')" style="cursor:pointer;vertical-align:middle">
        <svg class="icon icon-eye-close" id="eyeClosed_1">
            <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-eye-close"></use>
        </svg>
        <svg class="icon icon-eye-open" id="eyeOpen_1" style="display:none">
            <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-eye-open"></use>
        </svg>
    </span>
    ';

    hesk_process_messages(sprintf($hesklang['user_added_success'],$myuser['email'],$passwordHtml),'./manage_customers.php','SUCCESS');
} // End new_user()


function update_user()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check('POST');

    $_SESSION['save_userdata'] = TRUE;

	$tmp = intval( hesk_POST('userid') ) or hesk_error("$hesklang[int_error]: $hesklang[no_valid_id]");
    $trackingID = hesk_cleanID();

    $_SERVER['PHP_SELF'] = './manage_customers.php?a=edit&track='.$trackingID.'&id='.$tmp;
	$myuser = hesk_validateUserInfo($_SERVER['PHP_SELF']);
    $myuser['id'] = $tmp;

    /* Check for duplicate emails.  Don't care about registration state as the staff member can update an existing record */
    if ( ! empty($myuser['email'])) {
        $result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers`
            WHERE `email` = '".hesk_dbEscape($myuser['email'])."'
                AND `id` <> ".intval($myuser['id'])."
            LIMIT 1");
        if (hesk_dbNumRows($result) != 0) {
            hesk_process_messages($hesklang['customer_name_email_exists'],'manage_customers.php');
        }
    }

	$olduser = array('email' => '', 'verified' => 0);
	$res = hesk_dbQuery("SELECT `id`, `email`, `verified` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` WHERE `id` = ".intval($tmp));
	if (hesk_dbNumRows($res) == 1)
	{
    	$olduser = hesk_dbFetchAssoc($res);
        $myuser['verified'] = $myuser['verified'] === 1 ? 1 : intval($olduser['verified']);
	}

    $password_part = '';
    if ($myuser['pass'] !== null && $hesk_settings['customer_accounts']) {
        $password_part = "`pass`='".hesk_dbEscape($myuser['pass'])."', `verification_token` = NULL, ";
        $myuser['verified'] = 1;
    }

    $delete_auth_tokens = $myuser['pass'] !== null || strcasecmp($olduser['email'], $myuser['email']) !== 0 || intval($olduser['verified']) !== intval($myuser['verified']);

    hesk_dbQuery(
    "UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` SET
    `name`='".hesk_dbEscape($myuser['name'])."',
    `email`='".hesk_dbEscape($myuser['email'])."',
    {$password_part}
    `verified`=".$myuser['verified']."
    WHERE `id`='".intval($myuser['id'])."'");

    if ($delete_auth_tokens) {
        hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."auth_tokens` WHERE `user_id` = ".intval($myuser['id'])." AND `user_type` = 'CUSTOMER'");
    }

    // Is the customer verified? Merge accounts if needed
    if ($myuser['verified'] === 1) {
        $merging_needed_rs = hesk_dbQuery("SELECT 1 AS `counter` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` 
        WHERE `email` = '".hesk_dbEscape($myuser['email'])."'");
        if (hesk_dbNumRows($merging_needed_rs) > 1) {
            hesk_merge_customer_accounts($myuser['email']);
        }
    }

    unset($_SESSION['save_userdata']);
    unset($_SESSION['userdata']);

    $_SESSION['seluser'] = [$myuser['id']];

    $return_url = $trackingID !== '' ? "./admin_ticket.php?track={$trackingID}" : './manage_customers.php';
    hesk_process_messages( $hesklang['user_profile_updated_success'], $return_url,'SUCCESS');
} // End update_profile()


function hesk_validateUserInfo($redirect_to = './manage_customers.php')
{
	global $hesk_settings, $hesklang;

    $hesk_error_buffer = '';
    $errors = array();

    if (hesk_input(hesk_POST('name'))) {
        $myuser['name'] = hesk_input(hesk_POST('name'));
    } else {
        $hesk_error_buffer .= '<li>' . $hesklang['enter_real_name'] . '</li>';
        $errors[] = 'name';
    }

    $myuser['email'] = hesk_validateEmail( hesk_POST('email'), 'ERR', 0);
    if (empty($myuser['email'])) {
        if (! $hesk_settings['require_email']) {
            $myuser['email'] = '';
        } else {
            $hesk_error_buffer .= '<li>' . $hesklang['enter_valid_email'] . '</li>';
            $errors[] = 'email';
        }
    }

    /* Password */
	$myuser['cleanpass'] = '';
    $myuser['pass'] = null;
    $myuser['verified'] = 0;

	$newpass = hesk_input( hesk_POST('newpass') );
	$passlen = strlen($newpass);

	if ($passlen > 0)
	{
        /* At least 5 chars? */
        if ($passlen < 5)
        {
        	$hesk_error_buffer .= '<li>' . $hesklang['password_not_valid'] . '</li>';
        	$errors[] = 'passwords';
        }
        // Too long?
        elseif ($passlen > 64)
        {
            $hesk_error_buffer .= '<li>' . $hesklang['pass_len'] . '</li>';
            $errors[] = 'passwords';
        }
        /* Check password confirmation */
        else
        {
        	$newpass2 = hesk_input( hesk_POST('newpass2') );

			if ($newpass != $newpass2)
			{
				$hesk_error_buffer .= '<li>' . $hesklang['passwords_not_same'] . '</li>';
                $errors[] = 'passwords';
			}
            else
            {
                $myuser['pass'] = hesk_password_hash($newpass);
                $myuser['cleanpass'] = $newpass;
                $myuser['verified'] = 1;
                define('PASSWORD_CHANGED', true);
            }
        }
	}

    /* Save entered info in session so we don't lose it in case of errors */
	$_SESSION['userdata'] = $myuser;

    /* Any errors */
    if (strlen($hesk_error_buffer))
    {
        $_SESSION['userdata']['errors'] = $errors;

        $hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
    	hesk_process_messages($hesk_error_buffer,$redirect_to);
    }

	return $myuser;
} // End hesk_validateUserInfo()


function remove()
{
	global $hesk_settings, $hesklang, $can_man_customers;

	/* A security check */
	hesk_token_check();
    $_SESSION['save_customer_search'] = true;

	$myuser = intval( hesk_GET('id' ) ) or hesk_error($hesklang['no_valid_id']);

    // Make sure we have permission to edit this user
    if (!$can_man_customers) {
        hesk_process_messages($hesklang['customer_permission_denied'],'manage_customers.php');
    }

    // Should we delete or anonymize tickets opened by this customer?
    $delete_method = hesk_GET('delete-method');
    if ($delete_method === 'delete') {
        hesk_deleteTicketsForCustomer($myuser);
    } elseif ($delete_method === 'anonymize') {
        hesk_anonymizeTicketsForCustomer($myuser);
    } else {
        // Keep tickets
    }

    // Remove customer from all tickets
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_customer` WHERE `customer_id` = ".$myuser);

    // Delete user info
	$res = hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` WHERE `id`='".$myuser."'");
	if (hesk_dbAffectedRows() != 1) {
        hesk_process_messages($hesklang['int_error'].': '.$hesklang['user_not_found'],'./manage_customers.php');
    }

    // Clear users' MFA tokens, MFA backup codes and auth tokens
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."mfa_verification_tokens` WHERE `user_id` = {$myuser} AND `user_type` = 'CUSTOMER'");
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."mfa_backup_codes` WHERE `user_id` = {$myuser} AND `user_type` = 'CUSTOMER'");
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."auth_tokens` WHERE `user_id` = {$myuser} AND `user_type` = 'CUSTOMER'");

    hesk_process_messages($hesklang['sel_user_removed'],'./manage_customers.php','SUCCESS');
} // End remove()

function reset_mfa() {
    global $hesk_settings, $hesklang, $can_man_customers;

    /* A security check */
    hesk_token_check();

    require(HESK_PATH . 'inc/mfa_functions.inc.php');

    $myuser = intval(hesk_GET('id')) or hesk_error($hesklang['no_valid_id']);

    // Make sure we have permission to edit this user
    if (!$can_man_customers) {
        hesk_process_messages($hesklang['customer_permission_denied'],'manage_customers.php');
    }

    $_SESSION['seluser'] = [$myuser];
    $_SESSION['save_customer_search'] = true;

    $target_enrollment = 0;
    if ($hesk_settings['require_mfa_customers']) {
        $target_enrollment = 1;
    }

    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` SET `mfa_enrollment` = {$target_enrollment}, `mfa_secret` = NULL WHERE `id` = {$myuser}");

    if (hesk_dbAffectedRows() != 1) {
        hesk_process_messages($hesklang['int_error'].': '.$hesklang['user_not_found'],'./manage_customers.php');
    }

    delete_mfa_backup_codes($myuser, 'CUSTOMER');
    delete_mfa_codes($myuser, 'CUSTOMER');
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."auth_tokens` WHERE `user_id` = {$myuser} AND `user_type` = 'CUSTOMER'");

    hesk_process_messages($hesklang['mfa_reset'], './manage_customers.php', 'SUCCESS');
}

function approve_registration($redirect = true) {
    global $hesk_settings, $hesklang;

    hesk_token_check();

    $myuser = intval( hesk_GET('id' ) ) or hesk_error($hesklang['no_valid_id']);

    $_SESSION['save_customer_search'] = true;

    $user_rs = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` WHERE `id` = ".intval($myuser));
    
    if (!hesk_dbNumRows($user_rs)) {
        hesk_process_messages($hesklang['int_error'].': '.$hesklang['user_not_found'],'./manage_customers.php');
    }
    $user = hesk_dbFetchAssoc($user_rs);

    //Only pending customers can be approved
    if ($user['verified'] == '2') {

        $_SESSION['seluser'] = [$myuser];

        // Approve the registration
        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` SET `verified` = 1 WHERE `id` = ".intval($myuser));
        hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."auth_tokens` WHERE `user_id` = ".intval($myuser)." AND `user_type` = 'CUSTOMER'");

        // Send approval email
        if (!function_exists('hesk_sendCustomerRegistrationApprovedEmail')) {
            require(HESK_PATH . 'inc/email_functions.inc.php');
        }
        hesk_sendCustomerRegistrationApprovedEmail($user);

        if ($redirect) {
            hesk_process_messages($hesklang['customer_account_approved'], 'manage_customers.php', 'SUCCESS');
        }
    }    

}

function reject_registration($redirect = true, $send_email_notification = true) {
    global $hesk_settings, $hesklang;

    hesk_token_check();

    $myuser = intval( hesk_GET('id' ) ) or hesk_error($hesklang['no_valid_id']);
    $_SESSION['save_customer_search'] = true;

    $user_rs = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` WHERE `id` = ".intval($myuser));
    if (!hesk_dbNumRows($user_rs)) {
        hesk_process_messages($hesklang['int_error'].': '.$hesklang['user_not_found'],'./manage_customers.php');
    }
    $user = hesk_dbFetchAssoc($user_rs);

    //Only pending customers can be rejected
    if ($user['verified'] == '2') {

        $_SESSION['seluser'] = [$myuser];

        // Reject the registration
        hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` WHERE `id` = ".intval($myuser));

        // Send email notification
        if ($send_email_notification) {
            if (!function_exists('hesk_sendCustomerRegistrationRejectedEmail')) {
                require(HESK_PATH . 'inc/email_functions.inc.php');
            }
            hesk_sendCustomerRegistrationRejectedEmail($user);
        }

        if ($redirect) {
            hesk_process_messages($hesklang['customer_account_rejected'], 'manage_customers.php', 'SUCCESS');
        }
    }
}

function delete_registration($redirect = true) {
    global $hesk_settings, $hesklang;

    hesk_token_check();
    $myuser = intval( hesk_GET('id' ) ) or hesk_error($hesklang['no_valid_id']);

    $user_rs = hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` WHERE `id` = ".intval($myuser));
    if (hesk_dbAffectedRows($user_rs) != 1) {
        hesk_process_messages($hesklang['int_error'].': '.$hesklang['user_not_found'],'./manage_customers.php');
    }

    if ($redirect) {
        hesk_process_messages($hesklang['customer_account_deleted'], 'manage_customers.php', 'SUCCESS');
    }
}

function handle_bulk_action() {
    global $hesk_settings, $hesklang;

    $_SESSION['save_customer_search'] = true;

    $ids = hesk_POST_array('id');
    $ids = array_map('intval', $ids);
    $ids = array_unique($ids);
    $ids = array_filter($ids, function ($x) {return $x > 0;});

    if (count($ids) < 1) {
        hesk_process_messages($hesklang['no_cust_sel'], 'manage_customers.php');
    }

    $_SESSION['seluser'] = [];
    $sel_ids = [];

    if (isset($_POST['bulk_approve'])) {
        foreach ($ids as $customer_id) {
            $_GET['id'] = $customer_id;
            approve_registration(false);

            if (isset($_SESSION['seluser'][0])) {
                $sel_ids[] = $_SESSION['seluser'][0];
            }
        }
        $message = $hesklang['customer_manage_bulk_approve_complete'];
    } elseif (isset($_POST['bulk_reject'])) {
        foreach ($ids as $customer_id) {
            $_GET['id'] = $customer_id;
            reject_registration(false);

            if (isset($_SESSION['seluser'][0])) {
                $sel_ids[] = $_SESSION['seluser'][0];
            }
        }
        $message = $hesklang['customer_manage_bulk_reject_complete'];
    } elseif (isset($_POST['bulk_delete'])) {
        foreach ($ids as $customer_id) {
            $_GET['id'] = $customer_id;
            delete_registration(false);
        }
        $message = $hesklang['customer_manage_bulk_delete_complete'];
    } elseif (isset($_POST['merge_customers'])) {

        // Check permissions for this feature
        hesk_checkPermission('can_merge_customers');

        // A security check
        hesk_token_check('POST');

        // We need more than 1 valid customer ID selected
        if ( ! isset($_POST['id'])) {
            hesk_process_messages($hesklang['merge_customer_err'] . ' ' . $hesklang['merge_more_error'],'manage_customers.php');
        }

        $merge_these = array();
        foreach ($_POST['id'] as $id) {
            $id = intval($id);
            if ($id > 0) {
                $merge_these[] = $id;
            }
        }

        if ( count($merge_these) < 1 ) {
            hesk_process_messages($hesklang['merge_customer_err'] . ' ' . $hesklang['merge_more_error'],'manage_customers.php');
        }

        // Sort IDs, customers will be merged to the lowest ID
        sort($merge_these, SORT_NUMERIC);

        // Select lowest ID as the target customer
        $merge_into = array_shift($merge_these);

        // Merge customers or throw an error
        if ( hesk_mergeCustomers($merge_these , $merge_into) ) {
            hesk_process_messages($hesklang['customer_merge_complete'],'manage_customers.php','SUCCESS');
        } else {
            $hesklang['merge_customer_err'] .= ' ' . $_SESSION['error'];
            hesk_cleanSessionVars($_SESSION['error']);
            hesk_process_messages($hesklang['merge_customer_err'],'manage_customers.php');
        }
    } else {
        hesk_error($hesklang['int_error'].': '.$hesklang['invalid_action']);
    }

    //Only pending customers can be approve or reject
    $total_ids = [];
    if (isset($_POST['bulk_approve']) || isset($_POST['bulk_reject'])) {
        $total_ids = $ids;
        $sel_ids = array_unique($sel_ids);
    } else {
        $_SESSION['seluser'] = $ids;
    }
    if ((isset($_POST['bulk_approve']) || isset($_POST['bulk_reject'])) && (count($sel_ids) == "0" || count($sel_ids) < count($total_ids))) {
        if (count($sel_ids) == "0") {
            hesk_process_messages($hesklang['error_msg_for_approved'],'manage_customers.php', 'ERROR');
        } else {
            hesk_process_messages(sprintf($message, count($sel_ids)).' ('.$hesklang['error_msg_for_approved'].')', 'manage_customers.php', 'SUCCESS');
        }
    }

    hesk_process_messages(sprintf($message, count($ids)), 'manage_customers.php', 'SUCCESS');
}

function resend_verification_email() {
    global $hesklang, $hesk_settings;

    $_SESSION['save_customer_search'] = true;
    $id = intval(hesk_GET('id', 0));
    if (!$id) {
        hesk_process_messages($hesklang['no_valid_id'], 'manage_customers.php');
        return;
    }

    $user_info_rs = hesk_dbQuery("SELECT *
        FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` AS `customer` 
        WHERE `id` = {$id} 
        AND `verified` = 0 
        AND `verification_token` IS NOT NULL
        LIMIT 1");

    if (hesk_dbNumRows($user_info_rs) !== 1) {
        hesk_process_messages($hesklang['no_valid_id'], 'manage_customers.php');
        return;
    }

    if (!function_exists('hesk_sendCustomerRegistrationEmail')) {
        require_once(HESK_PATH . 'inc/email_functions.inc.php');
    }

    $user_info = hesk_dbFetchAssoc($user_info_rs);
    hesk_sendCustomerRegistrationEmail($user_info, $user_info['verification_token']);
    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."customers`
        SET `verification_email_sent_at` = NOW()
        WHERE `id` = ".intval($user_info['id']));

    if (isset($_SESSION['img_verified']))
    {
        unset($_SESSION['img_verified']);
    }
    hesk_process_messages(sprintf($hesklang['customer_manage_verification_email_sent'], $user_info['email']), 'manage_customers.php', 'SUCCESS');
}

function build_sort_url($original_url, $current_sort_field, $sort_field, $current_sort_direction) {
    $target_sort_direction = $current_sort_direction === 'ASC' && $sort_field === $current_sort_field ? 'DESC' : 'ASC';
    $encoded_field = urlencode($sort_field);

    $new_url = str_replace("search_sort_column={$current_sort_field}", "search_sort_column={$encoded_field}", $original_url);
    $new_url = str_replace("search_sort_direction={$current_sort_direction}", "search_sort_direction=", $new_url);
    return str_replace("search_sort_direction=", "search_sort_direction={$target_sort_direction}", $new_url);
}

function hesk_render_customer_table($customers,$can_man_customers,$can_merge_customers,$pending_approval_count,$delete_modal_ids,$search_sort_column, $search_sort_direction,$sort_query_url,$url_sort_column,$check_ext) {
    global $hesklang, $hesk_settings;
    ?>
    <div class="table-wrap">
            <div class="table">
                <table id="default-table" class="table sindu-table">
                    <thead>
                    <tr>
                        <?php /*if (($pending_approval_count > 0 && $can_man_customers) || ($can_merge_customers && $hesk_settings['customer_accounts']>0)):*/ ?>
                        <?php if ($pending_approval_count > 0 && $can_man_customers && $check_ext == 'pending'): ?>
                            <th class="table__first_th sindu_handle" aria-label="<?php echo $hesklang['a_select']; ?>">
                                <div class="checkbox-custom">
                                    <input type="checkbox" id="customer_checkall_<?php echo $check_ext; ?>" onclick="toggleCheckboxes('customer_checkall_<?php echo $check_ext; ?>')">
                                    <label for="customer_checkall_<?php echo $check_ext; ?>">&nbsp;</label>
                                </div>
                            </th>
                        <?php elseif ($can_man_customers && $can_merge_customers && $hesk_settings['customer_accounts'] > 0): ?>
                            <th class="table__first_th sindu_handle" aria-label="<?php echo $hesklang['a_select']; ?>">
                            </th>
                        <?php endif; ?>
                        <th class="sindu-handle <?php echo $search_sort_column === 'id' ? hesk_mb_strtolower($search_sort_direction) : '' ?>">
                            <a href="<?php echo build_sort_url($sort_query_url, $url_sort_column, 'id', $search_sort_direction); ?>" aria-label="<?php echo ($hesklang['sort_by'] . ' ' .  $hesklang['id']); ?>">
                                <div class="sort">
                                    <span><?php echo $hesklang['id']; ?></span>
                                    <i class="handle"></i>
                                </div>
                            </a>

                        </th>
                        <th class="sindu-handle <?php echo $search_sort_column === 'name' ? hesk_mb_strtolower($search_sort_direction) : '' ?>">
                            <a href="<?php echo build_sort_url($sort_query_url, $url_sort_column, 'name', $search_sort_direction); ?>" aria-label="<?php echo ($hesklang['sort_by'] . ' ' .  $hesklang['name']); ?>">
                                <div class="sort">
                                    <span><?php echo $hesklang['name']; ?></span>
                                    <i class="handle"></i>
                                </div>
                            </a>
                        </th>
                        <th class="sindu-handle <?php echo $search_sort_column === 'email' ? hesk_mb_strtolower($search_sort_direction) : '' ?>">
                            <a href="<?php echo build_sort_url($sort_query_url, $url_sort_column, 'email', $search_sort_direction); ?>" aria-label="<?php echo ($hesklang['sort_by'] . ' ' .  $hesklang['email']); ?>">
                                <div class="sort">
                                    <span><?php echo $hesklang['email']; ?></span>
                                    <i class="handle"></i>
                                </div>
                            </a>
                        </th>
                        <th class="sindu-handle <?php echo $search_sort_column === 'tickets' ? hesk_mb_strtolower($search_sort_direction) : '' ?>">
                            <a href="<?php echo build_sort_url($sort_query_url, $url_sort_column, 'tickets', $search_sort_direction); ?>" aria-label="<?php echo ($hesklang['sort_by'] . ' ' .  $hesklang['tickets']); ?>">
                                <div class="sort">
                                    <span><?php echo $hesklang['not']; ?></span>
                                    <i class="handle"></i>
                                </div>
                            </a>
                        </th>
                        <th><?php echo $hesklang['mfa_short']; ?></th>
                        <?php if ($can_man_customers): ?>
                            <th aria-label="Actions"></th>
                        <?php endif; ?>
                    </tr>
                    </thead>
                    <tbody>
                    <?php
                    foreach ($customers as $myuser) {
                        if (defined('HESK_DEMO')) {
                            $myuser['email'] = 'hidden@demo.com';
                        }

                        $table_row = '';
                        if (isset($_SESSION['seluser']) && is_array($_SESSION['seluser']) && in_array($myuser['id'], $_SESSION['seluser'])) {
                            $table_row = 'class="ticket-new"';
                            $index = array_search($myuser['id'], $_SESSION['seluser']);
                            unset($_SESSION['seluser'][$index]);
                        }

                        //$checkbox_code = ($pending_approval_count > 0 && $can_man_customers) || ($can_merge_customers && $hesk_settings['customer_accounts'] > 0) ? '<td></td>' : '';
                        $checkbox_code = '';
                        $approval_code = '';
                        if ($can_man_customers && intval($myuser['verified']) === 2 || ($can_man_customers && $can_merge_customers && $hesk_settings['customer_accounts'] > 0)) {
                            if ($can_man_customers && intval($myuser['verified']) === 2){
                                $table_row = 'class="pending-approval"';
                            }
                            $checkbox_code = '<td class="table__first_th sindu_handle"><div class="checkbox-custom">
                            <input type="checkbox" id="customer_check_'.$myuser['id'].'" name="id[]" value="'.$myuser['id'].'" class="customer-checkbox" onchange="updateBulkButtonState(this)">
                            <label for="customer_check_'.$myuser['id'].'" aria-label="' . $hesklang['select'] . '">&nbsp;</label>
                        </div></td>';
                            if ($can_man_customers && intval($myuser['verified']) === 2){
                                $approval_code = '
                                <a href="manage_customers.php?a=approve&amp;id='.$myuser['id'].'&amp;token='.hesk_token_echo(0).'" class="edit tooltip"
                                    title="'.$hesklang['customer_manage_approve'].'">
                                    <svg class="icon icon-tick">
                                        <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-tick"></use>
                                    </svg>
                                </a>
                                <a href="manage_customers.php?a=reject&amp;id='.$myuser['id'].'&amp;token='.hesk_token_echo(0).'" class="edit tooltip" title="'.$hesklang['customer_manage_reject'].'">
                                    <svg class="icon icon-cross">
                                        <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-cross"></use>
                                    </svg>
                                </a>
                                <a href="manage_customers.php?a=delete&amp;id='.$myuser['id'].'&amp;token='.hesk_token_echo(0).'" class="edit tooltip" title="'.$hesklang['customer_manage_delete'].'">
                                    <svg class="icon icon-cross">
                                        <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-delete"></use>
                                    </svg>
                                </a>';
                            }   
                        } else {
                            $approval_code = '';
                        }

                        if ($can_man_customers && intval($myuser['verified']) !== 2) {
                            $edit_code = '
                            <a href="manage_customers.php?a=edit&amp;id='.$myuser['id'].'" class="edit tooltip" title="'.$hesklang['edit'].'">
                                <svg class="icon icon-edit-ticket">
                                    <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-edit-ticket"></use>
                                </svg>
                            </a>';
                        } else {
                            $edit_code = '';
                        }

                        if ($can_man_customers && intval($myuser['verified']) !== 2) {
                            $remove_code = '
                        <a href="javascript:" data-modal="[data-modal-id=\''.$delete_modal_ids[$myuser['id']].'\']"
                            title="'.$hesklang['remove'].'"
                            class="delete tooltip">
                            <svg class="icon icon-delete">
                                <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-delete"></use>
                            </svg>
                        </a>';
                        } else {
                            $remove_code = '';
                        }
                        if ($can_man_customers && intval($myuser['verified']) === 0 && $myuser['verification_token'] !== null) {
                            $resend_email_code = '
                        <a href="manage_customers.php?a=resend_verification_email&amp;id='.$myuser['id'].'"
                            title="'.$hesklang['customer_login_resend_verification_email'].'"
                            class="delete tooltip">
                            <svg class="icon icon-mail">
                                <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-mail"></use>
                            </svg>
                        </a>';
                        } else {
                            $resend_email_code = '';
                        }

                        $myuser_name = hesk_htmlspecialchars(hesk_htmlspecialchars_decode($myuser['name']));
                        $myuser_email = hesk_htmlspecialchars(hesk_htmlspecialchars_decode($myuser['email']));

                        echo <<<EOC
                        <tr $table_row>
                        $checkbox_code
                        <td>$myuser[id]</td>
                        <td>$myuser_name</td>
                        <td><a href="mailto:$myuser_email" aria-label="Mail to">$myuser_email</a></td>
                        <td><a href="find_tickets.php?what=customer&amp;q={$myuser['id']}&amp;s_my=1&amp;s_ot=1&amp;s_un=1">$myuser[tickets]</a></td>

EOC;

                        $mfa_enrollment = intval($myuser['mfa_enrollment']);
                        $mfa_status = $hesklang['mfa_method_none'];
                        $mfa_reset = '';
                        $modal_id = hesk_generate_old_delete_modal($hesklang['mfa_reset_to_default'],
                            $hesklang['mfa_reset_confirm'],
                            'manage_customers.php?a=resetmfa&amp;id='.$myuser['id'].'&amp;token='.hesk_token_echo(0),
                            $hesklang['mfa_reset_yes']);

                        if ($mfa_enrollment === 1) {
                            $mfa_status = $hesklang['mfa_method_email'];

                            if (!$hesk_settings['require_mfa_customers'] && $can_man_customers) {

                                $mfa_reset = '<div class="tooltype right out-close">
                                <a href="javascript:" data-modal="[data-modal-id=\''.$modal_id.'\']"
                                    title="'.$hesklang['mfa_reset_to_default'].'"
                                    class="delete tooltip">
                                    <svg class="icon icon-refresh">
                                        <use xlink:href="'. HESK_PATH . 'img/sprite.svg#icon-refresh"></use>
                                    </svg>
                                </a>
                            </div>';
                            }
                        } elseif ($mfa_enrollment === 2) {
                            $mfa_status = $hesklang['mfa_method_auth_app_short'];

                            if ($can_man_customers) {
                                $mfa_reset = '<div class="tooltype right out-close">
                                    <a href="javascript:" data-modal="[data-modal-id=\''.$modal_id.'\']"
                                        title="'.$hesklang['mfa_reset_to_default'].'"
                                        class="delete tooltip">
                                        <svg class="icon icon-refresh">
                                            <use xlink:href="'. HESK_PATH . 'img/sprite.svg#icon-refresh"></use>
                                        </svg>
                                    </a>
                                </div>';
                            }
                        }
                        $actions_html = $can_man_customers ? '<td class="nowrap buttons"><p>'.$approval_code.' '.$resend_email_code.' '.$edit_code.' '.$remove_code.'</p></td>' : '';
                        echo <<<EOC
                        <td>$mfa_status $mfa_reset</td>
                        $actions_html
                        </tr>

EOC;
                    } // End while
                    ?>
                    </tbody>
                </table>
            </div>
        </div>

        <p>&nbsp;</p>
<?php
    }// End hesk_render_customer_table()
?>
manage_knowledgebase.php
wget 'https://lists2.roe3.org/hesk/admin/manage_knowledgebase.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

// Check for POST requests larger than what the server can handle
if ( $_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) && ! empty($_SERVER['CONTENT_LENGTH']) )
{
	hesk_error($hesklang['maxpost']);
}

// For convenience allow adding at least 3 attachments at once in the KB
if ($hesk_settings['attachments']['max_number'] < 3)
{
	$hesk_settings['attachments']['max_number'] = 3;
}

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
if ( ! hesk_checkPermission('can_man_kb',0))
{
	/* This person can't manage the knowledgebase, but can read it */
	header('Location: knowledgebase_private.php');
    exit();
}

/* Is Knowledgebase enabled? */
if ( ! $hesk_settings['kb_enable'])
{
	hesk_error($hesklang['kbdis']);
}

/* This will tell the header to include WYSIWYG editor Javascript */
define('WYSIWYG',1);
define('ATTACHMENTS',1);

/* What should we do? */
if ( $action = hesk_REQUEST('a') )
{
	if ($action == 'add_article')		 {add_article();}
	elseif ($action == 'add_category')   {add_category();}
	elseif ($action == 'manage_cat') 	 {manage_category();}
	elseif ($action == 'edit_article') 	 {edit_article();}
	elseif ($action == 'import_article') {import_article();}
	elseif ($action == 'list_private')	 {list_private();}
	elseif ($action == 'list_draft')	 {list_draft();}
	elseif ( defined('HESK_DEMO') )		 {hesk_process_messages($hesklang['ddemo'], 'manage_knowledgebase.php', 'NOTICE');}
	elseif ($action == 'new_article')    {new_article();}
	elseif ($action == 'new_category') 	 {new_category();}
	elseif ($action == 'remove_article') {remove_article();}
	elseif ($action == 'save_article') 	 {save_article();}
	elseif ($action == 'order_article')	 {order_article();}
    elseif ($action == 'order_cat')		 {order_category();}
	elseif ($action == 'edit_category')	 {edit_category();}
	elseif ($action == 'remove_kb_att')	 {remove_kb_att();}
	elseif ($action == 'sticky')	 	 {toggle_sticky();}
	elseif ($action == 'update_count')	 {update_count(1);}
}

// Part of a trick to prevent duplicate article submissions by reloading pages
hesk_cleanSessionVars('article_submitted');

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
hesk_handle_messages();

// Total number of KB articles
$total_articles = 0;

// Get number of sub-categories for each parent category
$parent = array(0 => 1);
$result = hesk_dbQuery('SELECT `parent`, COUNT(*) AS `num` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` GROUP BY `parent`');
while ($row = hesk_dbFetchAssoc($result))
{
	$parent[$row['parent']] = $row['num'];
}
$parent_copy = $parent;

//print_r($parent);

// Get Knowledgebase structure
$kb_cat = array();
$result = hesk_dbQuery('SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` ORDER BY `parent` ASC, `cat_order` ASC');
while ($cat = hesk_dbFetchAssoc($result))
{
	// Can this category be moved at all?
	if (
    	$cat['id'] == 1                  || // Main category cannot be moved
        ! isset($parent[$cat['parent']]) || // if the parent category isn't set
        $parent[$cat['parent']] < 2         // Less than 2 articles in category
    )
    {
    	$cat['move_up']   = false;
        $cat['move_down'] = false;
    }
    else
    {
    	$cat['move_up']   = true;
        $cat['move_down'] = true;
    }

	$kb_cat[] = $cat;
}

//print_r($kb_cat);

/* Translate main category "Knowledgebase" if needed */
$kb_cat[0]['name'] = $hesklang['kb_text'];

require(HESK_PATH . 'inc/treemenu/TreeMenu.php');
$icon         = 'icon-chevron-right';
$expandedIcon = 'icon-knowledge';
$menu		  = new HTML_TreeMenu();

$thislevel = array('0');
$nextlevel = array();
$i = 1;
$j = 1;

if (isset($_SESSION['KB_CATEGORY']))
{
	$selected_catid = intval($_SESSION['KB_CATEGORY']);
}
else
{
	$selected_catid = 0;
}

while (count($kb_cat) > 0)
{

    foreach ($kb_cat as $k=>$cat)
    {

    	if (in_array($cat['parent'],$thislevel))
        {
        	$arrow = ($i - 2) % 10;
            $arrow_colors = array(
                0 => '#5ac05a',
                1 => '#a3a0ff',
                2 => '#ff8184',
                3 => '#e686ff',
                4 => '#e19900',
                5 => '#a9a9a9',
                6 => '#db9696',
                7 => '#b7ab00',
                8 => '#a2602d',
                9 => '#aff600'
            );

			$up = $cat['parent'];
			$my = $cat['id'];
			$type = $cat['type'] ? '*' : '';
			$selected = ($selected_catid == $my) ? 1 : 0;
            $cls = (isset($_SESSION['newcat']) && $_SESSION['newcat'] == $my) ? ' class="kbCatListON"' : '';

            $text = str_replace('\\','\\\\','<span id="c_'.$my.'"'.$cls.'><a href="manage_knowledgebase.php?a=manage_cat&catid='.$my.'">'.$cat['name'].'</a>').$type.'</span> (<span class="kb_published">'.$cat['articles'].'</span>, <span class="kb_private">'.$cat['articles_private'].'</span>, <span class="kb_draft">'.$cat['articles_draft'].'</span>) ';                  /* ' */

            $text_short = $cat['name'].$type.' ('.$cat['articles'].', '.$cat['articles_private'].', '.$cat['articles_draft'].')';

			$total_articles += $cat['articles'];

			// Generate KB menu icons
			$menu_icons =
			'<a class="tooltip" data-ztt_vertical_offset="0" href="manage_knowledgebase.php?a=add_article&amp;catid='.$my.'" title="'.$hesklang['kb_i_art'].'">'.
			    '<svg style="fill: #9c9c9c" class="icon icon-add">'.
                    '<use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-add"></use>'.
                '</svg>'.
             '</a>&nbsp;&nbsp;&nbsp;'
			.'<a class="tooltip" data-ztt_vertical_offset="0" href="manage_knowledgebase.php?a=add_category&amp;parent='.$my.'" title="'.$hesklang['kb_i_cat'].'">'.
                '<svg style="fill: #9c9c9c" class="icon icon-categories">'.
                    '<use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-categories"></use>'.
                '</svg>'.
              '</a>&nbsp;&nbsp;&nbsp;'
			.'<a class="tooltip" data-ztt_vertical_offset="0" href="manage_knowledgebase.php?a=manage_cat&amp;catid='.$my.'" title="'.$hesklang['kb_p_man'].'">'.
			    '<svg style="fill: #9c9c9c" class="icon icon-settings">'.
                    '<use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-settings"></use>'.
                '</svg>'.
              '</a> '
			;

			// Can this category be moved up?
			if ($cat['move_up'] == false || ($cat['move_up'] && $parent_copy[$cat['parent']] == $parent[$cat['parent']]) )
            {
                $menu_icons .= '<a href="#" style="visibility: hidden;width: 11px; display: inline-block" aria-label="' . $hesklang['move_up'] . '">'.
                        '<svg class="icon icon-chevron-up" style="font-size: 8px">'.
                            '<use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-chevron-down"></use>'.
                        '</svg>'.
                    '</a> ';
            }
            else
            {
                $menu_icons .= '<a class="tooltip" data-ztt_vertical_offset="0" style="width: 11px; display: inline-block" href="manage_knowledgebase.php?a=order_cat&amp;catid='.$my.'&amp;move=-15&amp;token=' . hesk_token_echo(0) . '" title="'.$hesklang['move_up'].'" aria-label="' . $hesklang['move_up'] . '">'.
                    '<svg class="icon icon-chevron-up" style="fill: '.$arrow_colors[$arrow].'; font-size: 8px">'.
                        '<use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-chevron-down"></use>'.
                    '</svg>'.
                '</a> ';
			}

			// Can this category be moved down?
			if ($cat['move_down'] == false || ($cat['move_down'] && $parent_copy[$cat['parent']] == 1) )
            {
				$menu_icons .= '<a href="#" style="visibility: hidden; width: 11px; display: inline-block" aria-label="' . $hesklang['move_dn'] . '">'.
                    '<svg class="icon icon-chevron-down">'.
                        '<use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-chevron-down"></use>'.
                    '</svg>'.
                '</a> ';
            }
            else
            {
                $menu_icons .= '<a class="tooltip" data-ztt_vertical_offset="0" style="width: 11px; display: inline-block" href="manage_knowledgebase.php?a=order_cat&amp;catid='.$my.'&amp;move=15&amp;token=' . hesk_token_echo(0) . '" title="'.$hesklang['move_dn'].'" aria-label="' . $hesklang['move_dn'] . '">'.
                    '<svg class="icon icon-chevron-down" style="fill: '.$arrow_colors[$arrow].'">'.
                        '<use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-chevron-down"></use>'.
                    '</svg>'.
                '</a> ';
			}

            if (isset($node[$up]))
            {
                $HTML_TreeNode[$my] = new HTML_TreeNode(array('hesk_selected' => $selected, 'text' => $text, 'text_short' => $text_short, 'menu_icons' => $menu_icons, 'hesk_catid' => $cat['id'], 'hesk_select' => 'option'.$j, 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => true));
	            $node[$my] = &$node[$up]->addItem($HTML_TreeNode[$my]);
            }
            else
            {
                $node[$my] = new HTML_TreeNode(array('hesk_selected' => $selected, 'text' => $text, 'text_short' => $text_short, 'menu_icons' => $menu_icons, 'hesk_catid' => $cat['id'], 'hesk_select' => 'option'.$j, 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => true));
            }

	        $nextlevel[] = $cat['id'];
            $parent_copy[$cat['parent']]--;
            $j++;
	        unset($kb_cat[$k]);

        }

    }

    $thislevel = $nextlevel;
    $nextlevel = array();

    /* Break after 20 recursions to avoid hang-ups in case of any problems */
    if ($i > 20)
    {
    	break;
    }
    $i++;
}

$menu->addItem($node[1]);

// Create the presentation class
$HTML_TreeMenu_DHTML = new HTML_TreeMenu_DHTML($menu, array('images' => '../img', 'defaultClass' => 'treeMenuDefault', 'isDynamic' => true));
$treeMenu = & ref_new($HTML_TreeMenu_DHTML);

$HTML_TreeMenu_Listbox = new HTML_TreeMenu_Listbox($menu);
$listBox  = & ref_new($HTML_TreeMenu_Listbox);

/* Hide new article and new category forms by default */
if (!isset($_SESSION['hide']))
{
	$_SESSION['hide'] = array(
		//'treemenu' => 1,
		'new_article' => 1,
		'new_category' => 1,
	);
}

/* Hide tree menu? */
if (!isset($_SESSION['hide']['treemenu']))
{
	?>
    <div class="main__content knowledgebase">
        <section class="knowledgebase__head">
            <h2>
                <?php echo $hesklang['kb']; ?>
                <div class="tooltype right out-close">
                    <svg class="icon icon-info">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                    </svg>
                    <div class="tooltype__content">
                        <div class="tooltype__wrapper">
                            <?php echo $hesklang['kb_intro']; ?>
                        </div>
                    </div>
                </div>
            </h2>
        </section>
        <div class="table-wrap">
            <?php
            // Show a notice if total public articles is less than 5
            if ($total_articles < 5)
            {
                echo '<div style="margin: -24px -24px 0 -16px;">';
                hesk_show_notice($hesklang['nkba']);
                echo '</div>';
            }
            ?>
            <!-- SUB NAVIGATION -->
            <?php show_subnav(); ?>
            <hr class="sub-navigation-border">
            <!-- SUB NAVIGATION -->
            <!-- SHOW THE CATEGORY TREE -->
            <?php show_treeMenu(); ?>
            <!-- SHOW THE CATEGORY TREE -->
            <h4 style="margin-top: 10px;font-size: 1rem; "><?php echo $hesklang['ktool']; ?></h4>
            <div>
                <svg style="fill: #9c9c9c" class="icon icon-search">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-search"></use>
                </svg>
                <a class="link" href="manage_knowledgebase.php?a=list_private"><?php echo $hesklang['listp']; ?></a>
            </div>
            <div>
                <svg style="fill: #9c9c9c" class="icon icon-search">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-search"></use>
                </svg>
                <a class="link" href="manage_knowledgebase.php?a=list_draft"><?php echo $hesklang['listd']; ?></a>
            </div>
            <div>
                <svg style="fill: #9c9c9c" class="icon icon-settings">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-settings"></use>
                </svg>
                <a class="link" href="manage_knowledgebase.php?a=update_count"><?php echo $hesklang['uac']; ?></a>
            </div>
            <div>
                <svg style="fill: #9c9c9c" class="icon icon-tools">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tools"></use>
                </svg>
                <a class="link" href="http://support.mozilla.com/en-US/kb/how-to-write-knowledge-base-articles" rel="nofollow" target="_blank"><?php echo $hesklang['goodkb']; ?></a>
            </div>
        </div>
    </div>
	<?php
} // END hide treemenu

/* Hide article form? */
if (!isset($_SESSION['hide']['new_article']))
{
	if (isset($_SESSION['new_article']))
    {
		$_SESSION['new_article'] = hesk_stripArray($_SESSION['new_article']);
    }
    elseif ( isset($_GET['type']) )
    {
		$_SESSION['new_article']['type'] = intval( hesk_GET('type') );
        if ($_SESSION['new_article']['type'] != 1 && $_SESSION['new_article']['type'] != 2)
        {
        	$_SESSION['new_article']['type'] = 0;
        }
    }

    if ($hesk_settings['kb_wysiwyg'])
    {
        hesk_tinymce_init('#content');
    }

    // If a category is selected, use it as default for articles and parents
    if (isset($_SESSION['KB_CATEGORY']))
    {
        $catid = intval($_SESSION['KB_CATEGORY']);
    }
    ?>

    <div class="main__content knowledge article">
        <form action="manage_knowledgebase.php" method="post" name="form1" enctype="multipart/form-data" aria-label="<?php echo $hesklang['kb_i_art']; ?>">
            <div class="article__detalies edit">
                <div class="article__detalies_head">
                    <h3><?php echo $hesklang['ad']; ?></h3>
                </div>
                <ul class="article__detalies_list">
                    <li>
                        <div class="checkbox-custom">
                            <input type="checkbox" id="add_sticky" name="sticky" value="Y" <?php if ( ! empty($_SESSION['new_article']['sticky'])) {echo 'checked';} ?>>
                            <label for="add_sticky"><?php echo $hesklang['sticky']; ?></label>
                        </div>
                    </li>
                    <li>
                        <div class="form-group">
                            <label><?php echo $hesklang['kb_type']; ?></label>
                            <div class="radio-list">
                                <div class="radio-custom">
                                    <input type="radio" id="add_type0" name="type" value="0" <?php if (!isset($_SESSION['new_article']['type']) || (isset($_SESSION['new_article']['type']) && $_SESSION['new_article']['type'] == 0) ) {echo 'checked';} ?>>
                                    <label for="add_type0"><?php echo $hesklang['kb_published']; ?></label>
                                </div>
                                <div style="margin-left: 24px; margin-bottom: 10px"><?php echo $hesklang['kb_published2']; ?></div>
                                <div class="radio-custom">
                                    <input type="radio" id="add_type1" name="type" value="1" <?php if (isset($_SESSION['new_article']['type']) && $_SESSION['new_article']['type'] == 1) {echo 'checked="checked"';} ?>>
                                    <label for="add_type1"><?php echo $hesklang['kb_private']; ?></label>
                                </div>
                                <div style="margin-left: 24px; margin-bottom: 10px"><?php echo $hesklang['kb_private2']; ?></div>
                                <div class="radio-custom">
                                    <input type="radio" id="add_type2" name="type" value="2" <?php if (isset($_SESSION['new_article']['type']) && $_SESSION['new_article']['type'] == 2) {echo 'checked="checked"';} ?>>
                                    <label for="add_type2"><?php echo $hesklang['kb_draft']; ?></label>
                                </div>
                                <div style="margin-left: 24px; margin-bottom: 10px"><?php echo $hesklang['kb_draft2']; ?></div>
                            </div>
                        </div>
                    </li>
                    <li>
                        <div class="name category">
                            <label for="add_catid"><?php echo $hesklang['kb_cat']; ?></label>
                        </div>
                        <div class="descr">
                            <div class="dropdown-select right out-close">
                                <select id="add_catid" name="catid"><?php $listBox->printMenu(); ?></select>
                            </div>
                        </div>
                    </li>
                </ul>
                <div class="article__detalies_action">
                    <button type="submit" class="btn btn-full" ripple="ripple"><?php echo $hesklang['kb_save']; ?></button>
                </div>
            </div>
            <div class="article__body form">
                <div class="article__back">
                    <a href="manage_knowledgebase.php?a=manage_cat&amp;catid=<?php echo $catid; ?>">
                        <svg class="icon icon-back">
                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                        </svg>
                        <span><?php echo $hesklang['wizard_back']; ?></span>
                    </a>
                </div>
                <div class="article__title">
                    <div class="form-group">
                        <label for="add_subject"><?php echo $hesklang['kb_subject']; ?></label>
                        <input id="add_subject" type="text" name="subject" class="form-control" maxlength="255"
                            <?php if (isset($_SESSION['new_article']['subject'])) {echo 'value="'.$_SESSION['new_article']['subject'].'"';} ?>>
                    </div>
                </div>
                <div class="article__description">
                    <?php
                    $displayType = $hesk_settings['kb_wysiwyg'] ? 'none' : 'block';
                    $displayWarn = 'none';
                    ?>
                    <span id="contentType" style="display:<?php echo $displayType; ?>">
                        <label><input type="radio" name="html" value="0" <?php if (!isset($_SESSION['new_article']['html']) || (isset($_SESSION['new_article']['html']) && $_SESSION['new_article']['html'] == 0) ) {echo 'checked="checked"';} ?> onclick="javascript:document.getElementById('kblinks').style.display = 'none'" /> <?php echo $hesklang['kb_dhtml']; ?></label><br />
                        <label><input type="radio" name="html" value="1" <?php $display = 'none'; if (isset($_SESSION['new_article']['html']) && $_SESSION['new_article']['html'] == 1) {echo 'checked="checked"'; $displayWarn = 'block';} ?> onclick="javascript:document.getElementById('kblinks').style.display = 'block'" /> <?php echo $hesklang['kb_ehtml']; ?></label><br />
                        <span id="kblinks" style="display:<?php echo $displayWarn; ?>"><i><?php echo $hesklang['kb_links']; ?></i></span>
                    </span>
                    <label>
                        <textarea name="content" rows="25" cols="70" id="content"><?php if (isset($_SESSION['new_article']['content'])) {echo $_SESSION['new_article']['content'];} ?></textarea>
                    </label>
                </div>
                <?php
                if ($hesk_settings['attachments']['use']) {
                    require_once(HESK_PATH . 'inc/attachments.inc.php');
                ?>
                <div class="attachments">
                    <svg class="icon icon-attach">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-attach"></use>
                    </svg>
                    <?php echo $hesklang['attachments']; ?>
                    <?php
                    build_dropzone_markup(true);
                    display_dropzone_field(HESK_PATH . 'upload_attachment.php', true);
                    dropzone_display_existing_files(hesk_SESSION_array('edit_attachments'));
                    hesk_cleanSessionVars('edit_attachments');
                    ?>
                </div>
                    <?php
                } // End attachments
                ?>
                <div class="form-group article__keywords">
                    <label for="keywords">
                        <b><?php echo $hesklang['kw']; ?></b>
                        <span><?php echo $hesklang['kw1']; ?></span>
                    </label>
                    <textarea class="form-control" style="height: inherit;" name="keywords" rows="3" cols="70" id="keywords"><?php if (isset($_SESSION['new_article']['keywords'])) {echo $_SESSION['new_article']['keywords'];} ?></textarea>
                </div>
            </div>
            <div class="d-flex-center sm-hidden mt2">
                <button type="submit" class="btn btn-full ml1" ripple="ripple"><?php echo $hesklang['kb_save']; ?></button>
            </div>
            <input type="hidden" name="a" value="new_article">
            <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
        </form>
        <script>$('#add_subject').focus();</script>
    </div>
	<?php
} // END hide article

/* Hide new category form? */
if (!isset($_SESSION['hide']['new_category']))
{

	if (isset($_SESSION['new_category']))
    {
		$_SESSION['new_category'] = hesk_stripArray($_SESSION['new_category']);
    }
	?>
    <div class="main__content categories">
        <div class="table-wrap">
            <form class="form" action="manage_knowledgebase.php" method="post" name="form2" aria-label="<?php echo $hesklang['kb_i_cat']; ?>">
                <h3 style="font-size: 1.3rem"><a name="new_category"></a><?php echo $hesklang['kb_cat_new']; ?></h3>
                <div class="form-group">
                    <label for="add_cat_title"><?php echo $hesklang['kb_cat_title']; ?></label>
                    <input type="text" name="title" class="form-control" id="add_cat_title" maxlength="255">
                </div>
                <div class="form-group">
                    <label for="add_cat_parent"><?php echo $hesklang['kb_cat_parent']; ?></label>
                    <div class="dropdown-select out-close">
                        <select id="add_cat_parent" name="parent"><?php $listBox->printMenu()?></select>
                    </div>
                </div>
                <div class="form-group">
                    <label><?php echo $hesklang['kb_type']; ?></label>
                    <div class="radio-list">
                        <div class="radio-custom">
                            <input type="radio" name="type" id="add_type0" value="0" <?php if (!isset($_SESSION['new_category']['type']) || (isset($_SESSION['new_category']['type']) && $_SESSION['new_category']['type'] == 0) ) {echo 'checked';} ?>>
                            <label for="add_type0"><?php echo $hesklang['kb_published']; ?></label>
                        </div>
                        <div style="margin-left: 24px; margin-bottom: 10px">
                            <?php echo $hesklang['kb_cat_published']; ?>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" name="type" id="add_type1" value="1" <?php if (isset($_SESSION['new_category']['type']) && $_SESSION['new_category']['type'] == 1) {echo 'checked';} ?>>
                            <label for="add_type1"><?php echo $hesklang['kb_private']; ?></label>
                        </div>
                        <div style="margin-left: 24px; margin-bottom: 10px">
                            <?php echo $hesklang['kb_cat_private']; ?>
                        </div>
                    </div>
                </div>
                <input type="hidden" name="a" value="new_category">
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                <div>
                    <button style="display: inline-flex" type="submit" class="btn btn-full" ripple="ripple"><?php echo $hesklang['kb_cat_add']; ?></button>
                    <a style="display: inline-flex" class="btn btn-border" href="manage_knowledgebase.php" ripple="ripple"><?php echo $hesklang['cancel']; ?></a>
                </div>
            </form>
        </div>
        <?php
        /* Show the treemenu? */
        if (isset($_SESSION['hide']['cat_treemenu']))
        {
            echo '<div class="table-wrap" style="margin-top: 20px">';
            show_treeMenu();
            echo '</div>';
        }
        ?>
        <script>$('#add_cat_title').focus();</script>
    </div>
	<?php
} // END hide new category form

/* Clean unneeded session variables */
hesk_cleanSessionVars(array('hide','new_article','new_category','KB_CATEGORY','manage_cat','edit_article','newcat'));
?>

<p>&nbsp;</p>

<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/

function list_draft() {
	global $hesk_settings, $hesklang;

    $catid  = 1;
    $kb_cat = hesk_getCategoriesArray(1);

	/* Translate main category "Knowledgebase" if needed */
	$kb_cat[0]['name'] = $hesklang['kb_text'];

	/* Print header */
	require_once(HESK_PATH . 'inc/header.inc.php');

	/* Print main manage users page */
	require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');
	?>
    <div class="main__content knowledge category">
        <div class="category__list visible">
            <div class="category__list_head">
                <h3><?php echo $hesklang['artd']; ?></h3>
            </div>
            <div class="category__list_table overflow-x-scroll" style="display: block">
                <div style="float: right; margin-bottom: 10px;">
                    <a class="btn btn--blue-border" href="manage_knowledgebase.php?a=add_article&amp;catid=<?php echo $catid; ?>&amp;type=2">
                        <?php echo $hesklang['kb_i_art2']; ?>
                    </a>
                </div>
                <table>
                    <tbody>
                    <?php
                    $result = hesk_dbQuery("SELECT * FROM `". hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `type`='2' ORDER BY `catid` ASC, `id` ASC");
                    $num = hesk_dbNumRows($result);

                    if ($num == 0)
                    {
                        echo '
                            <tr>
                                <td colspan="4" style="padding-left: 10px">'.$hesklang['kb_no_dart'].'</td>
                            </tr>
                            ';
                    }
                    else
                    {
                        while ($article=hesk_dbFetchAssoc($result))
                        {
                            // Check for articles with no existing parent category
                            if ( ! isset($kb_cat[$article['catid']]) )
                            {
                                $article['catid'] = hesk_stray_article($article['id']);
                            }

                            $table_row = 'class="';
                            if (isset($_SESSION['artord']) && $article['id'] == $_SESSION['artord'])
                            {
                                $table_row .= 'ticket-new ';
                                unset($_SESSION['artord']);
                            }

                            if ($article['sticky']) {
                                $table_row .= 'sticky';
                            }
                            $table_row .= '"';
                            ?>
                            <tr <?php echo $table_row; ?>>
                                <td class="title">
                                    <a href="knowledgebase_private.php?article=<?php echo $article['id']; ?>&amp;back=1<?php if ($article['type'] == 2) {echo '&amp;draft=1';} ?>">
                                        <?php echo $article['subject']; ?>
                                    </a>
                                </td>
                                <td class="view">
                                    <svg class="icon icon-eye-close tooltip" title="<?php echo $hesklang['views'].': '.$article['views'];?>">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-eye-close"></use>
                                    </svg>
                                    <?php echo $article['views']; ?>
                                </td>
                                <td class="status">
                                    <div style="margin-bottom: 3px"><?php echo $hesklang['kb_draft']; ?></div>
                                </td>
                                <td class="actions">
                                    <div class="actions--buttons">
                                        <a class="tooltip" href="manage_knowledgebase.php?a=edit_article&amp;id=<?php echo $article['id']; ?>"
                                           title="<?php echo $hesklang['edit']; ?>">
                                            <svg class="icon icon-edit-ticket">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-edit-ticket"></use>
                                            </svg>
                                        </a>
                                        <?php
                                        $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                                            $hesklang['del_art'],
                                            'manage_knowledgebase.php?a=remove_article&amp;id='. $article['id'] .'&amp;token='. hesk_token_echo(0));
                                        ?>
                                        <a class="tooltip" href="javascript:"
                                           data-modal="[data-modal-id='<?php echo $modal_id; ?>']"
                                           title="<?php echo $hesklang['delete']; ?>">
                                            <svg class="icon icon-delete">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-delete"></use>
                                            </svg>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php
                        } // End while
                    } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <?php

	/* Clean unneeded session variables */
	hesk_cleanSessionVars(array('hide','manage_cat','edit_article'));

    require_once(HESK_PATH . 'inc/footer.inc.php');
    exit();
} // END list_draft()


function list_private() {
	global $hesk_settings, $hesklang;

    $catid  = 1;
    $kb_cat = hesk_getCategoriesArray(1);

	/* Translate main category "Knowledgebase" if needed */
	$kb_cat[0]['name'] = $hesklang['kb_text'];

    /* Get list of private categories */
    $private_categories = array();
	$res = hesk_dbQuery("SELECT `id` FROM `". hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` WHERE `type`='1'");
    $num = hesk_dbNumRows($res);
    if ($num)
    {
    	while ($row = hesk_dbFetchAssoc($res))
		{
			$private_categories[] = intval($row['id']);
        }
    }

	/* Print header */
	require_once(HESK_PATH . 'inc/header.inc.php');

	/* Print main manage users page */
	require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');
	?>
    <div class="main__content knowledge category">
        <div class="category__list visible">
            <div class="category__list_head">
                <h3><?php echo $hesklang['artp']; ?></h3>
            </div>
            <div class="category__list_table overflow-x-scroll" style="display: block">
                <div style="float: right; margin-bottom: 10px;">
                    <a class="btn btn--blue-border" href="manage_knowledgebase.php?a=add_article&amp;catid=<?php echo $catid; ?>&amp;type=1">
                        <?php echo $hesklang['kb_i_art2']; ?>
                    </a>
                </div>
                <table>
                    <tbody>
                    <?php
                    $result = hesk_dbQuery("SELECT * FROM `". hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `type`='1' " . (count($private_categories) ? " OR `catid` IN('" . implode("','", $private_categories) . "') " : '') . " ORDER BY `catid` ASC, `id` ASC");
                    $num = hesk_dbNumRows($result);

                    if ($num == 0)
                    {
                        echo '
                            <tr>
                                <td colspan="4" style="padding-left: 10px">'.$hesklang['kb_no_part'].'</td>
                            </tr>
                            ';
                    }
                    else
                    {
                        while ($article=hesk_dbFetchAssoc($result))
                        {
                            // Check for articles with no existing parent category
                            if ( ! isset($kb_cat[$article['catid']]) )
                            {
                                $article['catid'] = hesk_stray_article($article['id']);
                            }

                            $table_row = 'class="';
                            if (isset($_SESSION['artord']) && $article['id'] == $_SESSION['artord'])
                            {
                                $table_row = 'ticket-new ';
                                unset($_SESSION['artord']);
                            }

                            if ($article['sticky']) {
                                $table_row .= 'sticky';
                            }
                            $table_row .= '"';


                            if ($hesk_settings['kb_rating'])
                            {
                                $alt = $article['rating'] ? sprintf($hesklang['kb_rated'], sprintf("%01.1f", $article['rating'])) : $hesklang['kb_not_rated'];
                                $type = hesk3_get_rating($article['rating'], $article['votes']);
                            }

                            ?>
                            <tr <?php echo $table_row; ?>>
                                <td class="title">
                                    <a href="knowledgebase_private.php?article=<?php echo $article['id']; ?>&amp;back=1<?php if ($article['type'] == 2) {echo '&amp;draft=1';} ?>">
                                        <?php echo $article['subject']; ?>
                                    </a>
                                </td>
                                <td class="view">
                                    <svg class="icon icon-eye-close tooltip" title="<?php echo $hesklang['views'].': '.$article['views'];?>">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-eye-close"></use>
                                    </svg>
                                    <?php echo $article['views']; ?>
                                </td>
                                <td class="status">
                                    <?php echo $type; ?>
                                </td>
                                <td class="actions">
                                    <div class="actions--buttons">
                                        <a class="tooltip" href="manage_knowledgebase.php?a=edit_article&amp;id=<?php echo $article['id']; ?>"
                                           title="<?php echo $hesklang['edit']; ?>">
                                            <svg class="icon icon-edit-ticket">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-edit-ticket"></use>
                                            </svg>
                                        </a>
                                        <?php
                                        $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                                            $hesklang['del_art'],
                                            'manage_knowledgebase.php?a=remove_article&amp;id='. $article['id'] .'&amp;token='. hesk_token_echo(0));
                                        ?>
                                        <a class="tooltip" href="javascript:"
                                           data-modal="[data-modal-id='<?php echo $modal_id; ?>']"
                                           title="<?php echo $hesklang['delete']; ?>">
                                            <svg class="icon icon-delete">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-delete"></use>
                                            </svg>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php
                        } // End while
                    } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <?php
	/* Clean unneeded session variables */
	hesk_cleanSessionVars(array('hide','manage_cat','edit_article'));

    require_once(HESK_PATH . 'inc/footer.inc.php');
    exit();
} // END list_private()


function import_article()
{
	global $hesk_settings, $hesklang, $listBox;

	$_SESSION['hide'] = array(
		'treemenu' => 1,
		//'new_article' => 1,
		'new_category' => 1,
	);

    $_SESSION['KB_CATEGORY'] = 1;

    // Get ticket ID
    $trackingID = hesk_cleanID();
	if (empty($trackingID))
	{
		return false;
	}

	// Get ticket info
	$res = hesk_dbQuery("SELECT `id`,`trackid`,`category`,`subject`,`message`,`owner`,`assignedby` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `trackid`='".hesk_dbEscape($trackingID)."' LIMIT 1");
	if (hesk_dbNumRows($res) != 1)
	{
		return false;
	}
	$ticket = hesk_dbFetchAssoc($res);

    // Permission to view this ticket?
    $ticket = hesk_verifyStaffTicketAccess($trackingID, $ticket);

    // Set article contents
    if ($hesk_settings['kb_wysiwyg'])
    {
    	// With WYSIWYG editor
		$_SESSION['new_article'] = array(
		'html' => 1,
		'subject' => $ticket['subject'],
		'content' => hesk_htmlspecialchars($ticket['message']),
		);
    }
    else
    {
    	// Without WYSIWYG editor *
		$_SESSION['new_article'] = array(
		'html' => 0,
		'subject' => $ticket['subject'],
		'content' => hesk_msgToPlain($ticket['message'], 0, 0),
		);
    }

	// Get messages from replies to the ticket
	$res = hesk_dbQuery("SELECT `message` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` WHERE `replyto`='".intval($ticket['id'])."' ORDER BY `id` ASC");

    while ($reply=hesk_dbFetchAssoc($res))
    {
    	if ($hesk_settings['kb_wysiwyg'])
        {
			$_SESSION['new_article']['content'] .= "<br /><br />" . hesk_htmlspecialchars($reply['message']);
        }
        else
        {
	        $_SESSION['new_article']['content'] .= "\n\n" . hesk_msgToPlain($reply['message'], 0, 0);
        }
    }

    // Make sure everything is extra slashed as stripslashes will be called later
    $_SESSION['new_article']['subject'] = addslashes($_SESSION['new_article']['subject']);
    $_SESSION['new_article']['content'] = addslashes($_SESSION['new_article']['content']);

    hesk_process_messages($hesklang['import'],'NOREDIRECT','NOTICE');

} // END add_article()


function add_article()
{
	global $hesk_settings, $hesklang;

	$_SESSION['hide'] = array(
		'treemenu' => 1,
		//'new_article' => 1,
		'new_category' => 1,
	);

    $_SESSION['KB_CATEGORY'] = intval( hesk_GET('catid', 1) );
} // END add_article()


function add_category()
{
	global $hesk_settings, $hesklang;

	$_SESSION['hide'] = array(
		'treemenu' => 1,
		'new_article' => 1,
		//'new_category' => 1,
        'cat_treemenu' => 1,
	);

    $_SESSION['KB_CATEGORY'] = intval( hesk_GET('parent', 1) );
} // END add_category()


function remove_kb_att()
{
	global $hesk_settings, $hesklang;

	// A security check
	hesk_token_check();

	$att_id  = intval( hesk_GET('kb_att') ) or hesk_error($hesklang['inv_att_id']);
    $id		 = intval( hesk_GET('id', 1) );

	// Get attachment details
	$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_attachments` WHERE `att_id`='".intval($att_id)."'");

    // Does the attachment exist?
	if ( hesk_dbNumRows($res) != 1 )
    {
    	hesk_process_messages($hesklang['inv_att_id'], 'manage_knowledgebase.php');
    }

    $att = hesk_dbFetchAssoc($res);

	// Delete the file if it exists
    hesk_unlink(HESK_PATH.$hesk_settings['attach_dir'].'/'.$att['saved_name']);

	hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_attachments` WHERE `att_id`='".intval($att_id)."'");

	$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `id`='".intval($id)."'");
    $art = hesk_dbFetchAssoc($res);

    // Make log entry
    $revision = sprintf($hesklang['thist12'],hesk_date(),$att['real_name'],addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');

    // Remove attachment from article
    $art['attachments'] = str_replace($att_id.'#'.$att['real_name'].',','',$art['attachments']);

	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` SET `attachments`='".hesk_dbEscape($art['attachments'])."', `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') WHERE `id`='".intval($id)."'");

    hesk_process_messages($hesklang['kb_att_rem'],'manage_knowledgebase.php?a=edit_article&id='.$id,'SUCCESS');
} // END remove_kb_att()


function edit_category()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check('POST');

	$_SESSION['hide'] = array(
		'article_list' => 1,
	);

    $hesk_error_buffer = array();

	$catid  = intval( hesk_POST('catid') ) or hesk_error($hesklang['kb_cat_inv']);
    $title  = hesk_input( hesk_POST('title') ) or $hesk_error_buffer[] = $hesklang['kb_cat_e_title'];
    $parent = intval( hesk_POST('parent', 1) );
    $type   = empty($_POST['type']) ? 0 : 1;

    /* Category can't be it's own parent */
    if ($parent == $catid)
    {
		$hesk_error_buffer[] = $hesklang['kb_spar'];
    }

    /* Any errors? */
    if (count($hesk_error_buffer))
    {
		$_SESSION['manage_cat'] = array(
		'type' => $type,
		'parent' => $parent,
		'title' => $title,
		);

		$tmp = '';
		foreach ($hesk_error_buffer as $error)
		{
			$tmp .= "<li>$error</li>\n";
		}
		$hesk_error_buffer = $tmp;

    	$hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
    	hesk_process_messages($hesk_error_buffer,'./manage_knowledgebase.php?a=manage_cat&catid='.$catid);
    }

    /* Delete category or just update it? */
    if ( hesk_POST('dodelete')=='Y')
    {
    	// Delete contents
    	if ( hesk_POST('movearticles') == 'N')
        {
			// Delete all articles and all subcategories
			delete_category_recursive($catid);
        }
        // Move contents
        else
        {
			// -> Update category of articles in the category we are deleting
			hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` SET `catid`=".intval($parent)." WHERE `catid`='".intval($catid)."'");

			// -> Update parent category of subcategories
			hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` SET `parent`=".intval($parent)." WHERE `parent`='".intval($catid)."'");

			// -> Update article counts to make sure they are correct
			update_count();
        }

        // Now delete the category
        hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` WHERE `id`='".intval($catid)."'");

        // Clear KB cache
        hesk_purge_cache('kb');

		$_SESSION['hide'] = array(
			//'treemenu' => 1,
			'new_article' => 1,
			'new_category' => 1,
		);

        hesk_process_messages($hesklang['kb_cat_dlt'],'./manage_knowledgebase.php','SUCCESS');
    }

	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` SET `name`='".hesk_dbEscape($title)."',`parent`=".intval($parent).",`type`='".intval($type)."' WHERE `id`='".intval($catid)."'");

    unset($_SESSION['hide']);

    hesk_process_messages($hesklang['your_cat_mod'],'./manage_knowledgebase.php?a=manage_cat&catid='.$catid,'SUCCESS');
} // END edit_category()


function save_article()
{
	global $hesk_settings, $hesklang, $hesk_error_buffer;

	/* A security check */
	hesk_token_check('POST');

    $hesk_error_buffer = array();

    $id    = intval( hesk_POST('id') ) or hesk_error($hesklang['kb_art_id']);
	$catid = intval( hesk_POST('catid', 1) );
    $type  = intval( hesk_POST('type') );
    $type  = ($type < 0 || $type > 2) ? 0 : $type;
    $html  = $hesk_settings['kb_wysiwyg'] ? 1 : (empty($_POST['html']) ? 0 : 1);
    $now   = hesk_date();
    $old_catid = intval( hesk_POST('old_catid') );
    $old_type  = intval( hesk_POST('old_type') );
    $old_type  = ($old_type < 0 || $old_type > 2) ? 0 : $old_type;
    $from = hesk_POST('from');

    if ( ! in_array($from, array('draft', 'private')))
    {
        $from = 'manage_cat';
    }

    $subject = hesk_input( hesk_POST('subject') ) or $hesk_error_buffer[] = $hesklang['kb_e_subj'];

    if ($html)
    {
	    if (empty($_POST['content']))
	    {
	    	$hesk_error_buffer[] = $hesklang['kb_e_cont'];
	    }
        
	    $content = hesk_getHTML( hesk_POST('content') );

        // Clean the HTML code
        require(HESK_PATH . 'inc/htmlpurifier/HeskHTMLPurifier.php');
        $purifier = new HeskHTMLPurifier($hesk_settings['cache_dir']);
        $content = $purifier->heskPurify($content);
    }
	else
    {
    	$content = hesk_input( hesk_POST('content') ) or $hesk_error_buffer[] = $hesklang['kb_e_cont'];
	    $content = nl2br($content);
	    $content = hesk_makeURL($content);
    }

    $sticky = isset($_POST['sticky']) ? 1 : 0;

    $keywords = hesk_input( hesk_POST('keywords') );

    $extra_sql = '';
    if ( hesk_POST('resetviews')=='Y')
    {
    	$extra_sql .= ',`views`=0 ';
    }
    if (hesk_POST('resetvotes')=='Y')
    {
    	$extra_sql .= ',`votes`=0, `rating`=0 ';
    }

    /* Article attachments */
	define('KB',1);
    require_once(HESK_PATH . 'inc/posting_functions.inc.php');
    $attachments = array();
    $use_legacy_attachments = hesk_POST('use-legacy-attachments', 0);
	$myattachments='';

	if ($hesk_settings['attachments']['use'])
	{
		require_once(HESK_PATH . 'inc/attachments.inc.php');

        if ($use_legacy_attachments) {
            for ($i=1; $i<=$hesk_settings['attachments']['max_number']; $i++)
            {
                $att = hesk_uploadFile($i);
                if ( ! empty($att))
                {
                    $attachments[$i] = $att;
                }
            }
        } else {
            // The user used the new drag-and-drop system.
            $temp_attachment_names = hesk_POST_array('attachments');
            foreach ($temp_attachment_names as $temp_attachment_name) {
                $temp_attachment = hesk_getTemporaryAttachment($temp_attachment_name);

                if ($temp_attachment !== null) {
                    $attachments[] = $temp_attachment;
                }
            }
        }
	}

    /* Any errors? */
    if (count($hesk_error_buffer))
    {
		// Remove any successfully uploaded attachments
		if ($hesk_settings['attachments']['use'])
		{
            if ($use_legacy_attachments) {
                hesk_removeAttachments($attachments);
            } else {
                $_SESSION['edit_attachments'] = $attachments;
            }
		}

		$_SESSION['edit_article'] = array(
		'type' => $type,
		'html' => $html,
		'subject' => $subject,
		'content' => hesk_input( hesk_POST('content') ),
		'keywords' => $keywords,
        'catid' => $catid,
        'sticky' => $sticky,
        'resetviews' => (isset($_POST['resetviews']) ? 'Y' : 0),
        'resetvotes' => (isset($_POST['resetvotes']) ? 'Y' : 0),
		);

		$tmp = '';
		foreach ($hesk_error_buffer as $error)
		{
			$tmp .= "<li>$error</li>\n";
		}
		$hesk_error_buffer = $tmp;

    	$hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
    	hesk_process_messages($hesk_error_buffer,'./manage_knowledgebase.php?a=edit_article&id='.$id.'&from='.$from);
    }

	/* Add to database */
	if (!empty($attachments))
	{
        if (!$use_legacy_attachments) {
            $attachments = hesk_migrateTempAttachments($attachments);
        }

	    foreach ($attachments as $myatt)
	    {
	        hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_attachments` (`saved_name`,`real_name`,`size`) VALUES ('".hesk_dbEscape($myatt['saved_name'])."', '".hesk_dbEscape($myatt['real_name'])."', '".intval($myatt['size'])."')");
	        $myattachments .= hesk_dbInsertID() . '#' . $myatt['real_name'] .',';
	    }

        $extra_sql .= ", `attachments` = CONCAT(`attachments`, '".$myattachments."') ";
	}

    /* Update article in the database */
    $revision = sprintf($hesklang['revision2'],$now,addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');

	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` SET
    `catid`=".intval($catid).",
    `subject`='".hesk_dbEscape($subject)."',
    `content`='".hesk_dbEscape($content)."',
    `keywords`='".hesk_dbEscape($keywords)."' $extra_sql ,
    `type`='".intval($type)."',
    `html`='".intval($html)."',
    `sticky`='".intval($sticky)."',
    `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."')
    WHERE `id`='".intval($id)."'");

    $_SESSION['artord'] = $id;

	// Update proper category article count
    // (just do them all to be sure, don't compliate...)
	update_count();

    // Update article order
    update_article_order($catid);

    // Clear KB cache
    hesk_purge_cache('kb');

    // Redirect to the correct page
    switch ($from)
    {
        case 'draft':
            $redirect_action = 'a=list_draft';
            break;
        case 'private':
            $redirect_action = 'a=list_private';
            break;
        default:
            $redirect_action = 'a=edit_article&id='.$id.'&from='.$from;
            break;
    }

    hesk_process_messages($hesklang['your_kb_mod'],'./manage_knowledgebase.php?'.$redirect_action,'SUCCESS');
} // END save_article()


function edit_article()
{
	global $hesk_settings, $hesklang, $listBox;

    $hesk_error_buffer = array();

    $id = intval( hesk_GET('id') ) or hesk_process_messages($hesklang['kb_art_id'],'./manage_knowledgebase.php');

    /* Get article details */
	$result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `id`='".intval($id)."' LIMIT 1");
    if (hesk_dbNumRows($result) != 1)
    {
        hesk_process_messages($hesklang['kb_art_id'],'./manage_knowledgebase.php');
    }
    $article = hesk_dbFetchAssoc($result);

    // If we're in plain text mode, convert any HTML message safely to text
    if ( ! $hesk_settings['kb_wysiwyg'] && ! $article['html'])
    {
            // Clean the HTML code and set the plaintext version
            require(HESK_PATH . 'inc/htmlpurifier/HeskHTMLPurifier.php');
            require(HESK_PATH . 'inc/html2text/html2text.php');
            $purifier = new HeskHTMLPurifier($hesk_settings['cache_dir']);
            $article['content'] = $purifier->heskPurify($article['content']);

            $article['content'] = convert_html_to_text($article['content']);
            $article['content'] = fix_newlines($article['content']);
    }

    $article['content'] = hesk_htmlspecialchars($article['content']);

    $catid = $article['catid'];

    $from = hesk_GET('from');

    if (isset($_SESSION['edit_article']))
    {
    	$_SESSION['edit_article'] = hesk_stripArray($_SESSION['edit_article']);
		$article['type'] = $_SESSION['edit_article']['type'];
        $article['html'] = $_SESSION['edit_article']['html'];
        $article['subject'] = $_SESSION['edit_article']['subject'];
        $article['content'] = $_SESSION['edit_article']['content'];
        $article['keywords'] = $_SESSION['edit_article']['keywords'];
        $article['catid'] = $_SESSION['edit_article']['catid'];
        $article['sticky'] = $_SESSION['edit_article']['sticky'];
    }

    /* Get categories */
	$result = hesk_dbQuery('SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` ORDER BY `parent` ASC, `cat_order` ASC');
	$kb_cat = array();

	while ($cat = hesk_dbFetchAssoc($result))
	{
		$kb_cat[] = $cat;
        if ($cat['id'] == $article['catid'])
        {
        	$this_cat = $cat;
            $this_cat['parent'] = $article['catid'];
        }
	}

	/* Translate main category "Knowledgebase" if needed */
	$kb_cat[0]['name'] = $hesklang['kb_text'];

	require(HESK_PATH . 'inc/treemenu/TreeMenu.php');
	$icon         = 'icon-chevron-right';
	$expandedIcon = 'icon-knowledge';
    $menu		  = new HTML_TreeMenu();

	$thislevel = array('0');
	$nextlevel = array();
	$i = 1;
	$j = 1;

	while (count($kb_cat) > 0)
	{

	    foreach ($kb_cat as $k=>$cat)
	    {

	    	if (in_array($cat['parent'],$thislevel))
	        {

	        	$up = $cat['parent'];
	            $my = $cat['id'];
	            $type = $cat['type'] ? '*' : '';

	            $text_short = $cat['name'].$type.' ('.$cat['articles'].', '.$cat['articles_private'].', '.$cat['articles_draft'].')';

	            if (isset($node[$up]))
	            {
                    $HTML_TreeNode[$my] = new HTML_TreeNode(array('hesk_parent' => $this_cat['parent'], 'text' => 'Text', 'text_short' => $text_short, 'hesk_catid' => $cat['id'], 'hesk_select' => 'option'.$j, 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => true));
		            $node[$my] = &$node[$up]->addItem($HTML_TreeNode[$my]);
	            }
	            else
	            {
	                $node[$my] = new HTML_TreeNode(array('hesk_parent' => $this_cat['parent'], 'text' => 'Text',  'text_short' => $text_short, 'hesk_catid' => $cat['id'], 'hesk_select' => 'option'.$j, 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => true));
	            }

		        $nextlevel[] = $cat['id'];
	            $j++;
		        unset($kb_cat[$k]);

	        }

	    }

	    $thislevel = $nextlevel;
	    $nextlevel = array();

	    /* Break after 20 recursions to avoid hang-ups in case of any problems */

	    if ($i > 20)
	    {
	    	break;
	    }
	    $i++;
	}

	$menu->addItem($node[1]);

	// Create the presentation class
    $HTML_TreeMenu_Listbox = new HTML_TreeMenu_Listbox($menu);
	$listBox  = & ref_new($HTML_TreeMenu_Listbox);

	/* Print header */
	require_once(HESK_PATH . 'inc/header.inc.php');

	/* Print main manage users page */
	require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

	/* This will handle error, success and notice messages */
	hesk_handle_messages();

    if ($hesk_settings['kb_wysiwyg'])
    {
        hesk_tinymce_init('#content');
    }
    ?>

    <div class="main__content knowledge article">
        <form action="manage_knowledgebase.php" method="post" name="form1" enctype="multipart/form-data" aria-label="<?php echo $hesklang['kb_art_edit']; ?>">
            <div class="article__detalies edit">
                <div class="article__detalies_head">
                    <h3><?php echo $hesklang['kb_art_edit']; ?></h3>
                </div>
                <ul class="article__detalies_list">
                    <li>
                        <div class="checkbox-list">
                            <div class="checkbox-custom" style="margin-bottom: 5px">
                                <input type="checkbox" id="edit_sticky" name="sticky" value="Y" <?php if ($article['sticky']) {echo 'checked';} ?>>
                                <label for="edit_sticky"><?php echo $hesklang['sticky']; ?></label>
                            </div>
                            <div class="checkbox-custom" style="margin-bottom: 5px">
                                <input type="checkbox" id="edit_resetviews" name="resetviews" value="Y" <?php if (isset($_SESSION['edit_article']['resetviews']) && $_SESSION['edit_article']['resetviews'] == 'Y') {echo 'checked';} ?>>
                                <label for="edit_resetviews"><?php echo $hesklang['rv']; ?></label>
                            </div>
                            <div class="checkbox-custom" style="margin-bottom: 5px">
                                <input type="checkbox" id="edit_resetvotes" name="resetvotes" value="Y" <?php if (isset($_SESSION['edit_article']['resetvotes']) && $_SESSION['edit_article']['resetvotes'] == 'Y') {echo 'checked';} ?>>
                                <label for="edit_resetvotes"><?php echo $hesklang['rr']; ?></label>
                            </div>
                        </div>
                    </li>
                    <li>
                        <div class="form-group">
                            <label><?php echo $hesklang['kb_type']; ?></label>
                            <div class="radio-list">
                                <div class="radio-custom">
                                    <input type="radio" id="edit_type0" name="type" value="0" <?php if ($article['type']==0) {echo 'checked';} ?>>
                                    <label for="edit_type0"><?php echo $hesklang['kb_published']; ?></label>
                                </div>
                                <div style="margin-left: 24px; margin-bottom: 10px"><?php echo $hesklang['kb_published2']; ?></div>
                                <div class="radio-custom">
                                    <input type="radio" id="edit_type1" name="type" value="1" <?php if ($article['type']==1) {echo 'checked';} ?>>
                                    <label for="edit_type1"><?php echo $hesklang['kb_private']; ?></label>
                                </div>
                                <div style="margin-left: 24px; margin-bottom: 10px"><?php echo $hesklang['kb_private2']; ?></div>
                                <div class="radio-custom">
                                    <input type="radio" id="edit_type2" name="type" value="2" <?php if ($article['type']==2) {echo 'checked';} ?>>
                                    <label for="edit_type2"><?php echo $hesklang['kb_draft']; ?></label>
                                </div>
                                <div style="margin-left: 24px; margin-bottom: 10px"><?php echo $hesklang['kb_draft2']; ?></div>
                            </div>
                        </div>
                    </li>
                    <li>
                        <div class="name category">
                            <label for="edit_catid"><?php echo $hesklang['kb_cat']; ?></label>
                        </div>
                        <div class="descr">
                            <div class="dropdown-select right out-close">
                                <select id="edit_catid" name="catid"><?php $listBox->printMenu()?></select>
                            </div>
                        </div>
                    </li>
                </ul>
                <div class="article__detalies_action">
                    <button type="submit" class="btn btn-full" ripple="ripple"><?php echo $hesklang['kb_save']; ?></button>
                    <?php
                    $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                        $hesklang['del_art'],
                        'manage_knowledgebase.php?a=remove_article&amp;id='. $article['id'] .'&amp;token='. hesk_token_echo(0));
                    ?>
                    <a class="btn btn--blue-border" href="javascript:" data-modal="[data-modal-id='<?php echo $modal_id; ?>']">
                        <?php echo $hesklang['delete_article']; ?>
                    </a>
                </div>
            </div>
            <?php
            // Redirect to the correct page
            switch ($from)
            {
                case 'draft':
                    $redirect_action = 'a=list_draft';
                    break;
                case 'private':
                    $redirect_action = 'a=list_private';
                    break;
                default:
                    $redirect_action = 'a=manage_cat&amp;catid='.$catid;
                    $from = 'manage_cat';
                    break;
            }
            ?>
            <div class="article__body form">
                <div class="article__back">
                    <a href="manage_knowledgebase.php?<?php echo $redirect_action; ?>">
                        <svg class="icon icon-back">
                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                        </svg>
                        <span><?php echo $hesklang['wizard_back']; ?></span>
                    </a>
                </div>
                <div class="article__title">
                    <div class="form-group">
                        <label for="edit_subject"><?php echo $hesklang['kb_subject']; ?></label>
                        <input id="edit_subject" type="text" class="form-control" name="subject" maxlength="255"
                               value="<?php echo $article['subject']; ?>">
                    </div>
                </div>
                <div class="article__description">
                    <?php
                    $displayType = $hesk_settings['kb_wysiwyg'] ? 'none' : 'block';
                    $displayWarn = $article['html'] ? 'block' : 'none';
                    ?>
                    <span id="contentType" style="display:<?php echo $displayType; ?>">
                        <label><input type="radio" name="html" value="0" <?php if (!$article['html']) {echo 'checked="checked"';} ?> onclick="javascript:document.getElementById('kblinks').style.display = 'none'" /> <?php echo $hesklang['kb_dhtml']; ?></label><br />
                        <label><input type="radio" name="html" value="1" <?php if ($article['html']) {echo 'checked="checked"';} ?> onclick="javascript:document.getElementById('kblinks').style.display = 'block'" /> <?php echo $hesklang['kb_ehtml']; ?></label>
                        <span id="kblinks" style="display:<?php echo $displayWarn; ?>"><i><?php echo $hesklang['kb_links']; ?></i></span>
                    </span>
                    <label>
                        <textarea class="form-control" style="height: inherit" name="content" rows="25" cols="70" id="content"><?php echo $article['content']; ?></textarea>
                    </label>
                </div>
                <?php
                if ( ! empty($article['attachments']) || $hesk_settings['attachments']['use'])
                {
                    ?>
                    <div class="attachments">
                        <svg class="icon icon-attach">
                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-attach"></use>
                        </svg>
                        <?php echo $hesklang['attachments']; ?><br>
                        <?php
                        // Existing attachments
                        if ( ! empty($article['attachments']))
                        {
                            $att=explode(',',substr($article['attachments'], 0, -1));
                            foreach ($att as $myatt)
                            {
                                list($att_id, $att_name) = explode('#', $myatt);

                                $tmp = 'White';
                                $style = 'class="option'.$tmp.'OFF" onmouseover="this.className=\'option'.$tmp.'ON\'" onmouseout="this.className=\'option'.$tmp.'OFF\'"';

                                echo '
                                    <a class="tooltip" style="text-decoration: none; margin-left: 16px; margin-right: 6px" title="'.$hesklang['dela'].'" href="manage_knowledgebase.php?a=remove_kb_att&amp;id='.$id.'&amp;kb_att='.$att_id.'&amp;token='.hesk_token_echo(0).'" onclick="return hesk_confirmExecute(\''.hesk_makeJsString($hesklang['delatt']).'\');">
                                        <svg class="icon icon-delete" style="vertical-align: middle;">
                                            <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-delete"></use>
                                        </svg>
                                    </a>&raquo; ';
                                echo '<a href="download_attachment.php?kb_att='.$att_id.'" title="'.$hesklang['dnl'].' '.$att_name.'">'.$att_name.'</a><br />';
                            }
                            echo '<br>';
                        }

                        // New attachments
                        if ($hesk_settings['attachments']['use'])
                        {
                            require_once(HESK_PATH . 'inc/attachments.inc.php');

                            build_dropzone_markup(true);
                            display_dropzone_field(HESK_PATH . 'upload_attachment.php', true);
                            dropzone_display_existing_files(hesk_SESSION_array('edit_attachments'));
                            hesk_cleanSessionVars('edit_attachments');
                        }
                        ?>
                    </div>
                    <?php
                } // End attachments
                ?>
                <div class="form-group article__keywords">
                    <label for="keywords">
                        <b><?php echo $hesklang['kw']; ?></b>
                        <span><?php echo $hesklang['kw1']; ?></span>
                    </label>
                    <textarea class="form-control" style="height: inherit" name="keywords" rows="3" cols="70" id="keywords"><?php echo $article['keywords']; ?></textarea>
                </div>
            </div>
            <div class="d-flex-center sm-hidden mt2">
                <?php
                $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                    $hesklang['del_art'],
                    'manage_knowledgebase.php?a=remove_article&amp;id='. $article['id'] .'&amp;token='. hesk_token_echo(0));
                ?>
                <a class="btn btn--blue-border" data-modal="[data-modal-id='<?php echo $modal_id; ?>']" href="javascript:">
                    <?php echo $hesklang['delete_article']; ?>
                </a>
                <button type="submit" class="btn btn-full ml1" ripple="ripple">
                    <?php echo $hesklang['kb_save']; ?>
                </button>
            </div>
            <input type="hidden" name="a" value="save_article">
            <input type="hidden" name="id" value="<?php echo $id; ?>">
            <input type="hidden" name="old_type" value="<?php echo $article['type']; ?>">
            <input type="hidden" name="old_catid" value="<?php echo $catid; ?>">
            <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
            <input type="hidden" name="from" value="<?php echo $from; ?>">
        </form>
        <div class="table-wrap">
            <h3 style="font-size: 16px; font-weight: bold">
                <?php echo $hesklang['revhist']; ?>
            </h3>
            <ul>
                <?php echo $article['history']; ?>
            </ul>
        </div>
    </div>

	<?php
    /* Clean unneeded session variables */
    hesk_cleanSessionVars('edit_article');

    require_once(HESK_PATH . 'inc/footer.inc.php');
    exit();
} // END edit_article()


function manage_category() {
	global $hesk_settings, $hesklang;

    $catid = intval( hesk_GET('catid') ) or hesk_error($hesklang['kb_cat_inv']);
    $this_cat = null;

	$result = hesk_dbQuery('SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` ORDER BY `parent` ASC, `cat_order` ASC');
	$kb_cat = array();

	while ($cat = hesk_dbFetchAssoc($result))
	{
		$kb_cat[] = $cat;
        if ($cat['id'] == $catid)
        {
        	$this_cat = $cat;
        }
	}

    if ($this_cat === null)
    {
        hesk_error($hesklang['kb_cat_inv']);
    }

    if (isset($_SESSION['manage_cat']))
    {
    	$_SESSION['manage_cat'] = hesk_stripArray($_SESSION['manage_cat']);
		$this_cat['type'] = $_SESSION['manage_cat']['type'];
        $this_cat['parent'] = $_SESSION['manage_cat']['parent'];
        $this_cat['name'] = $_SESSION['manage_cat']['title'];
    }

	/* Translate main category "Knowledgebase" if needed */
	$kb_cat[0]['name'] = $hesklang['kb_text'];

	require(HESK_PATH . 'inc/treemenu/TreeMenu.php');
	$icon         = 'icon-chevron-right';
	$expandedIcon = 'icon-knowledge';
    $menu		  = new HTML_TreeMenu();

	$thislevel = array('0');
	$nextlevel = array();
	$i = 1;
	$j = 1;

	while (count($kb_cat) > 0)
	{

	    foreach ($kb_cat as $k=>$cat)
	    {

            if ($cat['id'] == $catid)
            {
                continue;
            }

	    	if (in_array($cat['parent'],$thislevel))
	        {

	        	$up = $cat['parent'];
	            $my = $cat['id'];
	            $type = $cat['type'] ? '*' : '';

				$text_short = $cat['name'].$type.' ('.$cat['articles'].', '.$cat['articles_private'].', '.$cat['articles_draft'].')';

	            if (isset($node[$up]))
	            {
                    $HTML_TreeNode[$my] = new HTML_TreeNode(array('hesk_parent' => $this_cat['parent'], 'text' => 'Text', 'text_short' => $text_short, 'hesk_catid' => $cat['id'], 'hesk_select' => 'option'.$j, 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => true));
		            $node[$my] = &$node[$up]->addItem($HTML_TreeNode[$my]);
	            }
	            else
	            {
	                $node[$my] = new HTML_TreeNode(array('hesk_parent' => $this_cat['parent'], 'text' => 'Text',  'text_short' => $text_short, 'hesk_catid' => $cat['id'], 'hesk_select' => 'option'.$j, 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => true));
	            }

		        $nextlevel[] = $cat['id'];
	            $j++;
		        unset($kb_cat[$k]);

	        }

	    }

	    $thislevel = $nextlevel;
	    $nextlevel = array();

	    /* Break after 20 recursions to avoid hang-ups in case of any problems */

	    if ($i > 20)
	    {
	    	break;
	    }
	    $i++;
	}

	$menu->addItem($node[1]);

	// Create the presentation class
    $HTML_TreeMenu_Listbox = new HTML_TreeMenu_Listbox($menu);
	$listBox  = & ref_new($HTML_TreeMenu_Listbox);

	/* Print header */
	require_once(HESK_PATH . 'inc/header.inc.php');

	/* Print main manage users page */
	require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

    hesk_handle_messages();
	echo '<div class="main__content knowledge category">';
    if ( ! isset($_SESSION['hide']['article_list']))
    {
    ?>
        <div class="category__list visible">
            <div class="category__list_head">
                <h3><?php echo $this_cat['name']; ?></h3>
            </div>
            <div class="category__list_table overflow-x-scroll" style="display: block">
                <div style="float: right; margin-bottom: 10px;">
                    <a class="btn btn--blue-border" href="manage_knowledgebase.php?a=add_article&amp;catid=<?php echo $catid; ?>">
                        <?php echo $hesklang['kb_i_art2']; ?>
                    </a>
                </div>
                <table>
                    <tbody>
                    <?php
                    $result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `catid`='{$catid}' ORDER BY `sticky` DESC, `art_order` ASC");
                    $num    = hesk_dbNumRows($result);

                    if ($num == 0)
                    {
                        echo '
                        <tr>
                            <td colspan="4" style="padding-left: 10px">'.$hesklang['kb_no_art'].'</td>
                        </tr>
                        ';
                    }
                    else
                    {
                        /* Get number of sticky articles */
                        $res2 = hesk_dbQuery("SELECT COUNT(*) FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `catid`='{$catid}' AND `sticky` = '1' ");
                        $num_sticky = hesk_dbResult($res2);

                        $num_nosticky = $num - $num_sticky;

                        $i=1;
                        $j=1;
                        $k=1;
                        $previous_sticky=1;
                        $num = $num_sticky;

                        while ($article=hesk_dbFetchAssoc($result))
                        {

                            if ($previous_sticky != $article['sticky'])
                            {
                                $k = 1;
                                $num = $num_nosticky;
                                $previous_sticky = $article['sticky'];
                            }

                            $table_row = 'class="';
                            if (isset($_SESSION['artord']) && $article['id'] == $_SESSION['artord'])
                            {
                                $table_row .= 'ticket-new ';
                                unset($_SESSION['artord']);
                            }

                            if ($article['sticky']) {
                                $table_row .= 'sticky';
                            }
                            $table_row .= '"';

                            $i     = $i ? 0 : 1;

                            // Status
                            switch ($article['type'])
                            {
                                case '1':
                                    $type = '<div style="margin-bottom: 3px">' . $hesklang['kb_private'] . '</div>';
                                    break;
                                case '2':
                                    $type = '<div style="margin-bottom: 3px">' . $hesklang['kb_draft'] . '</div>';
                                    break;
                                default:
                                    $type = '<div style="margin-bottom: 3px">' . $hesklang['kb_published'] . '</div>';
                            }


                            if ($hesk_settings['kb_rating'] && $article['type'] != '2')
                            {
                                $type .= hesk3_get_rating($article['rating'], $article['votes']);
                            }

                            ?>
                            <tr <?php echo $table_row; ?>>
                                <td class="title">
                                    <a href="knowledgebase_private.php?article=<?php echo $article['id']; ?>&amp;back=1<?php if ($article['type'] == 2) {echo '&amp;draft=1';} ?>">
                                        <?php echo $article['subject']; ?>
                                    </a>
                                </td>
                                <td class="view">
                                    <svg class="icon icon-eye-close tooltip" title="<?php echo $hesklang['views'].': '.$article['views'];?>">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-eye-close"></use>
                                    </svg>
                                    <?php echo $article['views']; ?>
                                </td>
                                <td class="status">
                                    <?php echo $type; ?>
                                </td>
                                <td class="actions">
                                    <div class="actions--buttons">
                                        <?php
                                        if ($num > 1)
                                        {
                                            if ($k == 1)
                                            {
                                                ?>
                                                <a href="#" style="visibility: hidden" aria-label="<?php echo $hesklang['move_up']; ?>">
                                                    <svg class="icon icon-chevron-up">
                                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                                    </svg>
                                                </a>
                                                <a class="tooltip" href="manage_knowledgebase.php?a=order_article&amp;id=<?php echo $article['id']; ?>&amp;catid=<?php echo $catid; ?>&amp;move=15&amp;token=<?php hesk_token_echo(); ?>"
                                                   title="<?php echo $hesklang['move_dn']; ?>" aria-label="<?php echo $hesklang['move_dn']; ?>">
                                                    <svg class="icon icon-chevron-down">
                                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                                    </svg>
                                                </a>
                                                <?php
                                            }
                                            elseif ($k == $num)
                                            {
                                                ?>
                                                <a class="tooltip" href="manage_knowledgebase.php?a=order_article&amp;id=<?php echo $article['id']; ?>&amp;catid=<?php echo $catid; ?>&amp;move=-15&amp;token=<?php hesk_token_echo(); ?>"
                                                   title="<?php echo $hesklang['move_up']; ?>" aria-label="<?php echo $hesklang['move_up']; ?>">
                                                    <svg class="icon icon-chevron-up">
                                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                                    </svg>
                                                </a>
                                                <a href="#" style="visibility: hidden" aria-label="<?php echo $hesklang['move_dn']; ?>">
                                                    <svg class="icon icon-chevron-down">
                                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                                    </svg>
                                                </a>
                                                <?php
                                            }
                                            else
                                            {
                                                ?>
                                                <a class="tooltip" href="manage_knowledgebase.php?a=order_article&amp;id=<?php echo $article['id']; ?>&amp;catid=<?php echo $catid; ?>&amp;move=-15&amp;token=<?php hesk_token_echo(); ?>"
                                                   title="<?php echo $hesklang['move_up']; ?>" aria-label="<?php echo $hesklang['move_up']; ?>">
                                                    <svg class="icon icon-chevron-up">
                                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                                    </svg>
                                                </a>
                                                <a class="tooltip" href="manage_knowledgebase.php?a=order_article&amp;id=<?php echo $article['id']; ?>&amp;catid=<?php echo $catid; ?>&amp;move=15&amp;token=<?php hesk_token_echo(); ?>"
                                                   title="<?php echo $hesklang['move_dn']; ?>" aria-label="<?php echo $hesklang['move_dn']; ?>">
                                                    <svg class="icon icon-chevron-down">
                                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                                    </svg>
                                                </a>
                                                <?php
                                            }
                                        }
                                        elseif ( $num_sticky > 1 || $num_nosticky > 1 )
                                        {
                                            echo '
                                            <a href="#" style="visibility: hidden" aria-label="' . $hesklang['move_up'] . '">
                                                <svg class="icon icon-chevron-up">
                                                    <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-chevron-down"></use>
                                                </svg>
                                            </a>
                                            <a href="#" style="visibility: hidden" aria-label="' . $hesklang['move_dn'] . '">
                                                <svg class="icon icon-chevron-down">
                                                    <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-chevron-down"></use>
                                                </svg>
                                            </a>';
                                        }
                                        ?>
                                        <a class="tooltip" href="manage_knowledgebase.php?a=sticky&amp;s=<?php echo $article['sticky'] ? 0 : 1 ?>&amp;id=<?php echo $article['id']; ?>&amp;catid=<?php echo $catid; ?>&amp;token=<?php hesk_token_echo(); ?>"
                                           title="<?php echo $article['sticky'] ? $hesklang['stickyoff'] : $hesklang['stickyon']; ?>">
                                            <svg class="icon icon-pin <?php echo $article['sticky'] ? 'is-bookmark' : ''; ?>">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-pin"></use>
                                            </svg>
                                        </a>
                                        <a class="tooltip" href="manage_knowledgebase.php?a=edit_article&amp;id=<?php echo $article['id']; ?>"
                                           title="<?php echo $hesklang['edit']; ?>">
                                            <svg class="icon icon-edit-ticket">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-edit-ticket"></use>
                                            </svg>
                                        </a>
                                        <?php
                                        $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                                            $hesklang['del_art'],
                                            'manage_knowledgebase.php?a=remove_article&amp;id='. $article['id'] .'&amp;token='. hesk_token_echo(0));
                                        ?>
                                        <a class="tooltip" href="javascript:"
                                           data-modal="[data-modal-id='<?php echo $modal_id; ?>']"
                                           title="<?php echo $hesklang['delete']; ?>">
                                            <svg class="icon icon-delete">
                                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-delete"></use>
                                            </svg>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php
                            $j++;
                            $k++;
                        } // End while
                    } ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php
    } // END if hide article list

        /* Manage Category (except the default one) */
		if ($catid != 1)
		{
        ?>
            <div class="table-wrap">
                <h3 style="font-size: 16px;font-weight: bold;padding-bottom:5px;"><?php echo $hesklang['catset']; ?></h3>
                <div style="text-align:right; margin-bottom: 10px">
                    <?php echo '<a class="btn btn--blue-border" href="manage_knowledgebase.php?a=add_category&amp;parent='.$catid.'">'.$hesklang['kb_i_cat2'].'</a>'; ?>
                </div>
                <form action="manage_knowledgebase.php" method="post" name="form1"
                      class="form"
                      onsubmit="Javascript:return hesk_deleteIfSelected('dodelete','<?php echo hesk_makeJsString($hesklang['kb_delcat']); ?>')" aria-label="<?php echo $hesklang['edit_category']; ?>">
                    <div class="form-group">
                        <label for="edit_cat_title"><?php echo $hesklang['kb_cat_title']; ?></label>
                        <input id="edit_cat_title" class="form-control" type="text" name="title" maxlength="255" value="<?php echo $this_cat['name']; ?>">
                    </div>
                    <div class="form-group">
                        <label for="edit_cat_parent"><?php echo $hesklang['kb_cat_parent']; ?></label>
                        <div class="dropdown-select out-close">
                            <select id="edit_cat_parent" name="parent"><?php $listBox->printMenu();  ?></select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label><?php echo $hesklang['kb_type']; ?></label>
                        <div class="radio-list">
                            <div class="radio-custom">
                                <input id="edit_type0" type="radio" name="type" value="0" <?php if (!$this_cat['type']) {echo 'checked';} ?> >
                                <label for="edit_type0"><?php echo $hesklang['kb_published']; ?></label>
                            </div>
                            <div style="margin-left: 24px; margin-bottom: 10px">
                                <?php echo $hesklang['kb_cat_published']; ?>
                            </div>
                            <div class="radio-custom">
                                <input id="edit_type1" type="radio" name="type" value="1" <?php if ($this_cat['type']) {echo 'checked';} ?>>
                                <label for="edit_type1"><?php echo $hesklang['kb_private']; ?></label>
                            </div>
                            <div style="margin-left: 24px; margin-bottom: 10px">
                                <?php echo $hesklang['kb_cat_private']; ?>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label><?php echo $hesklang['opt']; ?></label>
                        <div class="checkbox-list">
                            <div class="checkbox-custom">
                                <input type="checkbox" name="dodelete" id="dodelete" value="Y" onclick="Javascript:hesk_toggleLayerDisplay('deleteoptions')">
                                <label for="dodelete"><?php echo $hesklang['delcat']; ?></label>
                            </div>
                        </div>
                    </div>
                    <div id="deleteoptions" style="display: none;">
                        <div class="form-group">
                            <div class="radio-list">
                                <div class="radio-custom">
                                    <input id="edit_movearticlesY" type="radio" name="movearticles" value="Y" checked>
                                    <label for="edit_movearticlesY"><?php echo $hesklang['move1']; ?></label>
                                </div>
                                <div class="radio-custom">
                                    <input id="edit_movearticlesN" type="radio" name="movearticles" value="N" />
                                    <label for="edit_movearticlesN"><?php echo $hesklang['move2']; ?></label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <input type="hidden" name="a" value="edit_category">
                    <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                    <input type="hidden" name="catid" value="<?php echo $catid; ?>">
                    <button type="submit" class="btn btn-full"><?php echo $hesklang['save_changes']; ?></button>
                </form>
            </div>
	<?php
    } // END if $catid != 1

    echo '</div>';

    echo '&nbsp;<br />&nbsp;';

	/* Clean unneeded session variables */
	hesk_cleanSessionVars(array('hide','manage_cat','edit_article'));

    require_once(HESK_PATH . 'inc/footer.inc.php');
    exit();
} // END manage_category()


function new_category() {
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check('POST');

	$_SESSION['hide'] = array(
		'treemenu' => 1,
		'new_article' => 1,
		//'new_category' => 1,
	);

    $parent = intval( hesk_POST('parent', 1) );
    $type   = empty($_POST['type']) ? 0 : 1;

    $_SESSION['KB_CATEGORY'] = $parent;
    $_SERVER['PHP_SELF'] = 'manage_knowledgebase.php';

    /* Check that title is valid */
	$title  = hesk_input( hesk_POST('title') );
	if (!strlen($title))
	{
		$_SESSION['new_category'] = array(
			'type' => $type,
		);

		hesk_process_messages($hesklang['kb_cat_e_title'],$_SERVER['PHP_SELF']);
	}

	/* Get the latest reply_order */
	$res = hesk_dbQuery('SELECT `cat_order` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` ORDER BY `cat_order` DESC LIMIT 1');
	$row = hesk_dbFetchRow($res);
    $my_order = isset($row[0]) ? intval($row[0]) + 10 : 10;

	$result = hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` (`name`,`parent`,`cat_order`,`type`) VALUES ('".hesk_dbEscape($title)."','".intval($parent)."','".intval($my_order)."','".intval($type)."')");

    $_SESSION['newcat'] = hesk_dbInsertID();

	$_SESSION['hide'] = array(
		'treemenu' => 1,
		'new_article' => 1,
		//'new_category' => 1,
        'cat_treemenu' => 1,
	);

    hesk_process_messages($hesklang['kb_cat_added2'],$_SERVER['PHP_SELF'],'SUCCESS');
} // End new_category()


function new_article()
{
	global $hesk_settings, $hesklang, $listBox;
    global $hesk_error_buffer;

	/* A security check */
	hesk_token_check('POST');

	$_SESSION['hide'] = array(
		'treemenu' => 1,
		//'new_article' => 1,
		'new_category' => 1,
	);

    $hesk_error_buffer = array();

	$catid = intval( hesk_POST('catid', 1) );
    $type  = empty($_POST['type']) ? 0 : (hesk_POST('type') == 2 ? 2 : 1);
    $html  = $hesk_settings['kb_wysiwyg'] ? 1 : (empty($_POST['html']) ? 0 : 1);
    $now   = hesk_date();

	// Prevent submitting duplicate articles by reloading manage_knowledgebase.php page
	if (isset($_SESSION['article_submitted']))
	{
		header('Location:manage_knowledgebase.php?a=manage_cat&catid=' . $catid);
	    exit();
	}

    $_SESSION['KB_CATEGORY'] = $catid;

    $subject = hesk_input( hesk_POST('subject') ) or $hesk_error_buffer[] = $hesklang['kb_e_subj'];

    if ($html)
    {
	    if (empty($_POST['content']))
	    {
        	$hesk_error_buffer[] = $hesklang['kb_e_cont'];
	    }

        $content = hesk_getHTML( hesk_POST('content') );

        // Clean the HTML code
        require(HESK_PATH . 'inc/htmlpurifier/HeskHTMLPurifier.php');
        $purifier = new HeskHTMLPurifier($hesk_settings['cache_dir']);
        $content = $purifier->heskPurify($content);
    }
	else
    {
    	$content = hesk_input( hesk_POST('content') ) or $hesk_error_buffer[] = $hesklang['kb_e_cont'];
	    $content = nl2br($content);
	    $content = hesk_makeURL($content);
    }

    $sticky = isset($_POST['sticky']) ? 1 : 0;

    $keywords = hesk_input( hesk_POST('keywords') );

    /* Article attachments */
	define('KB',1);
	require_once(HESK_PATH . 'inc/posting_functions.inc.php');
    $attachments = array();
    $use_legacy_attachments = hesk_POST('use-legacy-attachments', 0);
	$myattachments='';

	if ($hesk_settings['attachments']['use'])
	{
		require_once(HESK_PATH . 'inc/attachments.inc.php');

        if ($use_legacy_attachments) {
            for ($i=1; $i<=$hesk_settings['attachments']['max_number']; $i++)
            {
                $att = hesk_uploadFile($i);
                if ( ! empty($att))
                {
                    $attachments[$i] = $att;
                }
            }
        } else {
            // The user used the new drag-and-drop system.
            $temp_attachment_names = hesk_POST_array('attachments');
            foreach ($temp_attachment_names as $temp_attachment_name) {
                $temp_attachment = hesk_getTemporaryAttachment($temp_attachment_name);

                if ($temp_attachment !== null) {
                    $attachments[] = $temp_attachment;
                }
            }
        }
	}

    /* Any errors? */
    if (count($hesk_error_buffer))
    {
		// Remove any successfully uploaded attachments
		if ($hesk_settings['attachments']['use'])
		{
            if ($use_legacy_attachments) {
                hesk_removeAttachments($attachments);
            } else {
                $_SESSION['edit_attachments'] = $attachments;
            }
		}

		$_SESSION['new_article'] = array(
		'type' => $type,
		'html' => $html,
		'subject' => $subject,
		'content' => hesk_input( hesk_POST('content') ),
		'keywords' => $keywords,
        'sticky' => $sticky,
		);

		$tmp = '';
		foreach ($hesk_error_buffer as $error)
		{
			$tmp .= "<li>$error</li>\n";
		}
		$hesk_error_buffer = $tmp;

    	$hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
    	hesk_process_messages($hesk_error_buffer,'manage_knowledgebase.php');
    }

    $revision = sprintf($hesklang['revision1'],$now,addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');

	/* Add to database */
	if ( ! empty($attachments))
	{
        if (!$use_legacy_attachments) {
            $attachments = hesk_migrateTempAttachments($attachments);
        }

	    foreach ($attachments as $myatt)
	    {
	        hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_attachments` (`saved_name`,`real_name`,`size`) VALUES ('".hesk_dbEscape($myatt['saved_name'])."','".hesk_dbEscape($myatt['real_name'])."','".intval($myatt['size'])."')");
	        $myattachments .= hesk_dbInsertID() . '#' . $myatt['real_name'] .',';
	    }
	}

	/* Get the latest reply_order */
	$res = hesk_dbQuery("SELECT `art_order` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `catid`='".intval($catid)."' AND `sticky` = '" . intval($sticky) . "' ORDER BY `art_order` DESC LIMIT 1");
	$row = hesk_dbFetchRow($res);
    $my_order = isset($row[0]) ? intval($row[0]) + 10 : 10;

    /* Insert article into database */
	hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` (`catid`,`dt`,`author`,`subject`,`content`,`keywords`,`type`,`html`,`sticky`,`art_order`,`history`,`attachments`) VALUES (
    '".intval($catid)."',
    NOW(),
    '".intval($_SESSION['id'])."',
    '".hesk_dbEscape($subject)."',
    '".hesk_dbEscape($content)."',
    '".hesk_dbEscape($keywords)."',
    '".intval($type)."',
    '".intval($html)."',
    '".intval($sticky)."',
    '".intval($my_order)."',
    '".hesk_dbEscape($revision)."',
    '".hesk_dbEscape($myattachments)."'
    )");

    $_SESSION['artord'] = hesk_dbInsertID();

	// Update category article count
    if ($type == 0)
    {
	    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` SET `articles`=`articles`+1 WHERE `id`='".intval($catid)."'");
	}
    else if ($type == 1)
    {
	    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` SET `articles_private`=`articles_private`+1 WHERE `id`='".intval($catid)."'");
	}
    else
    {
	    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` SET `articles_draft`=`articles_draft`+1 WHERE `id`='".intval($catid)."'");
	}

    // Clear KB cache
    hesk_purge_cache('kb');

    unset($_SESSION['hide']);

	$_SESSION['article_submitted']=1;

    hesk_process_messages($hesklang['your_kb_added'],'NOREDIRECT','SUCCESS');
    $_GET['catid'] = $catid;
    manage_category();
} // End new_article()


function remove_article()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check();

	$id = intval( hesk_GET('id') ) or hesk_error($hesklang['kb_art_id']);

    /* Get article details */
	$result = hesk_dbQuery("SELECT `catid`, `type`, `attachments` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `id`='".intval($id)."' LIMIT 1");

    if (hesk_dbNumRows($result) != 1)
    {
    	hesk_error($hesklang['kb_art_id']);
    }

    $article = hesk_dbFetchAssoc($result);
	$catid = intval($article['catid']);
    $from = hesk_GET('from');

    $result = hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `id`='".intval($id)."'");

    // Remove any attachments
    delete_kb_attachments($article['attachments']);

    // Update category article count
    if ($article['type'] == 0)
    {
	    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` SET `articles`=`articles`-1 WHERE `id`='{$catid}'");
	}
    else if ($article['type'] == 1)
    {
	    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` SET `articles_private`=`articles_private`-1 WHERE `id`='{$catid}'");
	}
    else
    {
	    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` SET `articles_draft`=`articles_draft`-1 WHERE `id`='{$catid}'");
	}

    // Clear KB cache
    hesk_purge_cache('kb');

    // Redirect to the correct page
    switch ($from)
    {
        case 'draft':
            $redirect_action = 'a=list_draft';
            break;
        case 'private':
            $redirect_action = 'a=list_private';
            break;
        default:
            $redirect_action = 'a=manage_cat&catid='.$catid;
            break;
    }

	hesk_process_messages($hesklang['your_kb_deleted'],'./manage_knowledgebase.php?'.$redirect_action,'SUCCESS');
} // End remove_article()


function order_category()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check();

	$catid = intval( hesk_GET('catid') ) or hesk_error($hesklang['kb_cat_inv']);
	$move  = intval( hesk_GET('move') );

    $_SESSION['newcat'] = $catid;

	$result = hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` SET `cat_order`=`cat_order`+".intval($move)." WHERE `id`='".intval($catid)."'");
	if (hesk_dbAffectedRows() != 1)
    {
    	hesk_error($hesklang['kb_cat_inv']);
    }

    update_category_order();

	header('Location: manage_knowledgebase.php');
	exit();
} // End order_category()


function order_article()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check();

	$id    = intval( hesk_GET('id') ) or hesk_error($hesklang['kb_art_id']);
    $catid = intval( hesk_GET('catid') ) or hesk_error($hesklang['kb_cat_inv']);
	$move  = intval( hesk_GET('move') );

    $_SESSION['artord'] = $id;

	$result = hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` SET `art_order`=`art_order`+".intval($move)." WHERE `id`='".intval($id)."'");
	if (hesk_dbAffectedRows() != 1)
    {
    	hesk_error($hesklang['kb_art_id']);
    }

    /* Update article order */
    update_article_order($catid);

	header('Location: manage_knowledgebase.php?a=manage_cat&catid='.$catid);
	exit();
} // End order_article()


function show_treeMenu() {
	global $hesk_settings, $hesklang, $treeMenu;
	?>
	<script src="<?php echo HESK_PATH; ?>inc/treemenu/TreeMenu_v25.js" language="JavaScript" type="text/javascript"></script>

	<h4 style="margin-top: 10px;padding-bottom:5px;font-size:1rem"><?php echo $hesklang['kbstruct']; ?></h4>
    <?php
    $treeMenu->printMenu();
    ?>
    <div style="margin-top: 15px">
        <svg style="fill: #9c9c9c" class="icon icon-add">
            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-add"></use>
        </svg>
        <?php echo $hesklang['kb_p_art2']; ?>
    </div>
    <div>
        <svg style="fill: #9c9c9c" class="icon icon-settings">
            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-settings"></use>
        </svg>
        <?php echo $hesklang['kb_p_man2']; ?>
    </div>
    <div>
        (<span class="kb_published">1</span>, <span class="kb_private">2</span>, <span class="kb_draft">3</span>) = <?php echo $hesklang['xyz']; ?>
    </div>
    <?php
}


function show_subnav($hide='',$catid=1)
{
	global $hesk_settings, $hesklang;

	// If a category is selected, use it as default for articles and parents
	if (isset($_SESSION['KB_CATEGORY']))
	{
		$catid = intval($_SESSION['KB_CATEGORY']);
	}

    $link['view'] = '
        <a class="link not-underlined" href="knowledgebase_private.php" aria-label="' . $hesklang['gopr'] . '">
            <svg class="icon icon-search">
                <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-search"></use>
            </svg>        
        </a> 
        <a class="link" href="knowledgebase_private.php" aria-label="' . $hesklang['gopr'] . '">'.$hesklang['gopr'].'</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
    $link['newa'] = '
        <a class="link not-underlined" href="manage_knowledgebase.php?a=add_article&amp;catid='.$catid.'" aria-label="' . $hesklang['kb'] . '">
            <svg style="fill: #9c9c9c" class="icon icon-add">
              <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-add"></use>
            </svg>
        </a>
        <a class="link" href="manage_knowledgebase.php?a=add_article&amp;catid='.$catid.'" aria-label="' . $hesklang['kb'] . '">'.$hesklang['kb_i_art'].'</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
    $link['newc'] = '
        <a class="link not-underlined" href="manage_knowledgebase.php?a=add_category&amp;parent='.$catid.'" aria-label="' . $hesklang['kb'] . ' ' .  $hesklang['kb_cat'] . '">
            <svg style="fill: #9c9c9c" class="icon icon-categories">
                <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-categories"></use>
            </svg>
        </a> 
        <a class="link" href="manage_knowledgebase.php?a=add_category&amp;parent='.$catid.'" aria-label="' . $hesklang['kb'] . ' ' .  $hesklang['kb_cat'] . '">'.$hesklang['kb_i_cat'].'</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
    $link['fbid'] = '
        <svg style="fill: #9c9c9c" class="icon icon-edit">
            <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-edit"></use>        
        </svg>
        <form style="display: inline" class="form" method="get" action="manage_knowledgebase.php" aria-label="' . $hesklang['kb'] . '" aria-label="' . $hesklang['kb_art_edit'] . '">
        <input type="hidden" name="a" value="edit_article">
        '. $hesklang['aid'] .': <input type="text" name="id" class="form-control" style="width: 75px; height: inherit" aria-label="' . $hesklang['aid'] . '"> <button type="submit" class="btn btn--blue-border" style="height: 27px;"  aria-label="' . $hesklang['edit'] . '">'. $hesklang['edit'] .'</button>
        </form>
    ';

    if ($hide && isset($link[$hide]))
    {
    	$link[$hide] = preg_replace('#<a([^<]*)>#', '', $link[$hide]);
        $link[$hide] = str_replace('</a>','',$link[$hide]);
    }

    echo $link['view'];
    echo $link['newa'];
    echo $link['newc'];
    echo $link['fbid'];

    /* This will handle error, success and notice messages */
	hesk_handle_messages();

    return $catid;

} // End show_subnav()


function toggle_sticky()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check();

	$id    = intval( hesk_GET('id') ) or hesk_error($hesklang['kb_art_id']);
    $catid = intval( hesk_GET('catid') ) or hesk_error($hesklang['kb_cat_inv']);
    $sticky = empty($_GET['s']) ? 0 : 1;

    $_SESSION['artord'] = $id;

	/* Update article "sticky" status */
	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` SET `sticky`='" . intval($sticky) . " ' WHERE `id`='" . intval($id) . "'");

    /* Update article order */
    update_article_order($catid);

    $tmp = $sticky ? $hesklang['ason'] : $hesklang['asoff'];
	hesk_process_messages($tmp, './manage_knowledgebase.php?a=manage_cat&catid='.$catid,'SUCCESS');
} // END toggle_sticky()


function update_article_order($catid)
{
	global $hesk_settings, $hesklang;

	/* Get list of current articles ordered by sticky and article order */
	$res = hesk_dbQuery("SELECT `id`, `sticky` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `catid`='".intval($catid)."' ORDER BY `sticky` DESC, `art_order` ASC");

	$i = 10;
	$previous_sticky = 1;

	while ( $article = hesk_dbFetchAssoc($res) )
	{

		/* Different count for sticky and non-sticky articles */
		if ($previous_sticky != $article['sticky'])
		{
			$i = 10;
			$previous_sticky = $article['sticky'];
		}

	    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` SET `art_order`=".intval($i)." WHERE `id`='".intval($article['id'])."'");
	    $i += 10;
	}

	return true;
} // END update_article_order()


function update_category_order()
{
	global $hesk_settings, $hesklang;

	/* Get list of current articles ordered by sticky and article order */
	$res = hesk_dbQuery('SELECT `id`, `parent` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` ORDER BY `parent` ASC, `cat_order` ASC');

	$i = 10;

	while ( $category = hesk_dbFetchAssoc($res) )
	{

	    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` SET `cat_order`=".intval($i)." WHERE `id`='".intval($category['id'])."'");
	    $i += 10;
	}

	return true;
} // END update_category_order()


function update_count($show_success=0)
{
	global $hesk_settings, $hesklang;

	$update_these = array();

	// Get a count of all articles grouped by category and type
	$res = hesk_dbQuery('SELECT `catid`, `type`, COUNT(*) AS `num` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_articles` GROUP BY `catid`, `type`');
	while ( $row = hesk_dbFetchAssoc($res) )
	{
    	switch ($row['type'])
        {
        	case 0:
            	$update_these[$row['catid']]['articles'] = $row['num'];
                break;
        	case 1:
            	$update_these[$row['catid']]['articles_private'] = $row['num'];
                break;
        	default:
            	$update_these[$row['catid']]['articles_draft'] = $row['num'];
        }
	}

    // Set all article counts to 0
	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` SET `articles`=0, `articles_private`=0, `articles_draft`=0");

    // Now update categories that have articles with correct values
    foreach ($update_these as $catid => $value)
    {
    	$value['articles'] = isset($value['articles']) ? $value['articles'] : 0;
    	$value['articles_private'] = isset($value['articles_private']) ? $value['articles_private'] : 0;
    	$value['articles_draft'] = isset($value['articles_draft']) ? $value['articles_draft'] : 0;
		hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` SET `articles`={$value['articles']}, `articles_private`={$value['articles_private']}, `articles_draft`={$value['articles_draft']} WHERE `id`='{$catid}'");
    }

	// Show a success message?
	if ($show_success)
	{
		hesk_process_messages($hesklang['acv'], 'NOREDIRECT','SUCCESS');
	}

	return true;
} // END update_count()


function delete_category_recursive($catid)
{
	global $hesk_settings, $hesklang;

    $catid = intval($catid);

    // Don't allow infinite loops... just in case
    $hesk_settings['recursive_loop'] = isset($hesk_settings['recursive_loop']) ? $hesk_settings['recursive_loop'] + 1 : 1;
    if ($hesk_settings['recursive_loop'] > 20)
    {
    	return false;
    }

	// Make sure any attachments are deleted
	$result = hesk_dbQuery("SELECT `attachments` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `catid`='{$catid}'");
    while ($article = hesk_dbFetchAssoc($result))
    {
		delete_kb_attachments($article['attachments']);
    }

   	// Remove articles from database
	hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `catid`='{$catid}'");

	// Delete all sub-categories
	$result = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` WHERE `parent`='{$catid}'");
    while ($cat = hesk_dbFetchAssoc($result))
    {
		delete_category_recursive($cat['id']);
    }

    return true;

} // END delete_category_recursive()


function delete_kb_attachments($attachments)
{
	global $hesk_settings, $hesklang;

	// If nothing to delete just return
    if (empty($attachments))
    {
    	return true;
    }

	// Do the delete
	$att = explode(',',substr($attachments, 0, -1));
	foreach ($att as $myatt)
	{
		list($att_id, $att_name) = explode('#', $myatt);

		// Get attachment saved name
		$result = hesk_dbQuery("SELECT `saved_name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_attachments` WHERE `att_id`='".intval($att_id)."' LIMIT 1");

		if (hesk_dbNumRows($result) == 1)
		{
			$file = hesk_dbFetchAssoc($result);
			hesk_unlink(HESK_PATH.$hesk_settings['attach_dir'].'/'.$file['saved_name']);
		}

		$result = hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_attachments` WHERE `att_id`='".intval($att_id)."'");
	}

    return true;

} // delete_kb_attachments()


function hesk_stray_article($id)
{
	global $hesk_settings, $hesklang, $article;

	// Set article to category ID 1
	$article['catid'] = 1;

	// Update database
	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` SET `catid`=1 WHERE `id`='".intval($id)."'");

	// Update count of articles in categories
	update_count();

	// Return new category ID
	return 1;

} // END hesk_stray_article()

?>
manage_mfa.php
wget 'https://lists2.roe3.org/hesk/admin/manage_mfa.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

use RobThree\Auth\TwoFactorAuth;

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/mfa_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Demo mode
if ( defined('HESK_DEMO') ) {
    hesk_process_messages($hesklang['ddemo'], 'profile.php', 'NOTICE');
}

if ( ! isset($_SESSION['mfa_enrollment'])) {
    $_SESSION['mfa_enrollment'] = 0;
}

hesk_check_user_elevation('manage_mfa.php');

$display_step = 1;
$current_step = intval(hesk_POST('current-step'));
$tfa = build_tfa_instance();
if ($current_step > 0) {
    hesk_token_check('POST');
}
if ($current_step === 1) {
    // Intro -> Verification
    $mfa_method = intval(hesk_POST('mfa-method'));
    if ($mfa_method === 1) {
        $verification_code = generate_mfa_code();
        hash_and_store_mfa_verification_code($_SESSION['id'], $verification_code);
        $mfa_email_sent = send_mfa_email($_SESSION['name'], $_SESSION['email'], $verification_code);

        $display_step = 2;
    } elseif ($mfa_method === 2) {
        $_SESSION['tfa_secret'] = $tfa->createSecret();
        $display_step = 2;
    } elseif ($mfa_method === 0 && $hesk_settings['require_mfa'] === 0) {
        hesk_dbQuery("UPDATE `" . hesk_dbEscape($hesk_settings['db_pfix']) . "users` 
                SET `mfa_enrollment` = 0 
                WHERE `id` = " . intval($_SESSION['id']));
        delete_mfa_codes($_SESSION['id']);
        delete_mfa_backup_codes($_SESSION['id']);
        hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."auth_tokens` WHERE `user_id` = ".intval($_SESSION['id'])." AND `user_type` = 'STAFF'");
        hesk_setcookie('hesk_remember', '');
        $_SESSION['mfa_enrollment'] = 0;
        $display_step = 3;
    } else {
        hesk_process_messages($hesklang['mfa_invalid_method'], 'manage_mfa.php');
    }
} elseif ($current_step === 2) {
    $mfa_method = intval(hesk_POST('mfa-method'));
    if ($mfa_method === 1) {
        $verification_code = hesk_POST('verification-code');

        if (is_mfa_email_code_valid($_SESSION['id'], $verification_code)) {
            //-- Enable MFA for the user and delete the verification code
            hesk_dbQuery("UPDATE `" . hesk_dbEscape($hesk_settings['db_pfix']) . "users` 
                SET `mfa_enrollment` = 1 
                WHERE `id` = " . intval($_SESSION['id']));
            $_SESSION['mfa_enrollment'] = 1;
            hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."auth_tokens` WHERE `user_id` = ".intval($_SESSION['id'])." AND `user_type` = 'STAFF'");
            hesk_setcookie('hesk_remember', '');
            $_SESSION['mfa_backup_codes'] = generate_and_store_mfa_backup_codes($_SESSION['id']);
            $display_step = 3;
        } else {
            //-- Invalid code entered
            hesk_process_messages($hesklang['mfa_invalid_verification_code'], 'NOREDIRECT');
            $display_step = 2;
        }
    } elseif ($mfa_method === 2) {
        $secret = $_SESSION['tfa_secret'];
        if (is_mfa_app_code_valid($_SESSION['id'], hesk_POST('verification-code'), $secret)) {
            hesk_dbQuery("UPDATE `" . hesk_dbEscape($hesk_settings['db_pfix']) . "users` 
                SET `mfa_enrollment` = 2,
                    `mfa_secret` = '" . hesk_dbEscape($secret) . "' 
                WHERE `id` = " . intval($_SESSION['id']));
            $_SESSION['mfa_backup_codes'] = generate_and_store_mfa_backup_codes($_SESSION['id']);
            unset($_SESSION['tfa_secret']);
            $_SESSION['mfa_enrollment'] = 2;
            hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."auth_tokens` WHERE `user_id` = ".intval($_SESSION['id'])." AND `user_type` = 'STAFF'");
            hesk_setcookie('hesk_remember', '');
            $display_step = 3;
        } else {
            hesk_process_messages($hesklang['mfa_invalid_verification_code'], 'NOREDIRECT');
            $display_step = 2;
        }
    } else {
        hesk_process_messages($hesklang['mfa_invalid_method'], 'manage_mfa.php');
    }
} elseif (hesk_POST('delete_codes') === 'Y') {
    hesk_token_check();
    delete_mfa_backup_codes($_SESSION['id']);
    hesk_process_messages($hesklang['mfa_del_codes2'], 'NOREDIRECT', 'SUCCESS');
    $display_step = 1;
    $output_at_top = 1;
} elseif (hesk_POST('new_codes') === 'Y') {
    hesk_token_check();
    delete_mfa_backup_codes($_SESSION['id']);
    $new_mfa_backup_codes = generate_and_store_mfa_backup_codes($_SESSION['id']);
    $backup_codes = implode("\n", array_map(function($code, $key) { return str_pad(($key+1), 2, ' ', STR_PAD_LEFT) . '. ' . substr($code, 0, 4) . '-' . substr($code, 4); }, $new_mfa_backup_codes, array_keys($new_mfa_backup_codes)));
    hesk_process_messages($hesklang['mfa_new_codes2'] . '<p style="margin-top:10px">'.$hesklang['mfa_backup_codes_description'].'</p><pre style="margin-top:20px; font-family: monospace; font-size: 16px;">'.$backup_codes.'</pre>', 'NOREDIRECT', 'SUCCESS');
    $display_step = 1;
    $output_at_top = 1;
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');
?>
<div class="main__content profile">
    <section class="mfa__head">
        <h2>
            <?php echo $hesklang['mfa']; ?>
            <div class="tooltype right out-close">
                <svg class="icon icon-info">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                </svg>
                <div class="tooltype__content">
                    <div class="tooltype__wrapper">
                        <?php echo $hesklang['mfa_introduction']; ?>
                    </div>
                </div>
            </div>
        </h2>
    </section>

    <?php if (isset($output_at_top)) {hesk_handle_messages();} ?>

    <article class="profile__wrapper mfa" data-step="<?php echo $display_step; ?>">
        <?php if (intval($_SESSION['mfa_enrollment']) !== 0 && $display_step === 1) {
            hesk_show_notice($hesklang['mfa_reset_warning']);
        } ?>
        <div class="mfa-steps">
            <ul class="step-bar">
                <li data-link="1" data-all="3"><?php echo $hesklang['mfa_step_method']; ?></li>
                <li data-link="2" data-all="3"><?php echo $hesklang['mfa_step_verification']; ?></li>
                <li data-link="3" data-all="3"><?php echo $hesklang['mfa_step_complete']; ?></li>
            </ul>
        </div>
        <div class="step-slider">
            <?php if ( ! isset($output_at_top)) {hesk_handle_messages();} ?>
            <?php if ($display_step === 1) { ?>
            <div class="step-item step-1">
                <div><strong><?php echo $hesklang['mfa_select_method_colon']; ?><br>&nbsp;</strong></div>
                <form action="manage_mfa.php" method="post" aria-label="<?php echo $hesklang['mfa_select_method_colon']; ?>">
                    <div class="radio-list">
                        <div class="radio-custom">
                            <input type="radio" id="mfa_method_email" name="mfa-method" value="1" <?php echo intval($_SESSION['mfa_enrollment']) === 1 ? 'checked' : ''; ?>>
                            <label for="mfa_method_email">
                                <strong><?php echo $hesklang['mfa_method_email']; ?></strong><br>
                                <span><?php echo sprintf($hesklang['mfa_method_email_subtext'], $_SESSION['email']); ?><br>&nbsp;</span>
                            </label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" id="mfa_method_auth_app" name="mfa-method" value="2" <?php echo intval($_SESSION['mfa_enrollment']) === 2 ? 'checked' : ''; ?>>
                            <label for="mfa_method_auth_app">
                                <strong><?php echo $hesklang['mfa_method_auth_app']; ?></strong><br>
                                <span><?php echo $hesklang['mfa_method_auth_app_subtext']; ?><br>&nbsp;</span>
                            </label>
                        </div>
                        <?php if ($hesk_settings['require_mfa'] === 0): ?>
                        <div class="radio-custom">
                            <input type="radio" id="mfa_method_none" name="mfa-method" value="0" <?php echo intval($_SESSION['mfa_enrollment']) === 0 ? 'checked' : ''; ?>>
                            <label for="mfa_method_none">
                                <strong><?php echo $hesklang['mfa_method_none']; ?></strong><br>
                                <span><?php echo $hesklang['mfa_method_none_subtext']; ?><br>&nbsp;</span>
                            </label>
                        </div>
                        <?php endif; ?>
                    </div>
                    <input type="hidden" name="current-step" value="1">
                    <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                    <button type="submit" class="btn btn-full next" ripple="ripple"><?php echo $hesklang['wizard_next']; ?></button>
                </form>
            </div>
            <?php } elseif ($display_step === 2) { ?>
            <div class="step-item step-2">
                <?php if ($mfa_method === 1) { ?>
                    <div>
                        <h3><?php echo sprintf($hesklang['mfa_verification_header'], $hesklang['mfa_method_email']); ?></h3>
                        <?php
                        if (isset($mfa_email_sent) && $mfa_email_sent === true) {
                            hesk_show_notice(sprintf($hesklang['mfa_verification_email_intro'], $_SESSION['email']), ' ', false);
                        }
                        ?>
                    </div>
                <?php } elseif ($mfa_method === 2) { ?>
                    <div>
                        <h3><?php echo sprintf($hesklang['mfa_verification_header'], $hesklang['mfa_method_auth_app']); ?></h3>
                        <p><?php echo $hesklang['mfa_verification_auth_app_intro']; ?></p>
                        <?php if (function_exists('curl_init')): ?>
                        <img src="<?php echo $tfa->getQRCodeImageAsDataUri($hesk_settings['hesk_title'], $_SESSION['tfa_secret']); ?>" alt="QR Code">
                        <?php else: ?>
                        <?php hesk_show_notice($hesklang['mfa_curl']); ?>
                        <?php endif; ?>
                        <?php hesk_show_info(sprintf($hesklang['mfa_verification_auth_app_cant_scan'], chunk_split($_SESSION['tfa_secret'], 4, ' ')), ' ', false); ?>
                        <p>&nbsp;</p>
                        <p><?php echo $hesklang['mfa_verification_auth_app_enter_code']; ?><br>&nbsp;</p>
                    </div>
                <?php } ?>
                <?php if (empty($hide_form)): ?>
                <form id="verify-form" class="form" action="manage_mfa.php" method="post" aria-label="<?php echo $hesklang['mfa_verify']; ?>">
                    <div class="form-group">
                        <label for="verify-input"><?php echo $hesklang['mfa_code']; ?></label>
                        <input name="verification-code" id="verify-input" type="text" class="form-control" maxlength="6" placeholder="000000" autocomplete="off">
                        <input type="hidden" name="current-step" value="2">
                        <input type="hidden" name="mfa-method" value="<?php echo $mfa_method; ?>">
                        <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                        <button type="submit" class="btn btn-full" ripple="ripple"><?php echo $hesklang['mfa_verify']; ?></button>
                    </div>
                </form>
                <script>
                    $('#verify-form').preventDoubleSubmission();
                    $('#verify-form').submit(function() {
                        $(this).find('button[type="submit"]')
                            .attr('disabled', 'disabled')
                            .addClass('disabled');
                    });
                    $('#verify-input').keyup(function() {
                        if (this.value.length === 6) {
                            $('#verify-form').submit();
                        }
                    });
                </script>
                <?php endif; ?>
                <p>&nbsp;</p>
                <p>&nbsp;</p>
                <a href="manage_mfa.php">
                    <button type="button" class="btn btn--blue-border"><?php echo $hesklang['wizard_back']; ?></button>
                </a>
            </div>
            <?php } elseif ($display_step === 3) { ?>
            <div class="step-item step-3">
                <?php if (intval($_SESSION['mfa_enrollment']) !== 0) {
                    $backup_codes = implode("\n", array_map(function($code, $key) { return str_pad(($key+1), 2, ' ', STR_PAD_LEFT) . '. ' . substr($code, 0, 4) . '-' . substr($code, 4); }, $_SESSION['mfa_backup_codes'], array_keys($_SESSION['mfa_backup_codes'])));
                    hesk_show_success('<div class="shield-icon"><svg class="icon icon-anonymize"><use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-anonymize"></use></svg></div>' . $hesklang['mfa_configured'], ' ', false);
                    hesk_show_info('<p style="margin-top:10px">'.$hesklang['mfa_backup_codes_description'].'</p><pre style="margin-top:20px; font-family: monospace; font-size: 16px;">'.$backup_codes.'</pre>', $hesklang['mfa_backup_codes_header'] . '<br>', false);
                } else {
                    hesk_show_info($hesklang['mfa_removed'], ' ', false);
                } ?>
                <p>&nbsp;</p>
                <p>&nbsp;</p>
                <p>&nbsp;</p>
                <div class="verify-back">
                    <a href="profile.php" class="btn btn-full" ripple="ripple"><?php echo $hesklang['view_profile']; ?></a>
                </div>
            </div>
            <?php } ?>
        </div>
    </article>

    <?php
    if (intval($_SESSION['mfa_enrollment']) !== 0):
        $res = hesk_dbQuery("SELECT COUNT(*) FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."mfa_backup_codes` WHERE `user_id`=".intval($_SESSION['id']) . " AND `user_type`='STAFF'");
        $num = hesk_dbResult($res,0,0);
    ?>

    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>

    <section class="mfa__head">
        <h2>
            <?php echo $hesklang['mfa_backup_codes']; ?>
            <div class="tooltype right out-close">
                <svg class="icon icon-info">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                </svg>
                <div class="tooltype__content">
                    <div class="tooltype__wrapper">
                        <?php echo $hesklang['mfa_backup_codes_info']; ?>
                    </div>
                </div>
            </div>
        </h2>
    </section>
    <article class="profile__wrapper mfa">
        <div>
            <p><?php echo $hesklang['mfa_backup_codes_num']; ?></p>
            <p><?php echo sprintf($hesklang['mfa_backup_codes_num2'], $num); ?></p>
            <form class="form" action="manage_mfa.php" method="post" aria-label="<?php echo $hesklang['mfa_manage_profile']; ?>">
                <div class="form-group">
                    <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                    <button type="submit" name="new_codes" value="Y" class="btn btn--blue-border" ripple="ripple"><?php echo $hesklang['mfa_new_codes']; ?></button>
                    <button type="submit" name="delete_codes" value="Y" class="btn btn--blue-border" ripple="ripple"><?php echo $hesklang['mfa_del_codes']; ?></button>
                </div>
            </form>
        </div>
    </article>

    <?php endif; ?>

</div>

<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();
manage_permission_groups.php
wget 'https://lists2.roe3.org/hesk/admin/manage_permission_groups.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');
define('LOAD_TABS',1);

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/profile_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
hesk_checkPermission('can_man_permission_groups');

/* Possible user features */
$hesk_settings['features'] = array(
'can_view_tickets',     /* User can read tickets */
'can_reply_tickets',    /* User can reply to tickets */
'can_del_tickets',      /* User can delete tickets */
'can_edit_tickets',     /* User can edit tickets */
'can_merge_tickets',    /* User can merge tickets */
'can_link_tickets',     /* User can not linked ticket*/
'can_resolve',          /* User can resolve tickets */
'can_submit_any_cat',   /* User can submit a ticket to any category/department */
'can_del_notes',        /* User can delete ticket notes posted by other staff members */
'can_change_cat',       /* User can move ticket to any category/department */
'can_change_own_cat',   /* User can move ticket to a category/department he/she has access to */
'can_due_date',         /* User can set and modify due date */
'can_man_kb',           /* User can manage knowledgebase articles and categories */
'can_man_users',        /* User can create and edit staff accounts */
'can_view_users',       /* User can view staff accounts, but not create or edit them */
'can_man_cat',          /* User can manage categories/departments */
'can_man_canned',       /* User can manage canned responses */
'can_man_ticket_tpl',   /* User can manage ticket templates */
'can_man_settings',     /* User can manage help desk settings */
'can_add_archive',      /* User can mark tickets as "Tagged" */
'can_assign_self',      /* User can assign tickets to himself/herself */
'can_assign_others',    /* User can assign tickets to other staff members */
'can_view_unassigned',  /* User can view unassigned tickets */
'can_view_ass_others',  /* User can view tickets that are assigned to other staff */
'can_view_ass_by',      /* User can view tickets he/she assigned to others */
'can_run_reports',      /* User can run reports and see statistics (only allowed categories and self) */
'can_run_reports_full', /* User can run reports and see statistics (unrestricted) */
'can_export',           /* User can export own tickets to Excel */
'can_view_online',      /* User can view what staff members are currently online */
'can_ban_emails',       /* User can ban email addresses */
'can_unban_emails',     /* User can delete email address bans. Also enables "can_ban_emails" */
'can_ban_ips',          /* User can ban IP addresses */
'can_unban_ips',        /* User can delete IP bans. Also enables "can_ban_ips" */
'can_mute_emails',      /* User can mute email addresses */
'can_unmute_emails',    /* User can delete email address muted. Also enables "can_mute_emails" */
'can_privacy',          /* User can use privacy tools (Anonymize tickets) */
'can_service_msg',      /* User can manage service messages shown in customer interface */
'can_email_tpl',        /* User can manage email templates */
'can_man_customers',    /* User can create and edit customer accounts */
'can_merge_customers',  /* User can merge two or more customers*/
'can_view_customers',   /* User can view customer accounts, but not create or edit them */
'can_man_permission_groups' /* User can view and create permission groups */
);

/* Set default values */
$default_groupdata = array(
    'name' => '',
    'categories' => [],
    'features' => [],
    'users' => []
);

/* A list of all categories */
$hesk_settings['categories'] = array();
$res = hesk_dbQuery('SELECT `id`,`name` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'categories` ORDER BY `cat_order` ASC');
while ($row=hesk_dbFetchAssoc($res))
{
	if ( hesk_okCategory($row['id'], 0) )
    {
		$hesk_settings['categories'][$row['id']] = $row['name'];
    }
}

/* Non-admin users may not create permission groups with more permissions than they have */
if (!$_SESSION['isadmin'])
{
    /* Can only add features he/she has access to */
	$hesk_settings['features'] = array_intersect( explode(',', $_SESSION['heskprivileges']) , $hesk_settings['features']);
}

/* Use any set values, default otherwise */
foreach ($default_groupdata as $k => $v) {
	if (!isset($_SESSION['groupdata'][$k])) {
    	$_SESSION['groupdata'][$k] = $v;
    }
}

$_SESSION['groupdata'] = hesk_stripArray($_SESSION['groupdata']);

/* What should we do? */
if ($action = hesk_REQUEST('a')) {
	if ($action == 'reset_form') {
		$_SESSION['edit_groupdata'] = TRUE;
		header('Location: ./manage_permission_groups.php');
	}
	elseif ($action === 'edit')       {edit_group();}
	elseif ( defined('HESK_DEMO') )  {hesk_process_messages($hesklang['ddemo'], 'manage_permission_groups.php', 'NOTICE');}
	elseif ($action === 'new')        {new_group();}
	elseif ($action === 'save')       {update_group();}
	elseif ($action === 'remove')     {remove();}
    else 							 {hesk_error($hesklang['invalid_action']);}
}

else
{

/* If one came from the Edit page make sure we reset user values */
if (isset($_SESSION['save_groupdata']))
{
	$_SESSION['groupdata'] = $default_groupdata;
    $_SESSION['use_sort_vars'] = true;
    unset($_SESSION['save_groupdata']);
}
if (isset($_SESSION['edit_groupdata']))
{
    $_SESSION['use_sort_vars'] = true;
	$_SESSION['groupdata'] = $default_groupdata;
    unset($_SESSION['edit_groupdata']);
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

// Loader file include for AJAX Request
require_once(HESK_PATH . 'inc/loader.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
if (!hesk_SESSION(array('groupdata', 'errors'))) {
    hesk_handle_messages();
}

if (!isset($_SESSION['use_sort_vars']) && isset($_SESSION['sort_vars'])) {
    unset($_SESSION['sort_vars']);
}
$saved_search = hesk_SESSION_array('sort_vars');
$sort_column = isset($saved_search['sort_column']) ? $saved_search['sort_column'] : hesk_REQUEST('sort_column');
$sort_direction = isset($saved_search['sort_direction']) ? $saved_search['sort_direction'] : hesk_REQUEST('sort_direction');

// Now set the variables in the session for later
$_SESSION['sort_vars'] = [
    'sort_column' => $sort_column,
    'sort_direction' => $sort_direction
];
?>
<div class="main__content team">
    <section class="team__head">
        <h2>
            <?php echo $hesklang['permission_groups_title']; ?>
            <div class="tooltype right out-close">
                <svg class="icon icon-info">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                </svg>
                <div class="tooltype__content">
                    <div class="tooltype__wrapper">
                        <?php echo $hesklang['permission_groups_intro']; ?>
                    </div>
                </div>
            </div>
        </h2>
        <button class="btn btn btn--blue-border" ripple="ripple" data-action="team-create"><?php echo $hesklang['permission_groups_new']; ?></button>
    </section>
    <div class="table-wrap">
        <div class="table">
            <table id="default-table" class="table sindu-table">
                <thead>
                <tr>
                    <th class="sindu-handle <?php echo $sort_column === 'name' ? hesk_mb_strtolower($sort_direction) : '' ?>">
                        <a href="<?php echo build_sort_url($sort_column, 'name', $sort_direction); ?>" aria-label="<?php echo ($hesklang['sort_by'] . ' ' .  $hesklang['name']); ?>">
                            <div class="sort">
                                <span><?php echo $hesklang['permission_groups_name']; ?></span>
                                <i class="handle"></i>
                            </div>
                        </a>
                    </th>
                    <th><?php echo $hesklang['permission_groups_staff_count']; ?></th>
                    <th aria-label="Actions"></th>
                </tr>
                </thead>
                <tbody>
                <?php
                $query_sort_column = 'name';
                if ($sort_column !== null && $sort_column == 'name') {
                    $query_sort_column = $sort_column;
                }
                $query_sort_direction = $sort_direction === 'ASC' ? 'ASC' : 'DESC';
                $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_groups` 
                    ORDER BY `{$query_sort_column}` {$query_sort_direction}");
                $group_to_staff_count_rs = hesk_dbQuery("SELECT `group_id`, COUNT(1) AS `cnt` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_members`
                    GROUP BY `group_id`");
                $group_to_staff_count = [];
                while ($row = hesk_dbFetchAssoc($group_to_staff_count_rs)) {
                    $group_to_staff_count[$row['group_id']] = $row['cnt'];
                }

                if (hesk_dbNumRows($res) === 0) {
                    echo '<tr><td colspan="3">';
                    hesk_show_notice($hesklang['permission_groups_none'], ' ', false);
                    echo '</td></tr>';
                }
                while ($group = hesk_dbFetchAssoc($res)) {
                    if (!key_exists($group['id'], $group_to_staff_count)) {
                        $group_to_staff_count[$group['id']] = 0;
                    }

                    $can_manage_this_group = compare_user_permissions($group['id']);

                    $table_row = '';
                    if (isset($_SESSION['selgroup']) && $group['id'] == $_SESSION['selgroup']) {
                        $table_row = 'class="ticket-new"';
                        unset($_SESSION['selgroup']);
                    }

                    $modal_body = $hesklang['permission_groups_delete_confirm'];

                    $group_id = $group['id'];
                    $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                        $modal_body,
                        'manage_permission_groups.php?a=remove&amp;id='.$group_id.'&amp;token='.hesk_token_echo(0));
                    $edit_remove_code = '';
                    if ($can_manage_this_group) {
                        $edit_remove_code = '
                        <a href="manage_permission_groups.php?a=edit&amp;id='.$group_id.'" class="edit tooltip" title="'.$hesklang['edit'].'">
                            <svg class="icon icon-edit-ticket">
                                <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-edit-ticket"></use>
                            </svg>
                        </a>';
                        $edit_remove_code .= '
                        <a href="javascript:" data-group-id="'.$group['id'].'" class="edit tooltip copy-group" title="'.$hesklang['permission_groups_copy'].'">
                            <svg class="icon icon-merge">
                                <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-merge"></use>
                            </svg>
                        </a>';

                        if ($group_to_staff_count[$group_id] === 0) {
                            $edit_remove_code .= '<a href="javascript:" data-modal="[data-modal-id=\''.$modal_id.'\']"
                                title="'.$hesklang['remove'].'"
                                class="delete tooltip">
                                <svg class="icon icon-delete">
                                    <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-delete"></use>
                                </svg>
                            </a>';
                        } else {
                            $edit_remove_code .= '<a onclick="alert(\''.hesk_makeJsString($hesklang['permission_groups_delete_not_allowed']).'\')"
                                title="'.$hesklang['permission_groups_delete_not_allowed'].'"
                                class="delete tooltip not-allowed">
                                <svg class="icon icon-delete">
                                    <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-delete"></use>
                                </svg>
                            </a>';
                        }
                    }

                    echo <<<EOC
<tr $table_row>
<td>$group[name]</td>
<td>$group_to_staff_count[$group_id]</td>

EOC;

                    echo <<<EOC
<td class="nowrap buttons"><p>$edit_remove_code</p></td>
</tr>

EOC;
                } // End while
                ?>
                </tbody>
            </table>
        </div>
    </div>
    <script>
        $('.copy-group').click(function() {
            $('#overlay_loader').fadeIn(300);
            const groupId = $(this).attr('data-group-id');
            $.ajax({
                url: 'ajax/permission-groups/index.php?id=' + groupId,
                type: 'get',
                success: function(res) {
                    for (const category of res.categories) {
                        $('#category_' + category).attr('checked', 'checked');
                    }
                    for (const feature of res.features) {
                        $('#feature_' + feature).attr('checked', 'checked');
                    }

                    $('#overlay_loader').fadeOut(300);
                    $('button[data-action="team-create"]').click();
                }
            });
        });
    </script>
</div>
<div class="right-bar team-create" <?php echo hesk_SESSION(array('groupdata','errors')) ? 'style="display: block"' : ''; ?>>
    <div class="right-bar__body form permission-group-stepper" data-step="1">
        <h3>
            <a href="manage_permission_groups.php?a=reset_form">
                <svg class="icon icon-back">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                </svg>
                <span><?php echo $hesklang['permission_groups_create_title']; ?></span>
            </a>
        </h3>
        <?php
        if (hesk_SESSION(array('groupdata', 'errors'))) {
            hesk_handle_messages();
        }
        ?>
        <form name="form1" method="post" action="manage_permission_groups.php" class="form <?php echo hesk_SESSION(array('groupdata','errors')) ? 'invalid' : ''; ?>" aria-label="<?php echo $hesklang['permission_groups_title']; ?>">
            <?php
            $steps = [$hesklang['permission_groups_create_general_info'], $hesklang['menu_users']];

            $errors = hesk_SESSION(['groupdata', 'errors']);
            $errors = is_array($errors) ? $errors : [];
            ?>
            <!-- TABS -->
            <ul class="step-bar">
                <?php
                $i = 1;
                foreach ($steps as $step_name) : ?>
                    <li data-link="<?php echo $i++; ?>" data-all="<?php echo count($steps); ?>">
                        <?php echo $step_name; ?>
                    </li>
                <?php endforeach; ?>
            </ul>
            <?php
            $current_step = 1;
            ?>
            <div class="step-slider">
                <div class="step-item step-<?php echo $current_step++; ?>">
                    <h4><?php echo $hesklang['permission_groups_create_general_info']; ?></h4>
                    <div class="form-group">
                        <label for="group_name"><?php echo $hesklang['permission_groups_name']; ?></label>
                        <input type="text" class="form-control <?php echo in_array('name', $errors) ? 'isError' : ''; ?>" id="group_name" name="name" maxlength="255"
                               value="<?php echo $_SESSION['groupdata']['name']; ?>">
                    </div>
                    <div class="form-group">
                        <label><?php echo $hesklang['allowed_cat']; ?></label>
                        <?php foreach ($hesk_settings['categories'] as $catid => $catname): ?>
                            <div class="checkbox-custom <?php echo in_array('categories-features', $errors) ? 'isError' : ''; ?>">
                                <input type="checkbox" id="category_<?php echo $catid; ?>" name="categories[]" value="<?php echo $catid; ?>"
                                    <?php if (in_array($catid, $_SESSION['groupdata']['categories'])) { echo 'checked'; } ?>>
                                <label for="category_<?php echo $catid; ?>"><?php echo $catname; ?></label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <div class="form-group">
                        <label><?php echo $hesklang['allow_feat']; ?></label>
                        <?php foreach ($hesk_settings['features'] as $k): ?>
                            <div class="checkbox-custom <?php echo in_array('categories-features', $errors) ? 'isError' : ''; ?>">
                                <input type="checkbox" id="feature_<?php echo $k; ?>" name="features[]" value="<?php echo $k; ?>"
                                    <?php if (in_array($k, $_SESSION['groupdata']['features'])) { echo 'checked'; } ?>>
                                <label for="feature_<?php echo $k; ?>"><?php echo $hesklang[$k]; ?></label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="step-item step-<?php echo $current_step++; ?>">
                    <?php
                    $non_admins_rs = hesk_dbQuery("SELECT `id`, `name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `isadmin` = '0' ORDER BY `name` ASC");
                    if (hesk_dbNumRows($non_admins_rs) === 0) {
                        hesk_show_notice($hesklang['permission_groups_create_users_none']);
                    } else {
                        echo '<h4>'.$hesklang['menu_users'].'</h4>';
                    }
                    while ($user = hesk_dbFetchAssoc($non_admins_rs)): ?>
                        <div class="checkbox-custom <?php echo in_array('users', $errors) ? 'isError' : ''; ?>">
                            <input type="checkbox" id="user_<?php echo $user['id']; ?>" name="users[]" value="<?php echo $user['id']; ?>"
                                <?php if (in_array($user['id'], $_SESSION['groupdata']['users'])) { echo 'checked'; } ?>>
                            <label for="user_<?php echo $user['id']; ?>"><?php echo $user['name']; ?></label>
                        </div>
                    <?php endwhile; ?>
                </div>
            </div>

            <!-- Submit -->
            <div class="right-bar__footer">
                <input type="hidden" name="a" value="new">
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                <button type="button" class="btn btn-border" ripple="ripple" data-action="back"><?php echo $hesklang['wizard_back']; ?></button>
                <button type="button" class="btn btn-full next" data-action="next" ripple="ripple"><?php echo $hesklang['wizard_next']; ?></button>
                <button type="submit" class="btn btn-full save" data-action="save" ripple="ripple"><?php echo $hesklang['permission_groups_create_submit']; ?></button>
            </div>
        </form>
    </div>
</div>
<?php
unset($_SESSION['use_sort_vars']);

require_once(HESK_PATH . 'inc/footer.inc.php');
exit();

} // End else


/*** START FUNCTIONS ***/


function compare_user_permissions($group_id, $compare_categories = null, $compare_features = null)
{
	global $hesk_settings;

    // Admins have full access to all features
    if ( isset($_SESSION['isadmin']) && $_SESSION['isadmin']) {
        return true;
    }

    // Do we need to get data from the database?
    if ($compare_categories === null)
    {
        $compare_categories = [];
        $res = hesk_dbQuery("SELECT `category_id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_categories` WHERE `group_id`=".intval($group_id));
        while ($row = hesk_dbFetchAssoc($res)) {
            $compare_categories[] = $row['category_id'];
        }

        $compare_features = [];
        $res = hesk_dbQuery("SELECT `feature` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_features` WHERE `group_id`=".intval($group_id));
        while ($row = hesk_dbFetchAssoc($res)) {
            $compare_features[] = $row['feature'];
        }
    }

	/* Compare categories */
    foreach ($compare_categories as $catid) {
    	if (!array_key_exists($catid, $hesk_settings['categories'])) {
        	return false;
        }
    }

	/* Compare features */
    foreach ($compare_features as $feature) {
    	if (!in_array($feature, $hesk_settings['features'])) {
        	return false;
        }
    }
    return true;
} // END compare_user_permissions()


function edit_group()
{
	global $hesk_settings, $hesklang, $default_groupdata;

	$id = intval( hesk_GET('id') ) or hesk_error("$hesklang[int_error]: $hesklang[no_valid_id]");

    $_SESSION['edit_groupdata'] = TRUE;

    if (!isset($_SESSION['save_groupdata']))
    {
        $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_groups` WHERE `id` = ".intval($id)." LIMIT 1");
    	$_SESSION['groupdata'] = hesk_dbFetchAssoc($res);

        $cat_rs = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_categories` WHERE `group_id` = ".intval($id));
        $_SESSION['groupdata']['categories'] = [];
        while ($row = hesk_dbFetchAssoc($cat_rs)) {
            $_SESSION['groupdata']['categories'][] = $row['category_id'];
        }

        $features_rs = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_features` WHERE `group_id` = ".intval($id));
        $_SESSION['groupdata']['features'] = [];
        while ($row = hesk_dbFetchAssoc($features_rs)) {
            $_SESSION['groupdata']['features'][] = $row['feature'];
        }

        $users_rs = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_members` WHERE `group_id` = ".intval($id));
        $_SESSION['groupdata']['users'] = [];
        while ($row = hesk_dbFetchAssoc($users_rs)) {
            $_SESSION['groupdata']['users'][] = $row['user_id'];
        }

    }

	/* Make sure we have permission to edit this group */
	if (!compare_user_permissions($id, $_SESSION['groupdata']['categories'], $_SESSION['groupdata']['features']) )
	{
		hesk_process_messages($hesklang['npea'],'manage_users.php');
	}

    /* Print header */
	require_once(HESK_PATH . 'inc/header.inc.php');

	/* Print main manage users page */
	require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');
	?>
    <div class="right-bar team-create" style="display: block">
        <div class="right-bar__body form permission-group-stepper" data-step="1">
            <h3>
                <a href="manage_permission_groups.php?a=reset_form">
                    <svg class="icon icon-back">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                    </svg>
                    <span><?php echo $hesklang['permission_groups_edit_title']; ?></span>
                </a>
            </h3>
            <?php
            if (hesk_SESSION(array('groupdata', 'errors'))) {
                /* This will handle error, success and notice messages */
                echo '<div style="margin: -24px -24px 10px -16px;">';
                hesk_handle_messages();
                echo '</div>';
            }
            ?>
            <form name="form1" method="post" action="manage_permission_groups.php" class="form <?php echo hesk_SESSION(array('groupdata','errors')) ? 'invalid' : ''; ?>" aria-label="<?php echo $hesklang['permission_groups_title']; ?>">
                <?php
                $steps = [$hesklang['permission_groups_create_general_info'], $hesklang['menu_users']];

                $errors = hesk_SESSION(['groupdata', 'errors']);
                $errors = is_array($errors) ? $errors : [];
                ?>
                <!-- TABS -->
                <ul class="step-bar">
                    <?php
                    $i = 1;
                    foreach ($steps as $step_name) : ?>
                        <li data-link="<?php echo $i++; ?>" data-all="<?php echo count($steps); ?>">
                            <?php echo $step_name; ?>
                        </li>
                    <?php endforeach; ?>
                </ul>
                <?php
                $current_step = 1;
                ?>
                <div class="step-slider">
                    <div class="step-item step-<?php echo $current_step++; ?>">
                        <h4><?php echo $hesklang['permission_groups_create_general_info']; ?></h4>
                        <div class="form-group">
                            <label for="group_name"><?php echo $hesklang['permission_groups_name']; ?></label>
                            <input type="text" class="form-control <?php echo in_array('name', $errors) ? 'isError' : ''; ?>" id="group_name" name="name" maxlength="255"
                                   value="<?php echo $_SESSION['groupdata']['name']; ?>">
                        </div>
                        <div class="form-group">
                            <label><?php echo $hesklang['allowed_cat']; ?></label>
                            <?php foreach ($hesk_settings['categories'] as $catid => $catname): ?>
                                <div class="checkbox-custom <?php echo in_array('categories-features', $errors) ? 'isError' : ''; ?>">
                                    <input type="checkbox" id="category_<?php echo $catid; ?>" name="categories[]" value="<?php echo $catid; ?>"
                                        <?php if (in_array($catid, $_SESSION['groupdata']['categories'])) { echo 'checked'; } ?>>
                                    <label for="category_<?php echo $catid; ?>"><?php echo $catname; ?></label>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <div class="form-group">
                            <label><?php echo $hesklang['allow_feat']; ?></label>
                            <?php foreach ($hesk_settings['features'] as $k): ?>
                                <div class="checkbox-custom <?php echo in_array('categories-features', $errors) ? 'isError' : ''; ?>">
                                    <input type="checkbox" id="feature_<?php echo $k; ?>" name="features[]" value="<?php echo $k; ?>"
                                        <?php if (in_array($k, $_SESSION['groupdata']['features'])) { echo 'checked'; } ?>>
                                    <label for="feature_<?php echo $k; ?>"><?php echo $hesklang[$k]; ?></label>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <div class="step-item step-<?php echo $current_step++; ?>">
                        <?php
                        $non_admins_rs = hesk_dbQuery("SELECT `id`, `name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `isadmin` = '0' ORDER BY `name` ASC");
                        if (hesk_dbNumRows($non_admins_rs) === 0) {
                            hesk_show_notice($hesklang['permission_groups_create_users_none']);
                        } else {
                            echo '<h4>'.$hesklang['menu_users'].'</h4>';
                        }
                        while ($user = hesk_dbFetchAssoc($non_admins_rs)): ?>
                            <div class="checkbox-custom <?php echo in_array('users', $errors) ? 'isError' : ''; ?>">
                                <input type="checkbox" id="user_<?php echo $user['id']; ?>" name="users[]" value="<?php echo $user['id']; ?>"
                                    <?php if (in_array($user['id'], $_SESSION['groupdata']['users'])) { echo 'checked'; } ?>>
                                <label for="user_<?php echo $user['id']; ?>"><?php echo $user['name']; ?></label>
                            </div>
                        <?php endwhile; ?>
                    </div>
                </div>

                <!-- Submit -->
                <div class="right-bar__footer">
                    <input type="hidden" name="a" value="save">
                    <input type="hidden" name="groupid" value="<?php echo $id; ?>" />
                    <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                    <button type="button" class="btn btn-border" ripple="ripple" data-action="back"><?php echo $hesklang['wizard_back']; ?></button>
                    <button type="button" class="btn btn-full next" data-action="next" ripple="ripple"><?php echo $hesklang['wizard_next']; ?></button>
                    <button type="submit" class="btn btn-full save" data-action="save" ripple="ripple"><?php echo $hesklang['save_changes']; ?></button>
                </div>
            </form>
        </div>
    </div>

	<?php
	require_once(HESK_PATH . 'inc/footer.inc.php');
	exit();
} // End edit_group()


function new_group()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check('POST');

	$mygroup = hesk_validateGroupInfo();

    /* Check for duplicate group names */
	$result = hesk_dbQuery("SELECT 1 FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_groups` WHERE `name` = '".hesk_dbEscape($mygroup['name'])."' LIMIT 1");
	if (hesk_dbNumRows($result) != 0)
	{
        // Stripping slashes because they're added in hesk_validateGroupInfo()
        hesk_process_messages(sprintf($hesklang['permission_groups_error_duplicate'], stripslashes($mygroup['name'])),'manage_permission_groups.php');
        return;
	}

    // Insert permission group
    hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_groups` (`name`) VALUES ('".hesk_dbEscape($mygroup['name'])."')");
    $group_id = hesk_dbInsertID();

    // Insert categories
    if (!empty($mygroup['categories'])) {
        $categories_insert = [];
        foreach ($mygroup['categories'] as $category) {
            $categories_insert[] = '('.intval($group_id).', '.intval($category).')';
        }
        hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_categories` (`group_id`, `category_id`)
        VALUES ".implode(',', $categories_insert));
    }


    // Insert features
    if (!empty($mygroup['features'])) {
        $features_insert = [];
        foreach ($mygroup['features'] as $feature) {
            $features_insert[] = "(".intval($group_id).", '".hesk_dbEscape($feature)."')";
        }
        hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_features` (`group_id`, `feature`)
        VALUES ".implode(',', $features_insert));
    }

    // Insert users
    if (!empty($mygroup['users'])) {
        $users_insert = [];
        foreach ($mygroup['users'] as $user) {
            $users_insert[] = '('.intval($group_id).', '.intval($user).')';
        }
        hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_members` (`group_id`, `user_id`)
        VALUES ".implode(',', $users_insert));
    }

    $_SESSION['selgroup'] = $group_id;

    unset($_SESSION['groupdata']);

    hesk_process_messages(sprintf($hesklang['permission_groups_create_success'], $mygroup['name']),'./manage_permission_groups.php','SUCCESS');
} // End new_group()


function update_group()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check('POST');

    $_SESSION['save_groupdata'] = TRUE;

	$tmp = intval( hesk_POST('groupid') ) or hesk_error("$hesklang[int_error]: $hesklang[no_valid_id]");

    $_SERVER['PHP_SELF'] = './manage_permission_groups.php?a=edit&id='.$tmp;
	$mygroup = hesk_validateGroupInfo();
    $mygroup['id'] = $tmp;

    // Make sure we have permission to edit this group
    if (!compare_user_permissions($mygroup['id']))
    {
        hesk_process_messages($hesklang['npea'],'manage_users.php');
    }

    /* Check for duplicate group names */
	$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_groups` WHERE `name` = '".hesk_dbEscape($mygroup['name'])."' LIMIT 1");
	if (hesk_dbNumRows($res) === 1)
	{
    	$tmp = hesk_dbFetchAssoc($res);

        /* Duplicate? */
        if (intval($tmp['id']) !== $mygroup['id'])
        {
        	hesk_process_messages(sprintf($hesklang['permission_groups_error_duplicate'], $mygroup['name']),$_SERVER['PHP_SELF']);
        }

		/* Do we have permission to edit this group? */
		if (!compare_user_permissions($tmp['id']))
		{
			hesk_process_messages($hesklang['permission_groups_error_permissions'],'manage_permission_groups.php');
		}
	}

    // Update base group
    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_groups`
        SET `name` = '".hesk_dbEscape($mygroup['name'])."'
        WHERE `id` = ".intval($mygroup['id']));

    // Update categories
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_categories` 
        WHERE `group_id` = ".intval($mygroup['id']));
    if (!empty($mygroup['categories'])) {
        $categories_insert = [];
        foreach ($mygroup['categories'] as $category) {
            $categories_insert[] = '('.intval($mygroup['id']).', '.intval($category).')';
        }
        hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_categories` (`group_id`, `category_id`)
        VALUES ".implode(',', $categories_insert));
    }

    // Update features
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_features` 
        WHERE `group_id` = ".intval($mygroup['id']));
    if (!empty($mygroup['features'])) {
        $features_insert = [];
        foreach ($mygroup['features'] as $feature) {
            $features_insert[] = "(".intval($mygroup['id']).", '".hesk_dbEscape($feature)."')";
        }
        hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_features` (`group_id`, `feature`)
        VALUES ".implode(',', $features_insert));
    }

    // Update users
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_members`
        WHERE `group_id` = ".intval($mygroup['id'])." AND `user_id` NOT IN (SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `active` = 0)");
    if (!empty($mygroup['users'])) {
        $users_insert = [];
        foreach ($mygroup['users'] as $user) {
            $users_insert[] = '('.intval($mygroup['id']).', '.intval($user).')';
        }
        hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_members` (`group_id`, `user_id`)
        VALUES ".implode(',', $users_insert));
    }

    unset($_SESSION['save_groupdata']);
    unset($_SESSION['groupdata']);

    $_SESSION['selgroup'] = $mygroup['id'];

    hesk_process_messages($hesklang['permission_groups_edit_success'],'./manage_permission_groups.php','SUCCESS');
} // End update_group()


function hesk_validateGroupInfo()
{
	global $hesk_settings, $hesklang;

    $hesk_error_buffer = '';
    $errors = array();

    if (hesk_input(hesk_POST('name'))) {
        $mygroup['name'] = hesk_input(hesk_POST('name'));
    } else {
        $hesk_error_buffer .= '<li>' . $hesklang['permission_groups_error_name'] . '</li>';
        $errors[] = 'name';
    }

    /* At least one category or one feature is required */
    $mygroup['categories'] = [];
    $mygroup['features'] = [];
    $mygroup['users'] = hesk_POST_array('users');


    $categories = hesk_POST_array('categories');
    $features = hesk_POST_array('features');
    if (empty($categories) && empty($features))
    {
        $hesk_error_buffer .= '<li>' . $hesklang['permission_groups_error_missing_category_feature'] . '</li>';
        $errors[] = 'categories-features';
    }
    else
    {
        foreach ($categories as $tmp)
        {
            if (is_array($tmp))
            {
                continue;
            }

            if ($tmp = intval($tmp))
            {
                $mygroup['categories'][] = $tmp;
            }
        }

        foreach ($features as $tmp)
        {
            if (in_array($tmp, $hesk_settings['features']))
            {
                $mygroup['features'][] = $tmp;
            }
        }
    }

    /* Save entered info in session so we don't lose it in case of errors */
	$_SESSION['groupdata'] = $mygroup;

    /* Any errors */
    if (strlen($hesk_error_buffer))
    {
        $_SESSION['groupdata']['errors'] = $errors;

        $hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
    	hesk_process_messages($hesk_error_buffer, './manage_permission_groups.php');
    }

    // One needs view tickets permissions in one has reply to permission
    if (in_array('can_reply_tickets', $mygroup['features']) && !in_array('can_view_tickets', $mygroup['features']))
    {
        $mygroup['features'][] = 'can_view_tickets';
    }

	// "can_unban_emails" feature also enables "can_ban_emails"
	if ( in_array('can_unban_emails', $mygroup['features']) && ! in_array('can_ban_emails', $mygroup['features']) )
	{
        $mygroup['features'][] = 'can_ban_emails';
	}

    // "can_unmute_emails" feature also enables "can_mute_emails"
    if ( in_array('can_unmute_emails', $mygroup['features']) && ! in_array('can_mute_emails', $mygroup['features']) )
    {
        $mygroup['features'][] = 'can_mute_emails';
    }

    // "can_unban_ips" feature also enables "can_ban_ips"
    if ( in_array('can_unban_ips', $mygroup['features']) && ! in_array('can_ban_ips', $mygroup['features']) )
    {
        $mygroup['features'][] = 'can_ban_ips';
    }

	return $mygroup;
} // End hesk_validateGroupInfo()


function remove()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check();

	$mygroup = intval( hesk_GET('id' ) ) or hesk_error($hesklang['no_valid_id']);

    if (!compare_user_permissions($mygroup)) {
        hesk_process_messages($hesklang['permission_groups_error_permissions'],'manage_permission_groups.php');
        return;
    }

    // Delete all user mappings
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_members` WHERE `group_id` = ".$mygroup);

    // Delete all feature mappings
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_features` WHERE `group_id` = ".$mygroup);

    // Delete all category mappings
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_categories` WHERE `group_id` = ".$mygroup);

    // Delete permission group
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_groups` WHERE `id` = ".$mygroup);

    hesk_process_messages($hesklang['permission_groups_deleted'],'./manage_permission_groups.php','SUCCESS');
} // End remove()


function build_sort_url($current_sort_field, $sort_field, $current_sort_direction) {
    $target_sort_direction = $current_sort_direction === 'ASC' && $sort_field === $current_sort_field ? 'DESC' : 'ASC';
    $encoded_field = urlencode($sort_field);

    return "manage_users.php?sort_column={$encoded_field}&sort_direction={$target_sort_direction}";
}
?>
manage_ticket_templates.php
wget 'https://lists2.roe3.org/hesk/admin/manage_ticket_templates.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
hesk_checkPermission('can_man_ticket_tpl');

// Define required constants
define('LOAD_TABS',1);

if ($hesk_settings['staff_ticket_formatting'] == 2) {
    define('WYSIWYG',1);
}


/* What should we do? */
if ( $action = hesk_REQUEST('a') )
{
    if ( defined('HESK_DEMO') )  {hesk_process_messages($hesklang['ddemo'], 'manage_ticket_templates.php', 'NOTICE');}
    elseif ($action == 'new')    {new_saved();}
    elseif ($action == 'edit')   {edit_saved();}
    elseif ($action == 'remove') {remove();}
    elseif ($action == 'order')  {order_saved();}
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');
?>
<script language="javascript" type="text/javascript"><!--
    function confirm_delete()
    {
        if (confirm('<?php echo hesk_makeJsString($hesklang['delete_tpl']); ?>')) {return true;}
        else {return false;}
    }

    var heskManageTemplateSubmitting = false;
    function hesk_disableTemplateSubmit(buttonID)
    {
        if (heskManageTemplateSubmitting)
        {
            return false;
        }

        heskManageTemplateSubmitting = true;

        var button = document.getElementById(buttonID);
        if (button)
        {
            button.disabled = true;
            button.innerHTML = '<?php echo hesk_makeJsString($hesklang['please_wait']); ?>';
        }

        return true;
    }
//-->
</script>
<?php
/* This will handle error, success and notice messages */
if (!isset($_SESSION['canned']['what'])) {
    hesk_handle_messages();
}

// Get canned responses from database
$result = hesk_dbQuery('SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'ticket_templates` ORDER BY `tpl_order` ASC');
$javascript_messages='';
$javascript_titles='';

$i=1;
$j=0;
$num = hesk_dbNumRows($result);
?>
<div class="main__content templates">
    <section class="templates__head">
        <h2>
            <?php echo $hesklang['ticket_tpl']; ?>
            <div class="tooltype right out-close">
                <svg class="icon icon-info">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                </svg>
                <div class="tooltype__content">
                    <div class="tooltype__wrapper">
                        <?php echo $hesklang['ticket_tpl_intro']; ?>
                    </div>
                </div>
            </div>
        </h2>
        <div class="btn btn--blue-border" ripple="ripple" data-action="create-template" onclick="displayAddTitle()"><?php echo $hesklang['ticket_tpl_add']; ?></div>
    </section>
    <ul class="response__list">
        <?php if ($num < 1): ?>
            <li><h3><?php echo $hesklang['no_ticket_tpl']; ?></h3></li>
        <?php
        endif;

        while ($mysaved=hesk_dbFetchAssoc($result))
        {
            $j++;

            $table_row = '';
            if (isset($_SESSION['canned']['selcat2']) && $mysaved['id'] == $_SESSION['canned']['selcat2']) {
                $table_row = 'class="ticket-new"';
                unset($_SESSION['canned']['selcat2']);
            }

            $message_text = $hesk_settings['staff_ticket_formatting'] == 2 ? $mysaved['message_html'] : $mysaved['message'];

            $javascript_messages.='myMsgTxt['.$mysaved['id'].']='.hesk_json_encode_for_js($message_text).";\n";
            $javascript_titles.='myTitle['.$mysaved['id'].']='.hesk_json_encode_for_js($mysaved['title']).";\n";

            echo '
	    <li ' . $table_row . '>
	    <h3>'.$mysaved['title'].'</h3>
        ';

            if ($num > 1)
            {
                if ($j == 1)
                {
                    echo'
                    <a href="#" style="visibility: hidden">
                        <svg class="icon icon-chevron-down">
                            <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-chevron-down"></use>
                        </svg>
                    </a>
                    <a class="tooltip" title="'.$hesklang['move_dn'].'" href="manage_ticket_templates.php?a=order&amp;replyid='.$mysaved['id'].'&amp;move=15&amp;token='.hesk_token_echo(0).'">
                        <svg class="icon icon-chevron-down">
                            <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-chevron-down"></use>
                        </svg>
                    </a>';
                }
                elseif ($j == $num)
                {
                    echo'
                    <a class="tooltip" title="'.$hesklang['move_up'].'" href="manage_ticket_templates.php?a=order&amp;replyid='.$mysaved['id'].'&amp;move=-15&amp;token='.hesk_token_echo(0).'">
                        <svg class="icon icon-chevron-up">
                            <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-chevron-down"></use>
                        </svg>
                    </a>
                    <a href="#" style="visibility: hidden">
                        <svg class="icon icon-chevron-down">
                            <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-chevron-down"></use>
                        </svg>
                    </a>';
                }
                else
                {
                    echo'
                    <a class="tooltip" title="'.$hesklang['move_up'].'" href="manage_ticket_templates.php?a=order&amp;replyid='.$mysaved['id'].'&amp;move=-15&amp;token='.hesk_token_echo(0).'">
                        <svg class="icon icon-chevron-up">
                            <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-chevron-down"></use>
                        </svg>
                    </a>
                    <a class="tooltip" title="'.$hesklang['move_dn'].'" href="manage_ticket_templates.php?a=order&amp;replyid='.$mysaved['id'].'&amp;move=15&amp;token='.hesk_token_echo(0).'">
                        <svg class="icon icon-chevron-down">
                            <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-chevron-down"></use>
                        </svg>
                    </a>';
                }
            }
            else
            {
                echo '';
            }

            $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                $hesklang['delete_tpl'],
                'manage_ticket_templates.php?a=remove&amp;id='.$mysaved['id'].'&amp;token='.hesk_token_echo(0));

            echo '
            <a class="tooltip" title="'.$hesklang['edit'].'" href="javascript:setMessage(' . $mysaved['id'] . ')">
                <svg class="icon icon-edit-ticket">
                    <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-edit-ticket"></use>
                </svg>
            </a>
            <a class="tooltip" title="'.$hesklang['remove'].'" href="javascript:" data-modal="[data-modal-id=\''.$modal_id.'\']">
                <svg class="icon icon-delete">
                    <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-delete"></use>
                </svg>
            </a>
	    </li>
		';
        } // End while
        ?>
    </ul>
</div>
<div class="right-bar template-create" <?php if (isset($_SESSION['canned']['what'])) { echo 'style="display: block"'; } ?>>
    <div class="right-bar__body template-create__body">
        <h3>
            <a href="javascript:">
                <svg class="icon icon-back">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                </svg>
                <span <?php if (isset($_SESSION['canned']['what']) && $_SESSION['canned']['what'] !== 'NEW') { echo 'style="display: none"'; } ?> id="add-title"><?php echo $hesklang['ticket_tpl_add']; ?></span>
                <span <?php if (isset($_SESSION['canned']['what']) && $_SESSION['canned']['what'] !== 'EDIT') { echo 'style="display: none"'; } ?> id="edit-title"><?php echo $hesklang['ticket_tpl_edit']; ?></span>
            </a>
        </h3>
        <div class="form">
            <?php
            /* This will handle error, success and notice messages */
            if (isset($_SESSION['canned']['what'])) {
                echo '<div style="margin: -24px -24px 10px -16px;">';
                hesk_handle_messages();
                echo '</div>';
            }

            $errors = hesk_SESSION(array('canned', 'errors'));
            $errors = is_array($errors) ? $errors : array();
            ?>
            <form action="manage_ticket_templates.php" method="post" name="form1"
                  class="form <?php echo hesk_SESSION(array('canned', 'errors')) ? 'invalid' : ''; ?>" aria-label="<?php echo $hesklang['ticket_tpl_man']; ?>" onsubmit="return hesk_disableTemplateSubmit('ticket-template-submit');">
                <div class="form-group">
                    <label for="canned_title"><?php echo $hesklang['saved_title']; ?></label>
                    <span id="HeskTitle">
                        <input type="text" class="form-control <?php echo in_array('name', $errors) ? 'isError' : ''; ?>" id="canned_title" name="name" maxlength="50"
                            <?php if (isset($_SESSION['canned']['name'])) {echo ' value="'.stripslashes($_SESSION['canned']['name']).'" ';} ?>>
                    </span>
                </div>
                <div class="form-group">
                    <label for="canned_message"><?php echo $hesklang['message']; ?></label>
                    <span id="HeskMsg">
                        <textarea class="form-control <?php echo in_array('msg', $errors) ? 'isError' : ''; ?>" name="msg" rows="40" cols="70" id="canned_message" style="resize: vertical; transition: none;"><?php
                            if (isset($_SESSION['canned']['msg'])) {
                                echo stripslashes($_SESSION['canned']['msg']);
                            }
                            ?></textarea>
                    </span>
                    <?php
                    if ($hesk_settings['staff_ticket_formatting'] == 2) {
                        hesk_tinymce_init('#canned_message');
                    }
                    ?>
                </div>
                <div class="template--submit">
                    <?php if(isset($_SESSION['canned']['what']) && $_SESSION['canned']['what'] == 'EDIT'): ?>
                        <input type="hidden" name="a" value="edit">
                        <input type="hidden" name="saved_replies" value="<?php echo $_SESSION['canned']['id']; ?>">
                    <?php else: ?>
                        <input type="hidden" name="a" value="new">
                        <input type="hidden" name="saved_replies" value="0">
                    <?php endif; ?>
                    <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                    <button type="submit" class="btn btn-full" ripple="ripple" id="ticket-template-submit"><?php echo $hesklang['save_ticket_tpl']; ?></button>
                </div>
            </form>
        </div>
    </div>
</div>
<script language="javascript" type="text/javascript"><!--
var myMsgTxt = new Array();
myMsgTxt[0]='';
var myTitle = new Array();
myTitle[0]='';

<?php
echo $javascript_titles;
echo $javascript_messages;
?>

function heskDecodeHtmlEntities(value)
{
    var textarea = document.createElement('textarea');
    textarea.innerHTML = String(value).replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return textarea.value;
}

function setMessage(msgid) {
    if (document.getElementById) {
        <?php if ($hesk_settings['staff_ticket_formatting'] == 2): ?>
        tinymce.get("canned_message").setContent('');
        tinymce.get("canned_message").setContent(myMsgTxt[msgid]);
        <?php else: ?>
        document.getElementById('canned_message').value = heskDecodeHtmlEntities(myMsgTxt[msgid]);
        <?php endif; ?>
        document.getElementById('canned_title').value = heskDecodeHtmlEntities(myTitle[msgid]);
    } else {
        document.form1.msg.value=heskDecodeHtmlEntities(myMsgTxt[msgid]);
        document.form1.name.value=heskDecodeHtmlEntities(myTitle[msgid]);
    }

    document.form1.a.value = 'edit';
    document.form1.saved_replies.value = msgid;
    document.getElementById('add-title').style.display = 'none';
    document.getElementById('edit-title').style.display = 'block';
    document.getElementsByClassName('template-create')[0].style.display = 'block';
}

function displayAddTitle() {
    document.form1.msg.value = '';
    document.form1.name.value = '';
    document.form1.saved_replies.value = 0;
    document.form1.a.value = 'new';
    <?php if ($hesk_settings['staff_ticket_formatting'] == 2): ?>
    tinymce.get("canned_message").setContent('');
    <?php endif; ?>
    document.getElementById('add-title').style.display = 'block';
    document.getElementById('edit-title').style.display = 'none';
}
//-->
</script>
<?php

hesk_cleanSessionVars('canned');

require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/
function edit_saved()
{
    global $hesk_settings, $hesklang;

    /* A security check */
    hesk_token_check('POST');

    $hesk_error_buffer = '';
    $errors = array();

    $id = intval( hesk_POST('saved_replies') );
    if (!$id) {
        $hesk_error_buffer .= '<li>' . $hesklang['sel_ticket_tpl'] . '</li>';
        $errors[] = 'id';
    }
    $savename = hesk_input( hesk_POST('name') );
    if (!$savename) {
        $hesk_error_buffer .= '<li>' . $hesklang['ent_ticket_tpl_title'] . '</li>';
        $errors[] = 'name';
    }
    $msg = hesk_input( hesk_POST('msg') );
    if (!$msg) {
        $hesk_error_buffer .= '<li>' . $hesklang['ent_ticket_tpl_msg'] . '</li>';
        $errors[] = 'msg';
    }

    // Avoid problems with utf-8 newline chars in Javascript code, detect and remove them
    $msg = preg_replace('/\R/u', "\r\n", $msg);

    $_SESSION['canned']['what'] = 'EDIT';
    $_SESSION['canned']['id'] = $id;
    $_SESSION['canned']['name'] = $savename;
    $_SESSION['canned']['msg'] = $msg;
    $_SESSION['canned']['errors'] = $errors;

    /* Any errors? */
    if (strlen($hesk_error_buffer))
    {
        $hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
        hesk_process_messages($hesk_error_buffer,'manage_ticket_templates.php?saved_replies='.$id);
    }

    if ($hesk_settings['staff_ticket_formatting'] == 2) {
        // Decode the message we encoded earlier
        $msg_html = hesk_html_entity_decode($msg);

        // Clean the HTML code and set the plaintext version
        require(HESK_PATH . 'inc/htmlpurifier/HeskHTMLPurifier.php');
        require(HESK_PATH . 'inc/html2text/html2text.php');
        $purifier = new HeskHTMLPurifier($hesk_settings['cache_dir']);
        $msg_html = $purifier->heskPurify($msg_html);

        $msg = convert_html_to_text($msg_html);
        $msg = fix_newlines($msg);
        // Replace regular newlines with \r\n to match regular plaintext storage... but then get rid of any accidental \r\r\n outputs
        $msg = str_replace("\n", "\r\n", $msg);
        $msg = str_replace("\r\r\n", "\r\n", $msg);

        // Re-encode the message
        $msg = hesk_htmlspecialchars($msg);
    } else {
        $msg_html = hesk_makeURL($msg);
        $msg_html = nl2br($msg_html);
    }

    $result = hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_templates` SET `title`='".hesk_dbEscape($savename)."',`message`='".hesk_dbEscape($msg)."', `message_html`='".hesk_dbEscape($msg_html)."' WHERE `id`='".intval($id)."'");
    $_SESSION['canned']['selcat2'] = $id;

    unset($_SESSION['canned']['what']);
    unset($_SESSION['canned']['id']);
    unset($_SESSION['canned']['name']);
    unset($_SESSION['canned']['msg']);
    unset($_SESSION['canned']['errors']);

    hesk_process_messages($hesklang['ticket_tpl_saved'],'manage_ticket_templates.php?saved_replies='.$id,'SUCCESS');
} // End edit_saved()

function new_saved()
{
    global $hesk_settings, $hesklang;

    /* A security check */
    hesk_token_check('POST');

    $hesk_error_buffer = '';
    $errors = array();

    $savename = hesk_input( hesk_POST('name') );
    if (!$savename) {
        $hesk_error_buffer .= '<li>' . $hesklang['ent_ticket_tpl_title'] . '</li>';
        $errors[] = 'name';
    }
    $msg = hesk_input( hesk_POST('msg') );
    if (!$msg) {
        $hesk_error_buffer .= '<li>' . $hesklang['ent_ticket_tpl_msg'] . '</li>';
        $errors[] = 'msg';
    }

    // Avoid problems with utf-8 newline chars in Javascript code, detect and remove them
    $msg = preg_replace('/\R/u', "\r\n", $msg);

    $_SESSION['canned']['what'] = 'NEW';
    $_SESSION['canned']['name'] = $savename;
    $_SESSION['canned']['msg'] = $msg;
    $_SESSION['canned']['errors'] = $errors;

    /* Any errors? */
    if (strlen($hesk_error_buffer))
    {
        $hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
        hesk_process_messages($hesk_error_buffer,'manage_ticket_templates.php');
    }

    if ($hesk_settings['staff_ticket_formatting'] == 2) {
        // Decode the message we encoded earlier
        $msg_html = hesk_html_entity_decode($msg);

        // Clean the HTML code and set the plaintext version
        require(HESK_PATH . 'inc/htmlpurifier/HeskHTMLPurifier.php');
        require(HESK_PATH . 'inc/html2text/html2text.php');
        $purifier = new HeskHTMLPurifier($hesk_settings['cache_dir']);
        $msg_html = $purifier->heskPurify($msg_html);

        $msg = convert_html_to_text($msg_html);
        $msg = fix_newlines($msg);
        // Replace regular newlines with \r\n to match regular plaintext storage... but then get rid of any accidental \r\r\n outputs
        $msg = str_replace("\n", "\r\n", $msg);
        $msg = str_replace("\r\r\n", "\r\n", $msg);

        // Re-encode the message
        $msg = hesk_htmlspecialchars($msg);
    } else {
        $msg_html = hesk_makeURL($msg);
        $msg_html = nl2br($msg_html);
    }

    /* Get the latest tpl_order */
    $result = hesk_dbQuery('SELECT `tpl_order` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'ticket_templates` ORDER BY `tpl_order` DESC LIMIT 1');
    $row = hesk_dbFetchRow($result);
    $my_order = isset($row[0]) ? intval($row[0]) + 10 : 10;

    hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_templates` (`title`,`message`,`message_html`,`tpl_order`) VALUES ('".hesk_dbEscape($savename)."','".hesk_dbEscape($msg)."','".hesk_dbEscape($msg_html)."','".intval($my_order)."')");
    $_SESSION['canned']['selcat2'] = hesk_dbInsertID();

    unset($_SESSION['canned']['what']);
    unset($_SESSION['canned']['name']);
    unset($_SESSION['canned']['msg']);
    unset($_SESSION['canned']['errors']);

    hesk_process_messages($hesklang['ticket_tpl_saved'],'manage_ticket_templates.php','SUCCESS');
} // End new_saved()

function remove()
{
    global $hesk_settings, $hesklang;

    /* A security check */
    hesk_token_check();

    $mysaved = intval( hesk_GET('id') ) or hesk_error($hesklang['id_not_valid']);

    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_templates` WHERE `id`='".intval($mysaved)."'");
    if (hesk_dbAffectedRows() != 1)
    {
        hesk_error("$hesklang[int_error]: $hesklang[ticket_tpl_not_found].");
    }

    hesk_process_messages($hesklang['ticket_tpl_removed'],'manage_ticket_templates.php','SUCCESS');
} // End remove()

function order_saved()
{
    global $hesk_settings, $hesklang;

    /* A security check */
    hesk_token_check();

    $tplid = intval( hesk_GET('replyid') ) or hesk_error($hesklang['ticket_tpl_id']);
    $_SESSION['canned']['selcat2'] = $tplid;

    $tpl_move = intval( hesk_GET('move') );

    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_templates` SET `tpl_order`=`tpl_order`+".intval($tpl_move)." WHERE `id`='".intval($tplid)."'");
    if (hesk_dbAffectedRows() != 1) {hesk_error("$hesklang[int_error]: $hesklang[ticket_tpl_not_found].");}

    /* Update all category fields with new order */
    $result = hesk_dbQuery('SELECT `id` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'ticket_templates` ORDER BY `tpl_order` ASC');

    $i = 10;
    while ($mytpl=hesk_dbFetchAssoc($result))
    {
        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_templates` SET `tpl_order`=".intval($i)." WHERE `id`='".intval($mytpl['id'])."'");
        $i += 10;
    }

    header('Location: manage_ticket_templates.php');
    exit();
} // End order_saved()

?>
manage_users.php
wget 'https://lists2.roe3.org/hesk/admin/manage_users.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');
define('LOAD_TABS',1);

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/profile_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
$can_man_users = hesk_checkPermission('can_man_users', false);

// This is a sensitive page, double-check user authentication
if ($can_man_users) {
    $can_view_users = true;
    hesk_check_user_elevation('manage_users.php');
} else {
    $can_view_users = hesk_checkPermission('can_view_users');
}

/* Possible user features */
$hesk_settings['features'] = array(
'can_view_tickets',     /* User can read tickets */
'can_reply_tickets',    /* User can reply to tickets */
'can_del_tickets',      /* User can delete tickets */
'can_edit_tickets',     /* User can edit tickets */
'can_merge_tickets',    /* User can merge tickets */
'can_link_tickets',     /* User can not linked ticket*/
'can_resolve',          /* User can resolve tickets */
'can_submit_any_cat',   /* User can submit a ticket to any category/department */
'can_del_notes',        /* User can delete ticket notes posted by other staff members */
'can_change_cat',       /* User can move ticket to any category/department */
'can_change_own_cat',   /* User can move ticket to a category/department he/she has access to */
'can_due_date',         /* User can set and modify due date */
'can_man_kb',           /* User can manage knowledgebase articles and categories */
'can_man_users',        /* User can create and edit staff accounts */
'can_view_users',       /* User can view staff accounts, but not create or edit them */
'can_man_cat',          /* User can manage categories/departments */
'can_man_canned',       /* User can manage canned responses */
'can_man_ticket_tpl',   /* User can manage ticket templates */
'can_man_settings',     /* User can manage help desk settings */
'can_add_archive',      /* User can mark tickets as "Tagged" */
'can_assign_self',      /* User can assign tickets to himself/herself */
'can_assign_others',    /* User can assign tickets to other staff members */
'can_view_unassigned',  /* User can view unassigned tickets */
'can_view_ass_others',  /* User can view tickets that are assigned to other staff */
'can_view_ass_by',      /* User can view tickets he/she assigned to others */
'can_run_reports',      /* User can run reports and see statistics (only allowed categories and self) */
'can_run_reports_full', /* User can run reports and see statistics (unrestricted) */
'can_export',           /* User can export own tickets to Excel */
'can_view_online',      /* User can view what staff members are currently online */
'can_ban_emails',       /* User can ban email addresses */
'can_unban_emails',     /* User can delete email address bans. Also enables "can_ban_emails" */
'can_ban_ips',          /* User can ban IP addresses */
'can_unban_ips',        /* User can delete IP bans. Also enables "can_ban_ips" */
'can_mute_emails',      /* User can mute email addresses */
'can_unmute_emails',    /* User can delete email address muted. Also enables "can_mute_emails" */
'can_privacy',          /* User can use privacy tools (Anonymize tickets) */
'can_service_msg',      /* User can manage service messages shown in customer interface */
'can_email_tpl',        /* User can manage email templates */
'can_man_customers',    /* User can create and edit customer accounts */
'can_merge_customers',  /* User can merge two or more customers*/
'can_view_customers',   /* User can view customer accounts, but not create or edit them */
'can_man_permission_groups' /* User can view and create permission groups */
);

/* Set default values */
$default_userdata = array(

	// Profile info
	'name' => '',
	'email' => '',
    'nickname' => '',
	'cleanpass' => '',
	'user' => '',
	'autoassign' => 'Y',

	// Signature
	'signature' => '',

	// Permissions
	'isadmin' => 1,
	'categories' => array('1'),
	'features' => array('can_view_tickets','can_reply_tickets','can_change_cat','can_assign_self','can_view_unassigned','can_view_online','can_resolve','can_submit_any_cat'),

    // Permission Groups
    'permission_groups' => [],
    'pg_categories' => [],
    'pg_features' => [],

	// Preferences
	'afterreply' => 0,

	// Defaults
	'autostart' => 1,
	'notify_customer_new' => 1,
	'notify_customer_reply' => 1,
	'show_suggested' => 1,
	'autoreload' => 0,

	// Notifications
	'notify_new_unassigned' => 1,
	'notify_overdue_unassigned' => 1,
	'notify_new_my' => 1,
	'notify_overdue_my' => 1,
	'notify_reply_unassigned' => 1,
	'notify_reply_my' => 1,
	'notify_assigned' => 1,
	'notify_note' => 1,
	'notify_pm' => 1,
	'notify_customer_approval' => 1,
	'notify_collaborator_added' => 1,
	'notify_collaborator_customer_reply' => 1,
	'notify_collaborator_staff_reply' => 0,
	'notify_collaborator_note' => 1,
	'notify_collaborator_resolved' => 0,
	'notify_collaborator_overdue' => 1,
);

/* A list of all categories */
$hesk_settings['categories'] = array();
$res = hesk_dbQuery('SELECT `id`,`name` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'categories` ORDER BY `cat_order` ASC');
while ($row=hesk_dbFetchAssoc($res))
{
	if ( hesk_okCategory($row['id'], 0) )
    {
		$hesk_settings['categories'][$row['id']] = $row['name'];
    }
}

/* Non-admin users may not create users with more permissions than they have */
if ( ! $_SESSION['isadmin'])
{
	/* Can't create admin users */
    if ( isset($_POST['isadmin']) )
	{
    	unset($_POST['isadmin']);
	}

    /* Can only add features he/she has access to */
	$hesk_settings['features'] = array_intersect( explode(',', $_SESSION['heskprivileges']) , $hesk_settings['features']);

	/* Can user modify auto-assign setting? */
    if ($hesk_settings['autoassign'] && ( ! hesk_checkPermission('can_assign_self', 0) || ! hesk_checkPermission('can_assign_others', 0) ) )
    {
    	$hesk_settings['autoassign'] = 0;
    }
}

/* Use any set values, default otherwise */
foreach ($default_userdata as $k => $v)
{
	if ( ! isset($_SESSION['userdata'][$k]) )
    {
    	$_SESSION['userdata'][$k] = $v;
    }
}

$_SESSION['userdata'] = hesk_stripArray($_SESSION['userdata']);

/* What should we do? */
if ( $action = hesk_REQUEST('a') )
{
    // Check permission again - required manage users permission for all actions
    hesk_checkPermission('can_man_users');

	if ($action == 'reset_form')
	{
		$_SESSION['edit_userdata'] = TRUE;
		header('Location: ./manage_users.php');
	}
	elseif ($action == 'edit')       {edit_user();}
	elseif ( defined('HESK_DEMO') )  {hesk_process_messages($hesklang['ddemo'], 'manage_users.php', 'NOTICE');}
	elseif ($action == 'new')        {new_user();}
	elseif ($action == 'save')       {update_user();}
	elseif ($action == 'remove')     {remove();}
	elseif ($action == 'autoassign') {toggle_autoassign();}
    elseif ($action == 'resetmfa')   {reset_mfa();}
    elseif ($action == 'active')     {toggle_activation();}
    else 							 {hesk_error($hesklang['invalid_action']);}
}

else
{

/* If one came from the Edit page make sure we reset user values */
if (isset($_SESSION['save_userdata']))
{
	$_SESSION['userdata'] = $default_userdata;
    $_SESSION['use_sort_vars'] = true;
    unset($_SESSION['save_userdata']);
}
if (isset($_SESSION['edit_userdata']))
{
    $_SESSION['use_sort_vars'] = true;
	$_SESSION['userdata'] = $default_userdata;
    unset($_SESSION['edit_userdata']);
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
if (!hesk_SESSION(array('userdata', 'errors'))) {
    hesk_handle_messages();
}

// If POP3 fetching is active, no user should have the same email address
if ($hesk_settings['pop3'] && hesk_validateEmail($hesk_settings['pop3_user'], 'ERR', 0))
{
    $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `email` LIKE '".hesk_dbEscape($hesk_settings['pop3_user'])."' AND `active` = 1");

    if (hesk_dbNumRows($res) > 0)
    {
        while ($myuser = hesk_dbFetchAssoc($res))
        {
            if (compare_user_permissions($myuser['id'], $myuser['isadmin'], explode(',', $myuser['categories']) , explode(',', $myuser['heskprivileges'])))
            {
                hesk_show_notice(sprintf($hesklang['pop3_warning'], $myuser['name'], $hesk_settings['pop3_user']) . "<br /><br />" . $hesklang['fetch_warning'], $hesklang['warn']);
                break;
            }
        }
    }
}

// If IMAP fetching is active, no user should have the same email address
if ($hesk_settings['imap'] && hesk_validateEmail($hesk_settings['imap_user'], 'ERR', 0))
{
    $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `email` LIKE '".hesk_dbEscape($hesk_settings['imap_user'])."' AND `active` = 1");

    if (hesk_dbNumRows($res) > 0)
    {
        while ($myuser = hesk_dbFetchAssoc($res))
        {
            if (compare_user_permissions($myuser['id'], $myuser['isadmin'], explode(',', $myuser['categories']) , explode(',', $myuser['heskprivileges'])))
            {
                hesk_show_notice(sprintf($hesklang['imap_warning'], $myuser['name'], $hesk_settings['imap_user']) . "<br /><br />" . $hesklang['fetch_warning'], $hesklang['warn']);
                break;
            }
        }
    }
}

// We probably shouldn't have two or more users with the same email address; show a notice if so
$res = hesk_dbQuery('SELECT `email`, COUNT(*) AS `cnt` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'users` GROUP BY `email` HAVING `cnt` > 1');
if (hesk_dbNumRows($res) > 0)
{
    $emails = array();
    while ($row = hesk_dbFetchAssoc($res))
    {
        $emails[$row['email']] = $row['cnt'];
    }

    //hesk_show_notice($hesklang['uue'] . '<br><br>' . implode('<br>', array_keys($emails)));
    hesk_show_notice($hesklang['uue']);
}

    if (!isset($_SESSION['use_sort_vars']) && isset($_SESSION['sort_vars'])) {
        unset($_SESSION['sort_vars']);
    }
    $saved_search = hesk_SESSION_array('sort_vars');
    $sort_column = isset($saved_search['sort_column']) ? $saved_search['sort_column'] : hesk_REQUEST('sort_column');
    $sort_direction = isset($saved_search['sort_direction']) ? $saved_search['sort_direction'] : hesk_REQUEST('sort_direction');

    // Now set the variables in the session for later
    $_SESSION['sort_vars'] = [
        'sort_column' => $sort_column,
        'sort_direction' => $sort_direction
    ];
?>
<div class="main__content team">
    <section class="team__head">
        <h2>
            <?php echo $hesklang['team']; ?>
            <div class="tooltype right out-close">
                <svg class="icon icon-info">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                </svg>
                <div class="tooltype__content">
                    <div class="tooltype__wrapper">
                        <?php echo $hesklang['users_intro']; ?>
                    </div>
                </div>
            </div>
        </h2>
        <?php if ($can_man_users): ?>
        <button class="btn btn btn--blue-border" ripple="ripple" data-action="team-create"><?php echo $hesklang['new_team_member']; ?></button>
        <?php endif; ?>
    </section>
    <div class="table-wrap">
        <?php
        $query_sort_column = 'name';
        if ($sort_column !== null && in_array($sort_column, ['name', 'email', 'nickname'])) {
            $query_sort_column = $sort_column;
        }
        $query_sort_direction = $sort_direction === 'ASC' ? 'ASC' : 'DESC';
        $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` ORDER BY `{$query_sort_column}` {$query_sort_direction}");
        $all_users = [];
        $any_deactivated = false;
        while ($row = hesk_dbFetchAssoc($res)) {
            $all_users[] = $row;
            if (!$row['active']) {
                $any_deactivated = true;
            }
        }

        $cannot_manage = array();

        $tickets_per_user = array();
        $tickets_per_user_rs = hesk_dbQuery('SELECT COUNT(1) AS `cnt`, `owner`, CASE WHEN `status` = 3 THEN 0 ELSE 1 END AS `open` 
                    FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'tickets` 
                    GROUP BY `owner`, CASE WHEN `status` = 3 THEN 0 ELSE 1 END');
        while ($row = hesk_dbFetchAssoc($tickets_per_user_rs)) {
            if (!isset($tickets_per_user[$row['owner']])) {
                $tickets_per_user[$row['owner']] = array(
                        'open' => 0,
                        'closed' => 0,
                        'total' => 0
                );
            }

            $tickets_per_user[$row['owner']]['total'] += $row['cnt'];
            if ($row['open']) {
                $tickets_per_user[$row['owner']]['open'] += $row['cnt'];
            } else {
                $tickets_per_user[$row['owner']]['closed'] += $row['cnt'];
            }
        }
        ?>
        <div class="table">
            <table id="default-table" class="table sindu-table">
                <thead>
                <tr>
                    <th class="sindu-handle <?php echo $sort_column === 'name' ? hesk_mb_strtolower($sort_direction) : '' ?>">
                        <a href="<?php echo build_sort_url($sort_column, 'name', $sort_direction); ?>" aria-label="<?php echo ($hesklang['sort_by'] . ' ' .  $hesklang['name']); ?>">
                            <div class="sort">
                                <span><?php echo $hesklang['name']; ?></span>
                                <i class="handle"></i>
                            </div>
                        </a>
                    </th>
                    <th class="sindu-handle <?php echo $sort_column === 'email' ? hesk_mb_strtolower($sort_direction) : '' ?>">
                        <a href="<?php echo build_sort_url($sort_column, 'email', $sort_direction); ?>" aria-label="<?php echo ($hesklang['sort_by'] . ' ' .  $hesklang['email']); ?>">
                            <div class="sort">
                                <span><?php echo $hesklang['email']; ?></span>
                                <i class="handle"></i>
                            </div>
                        </a>
                    </th>
                    <?php if ($hesk_settings['staff_nicknames']): ?>
                    <th class="sindu-handle <?php echo $sort_column === 'nickname' ? hesk_mb_strtolower($sort_direction) : '' ?>">
                        <a href="<?php echo build_sort_url($sort_column, 'nickname', $sort_direction); ?>" aria-label="<?php echo ($hesklang['sort_by'] . ' ' .  $hesklang['nickname']); ?>">
                            <div class="sort">
                                <span><?php echo $hesklang['nickname']; ?></span>
                                <i class="handle"></i>
                            </div>
                        </a>
                    </th>
                    <?php endif; ?>
                    <th><?php echo $hesklang['username']; ?></th>
                    <th><?php echo $hesklang['role']; ?></th>
                    <?php
                    /* Is user rating enabled? */
                    if ($hesk_settings['rating']) {
                        ?>
                        <th><?php echo $hesklang['rating']; ?></th>
                        <?php
                    }

                    /* Is autoassign enabled? */
                    if ($hesk_settings['autoassign']) {
                        ?>
                        <th><?php echo $hesklang['aass']; ?></th>
                        <?php
                    }
                    ?>
                    <th><?php echo $hesklang['mfa_short']; ?></th>
                    <th aria-label="Actions"></th>
                </tr>
                </thead>
                <tbody>
                <?php
                foreach ($all_users as $myuser) {
                    if (!$myuser['active']) {
                        continue;
                    }

                    $can_manage_this_user = !$can_man_users ? false : compare_user_permissions($myuser['id'], $myuser['isadmin'], explode(',', $myuser['categories']) , explode(',', $myuser['heskprivileges']));
                    $can_view_this_user = ($can_manage_this_user || $can_view_users) ? true : false;

                    if (!$can_view_this_user) {
                        $cannot_manage[$myuser['id']] = array('name' => $myuser['name'], 'user' => $myuser['user'], 'email' => $myuser['email'], 'nickname' => $myuser['nickname']);
                        continue;
                    }

                    $table_row = '';
                    if (isset($_SESSION['seluser']) && $myuser['id'] == $_SESSION['seluser']) {
                        $table_row = 'class="ticket-new"';
                        unset($_SESSION['seluser']);
                    }

                    /* User online? */
                    if ($hesk_settings['online']) {
                        if (isset($hesk_settings['users_online'][$myuser['id']])) {
                            $myuser['name'] = '
                                <svg class="icon icon-assign is-online">
                                  <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-assign"></use>
                                </svg>' .
                                $myuser['name'];
                        }
                        else
                        {
                            $myuser['name'] = '
                                <svg class="icon icon-assign-no is-offline">
                                  <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-assign-no"></use>
                                </svg>' .
                                $myuser['name'];
                        }
                    }

                    /* To edit yourself go to "Profile" page, not here. */
                    if ($myuser['id'] == $_SESSION['id']) {
                        $edit_code = '
                            <a href="profile.php" class="edit tooltip" title="'.$hesklang['edit'].'">
                                <svg class="icon icon-edit-ticket">
                                    <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-edit-ticket"></use>
                                </svg>
                            </a>';
                    } elseif ($can_manage_this_user) {
                        $edit_code = '
                            <a href="manage_users.php?a=edit&amp;id='.$myuser['id'].'" class="edit tooltip" title="'.$hesklang['edit'].'">
                                <svg class="icon icon-edit-ticket">
                                    <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-edit-ticket"></use>
                                </svg>
                            </a>';
                    } else {
                        $edit_code = '';
                    }

                    if ($myuser['isadmin']) {
                        $myuser['isadmin'] = $hesklang['administrator'];
                    } else {
                        $myuser['isadmin'] = $hesklang['staff'];
                    }

                    $deactivate_code = '';
                    // Can only deactivate user if not default administrator, can manage the user, and it's not your own account
                    if ($myuser['id'] != 1 && $can_manage_this_user && $myuser['id'] != $_SESSION['id']) {
                        $modal_body = $hesklang['sure_deactivate_user'];
                        if (isset($tickets_per_user[$myuser['id']]) && $tickets_per_user[$myuser['id']]['total'] > 0) {
                            $total_tickets = $tickets_per_user[$myuser['id']]['total'];
                            $open_tickets = $tickets_per_user[$myuser['id']]['open'];
                            $modal_body .= '<br><br>'.
                                    '<div role="alert" class="notification orange">
                                    <b>'.$hesklang['sm_notice'].'</b><br> '.sprintf($hesklang['deactivating_user_with_tickets'], $total_tickets, $open_tickets).'
                                </div>';
                        }
                        $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deactivation'],
                                $modal_body,
                                'manage_users.php?a=active&amp;state=0&amp;id='.$myuser['id'].'&amp;token='.hesk_token_echo(0),
                                $hesklang['deactivate_user']);
                        $deactivate_code = '
                            <a href="javascript:" data-modal="[data-modal-id=\''.$modal_id.'\']" class="edit tooltip" title="'.$hesklang['deactivate_user'].'">
                                <svg class="icon icon-assign-no">
                                    <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-assign-no"></use>
                                </svg>
                            </a>';
                    }

                    /* Deleting user with ID 1 (default administrator) is not allowed */
                    if ($myuser['id'] == 1) {
                        $remove_code = '';
                    } elseif ($myuser['id'] == $_SESSION['id']) {
                        // You cannot delete your own account
                        $remove_code = '';
                    } elseif ($can_manage_this_user) {
                        $modal_body = $hesklang['sure_remove_user'];
                        if (isset($tickets_per_user[$myuser['id']]) && $tickets_per_user[$myuser['id']]['total'] > 0) {
                            $total_tickets = $tickets_per_user[$myuser['id']]['total'];
                            $open_tickets = $tickets_per_user[$myuser['id']]['open'];
                            $modal_body .= '<br><br>'.
                                '<div role="alert" class="notification orange">
                                    <b>'.$hesklang['sm_notice'].'</b><br> '.sprintf($hesklang['deleting_user_with_tickets'], $total_tickets, $open_tickets).'
                                </div>';
                        }

                        $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                            $modal_body,
                            'manage_users.php?a=remove&amp;id='.$myuser['id'].'&amp;token='.hesk_token_echo(0));
                        $remove_code = '
                        <a href="javascript:" data-modal="[data-modal-id=\''.$modal_id.'\']"
                            title="'.$hesklang['remove'].'"
                            class="delete tooltip">
                            <svg class="icon icon-delete">
                                <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-delete"></use>
                            </svg>
                        </a>';
                    } else {
                        $remove_code = '';
                    }

                    /* Is auto assign enabled? */
                    if ($hesk_settings['autoassign']) {
                        if ($myuser['autoassign']) {
                            $autoassign_code = '
                                <label class="switch-checkbox" aria-label="Auto-assign">
                                    <a class="tooltip" data-ztt_vertical_offset="-5" id="autoassign-'.$myuser['id'].'" href="manage_users.php?a=autoassign&amp;s=0&amp;id='.$myuser['id'].'&amp;token='.hesk_token_echo(0).'" title="'.$hesklang['aaon'].'">
                                        <input type="checkbox" checked>
                                        <div class="switch-checkbox__bullet">
                                            <i>
                                                <svg class="icon icon-close">
                                                    <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-close"></use>
                                                </svg>
                                                <svg class="icon icon-tick">
                                                    <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-tick"></use>
                                                </svg>
                                            </i>
                                        </div>
                                    </a>
                                </label>
                                ';
                        } elseif ($can_manage_this_user) {
                            $autoassign_code = '
                                <label class="switch-checkbox" aria-label="Auto-assign">
                                    <a class="tooltip" data-ztt_vertical_offset="-5" id="autoassign-'.$myuser['id'].'"  href="manage_users.php?a=autoassign&amp;s=1&amp;id='.$myuser['id'].'&amp;token='.hesk_token_echo(0).'" title="'.$hesklang['aaoff'].'">
                                        <input type="checkbox">
                                        <div class="switch-checkbox__bullet">
                                            <i>
                                                <svg class="icon icon-close">
                                                    <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-close"></use>
                                                </svg>
                                                <svg class="icon icon-tick">
                                                    <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-tick"></use>
                                                </svg>
                                            </i>
                                        </div>
                                    </a>
                                </label>';
                        } else {
                            $autoassign_code = '';
                        }
                    } else {
                        $autoassign_code = '';
                    }

                    echo '<tr '.$table_row.'>';
                    echo '<td>'.$myuser['name'].'</td>';
                    echo '<td><a href="mailto:'.$myuser['email'].'">'.$myuser['email'].'</a></td>';

                    if ($hesk_settings['staff_nicknames']) {
                        echo '<td>'.$myuser['nickname'].'</td>';
                    }

                    echo '<td>'.$myuser['user'].'</td>';
                    echo '<td>'.$myuser['isadmin'].'</td>';

                    if ($hesk_settings['rating']) {
                        $alt = $myuser['rating'] ? sprintf($hesklang['rated'], sprintf("%01.1f", $myuser['rating']), ($myuser['ratingneg']+$myuser['ratingpos'])) : $hesklang['not_rated'];
                        echo '<td style="text-align:center; white-space:nowrap;">
                            '.hesk3_get_rating($myuser['rating']).'
                        </td>';
                    }

                    if ($hesk_settings['autoassign']) {
                        echo '<td>' . $autoassign_code . '</td>';
                    }

                    $mfa_enrollment = intval($myuser['mfa_enrollment']);
                    $mfa_status = $hesklang['mfa_method_none'];
                    $mfa_reset = '';
                    $modal_id = hesk_generate_old_delete_modal($hesklang['mfa_reset_to_default'],
                        $hesklang['mfa_reset_confirm'],
                        'manage_users.php?a=resetmfa&amp;id='.$myuser['id'].'&amp;token='.hesk_token_echo(0),
                        $hesklang['mfa_reset_yes']);

                    if ($mfa_enrollment === 1) {
                        $mfa_status = $hesklang['mfa_method_email'];

                        if (!$hesk_settings['require_mfa'] && $can_manage_this_user) {

                            $mfa_reset = '<div class="tooltype right out-close">
                                <a href="javascript:" data-modal="[data-modal-id=\''.$modal_id.'\']"
                                    title="'.$hesklang['mfa_reset_to_default'].'"
                                    class="delete tooltip">
                                    <svg class="icon icon-refresh">
                                        <use xlink:href="'. HESK_PATH . 'img/sprite.svg#icon-refresh"></use>
                                    </svg>
                                </a>
                            </div>';
                        }
                    } elseif ($mfa_enrollment === 2) {
                        $mfa_status = $hesklang['mfa_method_auth_app_short'];

                        if ($can_manage_this_user) {
                            $mfa_reset = '<div class="tooltype right out-close">
                                    <a href="javascript:" data-modal="[data-modal-id=\''.$modal_id.'\']"
                                        title="'.$hesklang['mfa_reset_to_default'].'"
                                        class="delete tooltip">
                                        <svg class="icon icon-refresh">
                                            <use xlink:href="'. HESK_PATH . 'img/sprite.svg#icon-refresh"></use>
                                        </svg>
                                    </a>
                                </div>';
                        }
                    }

                    echo <<<EOC
<td>$mfa_status $mfa_reset</td>
<td class="nowrap buttons"><p>$edit_code $deactivate_code $remove_code</p></td>
</tr>

EOC;
                } // End while
                ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php if ($any_deactivated): ?>
    <br>
    <section class="team__head">
        <h3 class="cus_label">
            <?php echo $hesklang['deactivated_users']; ?>
        </h3>
    </section>
    <div class="table-wrap">
        <div class="table">
            <table id="deactivated-users" class="table sindu-table">
                <thead>
                <tr>
                    <th class="sindu-handle <?php echo $sort_column === 'name' ? hesk_mb_strtolower($sort_direction) : '' ?>" aria-label="<?php echo ($hesklang['sort_by'] . ' ' .  $hesklang['name']); ?>">
                        <div class="sort">
                            <span><?php echo $hesklang['name']; ?></span>
                            <i class="handle"></i>
                        </div>
                    </th>
                    <th class="sindu-handle <?php echo $sort_column === 'email' ? hesk_mb_strtolower($sort_direction) : '' ?>">
                        <a href="<?php echo build_sort_url($sort_column, 'email', $sort_direction); ?>" aria-label="<?php echo ($hesklang['sort_by'] . ' ' .  $hesklang['email']); ?>">
                            <div class="sort">
                                <span><?php echo $hesklang['email']; ?></span>
                                <i class="handle"></i>
                            </div>
                        </a>
                    </th>
                    <?php if ($hesk_settings['staff_nicknames']): ?>
                        <th class="sindu-handle <?php echo $sort_column === 'nickname' ? hesk_mb_strtolower($sort_direction) : '' ?>">
                            <a href="<?php echo build_sort_url($sort_column, 'nickname', $sort_direction); ?>" aria-label="<?php echo ($hesklang['sort_by'] . ' ' .  $hesklang['nickname']); ?>">
                                <div class="sort">
                                    <span><?php echo $hesklang['nickname']; ?></span>
                                    <i class="handle"></i>
                                </div>
                            </a>
                        </th>
                    <?php endif; ?>
                    <th><?php echo $hesklang['username']; ?></th>
                    <th><?php echo $hesklang['role']; ?></th>
                    <?php
                    /* Is user rating enabled? */
                    if ($hesk_settings['rating']) {
                        ?>
                        <th><?php echo $hesklang['rating']; ?></th>
                        <?php
                    }
                    /* Is autoassign enabled? */
                    if ($hesk_settings['autoassign']) {
                        ?>
                        <th><?php echo $hesklang['aass']; ?></th>
                        <?php
                    }
                    ?>
                    <th><?php echo $hesklang['mfa_short']; ?></th>
                    <th aria-label="Actions"></th>
                </tr>
                </thead>
                <tbody>
                <?php
                foreach ($all_users as $myuser) {
                    if ($myuser['active']) {
                        continue;
                    }

                    $can_manage_this_user = !$can_man_users ? false : compare_user_permissions($myuser['id'], $myuser['isadmin'], explode(',', $myuser['categories']) , explode(',', $myuser['heskprivileges']));
                    $can_view_this_user = ($can_manage_this_user || $can_view_users) ? true : false;

                    if (!$can_view_this_user) {
                        $cannot_manage[$myuser['id']] = array('name' => $myuser['name'], 'user' => $myuser['user'], 'email' => $myuser['email'], 'nickname' => $myuser['nickname']);
                        continue;
                    }

                    $table_row = '';
                    if (isset($_SESSION['seluser']) && $myuser['id'] == $_SESSION['seluser']) {
                        $table_row = 'class="ticket-new"';
                        unset($_SESSION['seluser']);
                    }

                    $reactivate_code = '';
                    /* To edit yourself go to "Profile" page, not here. */
                    if ($can_manage_this_user) {
                        $reactivate_code = '
                            <a href="manage_users.php?a=active&amp;state=1&amp;id='.$myuser['id'].'&amp;token='.hesk_token_echo(0).'" class="edit tooltip" title="'.$hesklang['activate_user'].'">
                                <svg class="icon icon-assign-plus">
                                    <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-assign-plus"></use>
                                </svg>
                            </a>';
                    }

                    if ($myuser['isadmin']) {
                        $myuser['isadmin'] = $hesklang['administrator'];
                    } else {
                        $myuser['isadmin'] = $hesklang['staff'];
                    }

                    $edit_code = '';
                    if ($can_manage_this_user) {
                        $edit_code = '
                            <a href="manage_users.php?a=edit&amp;id='.$myuser['id'].'" class="edit tooltip" title="'.$hesklang['edit'].'">
                                <svg class="icon icon-edit-ticket">
                                    <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-edit-ticket"></use>
                                </svg>
                            </a>';
                    }

                    /* Deleting user with ID 1 (default administrator) is not allowed */
                    if ($myuser['id'] == 1) {
                        $remove_code = '';
                    } elseif ($can_manage_this_user) {
                        $modal_body = $hesklang['sure_remove_user'];
                        if (isset($tickets_per_user[$myuser['id']]) && $tickets_per_user[$myuser['id']]['total'] > 0) {
                            $total_tickets = $tickets_per_user[$myuser['id']]['total'];
                            $open_tickets = $tickets_per_user[$myuser['id']]['open'];
                            $modal_body .= '<br><br>'.
                                    '<div role="alert" class="notification orange">
                                    <b>'.$hesklang['sm_notice'].'</b><br> '.sprintf($hesklang['deleting_user_with_tickets'], $total_tickets, $open_tickets).'
                                </div>';
                        }

                        $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                                $modal_body,
                                'manage_users.php?a=remove&amp;id='.$myuser['id'].'&amp;token='.hesk_token_echo(0));
                        $remove_code = '
                        <a href="javascript:" data-modal="[data-modal-id=\''.$modal_id.'\']"
                            title="'.$hesklang['remove'].'"
                            class="delete tooltip">
                            <svg class="icon icon-delete">
                                <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-delete"></use>
                            </svg>
                        </a>';
                    } else {
                        $remove_code = '';
                    }

                    /* Is auto assign enabled? */
                    if ($hesk_settings['autoassign']) {
                        $autoassign_code = $myuser['autoassign'] ? $hesklang['yes'] : $hesklang['no'];
                    } else {
                        $autoassign_code = '';
                    }

                    echo '<tr '.$table_row.'>';
                    echo '<td>'.$myuser['name'].'</td>';
                    echo '<td><a href="mailto:'.$myuser['email'].'">'.$myuser['email'].'</a></td>';

                    if ($hesk_settings['staff_nicknames']) {
                        echo '<td>'.$myuser['nickname'].'</td>';

                    }

                    echo '<td>'.$myuser['user'].'</td>';
                    echo '<td>'.$myuser['isadmin'].'</td>';

                    if ($hesk_settings['rating']) {
                        $alt = $myuser['rating'] ? sprintf($hesklang['rated'], sprintf("%01.1f", $myuser['rating']), ($myuser['ratingneg']+$myuser['ratingpos'])) : $hesklang['not_rated'];
                        echo '<td style="text-align:center; white-space:nowrap;">
                            '.hesk3_get_rating($myuser['rating']).'
                        </td>';
                    }

                    if ($hesk_settings['autoassign']) {
                        echo '<td>' . $autoassign_code . '</td>';
                    }

                    $mfa_enrollment = intval($myuser['mfa_enrollment']);
                    $mfa_status = $hesklang['mfa_method_none'];

                    if ($mfa_enrollment === 1) {
                        $mfa_status = $hesklang['mfa_method_email'];
                    } elseif ($mfa_enrollment === 2) {
                        $mfa_status = $hesklang['mfa_method_auth_app_short'];
                    }

                    echo <<<EOC
<td>$mfa_status</td>
<td class="nowrap buttons"><p>$edit_code $reactivate_code $remove_code</p></td>
</tr>

EOC;
                } // End while
                ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>
</div>
<?php if ($can_man_users): ?>
<div class="right-bar team-create" <?php echo hesk_SESSION(array('userdata','errors')) ? 'style="display: block"' : ''; ?>>
    <div class="right-bar__body form" data-step="1">
        <h3>
            <a href="manage_users.php?a=reset_form">
                <svg class="icon icon-back">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                </svg>
                <span><?php echo $hesklang['add_user']; ?></span>
            </a>
        </h3>
        <?php
        if (hesk_SESSION(array('userdata', 'errors'))) {
            hesk_handle_messages();
        }
        ?>
        <form name="form1" method="post" action="manage_users.php" class="form <?php echo hesk_SESSION(array('userdata','errors')) ? 'invalid' : ''; ?>" aria-label="<?php echo $hesklang['manage_users']; ?>">
            <?php hesk_profile_tab('userdata', false); ?>

            <!-- Submit -->
            <div class="right-bar__footer">
                <input type="hidden" name="a" value="new">
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                <button type="button" class="btn btn-border" ripple="ripple" data-action="back"><?php echo $hesklang['wizard_back']; ?></button>
                <button type="button" class="btn btn-full next" data-action="next" ripple="ripple"><?php echo $hesklang['wizard_next']; ?></button>
                <button type="submit" class="btn btn-full save" data-action="save" ripple="ripple"><?php echo $hesklang['create_user']; ?></button>
            </div>
        </form>
    </div>
</div>
<script>
function pwToggle(pwId, eyeClosedId, eyeOpenId, pw, stars) {
    var pwEl = document.getElementById(pwId);
    var eyeClosed = document.getElementById(eyeClosedId);
    var eyeOpen = document.getElementById(eyeOpenId);

    var visible = pwEl.textContent === pw;

    pwEl.textContent = visible ? stars : pw;
    eyeClosed.style.display = visible ? '' : 'none';
    eyeOpen.style.display   = visible ? 'none' : '';
}
</script>
<?php
endif;
unset($_SESSION['use_sort_vars']);

require_once(HESK_PATH . 'inc/footer.inc.php');
exit();

} // End else


/*** START FUNCTIONS ***/


function compare_user_permissions($compare_id, $compare_isadmin = null, $compare_categories = null, $compare_features = null)
{
	global $hesk_settings;

    /* Comparing myself? */
    if ($compare_id == $_SESSION['id'])
    {
    	return true;
    }

    /* Admins have full access, no need to compare */
	if ($_SESSION['isadmin'])
    {
    	return true;
    }
    elseif ($compare_isadmin)
    {
    	return false;
    }

    // Do we need to get data from the database?
    if ($compare_categories === null)
    {
        $res = hesk_dbQuery("SELECT `isadmin`, `categories`, `heskprivileges` AS `features` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id`='".intval($compare_id)."' LIMIT 1");
        $row = hesk_dbFetchAssoc($res);

        // If this user is an admin and we're not - no need to check further
        if ($row['isadmin'])
        {
            return false;
        }

        $compare_features = explode(',', $row['features']);
        $compare_categories = explode(',', $row['categories']);
    }

    // Also fetch any features/categories included via permission groups
    $permission_groups_rs = hesk_dbQuery("SELECT `category`.`category_id` AS `category_feature_value`, 'CATEGORY' AS `category_feature_type` 
        FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_categories` AS `category`
        WHERE `category`.`group_id` IN (SELECT `group_id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_members` WHERE `user_id` = ".intval($compare_id).")
        UNION ALL
        SELECT `feature`.`feature` AS `category_feature_value`, 'FEATURE' AS `category_feature_type` 
        FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_features` AS `feature`
        WHERE `feature`.`group_id` IN (SELECT `group_id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_members` WHERE `user_id` = ".intval($compare_id).")");
    while ($row = hesk_dbFetchAssoc($permission_groups_rs)) {
        if ($row['category_feature_type'] === 'CATEGORY' && !in_array($row['category_feature_value'], $compare_categories)) {
            $compare_categories[] = $row['category_feature_value'];
        } elseif (!in_array($row['category_feature_value'], $compare_features)) {
            $compare_features[] = $row['category_feature_value'];
        }
    }

	/* Compare categories */
    foreach ($compare_categories as $catid)
    {
    	if ( ! array_key_exists($catid, $hesk_settings['categories']) )
        {
        	return false;
        }
    }

	/* Compare features */
    foreach ($compare_features as $feature)
    {
    	if ( ! in_array($feature, $hesk_settings['features']) )
        {
        	return false;
        }
    }

    return true;

} // END compare_user_permissions()


function edit_user()
{
	global $hesk_settings, $hesklang, $default_userdata;

	$id = intval( hesk_GET('id') ) or hesk_error("$hesklang[int_error]: $hesklang[no_valid_id]");

	/* To edit self fore using "Profile" page */
    if ($id == $_SESSION['id'])
    {
    	hesk_process_messages($hesklang['eyou'],'profile.php','NOTICE');
    }

    $_SESSION['edit_userdata'] = TRUE;

    if ( ! isset($_SESSION['save_userdata']))
    {
		$res = hesk_dbQuery("SELECT *,`heskprivileges` AS `features` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id`='".intval($id)."' LIMIT 1");
    	$_SESSION['userdata'] = hesk_dbFetchAssoc($res);

        /* Store original username for display until changes are saved successfully */
        $_SESSION['original_user'] = $_SESSION['userdata']['user'];

        /* A few variables need special attention... */
        if ($_SESSION['userdata']['isadmin'])
        {
	        $_SESSION['userdata']['features'] = $default_userdata['features'];
	        $_SESSION['userdata']['categories'] = $default_userdata['categories'];
        }
        else
        {
	        $_SESSION['userdata']['features'] = explode(',',$_SESSION['userdata']['features']);
	        $_SESSION['userdata']['categories'] = explode(',',$_SESSION['userdata']['categories']);
        }
        $_SESSION['userdata']['cleanpass'] = '';
        $_SESSION['userdata']['permission_groups'] = [];
        $_SESSION['userdata']['pg_categories'] = [];
        $_SESSION['userdata']['pg_features'] = [];

        // Add any permission groups they may have
        $permission_group_categories_rs = hesk_dbQuery("SELECT `group_id`,`category_id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_categories` WHERE `group_id` IN (
            SELECT `group_id`
            FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_members`
            WHERE `user_id` = ".intval($id)."
        )");
        while ($row = hesk_dbFetchAssoc($permission_group_categories_rs)) {
            if (!in_array($row['group_id'], $_SESSION['userdata']['permission_groups'])) {
                $_SESSION['userdata']['permission_groups'][] = $row['group_id'];
            }
            $_SESSION['userdata']['pg_categories'][] = intval($row['category_id']);
        }
        $permission_group_features_rs = hesk_dbQuery("SELECT `group_id`,`feature` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_features` WHERE `group_id` IN (
            SELECT `group_id`
            FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_members`
            WHERE `user_id` = ".intval($id)."
        )");
        while ($row = hesk_dbFetchAssoc($permission_group_features_rs)) {
            if (!in_array($row['group_id'], $_SESSION['userdata']['permission_groups'])) {
                $_SESSION['userdata']['permission_groups'][] = $row['group_id'];
            }
            $_SESSION['userdata']['pg_features'][] = $row['feature'];
        }
    }

	/* Make sure we have permission to edit this user */
	if ( ! compare_user_permissions($id, $_SESSION['userdata']['isadmin'], $_SESSION['userdata']['categories'], $_SESSION['userdata']['features']) )
	{
		hesk_process_messages($hesklang['npea'],'manage_users.php');
	}

    /* Print header */
	require_once(HESK_PATH . 'inc/header.inc.php');

	/* Print main manage users page */
	require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');
	?>
    <div class="right-bar team-create" style="display: block">
        <div class="right-bar__body form" data-step="1">
            <h3>
                <a href="manage_users.php">
                    <svg class="icon icon-back">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                    </svg>
                    <span><?php echo $hesklang['editing_user'].' '.$_SESSION['original_user']; ?></span>
                </a>
            </h3>
            <?php
            if (hesk_SESSION(array('userdata', 'errors'))) {
                hesk_handle_messages();
            }
            ?>
            <form name="form1" method="post" action="manage_users.php" class="form <?php echo hesk_SESSION(array('userdata','errors')) ? 'invalid' : ''; ?>" aria-label="<?php echo $hesklang['manage_users']; ?>">
                <?php hesk_profile_tab('userdata', false); ?>

                <!-- Submit -->
                <div class="right-bar__footer">
                    <input type="hidden" name="a" value="save">
                    <input type="hidden" name="userid" value="<?php echo $id; ?>" />
                    <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
                    <button type="button" class="btn btn-border" ripple="ripple" data-action="back"><?php echo $hesklang['wizard_back']; ?></button>
                    <button type="button" class="btn btn-full next" data-action="next" ripple="ripple"><?php echo $hesklang['wizard_next']; ?></button>
                    <button type="submit" class="btn btn-full save" data-action="save" ripple="ripple"><?php echo $hesklang['save_changes']; ?></button>
                </div>
            </form>
        </div>
    </div>

	<?php
	require_once(HESK_PATH . 'inc/footer.inc.php');
	exit();
} // End edit_user()


function new_user()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check('POST');

	$myuser = hesk_validateUserInfo();

    /* Categories and Features will be stored as a string */
    $myuser['categories'] = implode(',',$myuser['categories']);
    $myuser['features'] = implode(',',$myuser['features']);

    /* Check for duplicate usernames */
	$result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `user` = '".hesk_dbEscape($myuser['user'])."' LIMIT 1");
	if (hesk_dbNumRows($result) != 0)
	{
        $_SESSION['userdata']['errors'] = array('user');
        $hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesklang['duplicate_user'].'</ul>';
        hesk_process_messages($hesk_error_buffer,'manage_users.php');
	}

    /* Admins will have access to all features and categories */
    if ($myuser['isadmin'])
    {
		$myuser['categories'] = '';
		$myuser['features'] = '';
    }

    if ($hesk_settings['staff_nicknames']) {
        $nickname_where = '`nickname`,';
        $nickname_sql = "'".hesk_dbEscape($myuser['nickname'])."',";
    } else {
        $nickname_where = '';
        $nickname_sql = '';
    }

	hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."users` (
	`user`,
	`pass`,
	`isadmin`,
	`active`,
	`name`,
	`email`,
    {$nickname_where}
	`signature`,
	`categories`,
	`autoassign`,
	`heskprivileges`,
	`afterreply`,
	`autostart`,
	`autoreload`,
	`notify_customer_new`,
	`notify_customer_reply`,
	`show_suggested`,
	`notify_new_unassigned`,
	`notify_overdue_unassigned`,
	`notify_new_my`,
	`notify_overdue_my`,
	`notify_reply_unassigned`,
	`notify_reply_my`,
	`notify_assigned`,
	`notify_pm`,
	`notify_note`,
	`notify_customer_approval`,
	`notify_collaborator_added`,
	`notify_collaborator_customer_reply`,
	`notify_collaborator_staff_reply`,
	`notify_collaborator_note`,
	`notify_collaborator_resolved`,
	`notify_collaborator_overdue`
	) VALUES (
	'".hesk_dbEscape($myuser['user'])."',
	'".hesk_dbEscape($myuser['pass'])."',
	'".intval($myuser['isadmin'])."',
	1,
	'".hesk_dbEscape($myuser['name'])."',
	'".hesk_dbEscape($myuser['email'])."',
    {$nickname_sql}
	'".hesk_dbEscape($myuser['signature'])."',
	'".hesk_dbEscape($myuser['categories'])."',
	'".intval($myuser['autoassign'])."',
	'".hesk_dbEscape($myuser['features'])."',
	'".($myuser['afterreply'])."' ,
	'".($myuser['autostart'])."' ,
	'".($myuser['autoreload'])."' ,
	'".($myuser['notify_customer_new'])."' ,
	'".($myuser['notify_customer_reply'])."' ,
	'".($myuser['show_suggested'])."' ,
	'".($myuser['notify_new_unassigned'])."' ,
	'".($myuser['notify_overdue_unassigned'])."',
	'".($myuser['notify_new_my'])."' ,
	'".($myuser['notify_overdue_my'])."' ,
	'".($myuser['notify_reply_unassigned'])."' ,
	'".($myuser['notify_reply_my'])."' ,
	'".($myuser['notify_assigned'])."' ,
	'".($myuser['notify_pm'])."',
	'".($myuser['notify_note'])."',
	'".($myuser['notify_customer_approval'])."',
	'".($myuser['notify_collaborator_added'])."',
	'".($myuser['notify_collaborator_customer_reply'])."',
	'".($myuser['notify_collaborator_staff_reply'])."',
	'".($myuser['notify_collaborator_note'])."',
	'".($myuser['notify_collaborator_resolved'])."',
	'".($myuser['notify_collaborator_overdue'])."'
	)" );

    $_SESSION['seluser'] = hesk_dbInsertID();

    if (count($myuser['permission_groups']) > 0) {
        $permission_group_inserts = [];
        foreach ($myuser['permission_groups'] as $permission_group) {
            $permission_group_inserts[] = 'SELECT '.intval($permission_group).', '.intval($_SESSION['seluser']);
        }
        hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_members` (`group_id`, `user_id`) ".implode(' UNION ', $permission_group_inserts));
    }

    unset($_SESSION['userdata']);

    $stars = str_repeat('*', strlen($myuser['cleanpass']));

    $passwordHtml = '
    <span id="pw_1" style="font-weight:bold">'.$stars.'</span>
    <span onclick="pwToggle(\'pw_1\', \'eyeClosed_1\', \'eyeOpen_1\', \''.$myuser['cleanpass'].'\', \''.$stars.'\')" style="cursor:pointer;vertical-align:middle">
        <svg class="icon icon-eye-close" id="eyeClosed_1">
            <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-eye-close"></use>
        </svg>
        <svg class="icon icon-eye-open" id="eyeOpen_1" style="display:none">
            <use xlink:href="'.HESK_PATH.'img/sprite.svg#icon-eye-open"></use>
        </svg>
    </span>
    ';

    hesk_process_messages(sprintf($hesklang['user_added_success'],$myuser['user'],$passwordHtml),'./manage_users.php','SUCCESS');
} // End new_user()


function update_user()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check('POST');

    $_SESSION['save_userdata'] = TRUE;

	$tmp = intval( hesk_POST('userid') ) or hesk_error("$hesklang[int_error]: $hesklang[no_valid_id]");

	/* To edit self fore using "Profile" page */
    if ($tmp == $_SESSION['id'])
    {
    	hesk_process_messages($hesklang['eyou'],'profile.php','NOTICE');
    }

    $_SERVER['PHP_SELF'] = './manage_users.php?a=edit&id='.$tmp;
	$myuser = hesk_validateUserInfo(0,$_SERVER['PHP_SELF']);
    $myuser['id'] = $tmp;

    // Make sure we have permission to edit this user
    if ( ! compare_user_permissions($myuser['id']))
    {
        hesk_process_messages($hesklang['npea'],'manage_users.php');
    }

    $olduser_rs = hesk_dbQuery("SELECT `user`, `email` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id` = ".intval($myuser['id'])." LIMIT 1");
    $olduser = hesk_dbFetchAssoc($olduser_rs);

    /* Check for duplicate usernames */
	$res = hesk_dbQuery("SELECT `id`,`isadmin`,`categories`,`heskprivileges` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `user` = '".hesk_dbEscape($myuser['user'])."' LIMIT 1");
	if (hesk_dbNumRows($res) == 1)
	{
    	$tmp = hesk_dbFetchAssoc($res);

        /* Duplicate? */
        if ($tmp['id'] != $myuser['id'])
        {
            $_SESSION['userdata']['errors'] = array('user');
            $hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesklang['duplicate_user'].'</ul>';
            hesk_process_messages($hesk_error_buffer,$_SERVER['PHP_SELF']);
        }

		/* Do we have permission to edit this user? */
		if ( ! compare_user_permissions($tmp['id'], $tmp['isadmin'], explode(',', $tmp['categories']) , explode(',', $tmp['heskprivileges'])) )
		{
			hesk_process_messages($hesklang['npea'],'manage_users.php');
		}
	}

    /* Admins will have access to all features and categories */
    if ($myuser['isadmin'])
    {
		$myuser['categories'] = '';
		$myuser['features'] = '';
    }
	/* Not admin */
	else
    {
		/* Categories and Features will be stored as a string */
	    $myuser['categories'] = implode(',',$myuser['categories']);
	    $myuser['features'] = implode(',',$myuser['features']);

        // Remove and insert permission groups
        hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_members` WHERE `user_id` = ".intval($myuser['id']));

        // Remove the user as collaborator from cateogries with no permission
        if (strlen($myuser['categories'])) {
            hesk_dbQuery("DELETE `c` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_collaborator` AS `c` JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` AS `t` ON `c`.`ticket_id` = `t`.`id` WHERE `c`.`user_id`='".intval($myuser['id'])."' AND `category` NOT IN (".$myuser['categories'].")");
        }

        if (count($myuser['permission_groups']) > 0) {
            $permission_group_inserts = [];
            foreach ($myuser['permission_groups'] as $permission_group) {
                $permission_group_inserts[] = 'SELECT '.intval($permission_group).', '.intval($myuser['id']);
            }
            hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_members` (`group_id`, `user_id`) ".implode(' UNION ', $permission_group_inserts));
        }


        $individual_category_sql = '';
        $permission_group_category_sql = '';
        if ($myuser['categories'] !== '') {
            $individual_category_sql = " AND `category` NOT IN (".$myuser['categories'].") ";
        }
        if (count($myuser['permission_groups']) > 0) {
            $permission_group_category_sql = " AND `category` NOT IN (
                SELECT `category_id`
                FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_categories`
                WHERE `group_id` IN (".implode(',', $myuser['permission_groups']).")
            )";
        }
    	/* Unassign tickets from categories that the user had access before but doesn't anymore */
        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets`
            SET `owner`=0
            WHERE `owner`='".intval($myuser['id'])."'
            {$individual_category_sql}
            {$permission_group_category_sql}");
    }

    if ($hesk_settings['staff_nicknames']) {
        $nickname_sql = "`nickname`='".hesk_dbEscape($myuser['nickname'])."',";
    } else {
        $nickname_sql = '';
    }

	hesk_dbQuery(
    "UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."users` SET
    `user`='".hesk_dbEscape($myuser['user'])."',
    `name`='".hesk_dbEscape($myuser['name'])."',
    `email`='".hesk_dbEscape($myuser['email'])."',
    {$nickname_sql}
    `signature`='".hesk_dbEscape($myuser['signature'])."'," . ( isset($myuser['pass']) ? "`pass`='".hesk_dbEscape($myuser['pass'])."'," : '' ) . "
    `categories`='".hesk_dbEscape($myuser['categories'])."',
    `isadmin`='".intval($myuser['isadmin'])."',
    `autoassign`='".intval($myuser['autoassign'])."',
    `heskprivileges`='".hesk_dbEscape($myuser['features'])."',
	`afterreply`='".($myuser['afterreply'])."' ,
	`autostart`='".($myuser['autostart'])."' ,
	`autoreload`='".($myuser['autoreload'])."' ,
	`notify_customer_new`='".($myuser['notify_customer_new'])."' ,
	`notify_customer_reply`='".($myuser['notify_customer_reply'])."' ,
	`show_suggested`='".($myuser['show_suggested'])."' ,
	`notify_new_unassigned`='".($myuser['notify_new_unassigned'])."' ,
	`notify_overdue_unassigned`='".($myuser['notify_overdue_unassigned'])."' ,
	`notify_new_my`='".($myuser['notify_new_my'])."' ,
	`notify_overdue_my`='".($myuser['notify_overdue_my'])."' ,
	`notify_reply_unassigned`='".($myuser['notify_reply_unassigned'])."' ,
	`notify_reply_my`='".($myuser['notify_reply_my'])."' ,
	`notify_assigned`='".($myuser['notify_assigned'])."' ,
	`notify_pm`='".($myuser['notify_pm'])."',
	`notify_note`='".($myuser['notify_note'])."',
    `notify_customer_approval`='".($myuser['notify_customer_approval'])."',
    `notify_collaborator_added`='".($myuser['notify_collaborator_added'])."',
    `notify_collaborator_customer_reply`='".($myuser['notify_collaborator_customer_reply'])."',
    `notify_collaborator_staff_reply`='".($myuser['notify_collaborator_staff_reply'])."',
    `notify_collaborator_note`='".($myuser['notify_collaborator_note'])."',
    `notify_collaborator_resolved`='".($myuser['notify_collaborator_resolved'])."',
    `notify_collaborator_overdue`='".($myuser['notify_collaborator_overdue'])."'
    WHERE `id`='".intval($myuser['id'])."'");

    unset($_SESSION['save_userdata']);
    unset($_SESSION['userdata']);

    // Clear users' authentication tokens if username, email, or password changed
    if (defined('PASSWORD_CHANGED') || $olduser['user'] !== $myuser['user'] || strcasecmp($olduser['email'], $myuser['email']) !== 0) {
        hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."auth_tokens` WHERE `user_id` = ".intval($myuser['id'])." AND `user_type` = 'STAFF'");
    }

    $_SESSION['seluser'] = $myuser['id'];

    hesk_process_messages( $hesklang['user_profile_updated_success'], './manage_users.php','SUCCESS');
} // End update_profile()


function hesk_validateUserInfo($pass_required = 1, $redirect_to = './manage_users.php')
{
	global $hesk_settings, $hesklang;

    $hesk_error_buffer = '';
    $errors = array();

    if (hesk_input(hesk_POST('name'))) {
        $myuser['name'] = hesk_input(hesk_POST('name'));
    } else {
        $hesk_error_buffer .= '<li>' . $hesklang['enter_real_name'] . '</li>';
        $errors[] = 'name';
    }

    if (hesk_validateEmail( hesk_POST('email'), 'ERR', 0)) {
        $myuser['email'] = hesk_validateEmail( hesk_POST('email'), 'ERR', 0);
    } else {
        $hesk_error_buffer .= '<li>' . $hesklang['enter_valid_email'] . '</li>';
        $errors[] = 'email';
    }

    if (hesk_input( hesk_POST('user') )) {
        $myuser['user'] = hesk_input(hesk_POST('user'));
    } else {
        $hesk_error_buffer .= '<li>' . $hesklang['enter_username'] . '</li>';
        $errors[] = 'user';
    }

    $myuser['nickname']   = hesk_input(hesk_POST('nickname'));
	$myuser['isadmin']	  = empty($_POST['isadmin']) ? 0 : 1;
	$myuser['signature']  = hesk_input( hesk_POST('signature') );
    $myuser['autoassign'] = hesk_POST('autoassign') == 'Y' ? 1 : 0;
    $myuser['permission_groups'] = [];

    /* If it's not admin at least one category and fature is required */
    $myuser['categories']	= array();
    $myuser['features']		= array();

    if ($myuser['isadmin']==0)
    {
        // Set permission groups if exists
        foreach (hesk_POST_array('permissionGroups') as $permission_group) {
            if (($tmp = intval($permission_group)) > 0) {
                $myuser['permission_groups'][] = $tmp;
            }
        }
        $myuser['permission_groups'] = array_unique($myuser['permission_groups']);

        if ( ! hesk_validatePermissionGroupsForCurrentUser($myuser['permission_groups']))
        {
            $hesk_error_buffer .= '<li>' . $hesklang['npea'] . '</li>';
            $errors[] = 'permission_groups';
        }

        $has_pg_category = false;
        $has_pg_feature = false;
        if (count($myuser['permission_groups']) > 0) {
            // Check if permission groups contain at least one category and/or feature
            $has_pg_category_rs = hesk_dbQuery("SELECT 1 FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_categories` WHERE `group_id` IN (".implode(',', $myuser['permission_groups']).")");
            $has_pg_category = hesk_dbNumRows($has_pg_category_rs) > 0;
            $has_pg_feature_rs = hesk_dbQuery("SELECT 1 FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."permission_group_features` WHERE `group_id` IN (".implode(',', $myuser['permission_groups']).")");
            $has_pg_feature = hesk_dbNumRows($has_pg_feature_rs) > 0;
        }


    	if (!$has_pg_category && (empty($_POST['categories']) || !is_array($_POST['categories'])))
        {
			$hesk_error_buffer .= '<li>' . $hesklang['asign_one_cat'] . '</li>';
			$errors[] = 'categories';
        }
        else
        {
			foreach (hesk_POST_array('categories') as $tmp)
			{
            	if (is_array($tmp))
                {
                	continue;
                }

				if ($tmp = intval($tmp))
				{
					$myuser['categories'][] = $tmp;
				}
			}
        }

    	if (!$has_pg_feature && (empty($_POST['features']) || !is_array($_POST['features'])))
        {
			$hesk_error_buffer .= '<li>' . $hesklang['asign_one_feat'] . '</li>';
			$errors[] = 'features';
        }
        else
        {
			foreach (hesk_POST_array('features') as $tmp)
			{
				if (in_array($tmp,$hesk_settings['features']))
				{
					$myuser['features'][] = $tmp;
				}
			}
        }

        // One needs view tickets permissions in one has reply to permission
        if (in_array('can_reply_tickets', $myuser['features']))
        {
            $myuser['features'][] = 'can_view_tickets';
        }
	}

	if (hesk_mb_strlen($myuser['signature'])>1000)
    {
    	$hesk_error_buffer .= '<li>' . $hesklang['signature_long'] . '</li>';
    	$errors[] = 'signature';
    }

    /* Password */
	$myuser['cleanpass'] = '';

	$newpass = hesk_input( hesk_POST('newpass') );
	$passlen = strlen($newpass);

	if ($pass_required || $passlen > 0)
	{
        /* At least 5 chars? */
        if ($passlen < 5)
        {
        	$hesk_error_buffer .= '<li>' . $hesklang['password_not_valid'] . '</li>';
        	$errors[] = 'passwords';
        }
        // Too long?
        elseif ($passlen > 64)
        {
            $hesk_error_buffer .= '<li>' . $hesklang['pass_len'] . '</li>';
            $errors[] = 'passwords';
        }
        /* Check password confirmation */
        else
        {
        	$newpass2 = hesk_input( hesk_POST('newpass2') );

			if ($newpass != $newpass2)
			{
				$hesk_error_buffer .= '<li>' . $hesklang['passwords_not_same'] . '</li>';
                $errors[] = 'passwords';
			}
            else
            {
                $myuser['pass'] = hesk_password_hash($newpass);
                $myuser['cleanpass'] = $newpass;
                define('PASSWORD_CHANGED', true);
            }
        }
	}

    /* After reply */
    $myuser['afterreply'] = intval( hesk_POST('afterreply') );
    if ($myuser['afterreply'] != 1 && $myuser['afterreply'] != 2)
    {
    	$myuser['afterreply'] = 0;
    }

    // Defaults
    $myuser['autostart']				= isset($_POST['autostart']) ? 1 : 0;
    $myuser['notify_customer_new']		= isset($_POST['notify_customer_new']) ? 1 : 0;
    $myuser['notify_customer_reply']	= isset($_POST['notify_customer_reply']) ? 1 : 0;
    $myuser['show_suggested']			= isset($_POST['show_suggested']) ? 1 : 0;
    $myuser['autoreload']				= isset($_POST['autoreload']) ? 1 : 0;

    if ($myuser['autoreload'])
    {
        $myuser['autoreload'] = intval(hesk_POST('reload_time'));

        if (hesk_POST('secmin') == 'min')
        {
            $myuser['autoreload'] *= 60;
        }

        if ($myuser['autoreload'] < 30 || $myuser['autoreload'] > 65535)
        {
            $myuser['autoreload'] = 300;
        }
    }

    /* Notifications */
    $myuser['notify_new_unassigned']	    = empty($_POST['notify_new_unassigned']) ? 0 : 1;
    $myuser['notify_overdue_unassigned']    = empty($_POST['notify_overdue_unassigned']) ? 0 : 1;
    $myuser['notify_new_my'] 			    = empty($_POST['notify_new_my']) ? 0 : 1;
    $myuser['notify_overdue_my']            = empty($_POST['notify_overdue_my']) ? 0 : 1;
    $myuser['notify_reply_unassigned']	    = empty($_POST['notify_reply_unassigned']) ? 0 : 1;
    $myuser['notify_reply_my']			    = empty($_POST['notify_reply_my']) ? 0 : 1;
    $myuser['notify_assigned']			    = empty($_POST['notify_assigned']) ? 0 : 1;
    $myuser['notify_note']				    = empty($_POST['notify_note']) ? 0 : 1;
    $myuser['notify_pm']				    = empty($_POST['notify_pm']) ? 0 : 1;
    $myuser['notify_customer_approval']     = empty($_POST['notify_customer_approval']) ? 0 : 1;
    $myuser['notify_collaborator_added']          = empty($_POST['notify_collaborator_added']) ? 0 : 1;
    $myuser['notify_collaborator_customer_reply'] = empty($_POST['notify_collaborator_customer_reply']) ? 0 : 1;
    $myuser['notify_collaborator_staff_reply']    = empty($_POST['notify_collaborator_staff_reply']) ? 0 : 1;
    $myuser['notify_collaborator_note']           = empty($_POST['notify_collaborator_note']) ? 0 : 1;
    $myuser['notify_collaborator_resolved']       = empty($_POST['notify_collaborator_resolved']) ? 0 : 1;
    $myuser['notify_collaborator_overdue']        = empty($_POST['notify_collaborator_overdue']) ? 0 : 1;

    /* Save entered info in session so we don't lose it in case of errors */
	$_SESSION['userdata'] = $myuser;

    /* Any errors */
    if (strlen($hesk_error_buffer))
    {
		if ($myuser['isadmin'])
		{
			// Preserve default staff data for the form
			global $default_userdata;
        	$_SESSION['userdata']['features'] = $default_userdata['features'];
        	$_SESSION['userdata']['categories'] = $default_userdata['categories'];
		}
        $_SESSION['userdata']['errors'] = $errors;

        $hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
    	hesk_process_messages($hesk_error_buffer,$redirect_to);
    }

	// "can_unban_emails" feature also enables "can_ban_emails"
	if ( in_array('can_unban_emails', $myuser['features']) && ! in_array('can_ban_emails', $myuser['features']) )
	{
    	$myuser['features'][] = 'can_ban_emails';
	}

    // "can_unmute_emails" feature also enables "can_mute_emails"
    if ( in_array('can_unmute_emails', $myuser['features']) && ! in_array('can_mute_emails', $myuser['features']) )
    {
        $myuser['features'][] = 'can_mute_emails';
    }

    // "can_unban_ips" feature also enables "can_ban_ips"
    if ( in_array('can_unban_ips', $myuser['features']) && ! in_array('can_ban_ips', $myuser['features']) )
    {
        $myuser['features'][] = 'can_ban_ips';
    }

	return $myuser;

} // End hesk_validateUserInfo()


function remove()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check();

	$myuser = intval( hesk_GET('id' ) ) or hesk_error($hesklang['no_valid_id']);

    /* You can't delete the default user */
	if ($myuser == 1)
    {
        hesk_process_messages($hesklang['cant_del_admin'],'./manage_users.php');
    }

    /* You can't delete your own account (the one you are logged in) */
	if ($myuser == $_SESSION['id'])
    {
        hesk_process_messages($hesklang['cant_del_own'],'./manage_users.php');
    }

    // Make sure we have permission to edit this user
    if ( ! compare_user_permissions($myuser))
    {
        hesk_process_messages($hesklang['npea'],'manage_users.php');
    }

    /* Un-assign all tickets for this user */
    // Don't update resolved tickets "Last modified"
    // $res = hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `owner`=0, `lastchange`=`lastchange` WHERE `owner`='".intval($myuser)."' AND `status` = '3'");
    // For unresolved tickets, update the "Last modified"
    $res = hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `owner`=0 WHERE `owner`='".intval($myuser)."' AND `status` <> '3'");

    /* Delete user info */
	$res = hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id`='".intval($myuser)."'");
	if (hesk_dbAffectedRows() != 1)
    {
        hesk_process_messages($hesklang['int_error'].': '.$hesklang['user_not_found'],'./manage_users.php');
    }

	/* Delete any user reply drafts */
	hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."reply_drafts` WHERE `owner`={$myuser}");

    // Clear users' authentication and MFA tokens
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."auth_tokens` WHERE `user_id` = {$myuser} AND `user_type` = 'STAFF'");
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."mfa_verification_tokens` WHERE `user_id` = {$myuser} AND `user_type` = 'STAFF'");

    // Clear users' bookmarks
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."bookmarks` WHERE `user_id` = {$myuser}");

    // Remove user as collaborator
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_collaborator` WHERE `user_id` = {$myuser}");

	// Refresh autoassign configs to ensure their ID is gone
    hesk_updateAutoassignConfigs();

    hesk_process_messages($hesklang['sel_user_removed'],'./manage_users.php','SUCCESS');
} // End remove()


function toggle_autoassign()
{
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check();

	$myuser = intval( hesk_GET('id' ) ) or hesk_error($hesklang['no_valid_id']);

    // Make sure we have permission to edit this user
    if ( ! compare_user_permissions($myuser))
    {
        hesk_process_messages($hesklang['npea'],'manage_users.php');
    }

    $_SESSION['seluser'] = $myuser;

    if ( intval( hesk_GET('s') ) )
    {
		$autoassign = 1;
        $tmp = $hesklang['uaaon'];
    }
    else
    {
        $autoassign = 0;
        $tmp = $hesklang['uaaoff'];
    }

	/* Update auto-assign settings */
	$res = hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."users` SET `autoassign`='{$autoassign}' WHERE `id`='".intval($myuser)."'");
	if (hesk_dbAffectedRows() != 1)
    {
        hesk_process_messages($hesklang['int_error'].': '.$hesklang['user_not_found'],'./manage_users.php');
    }

    hesk_process_messages($tmp,'./manage_users.php','SUCCESS');
} // End toggle_autoassign()

function reset_mfa() {
    global $hesk_settings, $hesklang;

    /* A security check */
    hesk_token_check();

    require(HESK_PATH . 'inc/mfa_functions.inc.php');

    $myuser = intval(hesk_GET('id')) or hesk_error($hesklang['no_valid_id']);

    // Make sure we have permission to edit this user
    if ( ! compare_user_permissions($myuser))
    {
        hesk_process_messages($hesklang['npea'],'manage_users.php');
    }

    $_SESSION['seluser'] = $myuser;

    $target_enrollment = 0;
    if ($hesk_settings['require_mfa']) {
        $target_enrollment = 1;
    }

    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."users` SET `mfa_enrollment` = {$target_enrollment}, `mfa_secret` = NULL WHERE `id` = {$myuser}");

    if (hesk_dbAffectedRows() != 1) {
        hesk_process_messages($hesklang['int_error'].': '.$hesklang['user_not_found'],'./manage_users.php');
    }

    delete_mfa_backup_codes($myuser);
    delete_mfa_codes($myuser);
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."auth_tokens` WHERE `user_id` = {$myuser} AND `user_type` = 'STAFF'");

    hesk_process_messages($hesklang['mfa_reset'], './manage_users.php', 'SUCCESS');
}

function toggle_activation()
{
    global $hesk_settings, $hesklang;

    /* A security check */
    hesk_token_check();

    $myuser = intval( hesk_GET('id' ) ) or hesk_error($hesklang['no_valid_id']);
    $_SESSION['seluser'] = $myuser;

    /* You can't deactivate the default user */
    if ($myuser == 1)
    {
        hesk_process_messages($hesklang['cant_deactivate_admin'],'./manage_users.php');
    }

    /* You can't delete your own account (the one you are logged in) */
    if ($myuser == $_SESSION['id'])
    {
        hesk_process_messages($hesklang['cant_deactivate_own'],'./manage_users.php');
    }

    // Make sure we have permission to manage this user
    if ( ! compare_user_permissions($myuser))
    {
        hesk_process_messages($hesklang['npea'],'manage_users.php');
    }

    if ( intval( hesk_GET('state') ) )
    {
        $active = 1;
        $tmp = $hesklang['user_activated'];
    }
    else
    {
        $active = 0;
        $tmp = $hesklang['user_deactivated'];
    }

    /* Update activation settings */
    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."users` SET `active`='{$active}' WHERE `id`='".intval($myuser)."'");
    if (hesk_dbAffectedRows() != 1)
    {
        hesk_process_messages($hesklang['int_error'].': '.$hesklang['user_not_found'],'./manage_users.php');
    }

    // If user is deactivated, clean up some data
    if (!$active) {
        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `owner`=0 WHERE `owner`='".intval($myuser)."' AND `status` <> '3'");
        hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."auth_tokens` WHERE `user_id`={$myuser} AND `user_type` = 'STAFF'");
        hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_to_collaborator` WHERE `user_id` = {$myuser}");
        hesk_updateAutoassignConfigs();
    }

    hesk_process_messages($tmp,'./manage_users.php','SUCCESS');
} // End toggle_autoassign()

function build_sort_url($current_sort_field, $sort_field, $current_sort_direction) {
    $target_sort_direction = $current_sort_direction === 'ASC' && $sort_field === $current_sort_field ? 'DESC' : 'ASC';
    $encoded_field = urlencode($sort_field);

    return "manage_users.php?sort_column={$encoded_field}&sort_direction={$target_sort_direction}";
}
?>
module_escalate.php
wget 'https://lists2.roe3.org/hesk/admin/module_escalate.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/reporting_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_run_reports');

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

// Hesk free version
hesk_show_notice(sprintf($hesklang['modules_demo'], '<a href="https://www.hesk.com/get/hesk3-escalate">HESK Cloud</a>'), ' ', false);
?>
<div class="main__content reports">
    <form>
        <div class="reports__head">
            <h2>
                <?php echo $hesklang['escalate']['page_title']; ?>
                <div class="tooltype right out-close">
                    <svg class="icon icon-info">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                    </svg>
                    <div class="tooltype__content">
                        <div class="tooltype__wrapper">
                            <?php echo $hesklang['escalate']['intro']; ?>
                        </div>
                    </div>
                </div>
            </h2>
        </div>
    </form>

    <p><?php echo $hesklang['escalate']['intro']; ?></p>

    <ul style="list-style-type: disc ! important; padding-left: 40px ! important; margin-top: 20px; margin-bottom: 20px;">
        <li><?php echo $hesklang['escalate']['feat1']; ?>,</li>
        <li><?php echo $hesklang['escalate']['feat2']; ?>,</li>
        <li><?php echo $hesklang['escalate']['feat3']; ?>,</li>
        <li><?php echo $hesklang['escalate']['feat4']; ?>,</li>
        <li><?php echo $hesklang['and_more']; ?></li>
    </ul>

    <p><?php echo sprintf($hesklang['see_demo'], '<a href="https://www.hesk.com/get/hesk3-escalate-demo">HESK Demo</a>'); ?></p>

    <img src="<?php echo HESK_PATH; ?>img/escalate.jpg" alt="<?php echo $hesklang['escalate']['tab']; ?>" style="margin-top:35px;">

</div>

<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();
module_recurring_tickets.php
wget 'https://lists2.roe3.org/hesk/admin/module_recurring_tickets.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/setup_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_man_settings');

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

// Hesk free version
hesk_show_notice(sprintf($hesklang['modules_demo'], '<a href="https://www.hesk.com/get/hesk3-recurring">HESK Cloud</a>'), ' ', false);
?>
<div class="main__content reports">
    <form>
        <div class="reports__head">
            <h2>
                <?php echo $hesklang['recurring_tickets']['page_title']; ?>
                <div class="tooltype right out-close">
                    <svg class="icon icon-info">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                    </svg>
                    <div class="tooltype__content">
                        <div class="tooltype__wrapper">
                            <?php echo $hesklang['recurring_tickets']['intro']; ?>
                            <?php echo $hesklang['recurring_tickets']['intro2']; ?>
                        </div>
                    </div>
                </div>
            </h2>
        </div>
    </form>

    <p><?php echo $hesklang['recurring_tickets']['intro']; ?></p>

    <ul style="list-style-type: disc ! important; padding-left: 40px ! important; margin-top: 20px; margin-bottom: 20px;">
        <li><?php echo $hesklang['recurring_tickets']['feat1']; ?>,</li>
        <li><?php echo $hesklang['recurring_tickets']['feat2']; ?>,</li>
        <li><?php echo $hesklang['recurring_tickets']['feat3']; ?>.</li>
    </ul>

    <p><?php echo $hesklang['recurring_tickets']['intro2']; ?></p>
    <p>&nbsp;</p>
    <p><?php echo sprintf($hesklang['see_demo'], '<a href="https://www.hesk.com/get/hesk3-recurring-demo">HESK Demo</a>'); ?></p>

    <img src="<?php echo HESK_PATH; ?>img/recurring-tickets.png" alt="<?php echo $hesklang['satisfaction']['tab']; ?>" style="margin-top:35px;">

</div>

<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();
module_satisfaction.php
wget 'https://lists2.roe3.org/hesk/admin/module_satisfaction.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/reporting_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_run_reports');

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

// Hesk free version
hesk_show_notice(sprintf($hesklang['modules_demo'], '<a href="https://www.hesk.com/get/hesk3-satisfaction">HESK Cloud</a>'), ' ', false);
?>
<div class="main__content reports">
    <form>
        <div class="reports__head">
            <h2>
                <?php echo $hesklang['satisfaction']['title']; ?>
                <div class="tooltype right out-close">
                    <svg class="icon icon-info">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                    </svg>
                    <div class="tooltype__content">
                        <div class="tooltype__wrapper">
                            <?php echo $hesklang['satisfaction']['intro']; ?>
                        </div>
                    </div>
                </div>
            </h2>
        </div>
    </form>

    <p><?php echo $hesklang['satisfaction']['intro']; ?></p>

    <ul style="list-style-type: disc ! important; padding-left: 40px ! important; margin-top: 20px; margin-bottom: 20px;">
        <li><?php echo $hesklang['satisfaction']['feat1']; ?>,</li>
        <li><?php echo $hesklang['satisfaction']['feat2']; ?>,</li>
        <li><?php echo $hesklang['satisfaction']['feat3']; ?>.</li>
    </ul>

    <p><?php echo sprintf($hesklang['see_demo'], '<a href="https://www.hesk.com/get/hesk3-satisfaction-demo">HESK Demo</a>'); ?></p>

    <img src="<?php echo HESK_PATH; ?>img/satisfaction.jpg" alt="<?php echo $hesklang['satisfaction']['tab']; ?>" style="margin-top:35px;">

</div>

<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();
module_statistics.php
wget 'https://lists2.roe3.org/hesk/admin/module_statistics.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/reporting_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_run_reports');

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

// Hesk free version
hesk_show_notice(sprintf($hesklang['modules_demo'], '<a href="https://www.hesk.com/get/hesk3-statistics">HESK Cloud</a>'), ' ', false);
?>
<div class="main__content reports">
    <form>
        <div class="reports__head">
            <h2>
                <?php echo $hesklang['statistics']['tab']; ?>
                <div class="tooltype right out-close">
                    <svg class="icon icon-info">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                    </svg>
                    <div class="tooltype__content">
                        <div class="tooltype__wrapper">
                            <?php echo $hesklang['statistics']['intro']; ?>
                        </div>
                    </div>
                </div>
            </h2>
        </div>
    </form>

    <p><?php echo $hesklang['statistics']['intro']; ?></p>

    <ul style="list-style-type: disc ! important; padding-left: 40px ! important; margin-top: 20px; margin-bottom: 20px;">
        <li><?php echo $hesklang['statistics']['pie_title_ro']; ?>,</li>
        <li><?php echo $hesklang['statistics']['pie_title_so']; ?>,</li>
        <li><?php echo $hesklang['statistics']['chart_title_md']; ?>,</li>
        <li><?php echo $hesklang['statistics']['chart_title_wd']; ?>,</li>
        <li><?php echo $hesklang['statistics']['chart_title_hd']; ?>,</li>
        <li><?php echo $hesklang['statistics']['chart_title_tfr']; ?>,</li>
        <li><?php echo $hesklang['statistics']['chart_title_ttr']; ?>,</li>
        <li><?php echo $hesklang['statistics']['chart_title_srt']; ?>,</li>
        <li><?php echo $hesklang['and_more']; ?></li>
    </ul>

    <p><?php echo sprintf($hesklang['see_demo'], '<a href="https://www.hesk.com/get/hesk3-statistics-demo">HESK Demo</a>'); ?></p>

    <img src="<?php echo HESK_PATH; ?>img/statistics.jpg" alt="<?php echo $hesklang['statistics']['tab']; ?>" style="margin-top:35px;">

</div>

<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();
move_category.php
wget 'https://lists2.roe3.org/hesk/admin/move_category.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();
require(HESK_PATH . 'inc/email_functions.inc.php');
require_once(HESK_PATH . 'inc/customer_accounts.inc.php');

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
if ( ! hesk_checkPermission('can_change_cat', 0))
{
    hesk_checkPermission('can_change_own_cat');
}

/* A security check */
hesk_token_check('POST');

/* Ticket ID */
$trackingID = hesk_cleanID() or die($hesklang['int_error'].': '.$hesklang['no_trackID']);

/* Category ID */
$category   = intval( hesk_POST('category', -1) );
if ($category < 1)
{
	hesk_process_messages($hesklang['incat'],'admin_ticket.php?track='.$trackingID.'&Refresh='.rand(10000,99999),'NOTICE');
}

/* Get new category details */
$res = hesk_dbQuery("SELECT `name`,`autoassign` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE `id`='{$category}' LIMIT 1");
if (hesk_dbNumRows($res) != 1)
{
	hesk_error("$hesklang[int_error]: $hesklang[kb_cat_inv].");
}
$row = hesk_dbFetchAssoc($res);

/* Should tickets in new category be auto-assigned if necessary? */
if ( ! $row['autoassign'])
{
	$hesk_settings['autoassign'] = false;
}

/* Is user allowed to view tickets in new category? */
$category_ok = hesk_okCategory($category,0);

// Is user allowed to move tickets to this category?
if ( ! $category_ok && ! hesk_checkPermission('can_change_cat', 0) )
{
    hesk_process_messages($hesklang['noauth_move'],'admin_main.php');
}

/* Get details about the original ticket */
$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `trackid`='".hesk_dbEscape($trackingID)."' LIMIT 1");
if (hesk_dbNumRows($res) != 1)
{
	hesk_error($hesklang['ticket_not_found']);
}
$ticket = hesk_dbFetchAssoc($res);
hesk_verifyStaffTicketAccess($trackingID, $ticket);

if ($ticket['category'] == $category) {
    hesk_process_messages(sprintf($hesklang['ticket_already_in_category'], $row['name']),'admin_ticket.php?track='.$trackingID.'&Refresh='.rand(10000,99999),'NOTICE');
}

/* Log that ticket is being moved */
$history = sprintf($hesklang['thist1'],hesk_date(),addslashes($row['name']),addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');

/* Is the ticket assigned to someone? If yes, check that the user has access to category or change to unassigned */
$need_to_reassign = 0;
if ($ticket['owner'])
{
	if ($ticket['owner'] == $_SESSION['id'] && ! $category_ok )
    {
		$need_to_reassign = 1;
    }
    else
    {
		$res = hesk_dbQuery("SELECT `isadmin`,`categories` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id`='".intval($ticket['owner'])."' AND `active` = 1 LIMIT 1");
		if (hesk_dbNumRows($res) != 1)
		{
			$need_to_reassign = 1;
		}
        else
        {
        	$tmp = hesk_dbFetchAssoc($res);
            if ( ! hesk_okCategory($category,0,$tmp['isadmin'], explode(',',$tmp['categories']) ) )
            {
            	$need_to_reassign = 1;
            }
        }
    }
}

/* Reassign automatically if possible */
if ($need_to_reassign || ! $ticket['owner'])
{
	$need_to_reassign = 1;
	$autoassign_owner = hesk_autoAssignTicket($category);
	if ($autoassign_owner)
	{
		$ticket['owner'] = $autoassign_owner['id'];
	    $history .= sprintf($hesklang['thist10'],hesk_date(),addslashes($autoassign_owner['name']).' ('.$autoassign_owner['user'].')');
	}
    else
    {
    	$ticket['owner'] = 0;
    }
}

hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `category`='".intval($category)."', `owner`='".intval($ticket['owner'])."' , `history`=CONCAT(`history`,'".hesk_dbEscape($history)."') WHERE `trackid`='".hesk_dbEscape($trackingID)."'");

$ticket['category'] = $category;
$customers = hesk_get_customers_for_ticket($ticket['id']);
$customer_emails = array_map(function($customer) { return $customer['email']; }, $customers);
$customer_names = array_map(function($customer) { return $customer['name']; }, $customers);

/* --> Prepare message */

// 1. Generate the array with ticket info that can be used in emails
$info = array(
'email'			=> implode(';', $customer_emails),
'category'		=> $ticket['category'],
'priority'		=> $ticket['priority'],
'owner'			=> $ticket['owner'],
'trackid'		=> $ticket['trackid'],
'status'		=> $ticket['status'],
'name'			=> implode(',', $customer_names),
'subject'		=> $ticket['subject'],
'message'		=> $ticket['message'],
'message_html'  => $ticket['message_html'],
'attachments'	=> $ticket['attachments'],
'dt'			=> hesk_date($ticket['dt'], true),
'lastchange'	=> hesk_date($ticket['lastchange'], true),
'due_date'      => hesk_format_due_date($ticket['due_date']),
'id'			=> $ticket['id'],
'time_worked'   => $ticket['time_worked'],
'last_reply_by' => hesk_getReplierNameArray($ticket),
);

// 2. Add custom fields to the array
foreach ($hesk_settings['custom_fields'] as $k => $v)
{
	$info[$k] = $v['use'] ? $ticket[$k] : '';
}

// 3. Make sure all values are properly formatted for email
$ticket = hesk_ticketToPlain($info, 1, 0);

/* Need to notify any staff? */
/* --> From autoassign? */
if ($need_to_reassign && ! empty($autoassign_owner['email']) )
{
	hesk_notifyAssignedStaff($autoassign_owner, 'ticket_assigned_to_you', 'notify_assigned', false);
}
/* --> No autoassign, find and notify appropriate staff */
elseif ( ! $ticket['owner'] )
{
	hesk_notifyStaff('category_moved', "`notify_new_unassigned`='1' AND `id`!=".intval($_SESSION['id']) );
}

/* Is the user allowed to view tickets in the new category? */
if ($category_ok)
{
	/* Ticket has an owner */
	if ($ticket['owner'])
    {
    	/* Staff is owner or can view tickets assigned to others */
		if ($ticket['owner'] == $_SESSION['id'] || hesk_checkPermission('can_view_ass_others',0) )
        {
			hesk_process_messages($hesklang['moved_to'],'admin_ticket.php?track='.$trackingID.'&Refresh='.rand(10000,99999),'SUCCESS');
        }
        else
        {
			hesk_process_messages($hesklang['moved_to'],'admin_main.php','SUCCESS');
        }
    }
    /* Ticket is unassigned, staff can view unassigned tickets */
    elseif (hesk_checkPermission('can_view_unassigned',0))
    {
		hesk_process_messages($hesklang['moved_to'],'admin_ticket.php?track='.$trackingID.'&Refresh='.rand(10000,99999),'SUCCESS');
    }
    /* Ticket is unassigned, staff cannot view unassigned tickets */
	else
	{
	    hesk_process_messages($hesklang['moved_to'],'admin_main.php','SUCCESS');
	}
}
else
{
    hesk_process_messages($hesklang['moved_to'],'admin_main.php','SUCCESS');
}
?>
muted_emails.php
wget 'https://lists2.roe3.org/hesk/admin/muted_emails.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');

hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
hesk_checkPermission('can_mute_emails');
$can_unmute = hesk_checkPermission('can_unmute_emails', 0);

// Define required constants
define('LOAD_TABS',1);

// What should we do?
if ( $action = hesk_REQUEST('a') )
{
    if ( defined('HESK_DEMO') ) {hesk_process_messages($hesklang['ddemo'], 'muted_emails.php', 'NOTICE');}
    elseif ($action == 'mute') {mute_email();}
    elseif ($action == 'unmute' && $can_unmute) {unmute_email();}
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
hesk_handle_messages();
?>

<div class="main__content tools">
    <h2>
        <?php echo $hesklang['mute_emails']; ?>
        <div class="tooltype right out-close">
            <svg class="icon icon-info">
                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
            </svg>
            <div class="tooltype__content">
                <div class="tooltype__wrapper">
                    <?php echo $hesklang['mute_email_intro']; ?>
                </div>
            </div>
        </div>
    </h2>
    <form action="muted_emails.php" method="post" name="form1" aria-label="<?php echo $hesklang['mute_an_email']; ?>">
        <div class="tools__add-mail form">
            <div class="form-group">
                <input type="text" name="email" class="form-control" maxlength="255" aria-label="<?php echo $hesklang['mute_an_email'];?>"  placeholder="<?php echo htmlspecialchars($hesklang['mute_an_email']); ?>" autofocus>
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
                <input type="hidden" name="a" value="mute" />
                <button type="submit" class="btn btn--blue-border" ripple="ripple"><?php echo $hesklang['save_mute_email']; ?></button>
            </div>
            <div class="mail--examples"><?php echo $hesklang['banex']; ?> john@example.com, @example.com</div>
        </div>
    </form>
    <?php
        // Get muted emails from database
        $res = hesk_dbQuery('SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'muted_emails` ORDER BY `email` ASC');
        $num = hesk_dbNumRows($res);
    ?>
    <div class="table-wrapper email">
        <table id="default-table" class="table sindu-table">
            <thead>
            <tr>
                <th><?php echo $hesklang['email']; ?></th>
                <th><?php echo $hesklang['muted_by']; ?></th>
                <th><?php echo $hesklang['date']; ?></th>
                <?php if ($can_unmute): ?>
                    <th><?php echo $hesklang['opt']; ?></th>
                <?php endif; ?>
            </tr>
            </thead>
            <tbody>
            <?php if ($num < 1): ?>
            <tr>
                <td colspan="<?php echo $can_unmute ? 4 : 3; ?>"><?php echo $hesklang['no_mute_emails']; ?></td>
            </tr>
            <?php
            else:
                // List of staff
                if ( ! isset($admins) )
                {
                    $admins = array();
                    $res2 = hesk_dbQuery("SELECT `id`,`name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users`");
                    while ($row=hesk_dbFetchAssoc($res2))
                    {
                        $admins[$row['id']]=$row['name'];
                    }
                }

                while ($mute = hesk_dbFetchAssoc($res)):
                    $table_row = '';
                    if (isset($_SESSION['mute_email']['id']) && $mute['id'] == $_SESSION['mute_email']['id'])
                    {
                        $table_row = 'class="ticket-new"';
                        unset($_SESSION['mute_email']['id']);
                    }
                ?>
                <tr <?php echo $table_row; ?>>
                    <td><?php echo $mute['email']; ?></td>
                    <td><?php echo isset($admins[$mute['muted_by']]) ? $admins[$mute['muted_by']] : $hesklang['e_udel']; ?></td>
                    <td><?php echo hesk_date($mute['dt']); ?></td>
                    <?php if ($can_unmute): ?>
                    <td class="unmute">
                        <?php $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                            $hesklang['del_mute_confirm'],
                            'muted_emails.php?a=unmute&amp;id='. $mute['id'] .'&amp;token='. hesk_token_echo(0)); ?>
                        <a title="<?php echo $hesklang['del_mute']; ?>" href="javascript:" data-modal="[data-modal-id='<?php echo $modal_id; ?>']">
                            <?php echo $hesklang['del_mute']; ?>
                        </a>
                    </td>
                    <?php endif; ?>
                </tr>
                <?php endwhile;
                endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/

function mute_email()
{
    global $hesk_settings, $hesklang;

    // A security check
    hesk_token_check();

    // Get the email
    $email = hesk_emailCleanup( strtolower( hesk_input( hesk_REQUEST('email') ) ) );

    // Nothing entered?
    if ( ! strlen($email) )
    {
        hesk_process_messages($hesklang['enter_mute_email'],'muted_emails.php');
    }

    // Only allow one email to be entered
    $email = ($index = strpos($email, ',')) ? substr($email, 0,  $index) : $email;
    $email = ($index = strpos($email, ';')) ? substr($email, 0,  $index) : $email;

    // We don't need *@ to mute domains, remove the star if present
    if (strpos($email, '*@') === 0) {
        $email = ltrim($email, '*');
    }

    // Validate email address
    $hesk_settings['multi_eml'] = 0;

    if ( ! hesk_validateEmail($email, '', 0) && ! verify_email_domain($email) )
    {
        hesk_process_messages($hesklang['valid_mute_email'],'muted_emails.php');
    }

    // Redirect either to muted emails or ticket page from now on
    $redirect_to = ($trackingID = hesk_cleanID()) ? 'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999) : 'muted_emails.php';

    // Prevent duplicate rows
    if ( $_SESSION['mute_email']['id'] = hesk_isMutedEmail($email) )
    {
        hesk_process_messages( sprintf($hesklang['email_mute_exists'], $email) ,$redirect_to,'NOTICE');
    }

    // Type; 0 = domain, 1 = email
    $type = ($email[0] == '@') ? 0 : 1;

    // Insert the email address into database
    hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."muted_emails` (`email`, `type`, `muted_by`) VALUES ('".hesk_dbEscape($email)."', {$type}, '".intval($_SESSION['id'])."')");

    // Remember email that got muted
    $_SESSION['mute_email']['id'] = hesk_dbInsertID();

    // Show success
    hesk_process_messages( sprintf($hesklang['email_muted'], $email) ,$redirect_to,'SUCCESS');

} // End mute_email()


function unmute_email()
{
    global $hesk_settings, $hesklang;

    // A security check
    hesk_token_check();

    // Delete from mutes
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."muted_emails` WHERE `id`=" . intval( hesk_GET('id') ) );

    // Redirect either to muted emails or ticket page from now on
    $redirect_to = ($trackingID = hesk_cleanID()) ? 'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999) : 'muted_emails.php';

    // Show success
    hesk_process_messages($hesklang['email_unmuted'],$redirect_to,'SUCCESS');

} // End unmute_email()


function verify_email_domain($domain)
{
    // Does it start with an @?
    $atIndex = strrpos($domain, "@");
    if ($atIndex !== 0)
    {
        return false;
    }

    // Get the domain and domain length
    $domain = substr($domain, 1);
    $domainLen = strlen($domain);

    // Check domain part length
    if ($domainLen < 1 || $domainLen > 254)
    {
        return false;
    }

    // Check domain part characters
    if ( ! preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain) )
    {
        return false;
    }

    // Domain part mustn't have two consecutive dots
    if ( strpos($domain, '..') !== false )
    {
        return false;
    }

    // All OK
    return true;

} // END verify_email_domain()

?>
new_ticket.php
wget 'https://lists2.roe3.org/hesk/admin/new_ticket.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

// Auto-focus first empty or error field
define('AUTOFOCUS', true);

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Load custom fields
require_once(HESK_PATH . 'inc/custom_fields.inc.php');

// Load priorities
require_once(HESK_PATH . 'inc/priorities.inc.php');

// Load statuses
require_once(HESK_PATH . 'inc/statuses.inc.php');

// Load calendar JS and CSS
define('CALENDAR',1);
define('ATTACHMENTS',1);

if ($hesk_settings['staff_ticket_formatting'] == 2) {
    define('WYSIWYG',1);
}

$hesk_settings['datepicker'] = array();

// Pre-populate fields

// First, reset data if any query string value is present
if (isset($_REQUEST['name']) ||
    isset($_REQUEST['email']) ||
    isset($_REQUEST['priority']) ||
    isset($_REQUEST['status']) ||
    isset($_REQUEST['subject']) ||
    isset($_REQUEST['message']) ||
    isset($_REQUEST['due_date']) ||
    isset($_REQUEST['ticket_language'])
    ) {
    hesk_new_ticket_reset_data();
}

foreach ($hesk_settings['custom_fields'] as $k=>$v) {
    if ($v['use'] && isset($_REQUEST[$k])) {
        hesk_new_ticket_reset_data();
    }
}

// Customer name
$predefined_name = '';
$predefined_email = '';
if (isset($_REQUEST['name'])) {
	$predefined_name = $_REQUEST['name'];
}

// Customer email address
if (isset($_REQUEST['email'])) {
	$predefined_email = $_REQUEST['email'];
}

// Category ID
if (isset($_REQUEST['catid'])) {
	$_SESSION['as_category'] = intval($_REQUEST['catid']);
}
if (isset($_REQUEST['category'])) {
	$_SESSION['as_category'] = intval($_REQUEST['category']);
}

// Priority
if (isset($_REQUEST['priority'])) {
	$_SESSION['as_priority'] = intval($_REQUEST['priority']);
}

// Status
if (isset($_REQUEST['status'])) {
    $_SESSION['as_status'] = intval($_REQUEST['status']);
}

// Subject
if (isset($_REQUEST['subject'])) {
	$_SESSION['as_subject'] = $_REQUEST['subject'];
}

// Message
if (isset($_REQUEST['message'])) {
	$_SESSION['as_message'] = $_REQUEST['message'];
}

// Custom fields
foreach ($hesk_settings['custom_fields'] as $k=>$v) {
	if ($v['use'] && isset($_REQUEST[$k]) ) {
		$_SESSION['as_'.$k] = $_REQUEST[$k];
	}
}

// Due date
$can_due_date = hesk_checkPermission('can_due_date',0);
if ($can_due_date && isset($_REQUEST['due_date'])) {
    // Should be in one of valid formats
    // - in the datepicker format
    if (($dd = hesk_datepicker_get_date($_REQUEST['due_date']))) {
        $_SESSION['as_due_date'] = $_REQUEST['due_date'];
        $hesk_settings['datepicker']['#due_date']['timestamp'] = $dd->getTimestamp();
    }
    // - in a valid datetime format: https://www.php.net/manual/en/datetime.formats.date.php
    else {
        try {
            $current_date = new DateTime($_REQUEST['due_date']);
            $hesk_settings['datepicker']['#due_date']['timestamp'] = $current_date->getTimestamp();
            $_REQUEST['due_date'] = hesk_datepicker_format_date($current_date->getTimestamp());
            $_SESSION['as_due_date'] = $_REQUEST['due_date'];
        } catch(Exception $e) {
            $_SESSION['HESK_2ND_NOTICE']  = true;
            $_SESSION['HESK_2ND_MESSAGE'] = $hesklang['epdd'] . ' ' . $e->getMessage();
        }
    }
}

// Ticket language
if (isset($_REQUEST['ticket_language'])) {
    $_SESSION['as_language'] = $_REQUEST['ticket_language'];
}

/* Varibles for coloring the fields in case of errors */
if (!isset($_SESSION['iserror'])) {
	$_SESSION['iserror'] = array();
}

if (!isset($_SESSION['isnotice'])) {
	$_SESSION['isnotice'] = array();
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print admin navigation */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

// Get categories
$hesk_settings['categories'] = array();

if (hesk_checkPermission('can_submit_any_cat', 0))
{
    $res = hesk_dbQuery("SELECT `id`, `name`, `priority`, `autoassign` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` ORDER BY `cat_order` ASC");
}
else
{
    $res = hesk_dbQuery("SELECT `id`, `name`, `priority`, `autoassign` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE ".hesk_myCategories('id')." ORDER BY `cat_order` ASC");
}

while ($row=hesk_dbFetchAssoc($res))
{
	$hesk_settings['categories'][$row['id']] = array(
        'name' => $row['name'],
        'priority' => $row['priority'],
        'autoassign' => $row['autoassign']
    );
}

$number_of_categories = count($hesk_settings['categories']);

if ($number_of_categories == 0)
{
	$category = 1;
}
elseif ($number_of_categories == 1)
{
	$category = current(array_keys($hesk_settings['categories']));
}
else
{
	$category = isset($_GET['catid']) ? hesk_REQUEST('catid'): hesk_REQUEST('category');

	// Force the customer to select a category?
	if (! isset($hesk_settings['categories'][$category]) )
	{
		return print_select_category($number_of_categories);
	}
}

// List of users whom this ticket can be assigned to
$accessible_users = hesk_getUserIdsWithAccessToFeatureAndCategory('can_view_tickets', $category);
$admins = array();
$res = hesk_dbQuery("SELECT `id`,`name`,`isadmin`,`categories`,`heskprivileges` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `active` = 1 ORDER BY `name` ASC");
while ($row = hesk_dbFetchAssoc($res))
{
    // Is this an administrator or have access via permission group?
    if ($row['isadmin'] || in_array($row['id'], $accessible_users))
    {
        $admins[$row['id']]=$row['name'];
        continue;
    }

    // Not admin, is user allowed to view tickets?
    if (strpos($row['heskprivileges'], 'can_view_tickets') !== false)
    {
        // Is user allowed to access this category?
        $cat = substr($row['categories'], 0);
        $row['categories'] = explode(',', $cat);
        if (in_array($category, $row['categories']))
        {
            $admins[$row['id']] = $row['name'];
            continue;
        }
    }
}

// Set the default category priority
if ( ! isset($_SESSION['as_priority']))
{
    $_SESSION['as_priority'] = intval($hesk_settings['categories'][$category]['priority']);
}

// Set the default ticket status
if ( ! isset($_SESSION['as_status']))
{
    $_SESSION['as_status'] = 0;
}

$show_create_modal = false;
$existing_customer_id = hesk_SESSION('as_customer_id', null);
//-- If name/email provided, prefill it or display a modal
if ($predefined_name !== '') {
    // If email is blank, always show the modal
    if ($predefined_email !== '') {
        require_once(HESK_PATH . 'inc/customer_accounts.inc.php');
        $existing_customer_id = hesk_get_or_create_customer($predefined_name, $predefined_email, false);
    }

    if ($existing_customer_id === null) {
        $show_create_modal = true;
    }
}

?>
<div class="main__content categories ticket-create">
    <div class="table-wrap">

        <?php
        if ( ! isset($_SESSION['HESK_ERROR']))
        {
            hesk_show_info($hesklang['nti3'], ' ', false);
        }

        /* This will handle error, success and notice messages */
        hesk_handle_messages();
        ?>

        <h3 style="font-size: 1.3rem; margin-top: 10px"><?php echo $hesklang['nti2']; ?></h3>
        <h4><?php echo $hesklang['req_marked_with']; ?> <span class="important">*</span></h4>

        <form method="post" class="form <?php echo isset($_SESSION['iserror']) && count($_SESSION['iserror']) ? 'invalid' : ''; ?>"
              action="admin_submit_ticket.php" name="form1" id="submit-ticket"
              enctype="multipart/form-data" <?php echo $hesk_settings['disable_autofill_admin'] ? 'autocomplete="off" aria-autocomplete="none"' : ''; ?>
              aria-label="<?php echo $hesklang['nti2']; ?>">

            <?php if ($number_of_categories > 1): ?>
            <div class="form-group" style="margin-bottom: 0px;">
                <label for="change_category" style="display: inline;">
                    <?php echo $hesklang['category']; ?>:
                </label>
                &nbsp;
                <button type="button" class="btn btn--blue-border change_category" name="cc-btn" id="cc-btn" title="<?php echo $hesklang['chg_cat']; ?>"><?php echo hesk_getCategoryName($category); ?>
                    &nbsp;
                    <svg class="icon icon-edit">
                        <use xlink:href="../img/sprite.svg#icon-edit"></use>
                    </svg>
                </button>
                <input type="hidden" name="change_category" id="change_category" value="0">
                <script>
                $("#cc-btn").click(function() {
                    $("#change_category").val(1);
                    $("#submit-ticket").submit();
                });
                </script>
            </div>
            <?php endif;

            $session_customers = [];
            $session_followers = [];
            // Load in customers if validation failed
            if ($existing_customer_id !== null) {
                $sanitized_id = intval($existing_customer_id);
                $customer_sql = "SELECT `id`,`name`,`email` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers`
                    WHERE `id` = {$sanitized_id}";
                $existing_customers_rs = hesk_dbQuery($customer_sql);
                while ($row = hesk_dbFetchAssoc($existing_customers_rs)) {
                    $session_customers[] = $row;
                }
            }

            // Load in followers if validation failed
            if (isset($_SESSION['as_follower_ids']) && count($_SESSION['as_follower_ids']) > 0) {
                $sanitized_ids = array_map(function($id) { return intval($id); }, $_SESSION['as_follower_ids']);
                $ids = implode(',', $sanitized_ids);
                $follower_sql = "SELECT `id`,`name`,`email` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."customers`
                    WHERE `id` IN ({$ids})";
                $existing_followers_rs = hesk_dbQuery($follower_sql);
                while ($row = hesk_dbFetchAssoc($existing_followers_rs)) {
                    $session_followers[] = $row;
                }
            }
            ?>

            <div class="form-group">
                <label for="create_customer_input">
                    <?php echo $hesklang['customer']; ?> <span class="important">*</span><a href="javascript:" id="new-customer-link" data-modal="[data-modal-id='create-customer']">[<?php echo $hesklang['new_customer']; ?>]</a>
                </label>
                <select name="customer_id"
                        id="create_customer_input"
                        class="read-write"
                        placeholder="<?php echo hesk_addslashes($hesklang['search_by_name_or_email']); ?>">
                    <?php foreach ($session_customers as $row) { ?>
                        <option value="<?php echo $row['id']; ?>" selected><?php echo $row['email'] ? "{$row['name']} &lt;{$row['email']}&gt;" : $row['name']; ?></option>
                    <?php } ?>
                </select>
                <script>
                    <?php if ($show_create_modal): ?>
                    $(document).ready(function() {
                        $('[data-modal-id="create-customer"] input[name="name"]').val(<?php echo hesk_json_encode_for_js($predefined_name); ?>);
                        $('[data-modal-id="create-customer"] input[name="email"]').val(<?php echo hesk_json_encode_for_js($predefined_email); ?>);
                        $('[data-modal-id="create-customer"]').css('display', 'block');
                        $('#create_name').keyup();
                        $('#email').keyup();
                    });
                    <?php endif; ?>

                    let $createCustomerInput = $('#create_customer_input');
                    <?php
                    // Don't pre-select a customer if there wasn't one in the session
                    if ($existing_customer_id === null): ?>
                    $createCustomerInput.val(-1);
                    <?php endif; ?>
                    hesk_loadNoResultsSelectizePlugin('<?php echo hesk_jsString($hesklang['no_results_found']); ?>');
                    var plugins = ['no_results'];
                    var createCustomerSelectize = $createCustomerInput.selectize({
                        valueField: 'id',
                        labelField: 'displayName',
                        searchField: ['name','email'],
                        copyClassesToDropdown: true,
                        preload: true,
                        options: [],
                        loadThrottle: 300,
                        persist: false,
                        plugins: plugins,
                        load: function(query, callback) {
                            $.ajax({
                                url: 'ajax/search_customers.php?query=' + encodeURIComponent(query),
                                dataType: 'json',
                                success: function(data) {
                                    callback(data);
                                }
                            });
                        },

                        /* Using deconstruct (requires EMCA6, but it's required in a bunch of other code already, so shouldn't be an issue)
                        here to add a bunch of general functionality needed for the custom "Add Entry",
                        And passing only the necessary custom behaviour for this specific dropdown.
                        */
                        ...hesk_selectizeAddCustomAddEntryToDropdown(
                            {
                                newEntryTextPrefix: '<?php echo hesk_jsString($hesklang['add_customer']); ?>',
                                onAddEntryClickedFunction: function(selectizeInstance, selectizeSearchValue) {
                                    // populate the customer input field with the selected search value (either name or email)
                                    let nameValue = selectizeSearchValue;
                                    let emailValue = '';
                                    if (selectizeSearchValue.indexOf('@') > -1) {
                                        // if there's an @ part of search string, we simply assume it's an email
                                        nameValue = '';
                                        emailValue = selectizeSearchValue;
                                    }

                                    // simply reuse what new-customer-link already does for adding a new customer.
                                    $('#new-customer-link').trigger('click', { nameValue: nameValue, emailValue: emailValue });
                                }
                            }
                        )
                    });
                </script>
            </div>
            <?php if ($hesk_settings['multi_eml']): ?>
            <div class="form-group">
                <label for="followers_input">
                    <?php echo $hesklang['followers']; ?><a href="javascript:" id="new-follower-link" data-modal="[data-modal-id='create-customer']">[<?php echo $hesklang['new_follower']; ?>]</a>
                </label>
                <select name="follower_id[]"
                        multiple
                        id="followers_input"
                        class="read-write"
                        placeholder="<?php echo hesk_addslashes($hesklang['search_by_name_or_email']); ?>">
                    <?php foreach ($session_followers as $row) { ?>
                        <option value="<?php echo $row['id']; ?>" selected><?php echo $row['email'] ? "{$row['name']} &lt;{$row['email']}&gt;" : $row['name']; ?></option>
                    <?php } ?>
                </select>
                <script>
                    var plugins = ['no_results'<?php echo $hesk_settings['multi_eml'] ? ",'remove_button'" : ''; ?>];
                    var createFollowerSelectize = $('#followers_input').selectize({
                        valueField: 'id',
                        labelField: 'displayName',
                        searchField: ['name','email'],
                        copyClassesToDropdown: true,
                        preload: true,
                        options: [],
                        loadThrottle: 300,
                        persist: false,
                        plugins: plugins,
                        load: function(query, callback) {
                            $.ajax({
                                url: 'ajax/search_customers.php?query=' + encodeURIComponent(query),
                                dataType: 'json',
                                success: function(data) {
                                    callback(data);
                                }
                            });
                        },

                        /* Using deconstruct (requires EMCA6, but it's required in a bunch of other code already, so shouldn't be an issue)
                        here to add a bunch of general functionality needed for the custom "Add Entry",
                        And passing only the necessary custom behaviour for this specific dropdown.
                        */
                        ...hesk_selectizeAddCustomAddEntryToDropdown(
                            {
                                newEntryTextPrefix: '<?php echo hesk_jsString($hesklang['add_follower']); ?>',
                                onAddEntryClickedFunction: function(selectizeInstance, selectizeSearchValue) {
                                    // populate the follower input field with the selected search value (either name or email)
                                    let nameValue = selectizeSearchValue;
                                    let emailValue = '';
                                    if (selectizeSearchValue.indexOf('@') > -1) {
                                        // if there's an @ part of search string, we simply assume it's an email
                                        nameValue = '';
                                        emailValue = selectizeSearchValue;
                                    }

                                    // simply reuse what new-follower-link already does for adding a new customer.
                                    $('#new-follower-link').trigger('click', { nameValue: nameValue, emailValue: emailValue });
                                }
                            }
                        )
                    });
                </script>
            </div>
            <?php endif;?>
            <div class="form-group">
                <label for="priority" class="priority <?php if (in_array('priority',$_SESSION['iserror'])) {echo 'isErrorStr';} ?>"><?php echo $hesklang['priority']; ?>: <?php if ($hesk_settings['select_pri']) {echo '<span class="important">*</span>';} ?></label>
                <div class="dropdown-select out-close priority select-priority">
                    <select id="priority" name="priority">
                        <?php
                        // Show the "Click to select"?
                        if ($hesk_settings['select_pri'])
                        {
                            echo '<option value="">'.$hesklang['select'].'</option>';
                        }
                        ?>
                        <?php echo hesk_get_priority_select('', true, $_SESSION['as_priority']); ?>
                    </select>
                </div>
            </div>
            <div class="form-group ts" id="ticket-status-div">
                <label for="status-select"><?php echo $hesklang['status']; ?>:</label>
                <div class="dropdown-select out-close">
                    <select id="status-select" name="status" onchange="hesk_update_status_color(this.value)">
                        <?php echo hesk_get_status_select('', hesk_checkPermission('can_resolve', 0), $_SESSION['as_status']); ?>
                    </select>
                </div>
            </div>

            <!-- START CUSTOM BEFORE -->
            <?php

            foreach ($hesk_settings['custom_fields'] as $k=>$v)
            {
                if ($v['use'] && $v['place']==0 && hesk_is_custom_field_in_category($k, $category) )
                {
                    $v['req'] = $v['req']==2 ? '<span class="important">*</span>' : '';

                    if ($v['type'] == 'checkbox')
                    {
                        $k_value = array();
                        if (isset($_SESSION["as_$k"]) && is_array($_SESSION["as_$k"]))
                        {
                            foreach ($_SESSION["as_$k"] as $myCB)
                            {
                                $k_value[] = stripslashes(hesk_input($myCB));
                            }
                        }
                    }
                    elseif (isset($_SESSION["as_$k"]))
                    {
                        $k_value  = stripslashes(hesk_input($_SESSION["as_$k"]));
                    }
                    else
                    {
                        $k_value  = '';
                    }

                    switch ($v['type'])
                    {
                        /* Radio box */
                        case 'radio':
                            $cls = in_array($k,$_SESSION['iserror']) ? 'isError' : '';

                            echo '
                                <div class="form-group '.$cls.'">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>
                                    <div class="radio-list">';

                            $index = 0;
                            foreach ($v['value']['radio_options'] as $option)
                            {
                                if (strlen($k_value) == 0)
                                {
                                    $k_value = $option;
                                    $checked = empty($v['value']['no_default']) ? 'checked' : '';
                                }
                                elseif ($k_value == $option)
                                {
                                    $k_value = $option;
                                    $checked = 'checked';
                                }
                                else
                                {
                                    $checked = '';
                                }

                                echo '
                                            <div class="radio-custom" style="margin-bottom: 5px">
                                                <input type="radio" id="edit_'.$k.$index.'" name="'.$k.'" value="'.$option.'" '.$checked.'>
                                                <label for="edit_'.$k.$index.'">'.$option.'</label>
                                            </div>';
                                $index++;
                            }
                            echo '</div>
                                </div>';
                            break;

                        /* Select drop-down box */
                        case 'select':

                            $extra_classes = '';
                            $selectize_config = '';
                            $extra_attributes = '';
                            if (!empty($v['value']['is_searchable'])) {
                                $extra_classes .= "read-write";
                                $extra_attributes = ' placeholder="'.hesk_addslashes($hesklang['search_by_pattern']).'"';
                                $selectize_config = '{
                                        valueField: "id",
                                        labelField: "displayName",
                                        searchField: ["displayName"],
                                        create: false,
                                        copyClassesToDropdown: true,
                                        plugins: ["no_results"],
                                    }';
                            }
                            $cls = in_array($k,$_SESSION['iserror']) ? ' class="isError ' . $extra_classes . '" ' : ' class="' . $extra_classes .'" ';

                            echo '
                                <div class="form-group">
                                    <label for="edit_">'.$v['name:'].' '.$v['req'].'</label>
                                        <select name="'.$k.'" id="'.$k.'" '.$cls.$extra_attributes.'>';
                            // Show "Click to select"?
                            if ( ! empty($v['value']['show_select']))
                            {
                                echo '<option value="">'.$hesklang['select'].'</option>';
                            }

                            foreach ($v['value']['select_options'] as $option)
                            {
                                if ($k_value == trim($option))
                                {
                                    $k_value = $option;
                                    $selected = 'selected';
                                }
                                else
                                {
                                    $selected = '';
                                }

                                echo '<option '.$selected.'>'.$option.'</option>';
                            }
                            echo '</select>
                                </div>
                                <script>
                                    $(\'#'.$k.'\').selectize(' . $selectize_config . ');
                                </script>
                                ';
                            break;

                        /* Checkbox */
                        case 'checkbox':
                            $cls = in_array($k,$_SESSION['iserror']) ? 'isError' : '';

                            echo '
                                <div class="form-group '.$cls.'">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>';

                            $index = 0;
                            foreach ($v['value']['checkbox_options'] as $option)
                            {
                                if (in_array($option,$k_value))
                                {
                                    $checked = 'checked';
                                }
                                else
                                {
                                    $checked = '';
                                }

                                echo '
                                    <div class="checkbox-custom">
                                        <input type="checkbox" id="edit_'.$k.$index.'" name="'.$k.'[]" value="'.$option.'" '.$checked.'>
                                        <label for="edit_'.$k.$index.'"> '.$option.'</label>
                                    </div>';
                                $index++;
                            }

                            echo '</div>';
                            break;

                        /* Large text box */
                        case 'textarea':
                            $cls = in_array($k,$_SESSION['iserror']) ? ' isError" ' : '';
                            $k_value = hesk_msgToPlain($k_value,0,0);

                            echo '
                                <div class="form-group">
                                    <label for="text_'. $k .'">'.$v['name:'].' '.$v['req'].'</label>
                                    <textarea id="text_'.$k.'"  name="'.$k.'" class="form-control'.$cls.'" style="height: inherit" rows="'.intval($v['value']['rows']).'" cols="'.intval($v['value']['cols']).'" >'.$k_value.'</textarea>
                                </div>';
                            break;

                        // Date
                        case 'date':
                            $cls = in_array($k,$_SESSION['iserror']) ? 'isErrorStr' : '';
                            if (is_string($k_value) && ($dd = hesk_datepicker_get_date($k_value))) {
                                $hesk_settings['datepicker']['#'.$k]['timestamp'] = $dd->getTimestamp();
                            }
                            echo '
                                <section class="param calendar">
                                    <label class="'.$cls.'" for="'. $k .'">'.$v['name:'].' '.$v['req'].'</label>
                                    <div class="calendar--button">
                                        <button type="button" aria-label="' . $hesklang['date'] . '">
                                            <svg class="icon icon-calendar">
                                                <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-calendar"></use>
                                            </svg>
                                        </button>
                                        <input name="'. $k .'" id="'. $k .'"
                                               value="'. $k_value .'"
                                               type="text" class="datepicker" aria-label="' . $hesklang['date'] . '">
                                    </div>
                                    <div class="calendar--value" '. ($k_value ? 'style="display: block"' : '') . '>
                                        <span class="'. ($cls && ! empty($k_value) ? $cls : '') .'"><i>'. $k_value .'</i></span>
                                        <i class="close">
                                            <svg class="icon icon-close">
                                                <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-close"></use>
                                            </svg>
                                        </i>
                                    </div>
                                </section>';
                            break;

                        // Email
                        case 'email':
                            $cls = in_array($k,$_SESSION['iserror']) ? 'isError' : '';

                            $suggest = $hesk_settings['detect_typos'] ? 'onblur="Javascript:hesk_suggestEmail(\''.$k.'\', \''.$k.'_suggestions\', 0, 1'.($v['value']['multiple'] ? ',1' : '').')"' : '';

                            echo '
                                <div class="form-group">
                                    <label for="'.$k.'">'.$v['name:'].' '.$v['req'].'</label>
                                    <input class="form-control '.$cls.'" type="'.($v['value']['multiple'] ? 'text' : 'email').'" name="'.$k.'" id="'.$k.'" value="'.$k_value.'" size="40" '.$suggest.'>
                                </div>
                                <div id="'.$k.'_suggestions"></div>';
                            break;

                        // Hidden
                        // Handle as text fields for staff

                        /* Default text input */
                        default:
                            if (strlen($k_value) != 0 || isset($_SESSION["as_$k"]))
                            {
                                $v['value']['default_value'] = $k_value;
                            }

                            $cls = in_array($k,$_SESSION['iserror']) ? 'isError' : '';

                            echo '
                                <div class="form-group">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>
                                    <input class="form-control '.$cls.'" type="text" name="'.$k.'" size="40" maxlength="'.intval($v['value']['max_length']).'" value="'.$v['value']['default_value'].'">
                                </div>';
                    }
                }
            }
            ?>
            <!-- END CUSTOM BEFORE -->
            <?php
            // Lets handle ticket templates
            $can_options = '';

            // Get ticket templates from the database
            $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_templates` ORDER BY `tpl_order` ASC");

            // If we have any templates print them out
            if ( hesk_dbNumRows($res) )
            {
                ?>
                <script language="javascript" type="text/javascript"><!--
                    // -->
                    var myMsgTxt = new Array();
                    var mySubjectTxt = new Array();
                    myMsgTxt[0]='';
                    mySubjectTxt[0]='';

                    <?php
                    while ($mysaved = hesk_dbFetchAssoc($res))
                    {
                        $can_options .= '<option value="' . $mysaved['id'] . '">' . $mysaved['title']. "</option>\n";
                        $message_text = $hesk_settings['staff_ticket_formatting'] == 2 ? $mysaved['message_html'] : $mysaved['message'];
                        echo 'myMsgTxt['.$mysaved['id'].']='.hesk_json_encode_for_js($message_text).";\n";
                        echo 'mySubjectTxt['.$mysaved['id'].']='.hesk_json_encode_for_js($mysaved['title']).";\n";
                    }

                    ?>

                    function heskDecodeHtmlEntities(value)
                    {
                        var textarea = document.createElement('textarea');
                        textarea.innerHTML = String(value).replace(/</g, '&lt;').replace(/>/g, '&gt;');
                        return textarea.value;
                    }

                    function setMessage(msgid)
                    {
                        var myMsg=myMsgTxt[msgid];
                        var mySubject=mySubjectTxt[msgid];

                        if (myMsg == '')
                        {
                            if (document.form1.mode[1].checked)
                            {
                            <?php if ($hesk_settings['staff_ticket_formatting'] == 2): ?>
                                tinymce.get("message").setContent('');
                            <?php else: ?>
                                document.getElementById('message').value = '';
                            <?php endif; ?>
                                document.getElementById('subject').value = '';
                            }
                            return true;
                        }
                        if (document.getElementById)
                        {
                            if (document.getElementById('moderep').checked)
                            {
                                <?php if ($hesk_settings['staff_ticket_formatting'] == 2): ?>
                                tinymce.get("message").setContent('');
                                tinymce.get("message").setContent(myMsg);
                                <?php else: ?>
                                document.getElementById('message').value = heskDecodeHtmlEntities(myMsg);
                                <?php endif; ?>
                                document.getElementById('subject').value = heskDecodeHtmlEntities(mySubject);
                            }
                            else
                            {
                                <?php if ($hesk_settings['staff_ticket_formatting'] == 2): ?>
                                var oldMsg = tinymce.get("message").getContent();
                                tinymce.get("message").setContent('');
                                tinymce.get("message").setContent(oldMsg + myMsg);
                                <?php else: ?>
                                var oldMsg = document.getElementById('message').value;
                                document.getElementById('message').value = oldMsg + heskDecodeHtmlEntities(myMsg);
                                <?php endif; ?>
                                if (document.getElementById('subject').value == '')
                                {
                                    document.getElementById('subject').value = heskDecodeHtmlEntities(mySubject);
                                }
                            }
                        }
                        else
                        {
                            if (document.form1.mode[0].checked)
                            {
                                document.form1.message.value=heskDecodeHtmlEntities(myMsg);
                                document.form1.subject.value=heskDecodeHtmlEntities(mySubject);
                            }
                            else
                            {
                                var oldMsg = document.form1.message.value;
                                document.form1.message.value=oldMsg+heskDecodeHtmlEntities(myMsg);
                                if (document.form1.subject.value == '')
                                {
                                    document.form1.subject.value=heskDecodeHtmlEntities(mySubject);
                                }
                            }
                        }

                    }
                    //-->
                </script>
                <?php
            } // END fetchrows

            // Print templates
            if ( strlen($can_options) )
            {
                ?>
                <div class="form-group">
                    <label>
                        <?php echo $hesklang['ticket_tpl']; ?>
                        <?php echo hesk_checkPermission('can_man_ticket_tpl', 0) ? '(<a class="link" href="manage_ticket_templates.php">' . $hesklang['ticket_tpl_man'] . '</a>)' : ''; ?>
                    </label>
                    <div class="radio-list">
                        <div class="radio-custom" style="margin-bottom: 5px">
                            <input type="radio" name="mode" id="modeadd" value="1" checked="checked">
                            <label for="modeadd"><?php echo $hesklang['madd']; ?></label>
                        </div>
                        <div class="radio-custom" style="margin-bottom: 5px">
                            <input type="radio" name="mode" id="moderep" value="0">
                            <label for="moderep"><?php echo $hesklang['mrep']; ?></label>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="saved_replies"><?php echo $hesklang['select_ticket_tpl']; ?>:</label>
                    <div class="dropdown-select out-close">
                        <select id="saved_replies" name="saved_replies" onchange="setMessage(this.value)">
                            <option value="0"> - <?php echo $hesklang['select_empty']; ?> - </option>
                            <?php echo $can_options; ?>
                        </select>
                    </div>
                </div>
                <?php
            } // END printing templates
            elseif ( hesk_checkPermission('can_man_ticket_tpl', 0) )
            {
                ?>
                <div class="form-group">
                    <label><a href="manage_ticket_templates.php" class="link"><?php echo $hesklang['ticket_tpl_man']; ?></a></label>
                </div>
                <?php
            }
            ?>
            <div class="form-group">
                <label for="subject"><?php echo $hesklang['subject'] . ': ' . ($hesk_settings['require_subject']==1 ? '<span class="important">*</span>' : '') ; ?></label>
                <span id="HeskSub"><input class="form-control <?php if (in_array('subject',$_SESSION['iserror'])) {echo 'isError';} ?>" type="text" name="subject" id="subject" maxlength="70" value="<?php if (isset($_SESSION['as_subject'])) {echo stripslashes(hesk_input($_SESSION['as_subject']));} ?>" <?php echo $hesk_settings['disable_autofill_admin'] ? 'autocomplete="off" aria-autocomplete="none"' : ''; ?>></span>
            </div>
            <div class="form-group">
                <label for="message"><?php echo $hesklang['message'] . ': ' . ($hesk_settings['require_message']==1 ? '<span class="important">*</span>' : '') ; ?></label>
                <span id="HeskMsg">
                    <textarea style="height: inherit" class="form-control <?php if (in_array('message',$_SESSION['iserror'])) {echo 'isError';} ?>"
                              name="message" id="message" rows="12" cols="60" aria-label="<?php echo $hesklang['message']; ?>"><?php if (isset($_SESSION['as_message'])) {echo stripslashes(hesk_input($_SESSION['as_message']));} ?></textarea>
                </span>
            </div>
            <?php
            if ($hesk_settings['staff_ticket_formatting'] == 2) {
                hesk_tinymce_init('#message');
            }

            /* custom fields AFTER comments */
            foreach ($hesk_settings['custom_fields'] as $k=>$v)
            {
                if ($v['use'] && $v['place']==1 && hesk_is_custom_field_in_category($k, $category) )
                {
                    $v['req'] = $v['req']==2 ? '<span class="important">*</span>' : '';

                    if ($v['type'] == 'checkbox')
                    {
                        $k_value = array();
                        if (isset($_SESSION["as_$k"]) && is_array($_SESSION["as_$k"]))
                        {
                            foreach ($_SESSION["as_$k"] as $myCB)
                            {
                                $k_value[] = stripslashes(hesk_input($myCB));
                            }
                        }
                    }
                    elseif (isset($_SESSION["as_$k"]))
                    {
                        $k_value  = stripslashes(hesk_input($_SESSION["as_$k"]));
                    }
                    else
                    {
                        $k_value  = '';
                    }

                    switch ($v['type'])
                    {
                        /* Radio box */
                        case 'radio':
                            echo '
                                <div class="form-group">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>
                                    <div class="radio-list">';

                            $cls = in_array($k,$_SESSION['iserror']) ? ' class="isError" ' : '';

                            $index = 0;
                            foreach ($v['value']['radio_options'] as $option)
                            {
                                if (strlen($k_value) == 0)
                                {
                                    $k_value = $option;
                                    $checked = empty($v['value']['no_default']) ? 'checked' : '';
                                }
                                elseif ($k_value == $option)
                                {
                                    $k_value = $option;
                                    $checked = 'checked';
                                }
                                else
                                {
                                    $checked = '';
                                }

                                echo '
                                            <div class="radio-custom" style="margin-bottom: 5px">
                                                <input type="radio" id="edit_'.$k.$index.'" name="'.$k.'" value="'.$option.'" '.$checked.' '.$cls.'>
                                                <label for="edit_'.$k.$index.'">'.$option.'</label>
                                            </div>';
                                $index++;
                            }
                            echo '</div>
                                </div>';
                            break;

                        /* Select drop-down box */
                        case 'select':

                            $extra_classes = '';
                            $selectize_config = '';
                            $extra_attributes = '';
                            if (!empty($v['value']['is_searchable'])) {
                                $extra_classes .= "read-write";
                                $extra_attributes = ' placeholder="'.hesk_addslashes($hesklang['search_by_pattern']).'"';
                                $selectize_config = '{
                                    valueField: "id",
                                    labelField: "displayName",
                                    searchField: ["displayName"],
                                    create: false,
                                    copyClassesToDropdown: true,
                                    plugins: ["no_results"],
                                }';
                            }

                            $cls = in_array($k,$_SESSION['iserror']) ? ' class="isError ' . $extra_classes . '" ' : ' class="' . $extra_classes .'" ';

                            echo '
                                <div class="form-group">
                                    <label for="edit_">'.$v['name:'].' '.$v['req'].'</label>
                                        <select name="'.$k.'" id="'.$k.'" '.$cls.$extra_attributes.'">';
                            // Show "Click to select"?
                            if ( ! empty($v['value']['show_select']))
                            {
                                echo '<option value="">'.$hesklang['select'].'</option>';
                            }

                            foreach ($v['value']['select_options'] as $option)
                            {
                                if ($k_value == trim($option))
                                {
                                    $k_value = $option;
                                    $selected = 'selected';
                                }
                                else
                                {
                                    $selected = '';
                                }

                                echo '<option '.$selected.'>'.$option.'</option>';
                            }
                            echo '</select>
                                </div>
                                <script>
                                    $(\'#'.$k.'\').selectize(' . $selectize_config . ');
                                </script>
                                ';
                            break;

                        /* Checkbox */
                        case 'checkbox':
                            echo '
                                <div class="form-group">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>';

                            $cls = in_array($k,$_SESSION['iserror']) ? ' class="isError" ' : '';

                            $index = 0;
                            foreach ($v['value']['checkbox_options'] as $option)
                            {
                                if (in_array($option,$k_value))
                                {
                                    $checked = 'checked';
                                }
                                else
                                {
                                    $checked = '';
                                }

                                echo '
                                    <div class="checkbox-custom">
                                        <input type="checkbox" id="edit_'.$k.$index.'" name="'.$k.'[]" value="'.$option.'" '.$checked.' '.$cls.'>
                                        <label for="edit_'.$k.$index.'"> '.$option.'</label>
                                    </div>';
                                $index++;
                            }

                            echo '</div>';
                            break;

                        /* Large text box */
                        case 'textarea':
                            $cls = in_array($k,$_SESSION['iserror']) ? ' isError" ' : '';
                            $k_value = hesk_msgToPlain($k_value,0,0);

                            echo '
                                <div class="form-group">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>
                                    <textarea name="'.$k.'" class="form-control'.$cls.'" style="height: inherit" rows="'.intval($v['value']['rows']).'" cols="'.intval($v['value']['cols']).'" >'.$k_value.'</textarea>
                                </div>';
                            break;

                        // Date
                        case 'date':
                            $cls = in_array($k,$_SESSION['iserror']) ? 'isErrorStr' : '';
                            if (is_string($k_value) && ($dd = hesk_datepicker_get_date($k_value))) {
                                $hesk_settings['datepicker']['#'.$k]['timestamp'] = $dd->getTimestamp();
                            }
                            echo '
                                <section class="param calendar">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>
                                    <div class="calendar--button">
                                        <button type="button" aria-label="' . $hesklang['date'] . '">
                                            <svg class="icon icon-calendar">
                                                <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-calendar"></use>
                                            </svg>
                                        </button>
                                        <input name="'. $k .'" id="'. $k .'"
                                               value="'. $k_value .'"
                                               type="text" class="datepicker" aria-label="' . $hesklang['date'] . '>
                                    </div>
                                    <div class="calendar--value" '. ($k_value ? 'style="display: block"' : '') . '>
                                        <span class="'. $cls .'"><i>'. $k_value .'</i></span>
                                        <i class="close">
                                            <svg class="icon icon-close">
                                                <use xlink:href="'. HESK_PATH .'img/sprite.svg#icon-close"></use>
                                            </svg>
                                        </i>
                                    </div>
                                </section>';
                            break;

                        // Email
                        case 'email':
                            $cls = in_array($k,$_SESSION['iserror']) ? 'isError' : '';

                            $suggest = $hesk_settings['detect_typos'] ? 'onblur="Javascript:hesk_suggestEmail(\''.$k.'\', \''.$k.'_suggestions\', 0, 1'.($v['value']['multiple'] ? ',1' : '').')"' : '';

                            echo '
                                <div class="form-group">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>
                                    <input class="form-control '.$cls.'" type="'.($v['value']['multiple'] ? 'text' : 'email').'" name="'.$k.'" id="'.$k.'" value="'.$k_value.'" size="40" '.$suggest.'>
                                </div>
                                <div id="'.$k.'_suggestions"></div>';
                            break;

                        // Hidden
                        // Handle as text fields for staff

                        /* Default text input */
                        default:
                            if (strlen($k_value) != 0 || isset($_SESSION["as_$k"]))
                            {
                                $v['value']['default_value'] = $k_value;
                            }

                            $cls = in_array($k,$_SESSION['iserror']) ? 'isError' : '';

                            echo '
                                <div class="form-group">
                                    <label>'.$v['name:'].' '.$v['req'].'</label>
                                    <input class="form-control '.$cls.'" type="text" name="'.$k.'" size="40" maxlength="'.intval($v['value']['max_length']).'" value="'.$v['value']['default_value'].'">
                                </div>';
                    }
                }
            }
            ?>
            <!-- END CUSTOM AFTER -->

            <?php
            /* attachments */
            if ($hesk_settings['attachments']['use']) {
                require(HESK_PATH . 'inc/attachments.inc.php');
                ?>
                <div class="attachments">
                    <div class="block--attach">
                        <svg class="icon icon-attach">
                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-attach"></use>
                        </svg>
                        <div>
                            <?php echo $hesklang['attachments']; ?>:
                        </div>
                    </div>
                    <?php
                    build_dropzone_markup(true);
                    display_dropzone_field(HESK_PATH . 'upload_attachment.php', true);
                    dropzone_display_existing_files(hesk_SESSION_array('as_attachments'));
                    ?>
                </div>
                <?php
            }

            // Admin options
            if ( ! isset($_SESSION['as_notify']) )
            {
                $_SESSION['as_notify'] = $_SESSION['notify_customer_new'] ? 1 : 0;
            }
            ?>
            <div class="form-group" style="margin-top: 20px">
                <label><?php echo $hesklang['addop']; ?>:</label>
                <div class="checkbox-list">
                    <div class="checkbox-custom">
                        <input type="checkbox" id="create_notify1" name="notify" value="1" <?php echo empty($_SESSION['as_notify']) ? '' : 'checked'; ?>>
                        <label for="create_notify1"><?php echo $hesklang['seno']; ?></label>
                    </div>
                    <?php if (hesk_checkPermission('can_view_tickets',0)): ?>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="create_show1" name="show" value="1" <?php echo (!isset($_SESSION['as_show']) || !empty($_SESSION['as_show'])) ? 'checked' : ''; ?>>
                        <label for="create_show1"><?php echo $hesklang['otas']; ?></label>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php if ($can_due_date): ?>
            <section class="param calendar">
                <?php
                // Default due date
                $default_due_date_info = hesk_getCategoryDueDateInfo($category);

                $due_date = isset($_SESSION['as_due_date']) ? $_SESSION['as_due_date'] : null;
                if ($due_date && ($dd = hesk_datepicker_get_date($due_date))) {
                    $hesk_settings['datepicker']['#due_date']['timestamp'] = $dd->getTimestamp();
                } elseif ($default_due_date_info !== null && $due_date === null) {
                    $current_date = new DateTime('today midnight');
                    $current_date->add(DateInterval::createFromDateString("+{$default_due_date_info['amount']} {$default_due_date_info['unit']}s"));
                    $hesk_settings['datepicker']['#due_date']['timestamp'] = $current_date->getTimestamp();
                    $due_date = hesk_datepicker_format_date($current_date->getTimestamp());
                }
                ?>
                <label for="due_date"><?php echo $hesklang['due_date']; ?>:</label>
                <div class="calendar--button">
                    <button type="button" aria-label="<?php echo $hesklang['due_date']; ?>">
                        <svg class="icon icon-calendar">
                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-calendar"></use>
                        </svg>
                    </button>
                    <input name="due_date" id="due_date"
                           value="<?php if (isset($due_date)) {echo stripslashes(hesk_input($due_date));} ?>"
                           type="text" class="datepicker" aria-label="<?php echo $hesklang['due_date']; ?>">
                </div>
                <div class="calendar--value" style="<?php echo empty($due_date) ? '' : 'display: block'; ?>">
                <span><?php echo isset($due_date) ? stripslashes($due_date) : ''; ?></span>
                <i class="close">
                    <svg class="icon icon-close">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                    </svg>
                </i>
                </div>
            </section>
            <br>
            <?php endif; ?>
            <?php if ($hesk_settings['can_sel_lang']): ?>
            <div class="form-group">
                <label for="as_language"><?php echo $hesklang['tlan']; ?>:</label>
                <select name="as_language" id="as_language">
                    <?php
                        if (isset($_SESSION['as_language']) && isset($hesk_settings['languages'][$_SESSION['as_language']]))
                        {
                            $hesk_settings['language_copy'] = $hesk_settings['language'];
                            $hesk_settings['language'] = $_SESSION['as_language'];
                            hesk_listLanguages();
                            $hesk_settings['language'] = $hesk_settings['language_copy'];
                        }
                        else
                        {
                            hesk_listLanguages();
                        }
                    ?>
                </select>
            </div>
            <script>
                $('#as_language').selectize();
            </script>
            <?php endif; ?>
            <?php if (hesk_checkPermission('can_assign_others',0)) { ?>
                <div class="form-group">
                    <label><?php echo $hesklang['asst2']; ?>:</label>
                        <select name="owner" id="owner-select" <?php if (in_array('owner',$_SESSION['iserror'])) {echo ' class="isError" ';} ?>>
                            <option value="-1"> &gt; <?php echo $hesklang['unas']; ?> &lt; </option>
                            <?php

                            if ($hesk_settings['autoassign'])
                            {
                                $select = ( ! isset($_SESSION['as_owner']) && ! empty($hesk_settings['categories'][$category]['autoassign']) ) ? 'selected="selected"' : '';
                                echo '<option value="-2" '.$select.'> &gt; ' . $hesklang['aass'] . ' &lt; </option>';
                            }

                            $owner = isset($_SESSION['as_owner']) ? intval($_SESSION['as_owner']) : 0;

                            foreach ($admins as $k=>$v)
                            {
                                if ($k == $owner)
                                {
                                    echo '<option value="'.$k.'" selected="selected">'.$v.'</option>';
                                }
                                else
                                {
                                    echo '<option value="'.$k.'">'.$v.'</option>';
                                }

                            }
                            ?>
                        </select>
                        <script>
                            $('#owner-select').selectize();
                        </script>
                </div>
                <?php
            }
            elseif (hesk_checkPermission('can_assign_self',0))
            {
                $checked = (!isset($_SESSION['as_owner']) || !empty($_SESSION['as_owner'])) ? 'checked' : '';
                ?>
                <div class="form-group">
                    <label><?php echo $hesklang['owner']; ?></label>
                    <div class="checkbox-custom">
                        <input type="checkbox" id="create_assing_to_self1" name="assing_to_self" value="1" <?php echo $checked; ?>>
                        <label for="create_assing_to_self1"><?php echo $hesklang['asss2']; ?></label>
                    </div>
                </div>
                <?php
            }
            ?>

            <?php if ( defined('HESK_DEMO') ): ?>
                 <?php hesk_show_notice(sprintf($hesklang['antdemo'], 'https://www.hesk.com/demo/index.php?a=add')); ?>
                <button class="btn btn-full" id="recaptcha-submit"><?php echo $hesklang['sub_ticket']; ?></button>
            <?php else: ?>
                <button type="submit" class="btn btn-full" id="recaptcha-submit"><?php echo $hesklang['sub_ticket']; ?></button>
            <?php endif; ?>
            <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
            <input type="hidden" name="category" value="<?php echo $category; ?>">
        </form>
        <p>&nbsp;</p>
        <p>&nbsp;</p>
        <p>&nbsp;</p>
        <p>&nbsp;</p>
        <p>&nbsp;</p>
    </div>
</div>

<?php
    //Common include for the "Create Customer / Follower" 
    require_once(HESK_PATH . 'inc/customer_modal.inc.php'); 
?>

<div id="loading-overlay" class="loading-overlay">
    <div id="loading-message" class="loading-message">
        <div class="spinner"></div>
        <p><?php echo $hesklang['sending_wait']; ?></p>
    </div>
</div>
<?php

hesk_cleanSessionVars('iserror');
hesk_cleanSessionVars('isnotice');

// Clearing it out, otherwise users could delete an attachment, refresh, and it'll "supposedly" be back
hesk_cleanSessionVars('as_attachments');

$hesk_settings['print_status_select_box_jquery'] = true;

require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/


function print_select_category($number_of_categories)
{
	global $hesk_settings, $hesklang;

	// A categoy needs to be selected
	if (isset($_GET['category']) && empty($_GET['category']))
	{
		hesk_process_messages($hesklang['sel_app_cat'],'NOREDIRECT','NOTICE');
	}

    /* This will handle error, success and notice messages */
    hesk_handle_messages();
    ?>
    <div class="main__content categories">
        <?php
        // Print a select box if number of categories is large
        if ($number_of_categories > $hesk_settings['cat_show_select']) {
            ?>
            <div class="table-wrap">
                <h2 class="select__title-alt"><?php echo $hesklang['select_category_staff']; ?></h2>
                <form action="new_ticket.php" method="get" class="form" aria-label="<?php echo $hesklang['select_category']; ?>">
                    <select class="form-control" name="category" id="select_category">
                        <?php
                        if ($hesk_settings['select_cat'])
                        {
                            echo '<option value="">'.$hesklang['select'].'</option>';
                        }
                        foreach ($hesk_settings['categories'] as $k=>$v)
                        {
                            echo '<option value="'.$k.'">'.$v['name'].'</option>';
                        }
                        ?>
                    </select>
                    <button style="margin-top: 10px" type="submit" class="btn btn-full"><?php echo $hesklang['c2c']; ?></button>
                </form>
                <script>
                    $(document).ready(function() {
                        $('#select_category').selectize();
                    });
                </script>
            </div>
            <?php
        }
        // Otherwise print quick links
        else
        {
            ?>
            <h2 class="select__title"><?php echo $hesklang['select_category_staff']; ?></h2>
            <div class="nav">
                <?php foreach ($hesk_settings['categories'] as $k => $v): ?>
                <a href="new_ticket.php?a=add&amp;category=<?php echo $k; ?>" class="navlink <?php if ($number_of_categories > 8) echo "navlink-condensed"; ?>">
                    <div class="icon-in-circle">
                        <svg class="icon icon-chevron-right">
                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-right"></use>
                        </svg>
                    </div>
                    <div>
                        <h5 class="navlink__title"><!--[if IE]> &raquo; <![endif]--><?php echo $v['name']; ?></h5>
                    </div>
                </a>
                <?php endforeach; ?>
            </div>
            <?php
        }
        ?>
    </div>
    <?php

	hesk_cleanSessionVars('iserror');
	hesk_cleanSessionVars('isnotice');
    hesk_cleanSessionVars('as_priority');

	require_once(HESK_PATH . 'inc/footer.inc.php');
	exit();
} // END print_select_category()


function hesk_new_ticket_reset_data()
{
    global $hesk_settings;

    // Already reset
    if (isset($hesk_settings['POPULATE_DATA_RESET'])) {
        return true;
    }

    hesk_cleanSessionVars('as_customer_id');
    hesk_cleanSessionVars('as_follower_ids');
    hesk_cleanSessionVars('as_name');
    hesk_cleanSessionVars('as_email');
    hesk_cleanSessionVars('as_category');
    hesk_cleanSessionVars('as_priority');
    hesk_cleanSessionVars('as_status');
    hesk_cleanSessionVars('as_subject');
    hesk_cleanSessionVars('as_message');
    hesk_cleanSessionVars('as_owner');
    hesk_cleanSessionVars('as_notify');
    hesk_cleanSessionVars('as_show');
    hesk_cleanSessionVars('as_due_date');
    hesk_cleanSessionVars('as_language');
    foreach ($hesk_settings['custom_fields'] as $k=>$v) {
        hesk_cleanSessionVars("as_$k");
    }

    $hesk_settings['POPULATE_DATA_RESET'] = true;

    return true;

} // END hesk_new_ticket_reset_data()
oauth_providers.php
wget 'https://lists2.roe3.org/hesk/admin/oauth_providers.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

define('LOAD_TABS',1);

// Get all the req files and functions
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/setup_functions.inc.php');
require(HESK_PATH . 'inc/oauth_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_man_settings');

$help_folder = '../language/' . $hesk_settings['languages'][$hesk_settings['language']]['folder'] . '/help_files/';

// What should we do?
if ( $action = hesk_REQUEST('a') )
{
	if ($action == 'edit_provider') {edit_provider();}
	elseif ( defined('HESK_DEMO') ) {hesk_process_messages($hesklang['ddemo'], 'oauth_providers.php', 'NOTICE');}
	elseif ($action == 'new_provider') {new_provider();}
	elseif ($action == 'save_provider') {save_provider();}
	elseif ($action == 'remove_provider') {remove_provider();}
    elseif ($action == 'verify_provider') {verify_provider();}
} elseif (hesk_GET('state') !== '') {
    //-- OAuth response
    $provider_id = hesk_oauth_verify_provider_state(hesk_GET('state'));

    if ($provider_id === false) {
        hesk_process_messages($hesklang['oauth_error_invalid_state'], './oauth_providers.php');
        exit();
    }

    //-- Get provider data and confirm the provider actually exists
    $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."oauth_providers` WHERE `id`={$provider_id}");

    if (hesk_dbNumRows($res) != 1) {
        hesk_process_messages($hesklang['oauth_provider_not_found'], './oauth_providers.php');
        exit();
    }

    $provider = hesk_dbFetchAssoc($res);

    // Any errors so far?
    if (($error = hesk_GET('error')) !== '') {
        $error_description = hesk_GET('error_description');
        hesk_process_messages(hesk_htmlspecialchars($error) . '<br><br>' . hesk_htmlspecialchars($error_description), './oauth_providers.php');
        exit();
    }

    //-- Mark the provider as valid and grab the initial token
    hesk_oauth_fetch_and_store_initial_token($provider, hesk_GET('code'));
}

// Print header
require_once(HESK_PATH . 'inc/header.inc.php');

// Print main manage users page
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

// We need cURL for OAuth
$hesk_settings['curl_enabled'] = function_exists('curl_init');
if ( ! $hesk_settings['curl_enabled']) {
    hesk_show_error($hesklang['require_curl']);
}

/* This will handle error, success and notice messages */
if (!hesk_SESSION('edit_provider') && !hesk_SESSION(array('new_provider','errors'))) {
    hesk_handle_messages();
}

$oauth_providers_rs = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."oauth_providers`");
?>
<div class="main__content tools">
    <section class="tools__between-head">
        <h2>
            <?php echo $hesklang['email_oauth_providers']; ?>
            <div class="tooltype right out-close">
                <svg class="icon icon-info">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                </svg>
                <div class="tooltype__content">
                    <div class="tooltype__wrapper">
                        <?php echo $hesklang['email_oauth_providers_intro']; ?>
                    </div>
                </div>
            </div>
        </h2>
        <?php if ($hesk_settings['curl_enabled'] && $action !== 'edit_provider'): ?>
        <div class="btn btn--blue-border" ripple="ripple" data-action="create-custom-status">
            <?php echo $hesklang['email_oauth_new_provider']; ?>
        </div>
        <?php endif; ?>
    </section>
    <div class="table-wrapper status">
        <div class="table">
            <table id="default-table" class="table sindu-table">
                <thead>
                <tr>
                    <th><?php echo $hesklang['email_oauth_provider_name']; ?></th>
                    <th><?php echo $hesklang['email_oauth_provider_being_used_for']; ?></th>
                    <th><?php echo $hesklang['oauth_provider_verified']; ?></th>
                    <th aria-label="Actions"></th>
                </tr>
                </thead>
                <tbody>
                <?php if (hesk_dbNumRows($oauth_providers_rs) === 0): ?>
                <tr>
                    <td colspan="4"><?php echo $hesklang['email_oauth_providers_none']; ?></td>
                </tr>
                <?php endif; ?>
                <?php while ($row = hesk_dbFetchAssoc($oauth_providers_rs)):
                    $in_use = getProviderInUseArray($row['id']);
                    if (count($in_use)) {
                        $uses = implode(', ', $in_use);
                    } else {
                        $uses = $hesklang['none'];
                    }
                    ?>
                <tr>
                    <td><?php echo hesk_htmlspecialchars($row['name']); ?></td>
                    <td><?php echo hesk_htmlspecialchars($uses); ?></td>
                    <td>
                        <?php if ($row['verified']):
                            echo $hesklang['yes'];
                        else:
                            echo $hesklang['no']; ?>
                            <a href="oauth_providers.php?a=verify_provider&id=<?php echo $row['id'] ?>&token=<?php hesk_token_echo(); ?>" class="link">
                                (<?php echo $hesklang['oauth_provider_click_to_verify']; ?>)
                            </a>
                        <?php endif; ?>
                    </td>
                    <td class="nowrap buttons">
                        <?php $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                            $hesklang['email_oauth_confirm_delete_provider'],
                            'oauth_providers.php?a=remove_provider&amp;id='. $row['id'] .'&amp;token='. hesk_token_echo(0)); ?>
                        <p>
                            <a href="oauth_providers.php?a=edit_provider&amp;id=<?php echo $row['id']; ?>" class="edit tooltip" title="<?php echo $hesklang['edit']; ?>">
                                <svg class="icon icon-edit-ticket">
                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-edit-ticket"></use>
                                </svg>
                            </a>
                            <?php if ($uses !== $hesklang['none']): ?>
                                <a onclick="alert('<?php echo hesk_makeJsString($hesklang['email_oauth_provider_cannot_be_deleted']); ?>');"
                                   class="delete tooltip not-allowed"
                                   title="<?php echo $hesklang['email_oauth_provider_cannot_be_deleted']; ?>">
                                    <svg class="icon icon-delete">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-delete"></use>
                                    </svg>
                                </a>
                            <?php else: ?>
                                <a class="delete tooltip" title="<?php echo $hesklang['delete']; ?>" href="javascript:" data-modal="[data-modal-id='<?php echo $modal_id; ?>']">
                                    <svg class="icon icon-delete">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-delete"></use>
                                    </svg>
                                </a>
                            <?php
                            endif;
                            ?>
                        </p>
                    </td>
                </tr>
                <?php endwhile;?>
                </tbody>
            </table>
            <?php hesk_show_notice(sprintf($hesklang['email_oauth_provider_guide'], 'https://www.hesk.com/knowledgebase/?article=111'), ' ', false); ?>
        </div>
    </div>
</div>
<div class="right-bar create-status" <?php echo hesk_SESSION('edit_provider') || hesk_SESSION(array('new_provider','errors')) ? 'style="display: block"' : ''; ?>>
    <form action="oauth_providers.php" method="post" name="form1" class="form
        <?php echo hesk_SESSION(array('new_provider','errors')) ? 'invalid' : ''; ?>" autocomplete="off" aria-label="<?php echo $hesklang['email_oauth_edit_provider']; ?>">
        <div class="right-bar__body form">
            <h3>
                <a href="<?php echo hesk_SESSION('edit_provider') ? 'oauth_providers.php' : 'javascript:'; ?>">
                    <svg class="icon icon-back">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                    </svg>
                    <span><?php echo hesk_SESSION('edit_provider') ? $hesklang['email_oauth_edit_provider'] : $hesklang['email_oauth_new_provider']; ?></span>
                </a>
            </h3>
            <?php
            /* This will handle error, success and notice messages */
            if (hesk_SESSION(array('new_provider', 'errors'))) {
                echo '<div style="margin: -24px -24px 10px -16px;">';
                hesk_handle_messages();
                echo '</div>';
            }

            $provider_name = hesk_SESSION(array('new_provider','name'));
            $authorization_url = hesk_SESSION(array('new_provider','authorization_url'));
            $token_url = hesk_SESSION(array('new_provider','token_url'));
            $client_id = hesk_SESSION(array('new_provider','client_id'));
            $client_secret = hesk_SESSION(array('new_provider','client_secret'));
            $scope = hesk_SESSION(array('new_provider','scope'));
            $no_val_ssl = hesk_SESSION(array('new_provider','no_val_ssl'));
            $errors = hesk_SESSION(array('new_provider','errors'));
            $errors = is_array($errors) ? $errors : array();

            if ( ! hesk_SESSION('edit_provider') && isset($_SERVER['HTTP_HOST']) && isset($_SERVER['REQUEST_URI'])) {
                $oauth_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
                $oauth_link = hesk_clean_utf8($oauth_link);
                ?>
                <p><?php echo sprintf($hesklang['email_oauth_provider_uri'], '<a href="oauth_providers.php">' . hesk_htmlspecialchars($oauth_link) . '</a>'); ?></p>
                <p>&nbsp;</p>
                <?php
            }
            ?>
            <div class="form-group">
                <label for="p_name"><?php echo $hesklang['email_oauth_provider_name']; ?></label>
                <input type="text" class="form-control <?php echo in_array('name', $errors) ? 'isError' : ''; ?>" id="p_name" name="name"
                       value="<?php echo hesk_htmlspecialchars($provider_name); ?>" autocomplete="new-password">
            </div>
            <div class="form-group">
                <label for="authorization_url"><?php echo $hesklang['email_oauth_auth_url']; ?></label>
                <input type="text" class="form-control <?php echo in_array('authorization_url', $errors) ? 'isError' : ''; ?>" id="authorization_url" name="authorization_url"
                       value="<?php echo hesk_htmlspecialchars($authorization_url); ?>" placeholder="https://">
            </div>
            <div class="form-group">
                <label for="token_url"><?php echo $hesklang['email_oauth_token_url']; ?></label>
                <input type="text" class="form-control <?php echo in_array('token_url', $errors) ? 'isError' : ''; ?>" id="token_url" name="token_url"
                       value="<?php echo hesk_htmlspecialchars($token_url); ?>" placeholder="https://">
            </div>
            <div class="form-group">
                <label for="client_id"><?php echo $hesklang['email_oauth_client_id']; ?></label>
                <input type="text" class="form-control <?php echo in_array('client_id', $errors) ? 'isError' : ''; ?>" id="client_id" name="client_id"
                       value="<?php echo hesk_htmlspecialchars($client_id); ?>">
            </div>
            <div class="form-group">
                <label for="client_secret"><?php echo $hesklang['email_oauth_client_secret']; ?></label>
                <input type="text" class="form-control <?php echo in_array('client_secret', $errors) ? 'isError' : ''; ?>" id="client_secret" name="client_secret"
                       value="<?php echo hesk_htmlspecialchars($client_secret); ?>">
            </div>
            <div class="form-group">
                <label for="scope"><?php echo $hesklang['email_oauth_scope']; ?></label>
                <input type="text" class="form-control <?php echo in_array('scope', $errors) ? 'isError' : ''; ?>" id="scope" name="scope"
                       value="<?php echo hesk_htmlspecialchars($scope); ?>">
            </div>
            <div id="form-group">
                <div class="checkbox-custom">
                    <input type="checkbox" id="no_val_ssl" name="no_val_ssl" value="1" <?php if ($no_val_ssl) {echo 'checked';} ?>>
                    <label for="no_val_ssl"><?php echo $hesklang['noval_cert']; ?></label>
                    <a onclick="hesk_window('<?php echo $help_folder; ?>email.html#68','400','500')">
                        <div class="tooltype right" style="margin-left: 8px;">
                            <svg class="icon icon-info">
                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                            </svg>
                        </div>
                    </a>
                </div>
            </div>

            <div style="display: flex; gap: 10px;">
            <?php if (isset($_SESSION['edit_provider'])): ?>
                <input type="hidden" name="a" value="save_provider">
                <input type="hidden" name="id" value="<?php echo intval($_SESSION['new_provider']['id']); ?>">
            <?php else: ?>
                <input type="hidden" name="a" value="new_provider">
            <?php endif; ?>
            <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
            <a href="oauth_providers.php" class="btn btn-border save" style=""><?php echo $hesklang['cancel']; ?></a>
            <button type="submit" class="btn btn-full save" ripple="ripple"><?php echo $hesklang['status_save']; ?></button>
            </div>
        </div>
    </form>
</div>
<?php

hesk_cleanSessionVars( array('new_provider', 'edit_provider') );

require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/


function save_provider()
{
	global $hesk_settings, $hesklang;
	global $hesk_error_buffer;

	// A security check
	hesk_token_check('POST');

	// Get ID
	$id = intval( hesk_POST('id') ) or hesk_error($hesklang['status_e_id']);

	// Validate inputs
	if (($provider = provider_validate()) == false)
	{
		$_SESSION['edit_provider'] = true;
		$_SESSION['new_provider']['id'] = $id;

		$tmp = '';
		foreach ($hesk_error_buffer as $error)
		{
			$tmp .= "<li>$error</li>\n";
		}
		$hesk_error_buffer = $tmp;

		$hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
		hesk_process_messages($hesk_error_buffer,'oauth_providers.php');
	}

	// Save the provider
	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."oauth_providers` SET
	`name` = '".hesk_dbEscape($provider['name'])."',
	`authorization_url` = '".hesk_dbEscape($provider['authorization_url'])."',
	`token_url` = '".hesk_dbEscape($provider['token_url'])."',
	`client_id` = '".hesk_dbEscape($provider['client_id'])."',
	`client_secret` = '".hesk_dbEscape($provider['client_secret'])."',
	`scope` = '".hesk_dbEscape($provider['scope'])."',
	`no_val_ssl` = ".intval($provider['no_val_ssl']).",
    `verified` = 0
	WHERE `id`={$id}");

    // Redirect to OAuth provider for verification
    redirect_to_provider($provider, $id);

    /* TODO: only verify if needed?
    // If something changed in the DB, redirect to OAuth provider for verification
    if (hesk_dbAffectedRows() > 0) {
        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."oauth_providers` SET `verified` = 0 WHERE `id`={$id}");
        redirect_to_provider($provider, $id);
    }

    // No changes to the DB
    hesk_process_messages($hesklang['oauth_provider_saved'], 'NOREDIRECT', 'SUCCESS');
    */

} // End save_provider()


function edit_provider()
{
	global $hesk_settings, $hesklang;

	// Get ID
	$id = intval( hesk_GET('id') ) or hesk_error($hesklang['status_e_id']);

	// Get details from the database
	$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."oauth_providers` WHERE `id`={$id} LIMIT 1");
	if ( hesk_dbNumRows($res) != 1 )
	{
		hesk_error($hesklang['oauth_provider_not_found']);
	}
	$provider = hesk_dbFetchAssoc($res);

    if (defined('HESK_DEMO')) {
        $provider['authorization_url'] = 'https://api.example.com/oauth2/authorization';
        $provider['token_url'] = 'https://api.example.com/oauth2/token';
        $provider['client_id'] = $hesklang['hdemo'];
        $provider['client_secret'] = $hesklang['hdemo'];
    }

	$_SESSION['new_provider'] = $provider;
	$_SESSION['edit_provider'] = true;

} // End edit_provider()


function remove_provider()
{
	global $hesk_settings, $hesklang;

	// A security check
	hesk_token_check();

	// Get ID
	$id = intval( hesk_GET('id') ) or hesk_error($hesklang['status_e_id']);

    // Provider being used?
    if (count(getProviderInUseArray($id))) {
        hesk_process_messages($hesklang['email_oauth_provider_cannot_be_deleted'], './oauth_providers.php');
        return;
    }

	// Delete the provider
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."oauth_tokens` WHERE `provider_id`={$id}");
	hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."oauth_providers` WHERE `id`={$id}");

	// Were we successful?
	if ( hesk_dbAffectedRows() == 1 )
	{
		// Show success message
		hesk_process_messages($hesklang['oauth_provider_deleted'],'./oauth_providers.php','SUCCESS');
	}
	else
	{
		hesk_process_messages($hesklang['oauth_provider_not_found'],'./oauth_providers.php');
	}

} // End remove_provider()


function provider_validate()
{
	global $hesk_settings, $hesklang;
	global $hesk_error_buffer;

	$hesk_error_buffer = array();
    $provider = array();
    $errors = array();

	// Get name
	$provider['name'] = hesk_input(hesk_POST('name'));
    if (strlen($provider['name']) < 1) {
        $errors[] = 'name';
        $hesk_error_buffer[] = $hesklang['oauth_provider_err_name'];
    }

    // Auth URL
    $provider['authorization_url'] = hesk_validateURL(hesk_POST('authorization_url'));
    if (strlen($provider['authorization_url']) < 1) {
        $errors[] = 'authorization_url';
        $hesk_error_buffer[] = $hesklang['oauth_provider_err_auth_url'];
    }

    // Token URL
    $provider['token_url'] = hesk_validateURL(hesk_POST('token_url'));
    if (strlen($provider['token_url']) < 1) {
        $errors[] = 'token_url';
        $hesk_error_buffer[] = $hesklang['oauth_provider_err_token_url'];
    }

    // Client ID
    $provider['client_id'] = hesk_input(hesk_POST('client_id'), 0, 0, HESK_SLASH);
    if (strlen($provider['client_id']) < 1) {
        $errors[] = 'client_id';
        $hesk_error_buffer[] = $hesklang['oauth_provider_err_client_id'];
    }

    // Client Secret
    $provider['client_secret'] = hesk_input(hesk_POST('client_secret'), 0, 0, HESK_SLASH);
    if (strlen($provider['client_secret']) < 1) {
        $errors[] = 'client_secret';
        $hesk_error_buffer[] = $hesklang['oauth_provider_err_client_secret'];
    }

    // Scope
    $provider['scope'] = hesk_input(hesk_POST('scope'), 0, 0, HESK_SLASH);
    if (strlen($provider['scope']) < 1) {
        $errors[] = 'scope';
        $hesk_error_buffer[] = $hesklang['oauth_provider_err_scope'];
    }

    // Skip SSL certificate verification?
    $provider['no_val_ssl'] = (hesk_POST('no_val_ssl', 0) == 1) ? 1 : 0;

	// Any errors?
	if (count($hesk_error_buffer))
	{
        foreach ($provider as $k => $v) {
            $provider[$k] = stripslashes($v);
        }

		$_SESSION['new_provider'] = $provider;
		$_SESSION['new_provider']['errors'] = $errors;
		return false;
	}

	return $provider;
} // END provider_validate()


function new_provider()
{
	global $hesk_settings, $hesklang;
	global $hesk_error_buffer;

	// A security check
	hesk_token_check('POST');

	// Validate inputs
	if (($provider = provider_validate()) == false)
	{
		$tmp = '';
		foreach ($hesk_error_buffer as $error)
		{
			$tmp .= "<li>$error</li>\n";
		}
		$hesk_error_buffer = $tmp;

		$hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
		hesk_process_messages($hesk_error_buffer,'oauth_providers.php');
	}

	// Insert provider into database
    hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."oauth_providers` (`name`, `authorization_url`, `token_url`, `client_id`, `client_secret`, `scope`, `no_val_ssl`, `verified`)
        VALUES ('".hesk_dbEscape($provider['name'])."',
                '".hesk_dbEscape($provider['authorization_url'])."',
                '".hesk_dbEscape($provider['token_url'])."',
                '".hesk_dbEscape($provider['client_id'])."',
                '".hesk_dbEscape($provider['client_secret'])."',
                '".hesk_dbEscape($provider['scope'])."',
                ".intval($provider['no_val_ssl']).",
                0)");

    $inserted_id = hesk_dbInsertID();
    $_SESSION['providerord'] = $inserted_id;

    //-- Send user to OAuth provider
    redirect_to_provider($provider, $inserted_id);
} // End new_provider()

function redirect_to_provider($provider, $id) {
    $redirect_url = hesk_get_oauth_redirect_url();
    $state = hesk_oauth_prepare_provider_state($id);
    $return_location = $provider['authorization_url'] .
        "?client_id=" . urlencode($provider['client_id']) .
        "&response_type=code" .
        "&redirect_uri=" . urlencode($redirect_url) .
        "&response_mode=query" .
        "&access_type=offline" .
        "&scope=" . urlencode($provider['scope']) .
        "&state=" . urlencode($state);

    header('Location: '.$return_location);
    exit();
} // End redirect_to_provider()

function verify_provider() {
    global $hesk_settings, $hesklang;

    // A security check
    hesk_token_check();

    // Get ID
    $id = intval( hesk_GET('id') ) or hesk_error($hesklang['status_e_id']);

    $rs = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."oauth_providers` WHERE `id`=".$id);

    if (hesk_dbNumRows($rs) === 0) {
        hesk_process_messages($hesklang['oauth_provider_not_found'], './oauth_providers.php');
    }
    $row = hesk_dbFetchAssoc($rs);

    redirect_to_provider($row, $row['id']);
} // End verify_provider()

function getProviderInUseArray($id) {
    global $hesk_settings, $hesklang;

    $in_use = array();

    if ($hesk_settings['smtp'] && $hesk_settings['smtp_conn_type'] == 'oauth' && $hesk_settings['smtp_oauth_provider'] == $id) {
        $in_use[] = $hesklang['email_sending'];
    }

    if ($hesk_settings['imap'] && $hesk_settings['imap_conn_type'] == 'oauth' && $hesk_settings['imap_oauth_provider'] == $id) {
        $in_use[] = $hesklang['imap'];
    }

    if ($hesk_settings['pop3'] && $hesk_settings['pop3_conn_type'] == 'oauth' && $hesk_settings['pop3_oauth_provider'] == $id) {
        $in_use[] = $hesklang['pop3'];
    }

    return $in_use;
} // End getProviderInUseArray()

password.php
wget 'https://lists2.roe3.org/hesk/admin/password.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');

// Is the password reset function enabled?
if ( ! $hesk_settings['reset_pass'])
{
	die($hesklang['attempt']);
}

// Allow additional 5 attempts in case the user is already blocked
$hesk_settings['attempt_limit'] += 5;

$show_sent_email_message = false;

// Start session
hesk_session_start();

if (!isset($_SESSION['a_iserror']))
{
	$_SESSION['a_iserror'] = array();
}

$hesk_error_buffer = array();

// If this is a POST method, check input
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
	// Verify security image
	if ($hesk_settings['secimg_use'])
	{
		// Using reCAPTCHA?
		if ($hesk_settings['recaptcha_use'])
		{
			require(HESK_PATH . 'inc/recaptcha/recaptchalib_v2.php');

			$resp = null;
			$reCaptcha = new ReCaptcha($hesk_settings['recaptcha_private_key']);

			// Was there a reCAPTCHA response?
			if ( isset($_POST["g-recaptcha-response"]) )
			{
				$resp = $reCaptcha->verifyResponse(hesk_getClientIP(), hesk_POST("g-recaptcha-response") );
			}

			if ($resp != null && $resp->success)
			{
				//$_SESSION['img_a_verified']=true;
			}
			else
			{
				$hesk_error_buffer['mysecnum']=$hesklang['recaptcha_error'];
			}
		}
		// Using PHP generated image
		else
		{
			$mysecnum = intval( hesk_POST('mysecnum', 0) );

			if ( empty($mysecnum) )
			{
				$hesk_error_buffer['mysecnum'] = $hesklang['sec_miss'];
			}
			else
			{
				require(HESK_PATH . 'inc/secimg.inc.php');
				$sc = new PJ_SecurityImage($hesk_settings['secimg_sum']);
				if ( isset($_SESSION['checksum']) && $sc->checkCode($mysecnum, $_SESSION['checksum']) )
				{
					//$_SESSION['img_a_verified'] = true;
                    unset($_SESSION['checksum']);
				}
				else
				{
					$hesk_error_buffer['mysecnum'] = $hesklang['sec_wrng'];
				}
			}
		}
	}

	// Connect to database and check for brute force attempts
	hesk_load_database_functions();
	hesk_dbConnect();
	hesk_limitBfAttempts();

	// Get email
	$email = hesk_validateEmail( hesk_POST('email'), 'ERR', 0) or $hesk_error_buffer['email']=$hesklang['enter_valid_email'];

	// Any errors?
	if (count($hesk_error_buffer)!=0)
	{
		$_SESSION['a_iserror'] = array_keys($hesk_error_buffer);

		$tmp = '';
		foreach ($hesk_error_buffer as $error)
		{
			$tmp .= "<li>$error</li>\n";
		}
		$hesk_error_buffer = $tmp;

		$hesk_error_buffer = $hesklang['pcer'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
		hesk_process_messages($hesk_error_buffer,'NOREDIRECT');
	}
	elseif( defined('HESK_DEMO') )
	{
		hesk_process_messages($hesklang['ddemo'],'NOREDIRECT');
	}
	else
	{
		// Get user data from the database
        $res = hesk_dbQuery("SELECT `id`, `name`, `pass` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `email` = '".hesk_dbEscape($email)."' AND `active` = 1 LIMIT 1");
		if (hesk_dbNumRows($res) != 1)
		{
			hesk_process_messages($hesklang['noace'],'NOREDIRECT');
		}
		else
		{
			$row = hesk_dbFetchAssoc($res);
			$reset_token = hesk_create_password_reset_token();
			$reset_hash = hesk_hash_password_reset_token($reset_token);
			$staff_id = intval($row['id']);

			// Expire old verification hashes for this staff account
			hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."reset_password` WHERE `user_type` = 'STAFF' AND `user` = {$staff_id}");

			// Insert the verification hash into the database
			hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."reset_password` (`user`, `hash`, `ip`, `user_type`) VALUES ({$staff_id}, '".hesk_dbEscape($reset_hash)."', '".hesk_dbEscape(hesk_getClientIP())."', 'STAFF') ");

			// Prepare and send email
			require(HESK_PATH . 'inc/email_functions.inc.php');

			// Get the email message
			list($msg, $html_msg) = hesk_getEmailMessage('reset_password',array(),1,0,1);

			// Replace message special tags
            $staff_name = hesk_msgToPlain($row['name'], 1, 0);
            list($msg, $html_msg) = hesk_replace_email_tag('%%NAME%%', $staff_name, $msg, $html_msg);
            list($msg, $html_msg) = hesk_replace_email_tag('%%SITE_URL%%', $hesk_settings['site_url'], $msg, $html_msg);
            list($msg, $html_msg) = hesk_replace_email_tag('%%SITE_TITLE%%', $hesk_settings['site_title'], $msg, $html_msg);
            list($msg, $html_msg) = hesk_replace_email_tag('%%FIRST_NAME%%', hesk_full_name_to_first_name($staff_name), $msg, $html_msg);
            list($msg, $html_msg) = hesk_replace_email_tag('%%PASSWORD_RESET%%',
                $hesk_settings['hesk_url'].'/'.$hesk_settings['admin_dir'].'/password.php?h='.$reset_token,
                $msg,
                $html_msg);

            // Check two additional tags (avoid a bug in 3.3.0)
            list($msg, $html_msg) = hesk_replace_email_tag('%25%25PASSWORD_RESET%25%25',
                $hesk_settings['hesk_url'].'/'.$hesk_settings['admin_dir'].'/password.php?h='.$reset_token,
                $msg,
                $html_msg);
            list($msg, $html_msg) = hesk_replace_email_tag('%%TRACK_URL%%',
                $hesk_settings['hesk_url'].'/'.$hesk_settings['admin_dir'].'/password.php?h='.$reset_token,
                $msg,
                $html_msg);

			// Send email
			hesk_mail($email, [], $hesklang['reset_password'], $msg, $html_msg);

			// Show success
            $show_sent_email_message = true;
		}
	}
}
// If the "h" parameter is set verify it and reset the password
elseif ( isset($_GET['h']) )
{
	// Get the reset token and hash it for database lookup
	$reset_token = hesk_clean_password_reset_token($_GET['h']);
	$reset_hash = hesk_hash_password_reset_token($reset_token);

	// Connect to database
	hesk_load_database_functions();
	hesk_dbConnect();

	// Expire verification hashes older than 2 hours
	hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."reset_password` WHERE `dt` < (NOW() - INTERVAL 2 HOUR)");

	// Verify the hash exists
	$res = hesk_dbQuery("SELECT `user`, `ip` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."reset_password` WHERE `hash` = '".hesk_dbEscape($reset_hash)."' AND `user_type` = 'STAFF' LIMIT 1");
	if (hesk_dbNumRows($res) != 1)
	{
		// Not a valid hash
		hesk_limitBfAttempts();
		hesk_process_messages($hesklang['ehash'],'NOREDIRECT');
	}
	else
	{
		// Get info from database
		$row = hesk_dbFetchAssoc($res);

		// Only allow resetting password from the same IP address that submitted password reset request
		if ($row['ip'] != hesk_getClientIP())
		{
			hesk_limitBfAttempts();
			hesk_process_messages($hesklang['ehaip'],'NOREDIRECT');
		}
		else
		{
			$reset_user_id = intval($row['user']);

			// Make sure the staff account still exists and is active
			$res = hesk_dbQuery('SELECT `id`, `name`, `email` FROM `'.hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id` = {$reset_user_id} AND `active` = 1 LIMIT 1");
			if (hesk_dbNumRows($res) != 1)
			{
				hesk_limitBfAttempts();
				hesk_process_messages($hesklang['ehash'],'NOREDIRECT');
			}
			else
			{
				// Clean brute force attempts
				hesk_cleanBfAttempts();

				// Start a reset-only session. Do NOT create a full staff session here.
				hesk_session_stop();
				hesk_session_start();
				hesk_session_regenerate_id();

				$_SESSION['password_reset'] = true;
				$_SESSION['password_reset_user_id'] = $reset_user_id;
				$_SESSION['password_reset_hash'] = $reset_hash;
				$_SESSION['password_reset_ip'] = hesk_getClientIP();
				$_SESSION['password_reset_expires'] = time() + 7200;

				// Redirect to the reset-only password form
				header('Location: profile.php');
				exit();
			}

		} // End IP matches
	}
}

// Tell header to load reCaptcha API if needed
if ($hesk_settings['recaptcha_use'])
{
	define('RECAPTCHA',1);
}

$hesk_settings['tmp_title'] = $hesk_settings['hesk_title'] . ' - ' .$hesklang['passr'];
require_once(HESK_PATH . 'inc/header.inc.php');
$login_wrapper = true;
?>
<div class="wrapper login">
<main class="main" id="maincontent">
    <div class="reg__wrap">
        <div class="reg__image">
            <div class="bg-absolute"><img src="<?php echo HESK_PATH; ?>img/hero-bg.png" alt="Hesk" /></div>
        </div>
        <div class="reg__section reset-password">
            <div class="reg__box">
                <?php if ($show_sent_email_message): ?>
                    <h2 class="reg__heading delete">
                        <?php echo $hesklang['password_reset_check_your_email']; ?>
                    </h2>
                    <div class="reset-password__text">
                        <?php echo $hesklang['password_reset_link_sent']; ?>
                    </div>
                <?php else: ?>
                    <h2 class="reg__heading delete">
                        <?php echo $hesklang['reset_your_password']; ?>
                    </h2>
                    <div class="reset-password__text"><?php echo $hesklang['reset_password_instructions']; ?></div>
                    <div style="margin-right: -24px; margin-left: -16px">
                        <?php
                        /* This will handle error, success and notice messages */
                        hesk_handle_messages();
                        ?>
                    </div>
                    <!-- To activate the error add the class "invalid" to the form -->
                    <form action="password.php" class="form <?php echo isset($_SESSION['a_iserror']) && count($_SESSION['a_iserror']) ? 'invalid' : ''; ?>"
                          method="post" name="form1" id="form1" novalidate aria-label="<?php echo $hesklang['reset_your_password']; ?>">
                        <div class="form-group">
                            <label for="regInputUsername"><?php echo $hesklang['email']; ?></label>
                            <input type="email"
                                   name="email"
                                   class="form-control<?php echo in_array('email',$_SESSION['a_iserror']) ? ' isError' : ''; ?>"
                                   id="regInputUsername"
                                   placeholder="<?php echo htmlspecialchars($hesklang['enter_email']); ?>"
                                   value="<?php if (isset($email)) {echo stripslashes(hesk_input($email));} ?>">
                            <div class="form-control__error"><?php echo $hesklang['this_field_is_required']; ?></div>
                        </div>
                        <?php if ($hesk_settings['secimg_use'] && $hesk_settings['recaptcha_use'] != 1) {
                            if ($hesk_settings['recaptcha_use'] == 2) { ?>
                                <div class="g-recaptcha" data-sitekey="<?php echo $hesk_settings['recaptcha_public_key']; ?>"></div>
                            <?php } else {
                                $cls = in_array('mysecnum',$_SESSION['a_iserror']) ? ' class="form-control isError" ' : ' class="form-control" ';

                                echo '<div class="form-group"><label>'.$hesklang['sec_enter'].'</label><img src="print_sec_img.php?'.rand(10000,99999).'" width="150" height="40" alt="'.$hesklang['sec_img'].'" title="'.$hesklang['sec_img'].'" border="1" name="secimg" style="vertical-align:middle" /> '.
                                    '<a style="vertical-align: middle; display: inline" class="btn btn-refresh" href="javascript:" onclick="document.form1.secimg.src=\'print_sec_img.php?\'+ ( Math.floor((90000)*Math.random()) + 10000);">
                                            <svg class="icon icon-refresh">
                                                <use xlink:href="' . HESK_PATH . 'img/sprite.svg#icon-refresh"></use>
                                            </svg>
                                         </a>'.
                                    '<br><br><input type="text" name="mysecnum" size="20" maxlength="5" autocomplete="off" '.$cls.'></div>';
                            }
                        } ?>
                        <div class="form__submit">
                            <button class="btn btn-full" type="submit" id="recaptcha-submit"><?php echo $hesklang['passs']; ?></button>
                        </div>
                        <?php
                        // Use Invisible reCAPTCHA?
                        if ($hesk_settings['secimg_use'] && $hesk_settings['recaptcha_use'] == 1)
                        {
                            ?>
                            <div class="g-recaptcha" data-sitekey="<?php echo $hesk_settings['recaptcha_public_key']; ?>" data-bind="recaptcha-submit" data-callback="recaptcha_submitForm"></div>
                            <?php
                        }
                        ?>
                    </form>
                <?php endif; ?>
                <div class="reg__footer">
                    <a href="index.php" class="link"><?php echo $hesklang['back_to_login']; ?></a>
                </div>
            </div>
        </div>
    </div>

    <script>
    $(() => {
        $('form :visible[class*=isError]:first').focus();
    })
    </script>
<?php
// Clean session errors
hesk_cleanSessionVars('a_iserror');
hesk_cleanSessionVars('img_a_verified');

// Print footer
require_once(HESK_PATH . 'inc/footer.inc.php');
?>
print.php
wget 'https://lists2.roe3.org/hesk/admin/print.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
define('TEMPLATE_PATH', HESK_PATH . "theme/{$hesk_settings['site_theme']}/");
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require_once(HESK_PATH . 'inc/customer_accounts.inc.php');
hesk_load_database_functions();

hesk_session_start();

// Do we have parameters in query string? If yes, store them in session and redirect
if ( isset($_GET['track']) || isset($_GET['e']) )
{
    $_SESSION['p_track'] = hesk_GET('track');
    $_SESSION['p_email'] = hesk_GET('e');

    header('Location: print.php');
    die();
}

hesk_dbConnect();
hesk_isLoggedIn();

/* Get the tracking ID */
$trackingID = hesk_cleanID('p_track') or die("$hesklang[int_error]: $hesklang[no_trackID]");

// Load custom fields
require_once(HESK_PATH . 'inc/custom_fields.inc.php');

// Load statuses
require_once(HESK_PATH . 'inc/statuses.inc.php');

/* Clean ticket parameters from the session data, we don't need them anymore */
hesk_cleanSessionVars( array('p_track', 'p_email') );

/* Get ticket info */
$res = hesk_dbQuery("SELECT `t1`.* , `t2`.name AS `repliername`
					FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` AS `t1` LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."users` AS `t2` ON `t1`.`replierid` = `t2`.`id`
					WHERE `trackid`='".hesk_dbEscape($trackingID)."' LIMIT 1");

if (hesk_dbNumRows($res) != 1)
{
	hesk_error($hesklang['ticket_not_found']);
}
$ticket = hesk_dbFetchAssoc($res);
$ticket = hesk_verifyStaffTicketAccess($trackingID, $ticket);
$customers = hesk_get_customers_for_ticket($ticket['id']);

// Demo mode
if ( defined('HESK_DEMO') )
{
    foreach ($customers as $customer) {
        $customer['email'] = 'hidden@demo.com';
    }
	$ticket['ip']	 = '127.0.0.1';
}

/* Get category name and ID */
$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE `id`='{$ticket['category']}' LIMIT 1");

/* If this category has been deleted use the default category with ID 1 */
if (hesk_dbNumRows($res) != 1)
{
	$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE `id`='1' LIMIT 1");
}
$category = hesk_dbFetchAssoc($res);

/* Get replies */
$res  = hesk_dbQuery("SELECT `replies`.*, `reply_customer`.`name` AS `customer_name`, `reply_customer`.`email` AS `customer_email`, `reply_staff`.`name` AS `staff_name`
FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` AS `replies`
LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."customers` AS `reply_customer`
    ON `replies`.`customer_id` = `reply_customer`.`id`
LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."users` AS `reply_staff`
    ON `replies`.`staffid` = `reply_staff`.`id`
WHERE `replyto`='{$ticket['id']}' ORDER BY `replies`.`id` ASC");

$replies = [];
while ($row = hesk_dbFetchAssoc($res)) {
    if (intval($row['staffid']) > 0) {
        $row['name'] = $row['staff_name'];
    } else {
        $row['name'] = strlen($row['customer_name']) ? $row['customer_name'] : ( ! empty($row['customer_email']) ? $row['customer_email'] : $hesklang['pde']);
    }
    $replies[] = $row;
}

/* Get notes */
$notes = array();
if (!empty($_SESSION['id']))
{
    $res2 = hesk_dbQuery("SELECT t1.*, t2.`name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."notes` AS t1 LEFT JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."users` AS t2 ON t1.`who` = t2.`id` WHERE `ticket`='{$ticket['id']}' ORDER BY t1.`id`");
    while ($note = hesk_dbFetchAssoc($res2))
    {
        $notes[] = $note;
    }
}

$ticket['notes'] = $notes;
$ticket['replies'] = $replies;
$ticket['categoryName'] = $category['name'];
$ticket['customers'] = $customers;

$tickets = array($ticket);
require_once(HESK_PATH . 'inc/print_template.inc.php');

print_sec_img.php
wget 'https://lists2.roe3.org/hesk/admin/print_sec_img.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/secimg.inc.php');

hesk_session_start();

$_SESSION['secnum']   = mt_rand(10000,99999);
$_SESSION['checksum'] = sha1($_SESSION['secnum'] . $hesk_settings['secimg_sum']);

/* This will make sure the security image is not cached */
header("expires: -1");
header("cache-control: no-cache, no-store, must-revalidate, max-age=-1");
header("cache-control: post-check=0, pre-check=0", false);
header("pragma: no-store,no-cache");

$sc = new PJ_SecurityImage($hesk_settings['secimg_sum']);
$sc->printImage($_SESSION['secnum']);

exit();
priority.php
wget 'https://lists2.roe3.org/hesk/admin/priority.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
hesk_checkPermission('can_view_tickets');
hesk_checkPermission('can_reply_tickets');

/* A security check */
hesk_token_check('POST');

/* Ticket ID */
$trackingID = hesk_cleanID() or die($hesklang['int_error'].': '.$hesklang['no_trackID']);

// Load priorities
require_once(HESK_PATH . 'inc/priorities.inc.php');

$priority = hesk_POST('priority');
if ( ! hesk_is_valid_priority_id($priority)) {
    hesk_error($hesklang['priority_e_id']);
}
$priority = intval($priority);

// Get original ticket details
$res = hesk_dbQuery("SELECT `id`, `trackid`, `category`, `owner`, `assignedby`, `priority` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `trackid`='".hesk_dbEscape($trackingID)."' LIMIT 1");
if (hesk_dbNumRows($res) != 1) {
    hesk_error($hesklang['ticket_not_found']);
}
$ticket = hesk_dbFetchAssoc($res);
hesk_verifyStaffTicketAccess($trackingID, $ticket);

if ($ticket['priority'] == $priority) {
    hesk_process_messages(sprintf($hesklang['ticket_already_priority'], $hesk_settings['priorities'][$priority]['name']),'admin_ticket.php?track='.$trackingID.'&Refresh='.rand(10000,99999),'NOTICE');
}

$revision = sprintf($hesklang['thist8'],hesk_date(),$hesk_settings['priorities'][$priority]['name'],addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `priority`='{$priority}', `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') WHERE `id`='".intval($ticket['id'])."'");

hesk_process_messages(sprintf($hesklang['chpri2'],$hesk_settings['priorities'][$priority]['name']),'admin_ticket.php?track='.$trackingID.'&Refresh='.mt_rand(10000,99999),'SUCCESS');
profile.php
wget 'https://lists2.roe3.org/hesk/admin/profile.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');
define('LOAD_TABS',1);

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/profile_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();

// Password reset links create a reset-only session, not a full staff session.
// In reset-only mode this page may only display and process the new-password form.
if (hesk_isStaffPasswordResetOnly())
{
    hesk_handleStaffPasswordResetOnly();
}

hesk_isLoggedIn();

/* Check permissions */
$can_view_tickets = hesk_checkPermission('can_view_tickets',0);
$can_reply_tickets = hesk_checkPermission('can_reply_tickets',0);
$can_view_unassigned = hesk_checkPermission('can_view_unassigned',0);
$can_man_customers = hesk_checkPermission('can_man_customers',0);

/* Update profile? */
if ( ! empty($_POST['action']))
{
	// Demo mode
	if ( defined('HESK_DEMO') )
	{
		hesk_process_messages($hesklang['sdemo'], 'profile.php', 'NOTICE');
	}

    if ($_POST['action'] == 'password')
    {
        update_password();
    }
    else
    {
        update_profile();
    }
}
else
{
	$res = hesk_dbQuery('SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id` = '".intval($_SESSION['id'])."' LIMIT 1");
	$tmp = hesk_dbFetchAssoc($res);

	foreach ($tmp as $k=>$v)
	{
		if ($k == 'pass')
        {
			if ($v == '499d74967b28a841c98bb4baaabaad699ff3c079')
			{
				define('WARN_PASSWORD',true);
			}
			continue;
        }
        elseif ($k == 'categories')
		{
			continue;
		}
		$_SESSION['new'][$k]=$v;
	}
}

if ( ! isset($_SESSION['new']['username']))
{
	$_SESSION['new']['username'] = '';
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print admin navigation */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
if (!hesk_SESSION(array('new', 'errors')) && !hesk_SESSION(array('newpass', 'errors'))) {
    hesk_handle_messages();
}

if (defined('WARN_PASSWORD'))
{
	hesk_show_notice($hesklang['chdp2'],'<span class="important">'.$hesklang['security'].'</span>');
}
?>
<div class="main__content profile">
    <article class="profile__wrapper">
        <div class="profile__info">
            <div class="profile__info_list">
                <h3><?php echo $_SESSION['new']['name']; ?></h3>
                <div class="info--mail">
                    <a href="mailto:<?php echo $_SESSION['new']['email']; ?>"><?php echo $_SESSION['new']['email']; ?></a>
                </div>
            </div>
        </div>
        <div class="profile__control">
            <div class="profile__edit">
                <button class="btn btn--blue-border" data-action="profile-edit"><?php echo $hesklang['edit_profile']; ?></button>
            </div>
            <div class="profile__edit">
                <button class="btn btn--blue-border" data-action="profile-password"><?php echo $hesklang['edit_pass']; ?></button>
            </div>
            <a href="index.php?a=logout&token=<?php hesk_token_echo(); ?>" class="profile-log-out">
                <svg class="icon icon-log-out">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-log-out"></use>
                </svg>
                <span><?php echo $hesklang['logout']; ?></span>
            </a>
        </div>
    </article>
    <article class="profile__wrapper">
        <div class="profile__info">
            <div class="profile__info_list">
                <h3><?php echo $hesklang['mfa']; ?></h3>
                <div class="info--mail">
                    <?php if ($_SESSION['new']['mfa_enrollment'] === '0') { ?>
                        <?php if ($hesk_settings['require_mfa']): ?>
                        <div class="text-success">
                            <?php echo sprintf($hesklang['mfa_enabled'], $hesklang['mfa_method_email']); ?>
                        </div>
                        <?php else: ?>
                        <div class="text-danger">
                            <?php echo $hesklang['mfa_disabled']; ?>
                        </div>
                        <?php endif; ?>
                    <?php } elseif ($_SESSION['new']['mfa_enrollment'] === '1') { ?>
                        <div class="text-success">
                            <?php echo sprintf($hesklang['mfa_enabled'], $hesklang['mfa_method_email']); ?>
                        </div>
                    <?php } elseif ($_SESSION['new']['mfa_enrollment'] === '2') { ?>
                        <div class="text-success">
                            <?php echo sprintf($hesklang['mfa_enabled'], $hesklang['mfa_method_auth_app']); ?>
                        </div>
                    <?php } ?>
                </div>
            </div>
        </div>
        <div class="profile__control">
            <div class="profile__edit">
                <a href="manage_mfa.php">
                    <button class="btn btn-full wider">
                        <?php echo $hesklang['mfa_manage_profile']; ?>
                    </button>
                </a>
            </div>
        </div>
    </article>
</div>
<div class="right-bar profile-edit" <?php echo hesk_SESSION(array('new','errors')) ? 'style="display: block"' : ''; ?>>
    <div class="right-bar__body form" data-step="1">
        <h3>
            <a href="javascript:">
                <svg class="icon icon-back">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                </svg>
                <span><?php echo $hesklang['profile_for'].' <b>'.$_SESSION['new']['user']; ?></span>
            </a>
        </h3>
        <?php
        /* This will handle error, success and notice messages */
        if (hesk_SESSION(array('new', 'errors'))) {
            hesk_handle_messages();
        }

        if ($hesk_settings['can_sel_lang'])
        {
            /* Update preferred language in the database? */
            if (isset($_GET['save_language']) )
            {
                hesk_token_check();

                $newlang = hesk_input( hesk_GET('language') );

                /* Only update if it's a valid language */
                if ( isset($hesk_settings['languages'][$newlang]) )
                {
                    $newlang = ($newlang == HESK_DEFAULT_LANGUAGE) ? "NULL" : "'" . hesk_dbEscape($newlang) . "'";
                    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."users` SET `language`=$newlang WHERE `id`='".intval($_SESSION['id'])."'");
                }
            }

            $str  = '<form method="get" class="form" action="profile.php" style="margin:10px 0 0 0;padding:0;border:0;white-space:nowrap;" aria-label="' . $hesklang['chol'] . '">';
            $str .= '<input type="hidden" name="save_language" value="1" />';
            $str .= '<input type="hidden" name="token" value="' . hesk_token_echo(0) . '" />';
            $str .= '<div class="form-group"><label for="prof_language">'.$hesklang['chol'].'</label>';

            if ( ! isset($_GET) )
            {
                $_GET = array();
            }

            foreach ($_GET as $k => $v)
            {
                if ($k == 'language' || $k == 'save_language' || $k == 'token')
                {
                    continue;
                }
                $str .= '<input type="hidden" name="'.hesk_htmlentities($k).'" value="'.hesk_htmlentities($v).'" />';
            }

            $str .= '<div class="dropdown-select center out-close"><select class="form-control" name="language" onchange="this.form.submit()">';
            $str .= hesk_listLanguages(0);
            $str .= '</select></div></div>';

            ?>
            <script language="javascript" type="text/javascript">
                document.write('<?php echo str_replace(array('"','<','=','>',"'"),array('\42','\74','\75','\76','\47'),$str . '</p></form>'); ?>');
            </script>
            <noscript>
                <?php
                echo $str . '<input type="submit" value="'.$hesklang['go'].'" /></p></form>';
                ?>
            </noscript>
            <?php
        }
        ?>
        <form name="form1" method="post" action="profile.php" class="form <?php echo hesk_SESSION(array('new','errors')) ? 'invalid' : ''; ?>" aria-label="<?php echo $hesklang['update_profile']; ?>">
            <?php hesk_profile_tab(); ?>

            <!-- Submit -->
            <div class="right-bar__footer">
                <input type="hidden" name="action" value="update" />
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
                <button type="submit" class="btn btn-full save" data-action="save" ripple="ripple"><?php echo $hesklang['update_profile']; ?></button>
            </div>
        </form>
    </div>
</div>
<div class="right-bar profile-password" <?php echo (hesk_SESSION(array('newpass','errors')) || hesk_SESSION('password_reset')) ? 'style="display: block"' : ''; ?>>
    <div class="right-bar__body form" data-step="1">
        <h3>
            <a href="javascript:">
                <svg class="icon icon-back">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                </svg>
                <span><?php echo $hesklang['edit_pass']; ?></span>
            </a>
        </h3>
        <?php
        /* This will handle error, success and notice messages */
        if (hesk_SESSION(array('newpass', 'errors'))) {
            hesk_handle_messages();
        } elseif (hesk_SESSION('password_reset')) {
            hesk_show_notice($hesklang['resim'], ' ', false);
            hesk_show_info($hesklang['cur_pass3'], ' ', false, 'no-padding-top');
        } else {
            hesk_show_info($hesklang['cur_pass2'] . '<br><br>' . $hesklang['cur_pass3'], ' ', false);
        }

        $session_array='newpass';
        $errors = hesk_SESSION(array($session_array, 'errors'));
        $errors = is_array($errors) ? $errors : array();
        ?>
        <form name="form1" method="post" action="profile.php" class="form <?php echo hesk_SESSION(array('newpass','errors')) ? 'invalid' : ''; ?>" aria-label="<?php echo $hesklang['new_pass']; ?>">
            <section class="item--section">
                <?php if ( ! hesk_SESSION('password_reset')): ?>
                <div class="form-group">
                    <label for="pass_cur"><?php echo $hesklang['cur_pass']; ?></label>
                    <input type="password" id="pass_cur" name="pass_cur" autocomplete="off" class="form-control <?php echo in_array('current', $errors) ? 'isError' : ''; ?>"
                           value="<?php echo isset($_SESSION[$session_array]['pass_cur']) ? $_SESSION[$session_array]['pass_cur'] : ''; ?>">
                </div>
                <p>&nbsp;</p>
                <?php endif; ?>
                <div class="form-group">
                    <label for="pass_new"><?php echo $hesklang['new_pass']; ?></label>
                    <input type="password" id="pass_new" name="pass_new" autocomplete="off" class="form-control <?php echo in_array('new', $errors) ? 'isError' : ''; ?>"
                           value="<?php echo isset($_SESSION[$session_array]['pass_new']) ? $_SESSION[$session_array]['pass_new'] : ''; ?>"
                           onkeyup="hesk_checkPassword(this.value, 'progressBar2')">
                </div>
                <div class="form-group">
                    <label for="pass_new2"><?php echo $hesklang['confirm_new_pass']; ?></label>
                    <input type="password" id="pass_new2" name="pass_new2" autocomplete="off" class="form-control <?php echo in_array('new2', $errors) ? 'isError' : ''; ?>"
                           value="<?php echo isset($_SESSION[$session_array]['pass_new2']) ? $_SESSION[$session_array]['pass_new2'] : ''; ?>">
                </div>
                <div class="form-group">
                    <label><?php echo $hesklang['pwdst']; ?></label>
                    <div style="border: 1px solid #d4d6e3; width: 100%; height: 14px">
                        <div id="progressBar2" style="font-size: 1px; height: 12px; width: 0px; border: none;">
                        </div>
                    </div>
                </div>
            </section>

            <!-- Submit -->
            <div class="right-bar__footer">
                <input type="hidden" name="action" value="password" />
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
                <button type="submit" class="btn btn-full save" data-action="save" ripple="ripple"><?php echo $hesklang['save_pass']; ?></button>
            </div>
        </form>
    </div>
</div>
<?php

hesk_cleanSessionVars('newpass');
unset($_SESSION['new']['errors']);

require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/


function hesk_isStaffPasswordResetOnly()
{
    return hesk_SESSION('password_reset') && intval(hesk_SESSION('password_reset_user_id', 0)) > 0;
} // End hesk_isStaffPasswordResetOnly()


function hesk_handleStaffPasswordResetOnly()
{
    global $hesk_settings, $hesklang;

    $reset_user_id = intval(hesk_SESSION('password_reset_user_id', 0));
    $reset_hash = hesk_SESSION('password_reset_hash', '');

    // Reset-only sessions are bound to the requesting IP and expire after 2 hours
    if ($reset_user_id < 1 ||
        ! preg_match('/^[a-f0-9]{64}$/i', $reset_hash) ||
        intval(hesk_SESSION('password_reset_expires', 0)) < time() ||
        hesk_SESSION('password_reset_ip') != hesk_getClientIP())
    {
        hesk_staffPasswordResetLogout($hesklang['ehash']);
    }

    // Make sure the reset hash has not expired or already been used
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."reset_password` WHERE `dt` < (NOW() - INTERVAL 2 HOUR)");
    $res = hesk_dbQuery("SELECT `user` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."reset_password` WHERE `hash` = '".hesk_dbEscape($reset_hash)."' AND `user_type` = 'STAFF' AND `user` = {$reset_user_id} LIMIT 1");
    if (hesk_dbNumRows($res) != 1)
    {
        hesk_staffPasswordResetLogout($hesklang['ehash']);
    }

    // Make sure the staff account still exists and is active
    $res = hesk_dbQuery("SELECT `id`, `name`, `email` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id` = {$reset_user_id} AND `active` = 1 LIMIT 1");
    if (hesk_dbNumRows($res) != 1)
    {
        hesk_staffPasswordResetLogout($hesklang['ehash']);
    }
    $staff = hesk_dbFetchAssoc($res);

    // Only password updates are allowed in reset-only mode
    if ( ! empty($_POST['action']))
    {
        if ($_POST['action'] == 'password')
        {
            update_password(true);
        }
        else
        {
            hesk_process_messages($hesklang['attempt'], 'NOREDIRECT');
        }
    }

    hesk_printStaffPasswordResetForm($staff);
    exit();
} // End hesk_handleStaffPasswordResetOnly()


function hesk_staffPasswordResetLogout($message = '', $message_type = 'ERROR')
{
    // Stop reset-only session and clear staff login cookies
    hesk_session_stop();
    hesk_setcookie('hesk_username', '');
    hesk_setcookie('hesk_remember', '');

    // Start a clean session for the login-page message
    hesk_session_start();
    hesk_process_messages($message, 'index.php', $message_type);
    exit();
} // End hesk_staffPasswordResetLogout()


function hesk_printStaffPasswordResetForm($staff)
{
    global $hesk_settings, $hesklang;

    $hesk_settings['tmp_title'] = $hesk_settings['hesk_title'] . ' - ' . $hesklang['reset_your_password'];
    require_once(HESK_PATH . 'inc/header.inc.php');
    $login_wrapper = true;
    $errors = hesk_SESSION(array('newpass', 'errors'));
    $errors = is_array($errors) ? $errors : array();
    ?>
    <div class="wrapper login">
    <main class="main" id="maincontent">
        <div class="reg__wrap">
            <div class="reg__image">
                <div class="bg-absolute"><img src="<?php echo HESK_PATH; ?>img/hero-bg.png" alt="Hesk" /></div>
            </div>
            <div class="reg__section reset-password">
                <div class="reg__box">
                    <h2 class="reg__heading delete">
                        <?php echo $hesklang['reset_your_password']; ?>
                    </h2>
                    <div class="reset-password__text">
                        <?php echo $hesklang['resim']; ?><br><br><?php echo $hesklang['cur_pass3']; ?>
                    </div>
                    <div style="margin-right: -24px; margin-left: -16px">
                        <?php hesk_handle_messages(); ?>
                    </div>
                    <form name="form1" method="post" action="profile.php" class="form <?php echo count($errors) ? 'invalid' : ''; ?>" aria-label="<?php echo $hesklang['new_pass']; ?>">
                        <div class="form-group">
                            <label for="pass_new"><?php echo $hesklang['new_pass']; ?></label>
                            <input type="password" id="pass_new" name="pass_new" autocomplete="new-password" class="form-control <?php echo in_array('new', $errors) ? 'isError' : ''; ?>" onkeyup="hesk_checkPassword(this.value, 'progressBar2')">
                        </div>
                        <div class="form-group">
                            <label for="pass_new2"><?php echo $hesklang['confirm_new_pass']; ?></label>
                            <input type="password" id="pass_new2" name="pass_new2" autocomplete="new-password" class="form-control <?php echo in_array('new2', $errors) ? 'isError' : ''; ?>">
                        </div>
                        <div class="form-group">
                            <label><?php echo $hesklang['pwdst']; ?></label>
                            <div style="border: 1px solid #d4d6e3; width: 100%; height: 14px">
                                <div id="progressBar2" style="font-size: 1px; height: 12px; width: 0px; border: none;"></div>
                            </div>
                        </div>
                        <div class="form__submit">
                            <input type="hidden" name="action" value="password" />
                            <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
                            <button type="submit" class="btn btn-full" ripple="ripple"><?php echo $hesklang['save_pass']; ?></button>
                        </div>
                    </form>
                    <div class="reg__footer">
                        <a href="index.php" class="link"><?php echo $hesklang['back_to_login']; ?></a>
                    </div>
                </div>
            </div>
        </div>

        <script>
        $(() => {
            $('form :visible[class*=isError]:first').focus();
        })
        </script>
    <?php
    hesk_cleanSessionVars('newpass');
    require_once(HESK_PATH . 'inc/footer.inc.php');
} // End hesk_printStaffPasswordResetForm()


function update_password($password_reset_only = false) {
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check('POST');

    $hesk_error_buffer = '';
    $errors = array();
    $target_user_id = $password_reset_only ? intval(hesk_SESSION('password_reset_user_id', 0)) : intval($_SESSION['id']);

    if ($target_user_id < 1) {
        hesk_staffPasswordResetLogout($hesklang['ehash']);
    }

    // Current password
	$pass_cur = hesk_input( hesk_POST('pass_cur') );
    if ($password_reset_only) {
        // Allow password reset without the old password only in reset-only mode
    } elseif (!$pass_cur) {
        $hesk_error_buffer .= '<li>' . $hesklang['enter_pass'] . '</li>';
        $errors[] = 'current';
    } elseif (strlen($pass_cur) > 64) {
        $hesk_error_buffer .= '<li>' . $hesklang['pass_len'] . '</li>';
        $errors[] = 'current';
    } else {
        hesk_limitInternalBfAttempts();

        // Get current password hash from DB
        $result = hesk_dbQuery("SELECT `pass` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id` = {$target_user_id} LIMIT 1");
        if (hesk_dbNumRows($result) != 1)
        {
            hesk_forceLogout($hesklang['wrong_user']);
        }
        $user_row = hesk_dbFetchAssoc($result);

        // Validate current password
        if (hesk_password_verify($pass_cur, $user_row['pass'])) {
            hesk_cleanBfAttempts();
        } else {
            $hesk_error_buffer .= '<li>' . $hesklang['wrong_pass'] . '</li>';
            $errors[] = 'current';
        }
    }

    // New password
	$pass_new = hesk_input( hesk_POST('pass_new') );
	if (!$pass_new) {
        $hesk_error_buffer .= '<li>' . $hesklang['e_new_pass'] . '</li>';
        $errors[] = 'new';
    } elseif (strlen($pass_new) < 5) {
        $hesk_error_buffer .= '<li>' . $hesklang['password_not_valid'] . '</li>';
        $errors[] = 'new';
    } elseif (strlen($pass_new) > 64) {
        $hesk_error_buffer .= '<li>' . $hesklang['pass_len'] . '</li>';
        $errors[] = 'new';
    }

    // Confirm password
	$pass_new2 = hesk_input( hesk_POST('pass_new2') );
	if ($pass_new2 != $pass_new) {
        $hesk_error_buffer .= '<li>' . $hesklang['passwords_not_same'] . '</li>';
        $errors[] = 'new2';
    }

    if (strlen($hesk_error_buffer))
    {
        $hesk_error_buffer = '<div class="browser-default"><ul>'.$hesk_error_buffer.'</ul></div>';
        $_SESSION['newpass']['errors'] = $errors;
        hesk_process_messages($hesk_error_buffer,'NOREDIRECT');
    }
    else
    {
        if ($password_reset_only)
        {
            $reset_hash = hesk_SESSION('password_reset_hash', '');

            // Consume the reset hash only after the new password passes validation.
            // This keeps link scanners from invalidating the link on GET, but prevents POST replay/races.
            hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."reset_password` WHERE `hash` = '".hesk_dbEscape($reset_hash)."' AND `user` = {$target_user_id} AND `user_type` = 'STAFF'");
            if (hesk_dbAffectedRows() != 1)
            {
                hesk_staffPasswordResetLogout($hesklang['ehash']);
            }
        }

        $newpass_hash = hesk_password_hash($pass_new);
		hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."users` SET `pass` = '".hesk_dbEscape($newpass_hash)."' WHERE `id` = {$target_user_id}");

        if ($password_reset_only)
        {
            // Invalidate any remaining staff reset links, remember-me tokens and pending MFA verification codes
            hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."reset_password` WHERE `user` = {$target_user_id} AND `user_type` = 'STAFF'");
            hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."auth_tokens` WHERE `user_id` = {$target_user_id} AND `user_type` = 'STAFF'");
            hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."mfa_verification_tokens` WHERE `user_id` = {$target_user_id} AND `user_type` = 'STAFF'");

            hesk_staffPasswordResetLogout($hesklang['pass_login'], 'NOTICE');
        }

        // Force login after password change
        hesk_forceLogout($hesklang['pass_login'], null, null, 'NOTICE');
    }
} // End update_password()


function update_profile() {
	global $hesk_settings, $hesklang, $can_view_unassigned, $can_man_customers;

	/* A security check */
	hesk_token_check('POST');

    $sql_username = '';

    $hesk_error_buffer = '';
    $errors = array();

	$_SESSION['new']['name'] = hesk_input( hesk_POST('name') );
	if (!$_SESSION['new']['name']) {
        $hesk_error_buffer .= '<li>' . $hesklang['enter_your_name'] . '</li>';
        $errors[] = 'name';
    }

	$_SESSION['new']['email'] = hesk_validateEmail( hesk_POST('email'), 'ERR', 0);
	if (!$_SESSION['new']['email']) {
        $hesk_error_buffer .= '<li>' . $hesklang['enter_valid_email'] . '</li>';
        $errors[] = 'email';
    } else {
        // Make sure that the new email isn't already used by another user
        $email_used_rs = hesk_dbQuery("SELECT 1 FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `email` = '".hesk_dbEscape($_SESSION['new']['email'])."' AND `id`!=".intval($_SESSION['id'])." LIMIT 1");
        if (hesk_dbNumRows($email_used_rs) > 0) {
            $hesk_error_buffer .= '<li>' . sprintf($hesklang['profile_duplicate_email'], $_SESSION['new']['email']) . '</li>';
            $errors[] = 'email';
        }
    }

    if ($hesk_settings['staff_nicknames']) {
        $_SESSION['new']['nickname'] = hesk_input( hesk_POST('nickname') );
    }

	$_SESSION['new']['signature'] = hesk_input( hesk_POST('signature') );

	/* Signature */
	if (hesk_mb_strlen($_SESSION['new']['signature'])>1000)
    {
		$hesk_error_buffer .= '<li>' . $hesklang['signature_long'] . '</li>';
		$errors[] = 'signature';
    }

    /* Admins can change username */
    if ($_SESSION['isadmin'])
    {
		$_SESSION['new']['user']  = hesk_input( hesk_POST('user') ) or $hesk_error_buffer .= '<li>' . $hesklang['enter_username'] . '</li>';

	    /* Check for duplicate usernames */
		$result = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `user`='".hesk_dbEscape($_SESSION['new']['user'])."' AND `id`!='".intval($_SESSION['id'])."' LIMIT 1");
		if (hesk_dbNumRows($result) != 0)
		{
	        $hesk_error_buffer .= '<li>' . $hesklang['duplicate_user'] . '</li>';
	        $errors[] = 'user';
		}
        else
        {
        	$sql_username =  "`user`='" . hesk_dbEscape($_SESSION['new']['user']) . "', ";
        }
    }

    /* After reply */
    $_SESSION['new']['afterreply'] = intval( hesk_POST('afterreply') );
    if ($_SESSION['new']['afterreply'] != 1 && $_SESSION['new']['afterreply'] != 2)
    {
    	$_SESSION['new']['afterreply'] = 0;
    }

    // Defaults
    $_SESSION['new']['autostart']				= isset($_POST['autostart']) ? 1 : 0;
    $_SESSION['new']['notify_customer_new']		= isset($_POST['notify_customer_new']) ? 1 : 0;
    $_SESSION['new']['notify_customer_reply']	= isset($_POST['notify_customer_reply']) ? 1 : 0;
    $_SESSION['new']['show_suggested']			= isset($_POST['show_suggested']) ? 1 : 0;
    $_SESSION['new']['autoreload']				= isset($_POST['autoreload']) ? 1 : 0;

    if ($_SESSION['new']['autoreload'])
    {
        $_SESSION['new']['autoreload'] = intval(hesk_POST('reload_time'));

        if (hesk_POST('secmin') == 'min')
        {
            $_SESSION['new']['autoreload'] *= 60;
        }

        if ($_SESSION['new']['autoreload'] < 30 || $_SESSION['new']['autoreload'] > 65535)
        {
            $_SESSION['new']['autoreload'] = 300;
        }
    }
    else
    {
        hesk_setcookie('autorefresh', '', 0, '', false);
    }

    /* Notifications */
    $_SESSION['new']['notify_new_unassigned']       = empty($_POST['notify_new_unassigned']) || ! $can_view_unassigned ? 0 : 1;
    $_SESSION['new']['notify_overdue_unassigned']   = empty($_POST['notify_overdue_unassigned']) || !$can_view_unassigned ? 0 : 1;
    $_SESSION['new']['notify_new_my'] 			    = empty($_POST['notify_new_my']) ? 0 : 1;
    $_SESSION['new']['notify_overdue_my']           = empty($_POST['notify_overdue_my']) ? 0 : 1;
    $_SESSION['new']['notify_reply_unassigned']     = empty($_POST['notify_reply_unassigned']) || ! $can_view_unassigned ? 0 : 1;
    $_SESSION['new']['notify_reply_my']			    = empty($_POST['notify_reply_my']) ? 0 : 1;
    $_SESSION['new']['notify_assigned']			    = empty($_POST['notify_assigned']) ? 0 : 1;
    $_SESSION['new']['notify_note'] 				= empty($_POST['notify_note']) ? 0 : 1;
    $_SESSION['new']['notify_pm']	    			= empty($_POST['notify_pm']) ? 0 : 1;
    $_SESSION['new']['notify_customer_approval']    = empty($_POST['notify_customer_approval']) || ! $can_man_customers ? 0 : 1;
    $_SESSION['new']['notify_collaborator_added']          = empty($_POST['notify_collaborator_added']) ? 0 : 1;
    $_SESSION['new']['notify_collaborator_customer_reply'] = empty($_POST['notify_collaborator_customer_reply']) ? 0 : 1;
    $_SESSION['new']['notify_collaborator_staff_reply']    = empty($_POST['notify_collaborator_staff_reply']) ? 0 : 1;
    $_SESSION['new']['notify_collaborator_note']           = empty($_POST['notify_collaborator_note']) ? 0 : 1;
    $_SESSION['new']['notify_collaborator_resolved']       = empty($_POST['notify_collaborator_resolved']) ? 0 : 1;
    $_SESSION['new']['notify_collaborator_overdue']        = empty($_POST['notify_collaborator_overdue']) ? 0 : 1;

    /* Any errors? */
    if (strlen($hesk_error_buffer))
    {
		/* Process the session variables */
		$_SESSION['new'] = hesk_stripArray($_SESSION['new']);

		$hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
        $_SESSION['new']['errors'] = $errors;
		hesk_process_messages($hesk_error_buffer,'NOREDIRECT');
    }
    else
    {

        if ($hesk_settings['staff_nicknames']) {
            $nickname_sql = "`nickname`='".hesk_dbEscape($_SESSION['new']['nickname'])."',";
        } else {
            $nickname_sql = '';
        }

		/* Update database */
		hesk_dbQuery(
		"UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."users` SET
		`name`='".hesk_dbEscape($_SESSION['new']['name'])."',
		`email`='".hesk_dbEscape($_SESSION['new']['email'])."',
		`signature`='".hesk_dbEscape($_SESSION['new']['signature'])."',
        {$sql_username}
        {$nickname_sql}
		`afterreply`='".($_SESSION['new']['afterreply'])."' ,
		".($hesk_settings['time_worked'] ? "`autostart`='".($_SESSION['new']['autostart'])."'," : '')."
		`autoreload`='".($_SESSION['new']['autoreload'])."' ,
		`notify_customer_new`='".($_SESSION['new']['notify_customer_new'])."' ,
		`notify_customer_reply`='".($_SESSION['new']['notify_customer_reply'])."' ,
		`show_suggested`='".($_SESSION['new']['show_suggested'])."' ,
		`notify_new_unassigned`='".($_SESSION['new']['notify_new_unassigned'])."' ,
		`notify_overdue_unassigned`='".($_SESSION['new']['notify_overdue_unassigned'])."' ,
		`notify_new_my`='".($_SESSION['new']['notify_new_my'])."' ,
		`notify_overdue_my`='".($_SESSION['new']['notify_overdue_my'])."' ,
		`notify_reply_unassigned`='".($_SESSION['new']['notify_reply_unassigned'])."' ,
		`notify_reply_my`='".($_SESSION['new']['notify_reply_my'])."' ,
		`notify_assigned`='".($_SESSION['new']['notify_assigned'])."' ,
		`notify_pm`='".($_SESSION['new']['notify_pm'])."',
		`notify_note`='".($_SESSION['new']['notify_note'])."',
        `notify_customer_approval`='".($_SESSION['new']['notify_customer_approval'])."',
        `notify_collaborator_added`='".($_SESSION['new']['notify_collaborator_added'])."',
        `notify_collaborator_customer_reply`='".($_SESSION['new']['notify_collaborator_customer_reply'])."',
        `notify_collaborator_staff_reply`='".($_SESSION['new']['notify_collaborator_staff_reply'])."',
        `notify_collaborator_note`='".($_SESSION['new']['notify_collaborator_note'])."',
        `notify_collaborator_resolved`='".($_SESSION['new']['notify_collaborator_resolved'])."',
        `notify_collaborator_overdue`='".($_SESSION['new']['notify_collaborator_overdue'])."'
		WHERE `id`='".intval($_SESSION['id'])."'"
		);

		// Clear remember-me tokens if username or email changed
		if ($_SESSION['new']['email'] !== $_SESSION['email'] || (strlen($sql_username) && $_SESSION['new']['user'] !== $_SESSION['user']))
		{
			hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."auth_tokens` WHERE `user_id` = ".intval($_SESSION['id'])." AND `user_type` = 'STAFF'");
			hesk_setcookie('hesk_remember', '');
		}

		/* Process the session variables */
		$_SESSION['new'] = hesk_stripArray($_SESSION['new']);

		// Do we need a new session_veify tag?
		if ( strlen($sql_username) )
		{
			$res = hesk_dbQuery('SELECT `pass` FROM `'.hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id` = '".intval($_SESSION['id'])."' LIMIT 1");
			$_SESSION['session_verify'] = hesk_activeSessionCreateTag($_SESSION['new']['user'], hesk_dbResult($res) );
		}

        /* Update session variables */
        foreach ($_SESSION['new'] as $k => $v)
        {
        	$_SESSION[$k] = $v;
        }
        unset($_SESSION['new']);

		hesk_cleanSessionVars('as_notify');

	    hesk_process_messages($hesklang['profile_updated_success'],'profile.php','SUCCESS');
    }
} // End update_profile()

?>
reports.php
wget 'https://lists2.roe3.org/hesk/admin/reports.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
require(HESK_PATH . 'inc/reporting_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_run_reports');

// Should reports be full or limited to own tickets?
$can_run_reports_full = hesk_checkPermission('can_run_reports_full', 0);

// Set default values
define('CALENDAR',1);
define('MAIN_PAGE',1);
define('LOAD_TABS',1);

$selected = array(
	'w'    => array(0=>'',1=>''),
	'time' => array(1=>'',2=>'',3=>'',4=>'',5=>'',6=>'',7=>'',8=>'',9=>'',10=>'',11=>'',12=>''),
    'type' => array(1=>'',2=>'',3=>'',4=>''),
);
$is_all_time = 0;

// Default this month to date
$hesk_settings['datepicker'] = array();

$df = new DateTime("first day of this month");
$date_from = $df->format('Y-m-d');
$hesk_settings['datepicker']['#datefrom']['timestamp'] = $df->getTimestamp();

$dt = new DateTime();
$date_to = $dt->format('Y-m-d');
$hesk_settings['datepicker']['#dateto']['timestamp'] = $dt->getTimestamp();

$input_datefrom = hesk_translate_date_string(date($hesk_settings['format_datepicker_php'], strtotime('last month')));
$input_dateto = hesk_translate_date_string(date($hesk_settings['format_datepicker_php']));

/* Date */
if (!empty($_GET['w']))
{
    $df = hesk_datepicker_get_date( hesk_GET('datefrom') );
    if ($df === false) {
        try {
            $df = new DateTime( hesk_GET('datefrom') );
            $date_from = $df->format('Y-m-d');
            $input_datefrom = hesk_translate_date_string($df->format($hesk_settings['format_datepicker_php']));
        } catch(Exception $e) {
            $date_from = date('Y-m-d', strtotime('last month') );
        }
    } else {
        $date_from = $df->format('Y-m-d');
        $input_datefrom = hesk_translate_date_string($df->format($hesk_settings['format_datepicker_php']));
    }

    $dt = hesk_datepicker_get_date( hesk_GET('dateto') );
    if ($dt === false) {
        try {
            $dt = new DateTime( hesk_GET('dateto') );
            $date_to = $dt->format('Y-m-d');
            $input_dateto = hesk_translate_date_string($dt->format($hesk_settings['format_datepicker_php']));
        } catch(Exception $e) {
            $date_to = date('Y-m-d');
        }
    } else {
        $date_to = $dt->format('Y-m-d');
        $input_dateto = hesk_translate_date_string($dt->format($hesk_settings['format_datepicker_php']));
    }

    if ($date_from > $date_to)
    {
        $tmp = $date_from;
        $tmp2 = $input_datefrom;

        $date_from = $date_to;
        $input_datefrom = $input_dateto;

        $date_to = $tmp;
        $input_dateto = $tmp2;

        $note_buffer = $hesklang['datetofrom'];

        $df2 = $df;
        $df = $dt;
        $dt = $df2;
        unset($df2);
    }

    if ($date_to > date('Y-m-d'))
    {
        $dt = new DateTime();
        $date_to = $dt->format('Y-m-d');
        $input_dateto = hesk_translate_date_string(date($hesk_settings['format_datepicker_php']));
    }

    if ($df instanceof DateTime) {
        $hesk_settings['datepicker']['#datefrom']['timestamp'] = $df->getTimestamp();
    } elseif (isset($hesk_settings['datepicker']['#datefrom']['timestamp'])) {
        unset($hesk_settings['datepicker']['#datefrom']['timestamp']);
    }

    if ($dt instanceof DateTime) {
        $hesk_settings['datepicker']['#dateto']['timestamp'] = $dt->getTimestamp();
    } elseif (isset($hesk_settings['datepicker']['#dateto']['timestamp'])) {
        unset($hesk_settings['datepicker']['#dateto']['timestamp']);
    }

    $query_string = 'reports.php?w=1&amp;datefrom='.urlencode($input_datefrom).'&amp;dateto='.urlencode($input_dateto);
	$selected['w'][1]='checked="checked"';
    $selected['time'][3]='selected="selected"';
}
else
{
	$selected['w'][0]='checked="checked"';
	$_GET['time'] = intval( hesk_GET('time', 3) );

    switch ($_GET['time'])
    {
    	case 1:
			/* Today */
			$date_from = date('Y-m-d');
			$date_to = $date_from;
			$selected['time'][1]='selected="selected"';
            $is_all_time = 1;
        break;

    	case 2:
			/* Yesterday */
			$date_from = date('Y-m-d',mktime(0, 0, 0, date("m"), date("d")-1, date("Y")));
			$date_to = $date_from;
			$selected['time'][2]='selected="selected"';
            $is_all_time = 1;
        break;

    	case 4:
			/* Last month */
			$date_from = date('Y-m-d',mktime(0, 0, 0, date("m")-1, 1, date("Y")));
			$date_to = date('Y-m-d',mktime(0, 0, 0, date("m"), 0, date("Y")));
			$selected['time'][4]='selected="selected"';
        break;

    	case 5:
			/* Last 30 days */
			$date_from = date('Y-m-d',mktime(0, 0, 0, date("m")-1, date("d"), date("Y")));
			$date_to = date('Y-m-d');
			$selected['time'][5]='selected="selected"';
        break;

    	case 6:
			/* This week */
			list($date_from,$date_to)=dateweek(0);
            $date_to = date('Y-m-d');
			$selected['time'][6]='selected="selected"';
        break;

    	case 7:
			/* Last week */
			list($date_from,$date_to)=dateweek(-1);
			$selected['time'][7]='selected="selected"';
        break;

    	case 8:
			/* This business week */
			list($date_from,$date_to)=dateweek(0,1);
            $date_to = date('Y-m-d');
			$selected['time'][8]='selected="selected"';
        break;

    	case 9:
			/* Last business week */
			list($date_from,$date_to)=dateweek(-1,1);
			$selected['time'][9]='selected="selected"';
        break;

    	case 10:
			/* This year */
			$date_from = date('Y').'-01-01';
			$date_to = date('Y-m-d');
			$selected['time'][10]='selected="selected"';
        break;

    	case 11:
			/* Last year */
			$date_from = date('Y')-1 . '-01-01';
			$date_to = date('Y')-1 . '-12-31';
			$selected['time'][11]='selected="selected"';
        break;

    	case 12:
			/* All time */
			$date_from = hesk_getOldestDate();
			$date_to = date('Y-m-d');
			$selected['time'][12]='selected="selected"';
            $is_all_time = 1;
        break;

        default:
        	$_GET['time'] = 3;
			$selected['time'][3]='selected="selected"';
    }

    $query_string = 'reports.php?w=0&amp;time='.$_GET['time'];
}

unset($tmp);

/* Type */
$type = intval( hesk_GET('type', 1) );
if (isset($selected['type'][$type]))
{
	$selected['type'][$type] = 'selected="selected"';
}

// Setup date SQL so we don't have to call functions several times
$hesk_settings['dt_sql'] = " `dt` BETWEEN '" . hesk_dbEscape($date_from) . " 00:00:00' AND '" . hesk_dbEscape($date_to) . " 23:59:59' ";

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
hesk_handle_messages();
?>
<div class="main__content reports">
    <form action="reports.php" method="get" name="form1" aria-label="<?php echo $hesklang['reports_tab']; ?>">
        <div class="reports__head">
            <h2>
                <?php echo $hesklang['reports_tab']; ?>
                <div class="tooltype right out-close">
                    <svg class="icon icon-info">
                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                    </svg>
                    <div class="tooltype__content">
                        <div class="tooltype__wrapper">
                            <?php echo $hesklang['reports_intro']; ?>
                        </div>
                    </div>
                </div>
            </h2>
        </div>
        <div class="reports__range">
            <h4><?php echo $hesklang['dtrg']; ?></h4>
            <div class="reports__range_form form">
                <div class="radio-list">
                    <div class="radio-custom">
                        <input type="radio" name="w" value="0" id="w0" <?php echo $selected['w'][0]; ?>>
                        <label for="w0" aria-label="<?php echo $hesklang['dtrg']; ?>">&nbsp;</label>
                        <div class="dropdown-select center out-close">
                            <select name="time" onclick="document.getElementById('w0').checked = true" onchange="document.getElementById('w0').checked = true" style="margin-top:5px;margin-bottom:5px;">
                                <option value="1" <?php echo $selected['time'][1]; ?>><?php echo $hesklang['r1']; ?> (<?php echo $hesklang['d'.date('w')]; ?>)</option>
                                <option value="2" <?php echo $selected['time'][2]; ?>><?php echo $hesklang['r2']; ?> (<?php echo $hesklang['d'.date('w',mktime(0, 0, 0, date('m'), date('d')-1, date('Y')))]; ?>)</option>
                                <option value="3" <?php echo $selected['time'][3]; ?>><?php echo $hesklang['r3']; ?> (<?php echo $hesklang['m'.date('n')]; ?>)</option>
                                <option value="4" <?php echo $selected['time'][4]; ?>><?php echo $hesklang['r4']; ?> (<?php echo $hesklang['m'.date('n',mktime(0, 0, 0, date('m')-1, 1, date('Y')))]; ?>)</option>
                                <option value="5" <?php echo $selected['time'][5]; ?>><?php echo $hesklang['r5']; ?></option>
                                <option value="6" <?php echo $selected['time'][6]; ?>><?php echo $hesklang['r6']; ?></option>
                                <option value="7" <?php echo $selected['time'][7]; ?>><?php echo $hesklang['r7']; ?></option>
                                <option value="8" <?php echo $selected['time'][8]; ?>><?php echo $hesklang['r8']; ?></option>
                                <option value="9" <?php echo $selected['time'][9]; ?>><?php echo $hesklang['r9']; ?></option>
                                <option value="10" <?php echo $selected['time'][10]; ?>><?php echo $hesklang['r10']; ?> (<?php echo date('Y'); ?>)</option>
                                <option value="11" <?php echo $selected['time'][11]; ?>><?php echo $hesklang['r11']; ?> (<?php echo date('Y',mktime(0, 0, 0, date('m'), date('d'), date('Y')-1)); ?>)</option>
                                <option value="12" <?php echo $selected['time'][12]; ?>><?php echo $hesklang['r12']; ?></option>
                            </select>
                        </div>
                    </div>
                    <div class="radio-custom">
                        <input type="radio" name="w" value="1" id="w1" <?php echo $selected['w'][1]; ?>>
                        <label for="w1" aria-label="<?php echo $hesklang['cdr']; ?>">&nbsp;</label>
                        <?php echo $hesklang['from']; ?>
                        <section class="param calendar" style="margin-left: 10px; margin-right: 10px">
                            <div class="calendar--button">
                                <button type="button" onclick="document.getElementById('w1').checked = true" aria-label="<?php echo $hesklang['date'] . ' ' . $hesklang['from']; ?>">
                                    <svg class="icon icon-calendar">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-calendar"></use>
                                    </svg>
                                </button>
                                <input name="datefrom"
                                       id="datefrom"
                                    <?php if ($input_datefrom) {echo 'value="'.$input_datefrom.'"';} ?>
                                       type="text" class="datepicker" aria-label="<?php echo $hesklang['date'] . ' ' . $hesklang['from']; ?>">
                            </div>
                            <div class="calendar--value" <?php echo ($input_datefrom ? 'style="display: block"' : ''); ?>>
                                <span><?php echo $input_datefrom; ?></span>
                                <i class="close">
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                </i>
                            </div>
                        </section>
                        <?php echo $hesklang['to']; ?>
                        <section class="param calendar" style="margin-left: 10px;">
                            <div class="calendar--button">
                                <button type="button" onclick="document.getElementById('w1').checked = true" aria-label="<?php echo $hesklang['date'] . ' ' . $hesklang['to']; ?>">
                                    <svg class="icon icon-calendar">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-calendar"></use>
                                    </svg>
                                </button>
                                <input name="dateto"
                                       id="dateto"
                                    <?php if ($input_dateto) {echo 'value="'.$input_dateto.'"';} ?>
                                       type="text" class="datepicker" aria-label="<?php echo $hesklang['date'] . ' ' . $hesklang['to']; ?>">
                            </div>
                            <div class="calendar--value" <?php echo ($input_dateto ? 'style="display: block"' : ''); ?>>
                                <span><?php echo $input_dateto; ?></span>
                                <i class="close">
                                    <svg class="icon icon-close">
                                        <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-close"></use>
                                    </svg>
                                </i>
                            </div>
                        </section>
                    </div>
                </div>
            </div>
        </div>
        <div class="reports__type">
            <h4><?php echo $hesklang['crt']; ?></h4>
            <div class="dropdown-select center out-close">
                <select name="type">
                    <option value="1" <?php echo $selected['type'][1]; ?>><?php echo $hesklang['t1']; ?></option>
                    <option value="2" <?php echo $selected['type'][2]; ?>><?php echo $hesklang['t2']; ?></option>
                    <option value="3" <?php echo $selected['type'][3]; ?>><?php echo $hesklang['t3']; ?></option>
                    <option value="4" <?php echo $selected['type'][4]; ?>><?php echo $hesklang['t4']; ?></option>
                </select>
            </div>
        </div>
        <div class="reports__type">
            <button class="btn btn-full" ripple="ripple"><?php echo $hesklang['dire']; ?></button>
        </div>
        <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>">
    </form>

<?php
if ($date_from == $date_to)
{
	?>
	<h2 style="margin-top: 20px; margin-bottom: 20px"><?php echo hesk_date($date_from, true, true, true, $hesk_settings['format_date']); ?></h2>
	<?php
}
else
{
	?>
	<h2 style="margin-top: 20px; margin-bottom: 20px"><?php echo hesk_date($date_from, true, true, true, $hesk_settings['format_date']); ?> - <?php echo hesk_date($date_to, true, true, true, $hesk_settings['format_date']); ?></h2>
	<?php
}

// Show a note if reports are limited
if ( ! $can_run_reports_full)
{
	echo "<p>{$hesklang['roo']}</p>";
}

/* Report type */
switch ($type)
{
	case 2:
    	hesk_ticketsByMonth();
        break;
	case 3:
    	hesk_ticketsByUser();
        break;
	case 4:
    	hesk_ticketsByCategory();
        break;
	default:
    	hesk_ticketsByDay();
}

require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/


function hesk_ticketsByCategory()
{
	global $hesk_settings, $hesklang, $date_from, $date_to, $can_run_reports_full;

	/* List of categories */
	$cat = array();
	$res = hesk_dbQuery("SELECT `id`,`name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE " . ( $can_run_reports_full ? '1' : hesk_myCategories('id') ) . " ORDER BY `id` ASC");
	while ($row=hesk_dbFetchAssoc($res))
	{
		$cat[$row['id']]=$row['name'];
	}

	$tickets = array();
    $totals = array('num_tickets' => 0, 'resolved' => 0, 'all_replies' => 0, 'staff_replies' => 0, 'worked' => 0);

    /* Populate category counts */
    foreach ($cat as $id => $name)
    {
    	$tickets[$id] = array(
        'num_tickets' => 0,
        'resolved' => 0,
        'all_replies' => 0,
        'staff_replies' => 0,
		'worked' => '',
        );
    }

	/* SQL query for category stats */
	$res = hesk_dbQuery("SELECT `category`, COUNT(*) AS `num_tickets`, ".($hesk_settings['time_worked'] ? "SUM( TIME_TO_SEC(`time_worked`) ) AS `seconds_worked`," : '')." SUM(`replies`) AS `all_replies`, SUM(staffreplies) AS `staff_replies` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE {$hesk_settings['dt_sql']} " . ( $can_run_reports_full ? "" : " AND `owner` = '" . intval($_SESSION['id']) . "'" ) . " GROUP BY `category`");

	/* Update ticket values */
	while ($row = hesk_dbFetchAssoc($res))
	{
		if ( ! $hesk_settings['time_worked'])
		{
        	$row['seconds_worked'] = 0;
		}

    	if (isset($cat[$row['category']]))
        {
        	$tickets[$row['category']]['num_tickets'] += $row['num_tickets'];
            $tickets[$row['category']]['all_replies'] += $row['all_replies'];
            $tickets[$row['category']]['staff_replies'] += $row['staff_replies'];
            $tickets[$row['category']]['worked'] = $hesk_settings['time_worked'] ? hesk_SecondsToHHMMSS($row['seconds_worked']) : 0;
        }
        else
        {
        	/* Category deleted */
			if ( ! isset($tickets[9999]) )
			{
				$cat[9999] = $hesklang['catd'];
				$tickets[9999] = array('num_tickets' => $row['num_tickets'], 'resolved' => 0, 'all_replies' => $row['all_replies'], 'staff_replies' => $row['staff_replies'], 'worked' => $row['seconds_worked']);
			}
			else
			{
				$tickets[9999]['num_tickets'] += $row['num_tickets'];
				$tickets[9999]['all_replies'] += $row['all_replies'];
				$tickets[9999]['staff_replies'] += $row['staff_replies'];
				$tickets[9999]['worked'] += $row['seconds_worked'];
			}
        }

		$totals['num_tickets'] += $row['num_tickets'];
		$totals['all_replies'] += $row['all_replies'];
		$totals['staff_replies'] += $row['staff_replies'];
		$totals['worked'] += $row['seconds_worked'];
	}

	// Get number of resolved tickets
	$res = hesk_dbQuery("SELECT COUNT(*) AS `num_tickets` , `category` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `status` = '3' " . ( $can_run_reports_full ? "" : " AND `owner` = '" . intval($_SESSION['id']) . "'" ) . " AND {$hesk_settings['dt_sql']} GROUP BY `category`");

	// Update number of open and resolved tickets
	while ($row = hesk_dbFetchAssoc($res))
	{
    	if (isset($cat[$row['category']]))
        {
        	$tickets[$row['category']]['resolved'] += $row['num_tickets'];
        }
        else
        {
        	// Category deleted
        	$tickets[9999]['resolved'] += $row['num_tickets'];
        }

		$totals['resolved'] += $row['num_tickets'];
	}

	// Convert total seconds worked to HH:MM:SS
	$totals['worked'] = $hesk_settings['time_worked'] ? hesk_SecondsToHHMMSS($totals['worked']) : 0;
	if ( isset($tickets[9999]) )
	{
		$tickets[9999]['worked'] = $hesk_settings['time_worked'] ? hesk_SecondsToHHMMSS($tickets[9999]['worked']) : 0;
	}

	?>
    <div class="reports__table">
	    <table id="default-table" class="table sindu-table sindu_origin_table">
            <thead>
            <tr>
                <th><?php echo $hesklang['category']; ?></th>
                <th><?php echo $hesklang['tickets']; ?></th>
                <th><?php echo $hesklang['topen']; ?></th>
                <th><?php echo $hesklang['closed']; ?></th>
                <th><?php echo $hesklang['replies'] . ' (' . $hesklang['all'] .')'; ?></th>
                <th><?php echo $hesklang['replies'] . ' (' . $hesklang['staff'] .')'; ?></th>
                <?php
                if ($hesk_settings['time_worked'])
                {
                    echo '<th>'.$hesklang['ts'].'</th>';
                }
                ?>
            </tr>
            </thead>

	<?php
	$num_tickets = count($tickets);
	if ($num_tickets > 10)
	{
	?>
          <tr class="total">
	        <td><b><?php echo $hesklang['totals']; ?></b></td>
	        <td><b><?php echo $totals['num_tickets']; ?></b></td>
	        <td><b><?php echo $totals['num_tickets'] - $totals['resolved']; ?></b></td>
	        <td><b><?php echo $totals['resolved']; ?></b></td>
	        <td><b><?php echo $totals['all_replies']; ?></b></td>
	        <td><b><?php echo $totals['staff_replies']; ?></b></td>
			<?php
			if ($hesk_settings['time_worked'])
			{
				echo '<td><b>'.$totals['worked'].'</b></td>';
			}
			?>
	      </tr>
	<?php
	}

	foreach ($tickets as $k => $d)
	{
	    ?>
	      <tr>
	        <td><?php echo $cat[$k]; ?></td>
	        <td><?php echo $d['num_tickets']; ?></td>
	        <td><?php echo $d['num_tickets']-$d['resolved']; ?></td>
	        <td><?php echo $d['resolved']; ?></td>
	        <td><?php echo $d['all_replies']; ?></td>
	        <td><?php echo $d['staff_replies']; ?></td>
			<?php
			if ($hesk_settings['time_worked'])
			{
				echo '<td>'.$d['worked'].'</td>';
			}
			?>
	      </tr>
	    <?php
	}
	?>
	      <tr class="total">
	        <td><b><?php echo $hesklang['totals']; ?></b></td>
	        <td><b><?php echo $totals['num_tickets']; ?></b></td>
	        <td><b><?php echo $totals['num_tickets'] - $totals['resolved']; ?></b></td>
	        <td><b><?php echo $totals['resolved']; ?></b></td>
	        <td><b><?php echo $totals['all_replies']; ?></b></td>
	        <td><b><?php echo $totals['staff_replies']; ?></b></td>
			<?php
			if ($hesk_settings['time_worked'])
			{
				echo '<td><b>'.$totals['worked'].'</b></td>';
			}
			?>
	      </tr>
	    </table>
    </div>
    <?php
} // END hesk_ticketsByCategory


function hesk_ticketsByUser()
{
	global $hesk_settings, $hesklang, $date_from, $date_to;

	// Some variables we will need
	$tickets = array();
    $totals = array('asstickets' => 0, 'resolved' => 0, 'tickets' => 0, 'replies' => 0, 'worked' => 0, 'openedby' => 0);

	// Get list of users
	$admins = array();

	// I. ADMINISTRATORS can view all users
	if ($_SESSION['isadmin'] || hesk_checkPermission('can_run_reports_full', 0) )
	{
    	// -> get list of users
		$res = hesk_dbQuery("SELECT `id`,`name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` ORDER BY `name` ASC");

        // -> populate $admins and $tickets arrays
		while ($row=hesk_dbFetchAssoc($res))
		{
			$admins[$row['id']] = $row['name'];

	    	$tickets[$row['id']] = array(
		        'asstickets' => 0,
				'resolved' => 0,
		        'tickets' => 0,
		        'replies' => 0,
				'worked' => '',
                'openedby' => 0,
	        );
		}

        // -> get list of tickets
		$res = hesk_dbQuery("SELECT `owner`, COUNT(*) AS `cnt`".($hesk_settings['time_worked'] ? ", SUM( TIME_TO_SEC(`time_worked`) ) AS `seconds_worked`" : '')." FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `owner` IN ('" . implode("','", array_keys($admins) ) . "') AND {$hesk_settings['dt_sql']} GROUP BY `owner`");

		// -> update ticket list values
		while ($row = hesk_dbFetchAssoc($res))
		{
			if ( ! $hesk_settings['time_worked'])
			{
				$row['seconds_worked'] = 0;
			}

			$tickets[$row['owner']]['asstickets'] += $row['cnt'];
			$totals['asstickets'] += $row['cnt'];
			$tickets[$row['owner']]['worked'] = $hesk_settings['time_worked'] ? hesk_SecondsToHHMMSS($row['seconds_worked']) : 0;
			$totals['worked'] += $row['seconds_worked'];
		}

        // -> get list of resolved tickets
		$res = hesk_dbQuery("SELECT `owner`, COUNT(*) AS `cnt` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `owner` IN ('" . implode("','", array_keys($admins) ) . "') AND `status`='3' AND {$hesk_settings['dt_sql']} GROUP BY `owner`");

		// -> update resolved ticket list values
		while ($row = hesk_dbFetchAssoc($res))
		{
			$tickets[$row['owner']]['resolved'] += $row['cnt'];
			$totals['resolved'] += $row['cnt'];
		}

        // -> get number of replies
		$res = hesk_dbQuery("SELECT `staffid`, COUNT(*) AS `cnt`, COUNT(DISTINCT `replyto`) AS `tcnt` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` WHERE `staffid` IN ('" . implode("','", array_keys($admins) ) . "') AND {$hesk_settings['dt_sql']} GROUP BY `staffid`");

		// -> update number of replies values
		while ($row = hesk_dbFetchAssoc($res))
		{
			$tickets[$row['staffid']]['tickets'] += $row['tcnt'];
			$tickets[$row['staffid']]['replies'] += $row['cnt'];

			$totals['tickets'] += $row['tcnt'];
			$totals['replies'] += $row['cnt'];
		}
	}
	// II. OTHER STAFF may only see their own stats
	else
	{
		$admins[$_SESSION['id']] = $_SESSION['name'];

        $tickets[$_SESSION['id']] = array(
            'asstickets' => 0,
            'resolved' => 0,
            'tickets' => 0,
            'replies' => 0,
            'worked' => '',
            'openedby' => 0,
        );

        // -> get list of tickets
		$res = hesk_dbQuery("SELECT COUNT(*) AS `cnt`".($hesk_settings['time_worked'] ? ", SUM( TIME_TO_SEC(`time_worked`) ) AS `seconds_worked`" : '')." FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `owner` = '" . intval($_SESSION['id']) . "' AND {$hesk_settings['dt_sql']}");
        $row = hesk_dbFetchAssoc($res);
        if ( ! $hesk_settings['time_worked'] || empty($row['seconds_worked']))
        {
            $row['seconds_worked'] = 0;
        }

        // -> update ticket values
    	$tickets[$_SESSION['id']]['asstickets'] = $row['cnt'];
		$totals['asstickets'] = $row['cnt'];
    	$tickets[$_SESSION['id']]['worked'] = $hesk_settings['time_worked'] ? hesk_SecondsToHHMMSS($row['seconds_worked']) : 0;
		$totals['worked'] += $row['seconds_worked'];

        // -> get list of resolved tickets
		$res = hesk_dbQuery("SELECT COUNT(*) AS `cnt` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `owner` = '" . intval($_SESSION['id']) . "' AND `status`='3' AND {$hesk_settings['dt_sql']}");
        $row = hesk_dbFetchAssoc($res);

        // -> update resolved ticket values
    	$tickets[$_SESSION['id']]['resolved'] = $row['cnt'];
		$totals['resolved'] = $row['cnt'];

        // -> get number of replies
		$res = hesk_dbQuery("SELECT COUNT(*) AS `cnt`, COUNT(DISTINCT `replyto`) AS `tcnt` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` WHERE `staffid` = '" . intval($_SESSION['id']) . "' AND {$hesk_settings['dt_sql']}");
        $row = hesk_dbFetchAssoc($res);

		$tickets[$_SESSION['id']]['tickets'] = $row['tcnt'];
		$tickets[$_SESSION['id']]['replies'] = $row['cnt'];

		$totals['tickets'] = $row['tcnt'];
		$totals['replies'] = $row['cnt'];

	}

	// Convert total seconds worked to HH:MM:SS
	$totals['worked'] = $hesk_settings['time_worked'] ? hesk_SecondsToHHMMSS($totals['worked']) : 0;

	// Get total opened by tickets
	$res = hesk_dbQuery("SELECT `openedby`, COUNT(*) AS `cnt` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `openedby` IN ('" . implode("','", array_keys($admins) ) . "') AND DATE(`dt`) BETWEEN '" . hesk_dbEscape($date_from) . "' AND '" . hesk_dbEscape($date_to) . "' GROUP BY `openedby`");

	// -> update ticket list values
	while ($row = hesk_dbFetchAssoc($res))
	{
		$tickets[$row['openedby']]['openedby'] += $row['cnt'];
		$totals['openedby'] += $row['cnt'];
	}
	?>
    <div class="reports__table">
	    <table id="default-table" class="table sindu-table sindu_origin_table">
            <thead>
            <tr>
                <th><?php echo $hesklang['user']; ?></th>
                <th><?php echo $hesklang['numsub']; ?></th>
                <th><?php echo $hesklang['ticass']; ?></th>
                <th><?php echo $hesklang['topen']; ?></th>
                <th><?php echo $hesklang['closed']; ?></th>
                <th><?php echo $hesklang['ticall']; ?></th>
                <th><?php echo $hesklang['replies']; ?></th>
                <?php
                if ($hesk_settings['time_worked'])
                {
                    echo '<th>'.$hesklang['ts'].'</th>';
                }
                ?>
            </tr>
            </thead>

	<?php
	$num_tickets = count($tickets);
	if ($num_tickets > 10)
	{
	?>
          <tr class="total">
	        <td><b><?php echo $hesklang['totals']; ?></b></td>
            <td><b><?php echo $totals['openedby']; ?></b></td>
	        <td><b><?php echo $totals['asstickets']; ?></b></td>
	        <td><b><?php echo $totals['asstickets']-$totals['resolved']; ?></b></td>
	        <td><b><?php echo $totals['resolved']; ?></b></td>
	        <td><b><?php echo $totals['tickets']; ?></b></td>
	        <td><b><?php echo $totals['replies']; ?></b></td>
			<?php
			if ($hesk_settings['time_worked'])
			{
				echo '<td><b>'.$totals['worked'].'</b></td>';
			}
			?>
	      </tr>
	<?php
	}

	foreach ($tickets as $k => $d)
	{
	    ?>
	      <tr>
	        <td><?php echo $admins[$k]; ?></td>
            <td><?php echo $d['openedby']; ?></td>
	        <td><?php echo $d['asstickets']; ?></td>
	        <td><?php echo $d['asstickets']-$d['resolved']; ?></td>
	        <td><?php echo $d['resolved']; ?></td>
	        <td><?php echo $d['tickets']; ?></td>
	        <td><?php echo $d['replies']; ?></td>
			<?php
			if ($hesk_settings['time_worked'])
			{
				echo '<td>'.$d['worked'].'</td>';
			}
			?>
	      </tr>
	    <?php
	}
	?>
	      <tr class="total">
	        <td><b><?php echo $hesklang['totals']; ?></b></td>
            <td><b><?php echo $totals['openedby']; ?></b></td>
	        <td><b><?php echo $totals['asstickets']; ?></b></td>
	        <td><b><?php echo $totals['asstickets']-$totals['resolved']; ?></b></td>
	        <td><b><?php echo $totals['resolved']; ?></b></td>
	        <td><b><?php echo $totals['tickets']; ?></b></td>
	        <td><b><?php echo $totals['replies']; ?></b></td>
			<?php
			if ($hesk_settings['time_worked'])
			{
				echo '<td><b>'.$totals['worked'].'</b></td>';
			}
			?>
	      </tr>
	    </table>
    </div>
    <?php
} // END hesk_ticketsByUser


function hesk_ticketsByMonth()
{
	global $hesk_settings, $hesklang, $date_from, $date_to, $can_run_reports_full;

	$tickets = array();
    $totals = array('all' => 0, 'resolved' => 0, 'worked' => 0);
	$dt = MonthsArray($date_from,$date_to);

	// Pre-populate date values
	foreach ($dt as $month)
	{
		$tickets[$month] = array(
		'all' => 0,
		'resolved' => 0,
		'worked' => '',
		);
	}

	// SQL query for all
    $res = hesk_dbQuery("SELECT YEAR(`dt`) AS `myyear`, MONTH(`dt`) AS `mymonth`, COUNT(*) AS `cnt`".($hesk_settings['time_worked'] ? ", SUM( TIME_TO_SEC(`time_worked`) ) AS `seconds_worked`" : '')." FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE " . ( $can_run_reports_full ? '1' : "`owner` = '" . intval($_SESSION['id']) . "'" ) . " AND {$hesk_settings['dt_sql']} GROUP BY `myyear`,`mymonth`");

	// Update ticket values
	while ($row = hesk_dbFetchAssoc($res))
	{
		if ( ! $hesk_settings['time_worked'])
		{
			$row['seconds_worked'] = 0;
		}

    	$row['mymonth'] = sprintf('%02d',$row['mymonth']);
		$tickets[$row['myyear'].'-'.$row['mymonth'].'-01']['all'] += $row['cnt'];
		$tickets[$row['myyear'].'-'.$row['mymonth'].'-01']['worked'] = $hesk_settings['time_worked'] ? hesk_SecondsToHHMMSS($row['seconds_worked']) : 0;
	    $totals['all'] += $row['cnt'];
		$totals['worked'] += $row['seconds_worked'];
	}

	// SQL query for resolved
	$res = hesk_dbQuery("SELECT YEAR(`dt`) AS `myyear`, MONTH(`dt`) AS `mymonth`, COUNT(*) AS `cnt` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE " . ( $can_run_reports_full ? '1' : "`owner` = '" . intval($_SESSION['id']) . "'" ) . " AND `status` = '3' AND {$hesk_settings['dt_sql']} GROUP BY `myyear`,`mymonth`");

	// Update ticket values
	while ($row = hesk_dbFetchAssoc($res))
	{
    	$row['mymonth'] = sprintf('%02d',$row['mymonth']);
		$tickets[$row['myyear'].'-'.$row['mymonth'].'-01']['resolved'] += $row['cnt'];
	    $totals['resolved'] += $row['cnt'];
	}

	// Convert total seconds worked to HH:MM:SS
	$totals['worked'] = $hesk_settings['time_worked'] ? hesk_SecondsToHHMMSS($totals['worked']) : 0;

	?>
    <div class="reports__table">
	    <table id="default-table" class="table sindu-table sindu_origin_table">
            <thead>
            <tr>
                <th><?php echo $hesklang['month']; ?></th>
                <th><?php echo $hesklang['atik']; ?></th>
                <th><?php echo $hesklang['topen']; ?></th>
                <th><?php echo $hesklang['closed']; ?></th>
                <?php
                if ($hesk_settings['time_worked'])
                {
                    echo '<th>'.$hesklang['ts'].'</th>';
                }
                ?>
            </tr>
            </thead>

	<?php
	$num_tickets = count($tickets);
	if ($num_tickets > 10)
	{
	?>
          <tr class="total">
	        <td><b><?php echo $hesklang['totals']; ?></b></td>
	        <td><b><?php echo $totals['all']; ?></b></td>
	        <td><b><?php echo $totals['all']-$totals['resolved']; ?></b></td>
	        <td><b><?php echo $totals['resolved']; ?></b></td>
			<?php
			if ($hesk_settings['time_worked'])
			{
				echo '<td><b>'.$totals['worked'].'</b></td>';
			}
			?>
	      </tr>
	<?php
	}

	foreach ($tickets as $k => $d)
	{
	    ?>
	      <tr>
	        <td><?php echo hesk_dateToString($k,0,0,1); ?></td>
	        <td><?php echo $d['all']; ?></td>
	        <td><?php echo $d['all']-$d['resolved']; ?></td>
	        <td><?php echo $d['resolved']; ?></td>
			<?php
			if ($hesk_settings['time_worked'])
			{
				echo '<td>'.$d['worked'].'</td>';
			}
			?>
	      </tr>
	    <?php
	}
	?>
	      <tr class="total">
	        <td><b><?php echo $hesklang['totals']; ?></b></td>
	        <td><b><?php echo $totals['all']; ?></b></td>
	        <td><b><?php echo $totals['all']-$totals['resolved']; ?></b></td>
	        <td><b><?php echo $totals['resolved']; ?></b></td>
			<?php
			if ($hesk_settings['time_worked'])
			{
				echo '<td><b>'.$totals['worked'].'</b></td>';
			}
			?>
	      </tr>
	    </table>
    </div>
    <?php
} // END hesk_ticketsByMonth


function hesk_ticketsByDay()
{
	global $hesk_settings, $hesklang, $date_from, $date_to, $can_run_reports_full;

	$tickets = array();
    $totals = array('all' => 0, 'resolved' => 0, 'worked' => 0);
	$dt = DateArray($date_from,$date_to);

	// Pre-populate date values
	foreach ($dt as $day)
	{
		$tickets[$day] = array(
		'all' => 0,
		'resolved' => 0,
		'worked' => '',
		);
	}

	// SQL query for all
	$res = hesk_dbQuery("SELECT DATE(`dt`) AS `mydt`, COUNT(*) AS `cnt`".($hesk_settings['time_worked'] ? ", SUM( TIME_TO_SEC(`time_worked`) ) AS `seconds_worked`" : '')." FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE " . ( $can_run_reports_full ? '1' : "`owner` = '" . intval($_SESSION['id']) . "'" ) . " AND {$hesk_settings['dt_sql']} GROUP BY `mydt`");

	// Update ticket values
	while ($row = hesk_dbFetchAssoc($res))
	{
		if ( ! $hesk_settings['time_worked'])
		{
			$row['seconds_worked'] = 0;
		}

		$tickets[$row['mydt']]['all'] += $row['cnt'];
		$tickets[$row['mydt']]['worked'] = $hesk_settings['time_worked'] ? hesk_SecondsToHHMMSS($row['seconds_worked']) : 0;
	    $totals['all'] += $row['cnt'];
		$totals['worked'] += $row['seconds_worked'];
	}

	// SQL query for resolved
	$res = hesk_dbQuery("SELECT DATE(`dt`) AS `mydt`, COUNT(*) AS `cnt` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE " . ( $can_run_reports_full ? '1' : "`owner` = '" . intval($_SESSION['id']) . "'" ) . " AND `status`='3' AND {$hesk_settings['dt_sql']} GROUP BY `mydt`");

	// Update ticket values
	while ($row = hesk_dbFetchAssoc($res))
	{
		$tickets[$row['mydt']]['resolved'] += $row['cnt'];
	    $totals['resolved'] += $row['cnt'];
	}

	// Convert total seconds worked to HH:MM:SS
	$totals['worked'] = $hesk_settings['time_worked'] ? hesk_SecondsToHHMMSS($totals['worked']) : 0;

	?>
    <div class="reports__table">
	    <table id="default-table" class="table sindu-table sindu_origin_table">
            <thead>
            <tr>
                <th><?php echo $hesklang['date']; ?></th>
                <th><?php echo $hesklang['atik']; ?></th>
                <th><?php echo $hesklang['topen']; ?></th>
                <th><?php echo $hesklang['closed']; ?></th>
                <?php
                if ($hesk_settings['time_worked'])
                {
                    echo '<th>'.$hesklang['ts'].'</th>';
                }
                ?>
            </tr>
            </thead>

	<?php
	$num_tickets = count($tickets);
	if ($num_tickets > 10)
	{
	?>
          <tr class="total">
	        <td><b><?php echo $hesklang['totals']; ?></b></td>
	        <td><b><?php echo $totals['all']; ?></b></td>
	        <td><b><?php echo $totals['all']-$totals['resolved']; ?></b></td>
	        <td><b><?php echo $totals['resolved']; ?></b></td>
			<?php
			if ($hesk_settings['time_worked'])
			{
				echo '<td><b>'.$totals['worked'].'</b></td>';
			}
			?>
	      </tr>
	<?php
	}

	foreach ($tickets as $k => $d)
	{
	    ?>
	      <tr>
	        <td><?php echo hesk_dateToString($k); ?></td>
	        <td><?php echo $d['all']; ?></td>
	        <td><?php echo $d['all']-$d['resolved']; ?></td>
	        <td><?php echo $d['resolved']; ?></td>
			<?php
			if ($hesk_settings['time_worked'])
			{
				echo '<td>'.$d['worked'].'</td>';
			}
			?>
	      </tr>
	    <?php
	}
	?>
	      <tr class="total">
	        <td><b><?php echo $hesklang['totals']; ?></b></td>
	        <td><b><?php echo $totals['all']; ?></b></td>
	        <td><b><?php echo $totals['all']-$totals['resolved']; ?></b></td>
	        <td><b><?php echo $totals['resolved']; ?></b></td>
			<?php
			if ($hesk_settings['time_worked'])
			{
				echo '<td><b>'.$totals['worked'].'</b></td>';
			}
			?>
	      </tr>
	    </table>
    </div>
    <?php
} // END hesk_ticketsByDay
?>
</div>
resend_notification.php
wget 'https://lists2.roe3.org/hesk/admin/resend_notification.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();
require(HESK_PATH . 'inc/email_functions.inc.php');
require_once(HESK_PATH . 'inc/customer_accounts.inc.php');

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_view_tickets');

// A security check
hesk_token_check('GET');

// Ticket ID
$trackingID = hesk_cleanID() or die($hesklang['int_error'].': '.$hesklang['no_trackID']);

// Ticket details
$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `trackid`='".hesk_dbEscape($trackingID)."' LIMIT 1");
if (hesk_dbNumRows($res) != 1)
{
	hesk_error($hesklang['ticket_not_found']);
}
$ticket = hesk_dbFetchAssoc($res);
hesk_verifyStaffTicketAccess($trackingID, $ticket);
$opened_by = $ticket['openedby'];

// Reply or original message?
$reply_id  = intval( hesk_GET('reply', 0) );

if ($reply_id > 0)
{
    $result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` WHERE `id`={$reply_id} AND `replyto`=".intval($ticket['id'])." LIMIT 1");
    if (hesk_dbNumRows($result) != 1)
    {
        hesk_error($hesklang['ernf']);
    }

    $reply = hesk_dbFetchAssoc($result);

    $ticket['message'] = $reply['message'];
    $ticket['message_html'] = $reply['message_html'];
    $ticket['attachments'] = $reply['attachments'];
}

/* --> Prepare message */
$customers = hesk_get_customers_for_ticket($ticket['id']);
$customer_emails = array_map(function($customer) { return $customer['email']; }, $customers);
$customer_names = array_map(function($customer) { return $customer['name']; }, $customers);

// 1. Generate the array with ticket info that can be used in emails
$info = array(
'email'			=> implode(';', $customer_emails),
'category'		=> $ticket['category'],
'priority'		=> $ticket['priority'],
'owner'			=> $ticket['owner'],
'collaborators' => hesk_getTicketsCollaboratorIDs($ticket['id']),
'trackid'		=> $ticket['trackid'],
'status'		=> $ticket['status'],
'name'			=> implode(';', $customer_names),
'subject'		=> $ticket['subject'],
'message'		=> $ticket['message'],
'message_html'  => $ticket['message_html'],
'attachments'	=> $ticket['attachments'],
'dt'			=> hesk_date($ticket['dt'], true),
'lastchange'	=> hesk_date($ticket['lastchange'], true),
'due_date'      => hesk_format_due_date($ticket['due_date']),
'id'			=> $ticket['id'],
'time_worked'   => $ticket['time_worked'],
'last_reply_by' => hesk_getReplierNameArray($ticket),
'language'      => $ticket['language'],
);

// 2. Add custom fields to the array
foreach ($hesk_settings['custom_fields'] as $k => $v)
{
	$info[$k] = $v['use'] ? $ticket[$k] : '';
}

// 3. Make sure all values are properly formatted for email
$ticket = hesk_ticketToPlain($info, 1, 0);

// Remind assigned staff?
if (hesk_GET('remind') == 1 && $ticket['owner']) {
    hesk_notifyAssignedStaff(false, 'ticket_assigned_to_you');

    if ($ticket['collaborators']) {
        hesk_notifyCollaborators($ticket['collaborators'], 'collaborator_added', 'notify_collaborator_added');
    }

    $res = hesk_dbQuery("SELECT `user`,`name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id`=".intval($ticket['owner'])." LIMIT 1");
    $row = hesk_dbFetchAssoc($res);
    $revision = sprintf($hesklang['thist23'],hesk_date(),addslashes($row['name']).' ('.$row['user'].')',addslashes($_SESSION['name']).' ('.$_SESSION['user'].')');
    hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `lastchange`=`lastchange`, `history`=CONCAT(`history`,'" . hesk_dbEscape($revision) . "') WHERE `id`=" . intval($ticket['id']));
    hesk_process_messages($hesklang['remind_sent'],'admin_ticket.php?track='.$trackingID.'&Refresh='.rand(10000,99999),'SUCCESS');
}

// Notification of a reply
if ($reply_id > 0)
{
    // Reply by staff, send notification to customer
    if ($reply['staffid']) {
        hesk_notifyCustomer('new_reply_by_staff');

        if ($ticket['collaborators']) {
            hesk_notifyAssignedStaff(false, 'collaborator_staff_reply', 'notify_collaborator_staff_reply', 'notify_collaborator_staff_reply');
        }
    }
    // --> If ticket is assigned, notify the owner plus collaborators
    elseif ($ticket['owner']) {
        hesk_notifyAssignedStaff(false, 'new_reply_by_customer', 'notify_reply_my', 'notify_collaborator_customer_reply');
    }
    // --> No owner assigned, find and notify appropriate staff, including collaborators
    elseif ($ticket['collaborators']) {
        hesk_notifyStaff('new_reply_by_customer',"`notify_reply_unassigned`='1' OR (`notify_collaborator_customer_reply`='1' AND `id` IN (".implode(",", $ticket['collaborators'])."))", 1);
    }
    // --> No owner assigned, find and notify appropriate staff, no collaborators
    else {
        hesk_notifyStaff('new_reply_by_customer',"`notify_reply_unassigned`='1'", 1);
    }

    hesk_process_messages($hesklang['rns'],'admin_ticket.php?track='.$trackingID.'&Refresh='.rand(10000,99999),'SUCCESS');
}

// Notification of the original ticket
if ($opened_by) {
    hesk_notifyCustomer('new_ticket_by_staff');
} else {
    hesk_notifyCustomer();
}

// Notify staff?
if ($ticket['owner']) {
    hesk_notifyAssignedStaff(false, 'ticket_assigned_to_you');
    if ($ticket['collaborators']) {
        hesk_notifyCollaborators($ticket['collaborators'], 'collaborator_added', 'notify_collaborator_added');
    }
} elseif (count($ticket['collaborators'])) {
    hesk_notifyStaff('new_ticket_staff', "`notify_new_unassigned`='1' OR (`notify_collaborator_added`='1' AND `id` IN (".implode(",", $ticket['collaborators'])."))", 1);
} else {
    hesk_notifyStaff('new_ticket_staff', "`notify_new_unassigned`='1'", 1);
}

hesk_process_messages($hesklang['tns'],'admin_ticket.php?track='.$trackingID.'&Refresh='.rand(10000,99999),'SUCCESS');
save_ticket_draft_async.php
wget 'https://lists2.roe3.org/hesk/admin/save_ticket_draft_async.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();
require(HESK_PATH . 'inc/email_functions.inc.php');
require(HESK_PATH . 'inc/posting_functions.inc.php');

// We only allow POST requests from the HESK form to this file
if ( $_SERVER['REQUEST_METHOD'] != 'POST' )
{
    http_response_code(400);
    exit();
}

// Check for POST requests larger than what the server can handle
if ( empty($_POST) && ! empty($_SERVER['CONTENT_LENGTH']) )
{
    http_response_code(400);
    exit();
}

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_reply_tickets');

// A security check
hesk_token_check('POST');

// Original ticket ID
$ticket['id'] = intval( hesk_POST('orig_id', 0) ) or die($hesklang['int_error']);

// Get ticket info and verify access before saving a draft
$result = hesk_dbQuery("SELECT `id`, `trackid`, `category`, `owner`, `assignedby` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`=".intval($ticket['id'])." LIMIT 1");
if (hesk_dbNumRows($result) != 1)
{
    http_response_code(404);
    exit();
}
$ticket = hesk_dbFetchAssoc($result);
hesk_verifyStaffTicketAccess($ticket['trackid'], $ticket);

// Get existing draft ID
$result = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."reply_drafts` WHERE `owner`=".intval($_SESSION['id'])." AND `ticket`=".intval($ticket['id']));
if (hesk_dbNumRows($result) == 1) {
    $draft_id = hesk_dbResult($result);
} else {
    $draft_id = 0;
}

// Get the message
$message = hesk_input(hesk_POST('message'));

if (strlen($message))
{
    $message_html = $message;

    // Handle rich-text tickets
    if ($hesk_settings['staff_ticket_formatting'] == 2) {
        // Decode the message we encoded earlier
        $message_html = hesk_html_entity_decode($message_html);

        // Clean the HTML code and set the plaintext version
        require(HESK_PATH . 'inc/htmlpurifier/HeskHTMLPurifier.php');
        require(HESK_PATH . 'inc/html2text/html2text.php');
        $purifier = new HeskHTMLPurifier($hesk_settings['cache_dir']);
        $message_html = $purifier->heskPurify($message_html);

        $message = convert_html_to_text($message_html);
        $message = fix_newlines($message);

        // Prepare plain message for storage as HTML
        $message = hesk_htmlspecialchars($message);
        // nl2br done after adding signature
    } elseif ($hesk_settings['staff_ticket_formatting'] == 0) {
        $message_html = hesk_makeURL($message_html);
        $message_html = nl2br($message_html);
    }

    if ($draft_id) {
        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."reply_drafts` SET `message`='".hesk_dbEscape($message)."', `message_html`='".hesk_dbEscape($message_html)."' WHERE `id`=".intval($draft_id));
        echo "Draft updated";
    } else {
        hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."reply_drafts` (`owner`, `ticket`, `message`, `message_html`) VALUES (".intval($_SESSION['id']).", ".intval($ticket['id']).", '".hesk_dbEscape($message)."', '".hesk_dbEscape($message_html)."')");
        echo "Draft saved";
    }
} elseif ($draft_id > 0) {
    // Delete any existing drafts from this owner for this ticket
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."reply_drafts` WHERE `owner`=".intval($_SESSION['id'])." AND `ticket`=".intval($ticket['id']));
    echo "Draft deleted";
} else {
    echo "No message";
}

exit();
service_messages.php
wget 'https://lists2.roe3.org/hesk/admin/service_messages.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Check permissions for this feature */
hesk_checkPermission('can_service_msg');

// Define required constants
define('LOAD_TABS',1);
define('WYSIWYG',1);
if (isset($_SESSION['preview_sm']))
{
    define('STYLE_CODE',1);
}

// Valid service message locations (pages)
$hesk_settings['sm_locations'] = array(
    'ALL' => $hesklang['loc_all'],
    'home' => $hesklang['loc_home'],
    't-cat' => $hesklang['loc_t_cat'],
    't-add' => $hesklang['loc_t_add'],
    't-ok' => $hesklang['loc_t_ok'],
    't-view' => $hesklang['loc_t_view'],
    't-form' => $hesklang['loc_t_form'],
    'kb-main' => $hesklang['loc_kb_main'],
    'kb-sub' => $hesklang['loc_kb_sub'],
    'kb-art' => $hesklang['loc_kb_art'],
    'c-login' => $hesklang['loc_login'],
    'c-register' => $hesklang['loc_register'],
    'c-ok' => $hesklang['loc_register_ok'],
    'c-main' => $hesklang['loc_acc'],
    'c-profile' => $hesklang['loc_profile'],
);

// Do we need to show the language options?
$hesk_settings['show_language'] = (count($hesk_settings['languages']) > 1);

// What should we do?
if ( $action = hesk_REQUEST('a') )
{
	if ($action == 'edit_sm') {edit_sm();}
	elseif ( defined('HESK_DEMO') ) {hesk_process_messages($hesklang['ddemo'], 'service_messages.php', 'NOTICE');}
	elseif ($action == 'new_sm') {new_sm();}
	elseif ($action == 'save_sm') {save_sm();}
	elseif ($action == 'order_sm') {order_sm();}
	elseif ($action == 'remove_sm') {remove_sm();}
}

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print main manage users page */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');

/* This will handle error, success and notice messages */
if (!hesk_SESSION(array('new_sm', 'errors'))) {
    hesk_handle_messages();
}

// Get service messages from database
$res = hesk_dbQuery('SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'service_messages` ORDER BY `order` ASC');
$num = hesk_dbNumRows($res);
?>
<div class="main__content tools">
    <section class="tools__between-head">
        <h2>
            <?php echo $hesklang['sm_title']; ?>
            <div class="tooltype right out-close">
                <svg class="icon icon-info">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-info"></use>
                </svg>
                <div class="tooltype__content">
                    <div class="tooltype__wrapper">
                        <?php echo $hesklang['sm_intro']; ?>
                    </div>
                </div>
            </div>
        </h2>
        <?php if ($action !== 'edit_sm' && !isset($_SESSION['preview_sm'])): ?>
            <div class="btn btn--blue-border" ripple="ripple" data-action="create-service-message"><?php echo $hesklang['new_sm']; ?></div>
        <?php endif;?>
    </section>
    <div class="table-wrapper service-message">
        <div class="table">
            <table id="default-table" class="table sindu-table">
                <thead>
                <tr>
                    <th><?php echo $hesklang['sm_mtitle']; ?></th>
                    <th><?php echo $hesklang['sm_style']; ?></th>
                    <?php
                    if ($hesk_settings['show_language'])
                    {
                        ?>
                        <th><?php echo $hesklang['lgs']; ?></th>
                        <?php
                    }
                    ?>
                    <th><?php echo $hesklang['sm_author']; ?></th>
                    <th><?php echo $hesklang['sm_type']; ?></th>
                    <th><?php echo $hesklang['sm_location']; ?></th>
                    <th aria-label="Actions"></th>
                </tr>
                </thead>
                <tbody>
                <?php if ($num < 1): ?>
                <tr>
                    <td colspan="<?php echo $hesk_settings['show_language'] ? 7 : 6; ?>">
                        <?php echo $hesklang['no_sm']; ?>
                    </td>
                </tr>
                <?php
                else:
                    // List of staff
                    if (!isset($admins)) {
                        $admins = array();
                        $res2 = hesk_dbQuery("SELECT `id`,`name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users`");
                        while ($row=hesk_dbFetchAssoc($res2))
                        {
                            $admins[$row['id']]=$row['name'];
                        }
                    }

                    $k = 1;

                    while ($sm=hesk_dbFetchAssoc($res)) {
                        switch ($sm['style']) {
                            case 1:
                                $sm_style = "success";
                                break;
                            case 2:
                                $sm_style = "info";
                                break;
                            case 3:
                                $sm_style = "notice";
                                break;
                            case 4:
                                $sm_style = "error";
                                break;
                            default:
                                $sm_style = "none";
                        }

                        $table_row = '';
                        if (isset($_SESSION['smord']) && $_SESSION['smord'] == $sm['id']) {
                            $table_row = 'class="ticket-new"';
                            unset($_SESSION['smord']);
                        }

                        $type = $sm['type'] ? $hesklang['sm_draft']: $hesklang['sm_published'];
                        if (empty($sm['location'])) {
                            $locations = array('home');
                        } else {
                            $locations = explode(',', $sm['location']);
                        }

                        $location = '';
                        foreach ($locations as $loc) {
                            $location .= $hesk_settings['sm_locations'][$loc] . "<br>";
                        }
                        ?>
                        <tr <?php echo $table_row; ?>>
                            <td><?php echo $sm['title']; ?></td>
                            <td>
                                <div class="style <?php echo $sm_style; ?>">
                                    <?php echo $hesklang['sm_' . $sm_style]; ?>
                                </div>
                            </td>
                            <?php
                            if ($hesk_settings['show_language'])
                            {
                                ?>
                                <td><?php echo (is_string($sm['language']) && strlen($sm['language'])) ? $sm['language'] : $hesklang['all']; ?></td>
                                <?php
                            }
                            ?>
                            <td><?php echo (isset($admins[$sm['author']]) ? $admins[$sm['author']] : $hesklang['e_udel']); ?></td>
                            <td><?php echo $type; ?></td>
                            <td><?php echo $location; ?></td>
                            <td class="nowrap buttons">
                                <?php $modal_id = hesk_generate_old_delete_modal($hesklang['confirm_deletion'],
                                    $hesklang['del_sm'],
                                    'service_messages.php?a=remove_sm&amp;id='. $sm['id'] .'&amp;token='. hesk_token_echo(0)); ?>
                                <p>
                                    <?php
                                    if ($num > 1)
                                    {
                                        if ($k == 1)
                                        {
                                            ?>
                                            <a href="#" style="visibility: hidden" aria-label="<?php echo $hesklang['move_up']; ?>">
                                                <svg class="icon icon-chevron-up">
                                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                                </svg>
                                            </a>
                                            <a class="tooltip" href="service_messages.php?a=order_sm&amp;id=<?php echo $sm['id']; ?>&amp;move=15&amp;token=<?php hesk_token_echo(); ?>"
                                               title="<?php echo $hesklang['move_dn']; ?>">
                                                <svg class="icon icon-chevron-down">
                                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                                </svg>
                                            </a>
                                            <?php
                                        }
                                        elseif ($k == $num)
                                        {
                                            ?>
                                            <a class="tooltip" href="service_messages.php?a=order_sm&amp;id=<?php echo $sm['id']; ?>&amp;move=-15&amp;token=<?php hesk_token_echo(); ?>"
                                               title="<?php echo $hesklang['move_up']; ?>">
                                                <svg class="icon icon-chevron-up">
                                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                                </svg>
                                            </a>
                                            <a href="#" style="visibility: hidden"
                                               title="<?php echo $hesklang['move_dn']; ?>">
                                                <svg class="icon icon-chevron-down">
                                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                                </svg>
                                            </a>
                                            <?php
                                        }
                                        else
                                        {
                                            ?>
                                            <a class="tooltip" href="service_messages.php?a=order_sm&amp;id=<?php echo $sm['id']; ?>&amp;move=-15&amp;token=<?php hesk_token_echo(); ?>"
                                               title="<?php echo $hesklang['move_up']; ?>">
                                                <svg class="icon icon-chevron-up">
                                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                                </svg>
                                            </a>
                                            <a class="tooltip" href="service_messages.php?a=order_sm&amp;id=<?php echo $sm['id']; ?>&amp;move=15&amp;token=<?php hesk_token_echo(); ?>"
                                               title="<?php echo $hesklang['move_dn']; ?>">
                                                <svg class="icon icon-chevron-down">
                                                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-chevron-down"></use>
                                                </svg>
                                            </a>
                                            <?php
                                        }
                                    }
                                    ?>
                                    <a href="service_messages.php?a=edit_sm&amp;id=<?php echo $sm['id']; ?>" class="edit tooltip" title="<?php echo $hesklang['edit']; ?>">
                                        <svg class="icon icon-edit-ticket">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-edit-ticket"></use>
                                        </svg>
                                    </a>
                                    <a href="javascript:" class="delete tooltip" title="<?php echo $hesklang['delete']; ?>" data-modal="[data-modal-id='<?php echo $modal_id; ?>']">
                                        <svg class="icon icon-delete">
                                            <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-delete"></use>
                                        </svg>
                                    </a>
                                </p>
                            </td>
                        </tr>
                        <?php
                        $k++;
                    } // End while
                ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php
if ($hesk_settings['kb_wysiwyg'])
{
    hesk_tinymce_init('#content');
}
?>
<div class="right-bar service-message-create create-custom-field" <?php if ($action === 'edit_sm' || isset($_SESSION['preview_sm']) || hesk_SESSION(array('new_sm','errors'))) {echo 'style="display: block"';} ?>>
    <div class="right-bar__body form" data-step="1">
        <h3 class="">
            <a href="<?php echo $action === 'edit_sm' || isset($_SESSION['preview_sm']) ? 'service_messages.php' : 'javascript:' ?>">
                <svg class="icon icon-back">
                    <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-back"></use>
                </svg>
                <span><?php echo hesk_SESSION('edit_sm') ? $hesklang['edit_sm'] : $hesklang['new_sm']; ?></span>
            </a>
        </h3>
        <?php
        if (hesk_SESSION(array('new_sm', 'errors'))) {
            hesk_handle_messages();
        }

        if ( isset($_SESSION['new_sm']) && (isset($_SESSION['preview_sm']) || ! isset($_SESSION['edit_sm'])) )
        {
            $_SESSION['new_sm'] = hesk_stripArray($_SESSION['new_sm']);
        }

        /* Do we have a service message to preview? */
        if (isset($_SESSION['preview_sm'])) {
            if (isset($_SESSION['new_sm']['message_preview'])) {
                $tmp = $_SESSION['new_sm']['message'];
                $_SESSION['new_sm']['message'] = $_SESSION['new_sm']['message_preview'];
                hesk_service_message($_SESSION['new_sm']);
                $_SESSION['new_sm']['message'] = $tmp;
            } else {
                hesk_service_message($_SESSION['new_sm']);
            }
        }
        ?>
        <ul class="step-bar">
            <li data-link="1" data-all="2"><?php echo $hesklang['sm_content']; ?></li>
            <li data-link="2" data-all="2"><?php echo $hesklang['sm_settings']; ?></li>
        </ul>
        <form action="service_messages.php" method="post" name="form1" class="form <?php echo hesk_SESSION(array('new_sm','errors')) ? 'invalid' : ''; ?>" aria-label="<?php echo $hesklang['edit_sm']; ?>">
            <div class="step-slider">
                <div class="step-item step-1">
                    <div class="form-group">
                        <label for="sm-title"><?php echo $hesklang['sm_mtitle']; ?></label>
                        <input id="sm-title" type="text" name="title" class="form-control <?php echo hesk_SESSION(array('new_sm','errors')) ? 'isError' : ''; ?>" maxlength="255" <?php if (isset($_SESSION['new_sm']['title'])) {echo 'value="'.$_SESSION['new_sm']['title'].'"';} ?>>
                    </div>
                    <div class="form-group" style="width: 100%">
                        <label for="content"><?php echo $hesklang['sm_msg']; ?></label>
                        <textarea class="form-control" name="message" id="content" style="height: 300px;"><?php if (isset($_SESSION['new_sm']['message'])) {echo $_SESSION['new_sm']['message'];} ?></textarea>
                    </div>
                </div>
                <div class="step-item step-2">
                    <h4><?php echo $hesklang['sm_style']; ?></h4>
                    <div class="styles__radio">
                        <label class="none">
                            <input type="radio" value="0" name="style" <?php if (!isset($_SESSION['new_sm']['style']) || (isset($_SESSION['new_sm']['style']) && $_SESSION['new_sm']['style'] == 0) ) {echo 'checked';} ?>>
                            <svg class="icon icon-tick">
                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                            </svg>
                            <span><?php echo $hesklang['sm_none']; ?></span>
                        </label>
                        <label class="success">
                            <input type="radio" value="1" name="style" <?php if (isset($_SESSION['new_sm']['style']) && $_SESSION['new_sm']['style'] == 1 ) {echo 'checked';} ?>>
                            <svg class="icon icon-tick">
                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                            </svg>
                            <span><?php echo $hesklang['sm_success']; ?></span>
                        </label>
                        <label class="info">
                            <input type="radio" value="2" name="style" <?php if (isset($_SESSION['new_sm']['style']) && $_SESSION['new_sm']['style'] == 2) {echo 'checked';} ?>>
                            <svg class="icon icon-tick">
                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                            </svg>
                            <span><?php echo $hesklang['sm_info']; ?></span>
                        </label>
                        <label class="notice">
                            <input type="radio" value="3" name="style" <?php if (isset($_SESSION['new_sm']['style']) && $_SESSION['new_sm']['style'] == 3) {echo 'checked';} ?>>
                            <svg class="icon icon-tick">
                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                            </svg>
                            <span><?php echo $hesklang['sm_notice']; ?></span>
                        </label>
                        <label class="error">
                            <input type="radio" value="4" name="style" <?php if (isset($_SESSION['new_sm']['style']) && $_SESSION['new_sm']['style'] == 4) {echo 'checked';} ?>>
                            <svg class="icon icon-tick">
                                <use xlink:href="<?php echo HESK_PATH; ?>img/sprite.svg#icon-tick"></use>
                            </svg>
                            <span><?php echo $hesklang['sm_error']; ?></span>
                        </label>
                    </div>
                    <section class="param">
                        <span><?php echo $hesklang['sm_type']; ?></span>
                        <div class="dropdown-select center out-close">
                            <select name="type">
                                <option value="0" <?php if (!isset($_SESSION['new_sm']['type']) || (isset($_SESSION['new_sm']['type']) && $_SESSION['new_sm']['type'] == 0) ) {echo 'selected="selected"';} ?>>
                                    <?php echo $hesklang['sm_published']; ?>
                                </option>
                                <option value="1" <?php if (isset($_SESSION['new_sm']['type']) && $_SESSION['new_sm']['type'] == 1) {echo 'selected="selected"';} ?>>
                                    <?php echo $hesklang['sm_draft']; ?>
                                </option>
                            </select>
                        </div>
                    </section>
                    <?php if ($hesk_settings['show_language']): ?>
                    <section class="param">
                        <span><?php echo $hesklang['lgs']; ?></span>
                        <div class="dropdown-select center out-close">
                            <select name="language">
                                <option value=""><?php echo $hesklang['all']; ?></option>
                                <?php foreach ($hesk_settings['languages'] as $lang => $v): ?>
                                    <option value="<?php echo hesk_htmlspecialchars($lang); ?>" <?php echo (isset($_SESSION['new_sm']['language']) && $_SESSION['new_sm']['language'] == $lang ? 'selected="selected"' : ''); ?>>
                                        <?php echo $lang; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </section>
                    <?php endif; ?>
                    <h4><?php echo $hesklang['loc_sm']; ?></h4>
                    <section class="item--section">
                        <?php
                        $location = hesk_SESSION(array('new_sm','location'));
                        if ($location != 1 && $location != 2) {
                            $location = 0;
                        }
                        ?>
                        <div class="radio-custom">
                            <input type="radio" name="location" id="location0" value="0" onchange="hesk_setRadioOptions();" <?php if ($location == 0) {echo 'checked';} ?>>
                            <label for="location0"><?php echo $hesklang['loc_home']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" name="location" id="location1" value="1" onchange="hesk_setRadioOptions();" <?php if ($location == 1) {echo 'checked';} ?>>
                            <label for="location1"><?php echo $hesklang['loc_all'] . ' ' . $hesklang['loc_norec']; ?></label>
                        </div>
                        <div class="radio-custom">
                            <input type="radio" name="location" id="location2" value="2" onchange="hesk_setRadioOptions();" <?php if ($location == 2) {echo 'checked';} ?>>
                            <label for="location2"><?php echo $hesklang['loc_selected']; ?></label>
                        </div>
                        <div id="selloc" style="display:<?php echo $location == 2 ? 'block' : 'none'; ?>">
                            <select class="multiple form-control" name="locations[]" multiple="multiple" size="10" aria-label="<?php echo $hesklang['loc_sm']; ?>">
                                <?php
                                $locations = hesk_SESSION(array('new_sm','locations'));
                                $locations = is_array($locations) ? $locations : array();

                                foreach ($hesk_settings['sm_locations'] as $loc_id => $loc_name)
                                {
                                    if ($loc_id == 'ALL') {
                                        continue;
                                    }
                                    echo '<option value="'.$loc_id.'"'.(in_array($loc_id, $locations) ? ' selected="selected"' : '').'>'.$loc_name.'</option>';
                                }
                                ?>
                            </select>
                            <?php echo $hesklang['cf_ctrl']; ?>
                        </div>
                    </section>
                </div>
            </div>
            <div class="right-bar__footer">
                <button type="button" class="btn btn-border" ripple="ripple" data-action="back"><?php echo $hesklang['wizard_back']; ?></button>
                <button type="button" class="btn btn-full next" data-action="next" ripple="ripple"><?php echo $hesklang['sm_go_to_settings']; ?></button>
                <?php if (isset($_SESSION['edit_sm'])): ?>
                    <input type="hidden" name="a" value="save_sm" />
                    <input type="hidden" name="id" value="<?php echo intval($_SESSION['new_sm']['id']); ?>" />
                <?php else: ?>
                    <input type="hidden" name="a" value="new_sm" />
                <?php endif; ?>
                <button type="submit" name="sm_preview" class="btn btn-border preview" ripple="ripple"><?php echo $hesklang['sm_preview']; ?></button>
                <button type="submit" name="sm_save" class="btn btn-full save" ripple="ripple"><?php echo $hesklang['sm_save']; ?></button>
                <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
            </div>
        </form>
    </div>
</div>
<script type="text/javascript">
function hesk_toggleLayer(nr,setto) {
    if (document.all)
        document.all[nr].style.display = setto;
    else if (document.getElementById)
        document.getElementById(nr).style.display = setto;
}

function hesk_setRadioOptions() {
    if(document.getElementById('location2').checked) {
        hesk_toggleLayer('selloc', 'block');
    } else {
        hesk_toggleLayer('selloc', 'none');
    }
}
</script>

<?php

if ( isset($_SESSION['new_sm']) && ! isset($_SESSION['edit_sm']) )
{
	$_SESSION['new_sm'] = hesk_stripArray($_SESSION['new_sm']);
}

hesk_cleanSessionVars( array('new_sm', 'preview_sm', 'edit_sm') );

require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/


function save_sm()
{
	global $hesk_settings, $hesklang, $listBox;
    global $hesk_error_buffer;

	// A security check
	hesk_token_check('POST');

    $hesk_error_buffer = array();

	// Get service messageID
	$id = intval( hesk_POST('id') ) or hesk_error($hesklang['sm_e_id']);

	$style = intval( hesk_POST('style', 0) );
	if ($style > 4 || $style < 0)
	{
    	$style = 0;
	}

    $type  = empty($_POST['type']) ? 0 : 1;
    $language = hesk_input( hesk_POST('language') );
    if ( ! isset($hesk_settings['languages'][$language]))
    {
        $language = '';
    }

    $location = intval(hesk_POST('location'));
    if ($location == 2) {
        $locations = hesk_POST_array('locations');
        foreach ($locations as $key => $page) {
            if ( ! isset($hesk_settings['sm_locations'][$page])) {
                unset($locations[$key]);
            }
        }
        if (count($locations) == 0) {
            $hesk_error_buffer[] = $hesklang['loc_selerr'];
        }
    } elseif ($location == 1) {
        $locations = array('ALL');
    } else {
        $location = 0;
        $locations = array();
    }

    $title = hesk_input( hesk_POST('title') ) or $hesk_error_buffer[] = $hesklang['sm_e_title'];
    $message = $hesk_settings['kb_wysiwyg'] ? hesk_getHTML( hesk_POST('message') ) : nl2br( hesk_input( hesk_POST('message') ) );

    // Clean the HTML code
    require(HESK_PATH . 'inc/htmlpurifier/HeskHTMLPurifier.php');
    $purifier = new HeskHTMLPurifier($hesk_settings['cache_dir']);
    $message = $purifier->heskPurify($message);

    // Any errors?
    if (count($hesk_error_buffer))
    {
		$_SESSION['edit_sm'] = true;

		$_SESSION['new_sm'] = array(
		'id' => $id,
		'style' => $style,
		'type' => $type,
        'language' => $language,
        'location' => $location,
        'locations' => $locations,
		'title' => $title,
		'message' => hesk_input( hesk_POST('message') ),
        'errors' => array('title')
		);

		$tmp = '';
		foreach ($hesk_error_buffer as $error)
		{
			$tmp .= "<li>$error</li>\n";
		}
		$hesk_error_buffer = $tmp;

    	$hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
    	hesk_process_messages($hesk_error_buffer,'service_messages.php');
    }

	// Just preview the message?
	if ( isset($_POST['sm_preview']) )
	{
    	$_SESSION['preview_sm'] = true;
		$_SESSION['edit_sm'] = true;

		$_SESSION['new_sm'] = array(
		'id' => $id,
		'style' => $style,
		'type' => $type,
        'language' => $language,
        'location' => $location,
        'locations' => $locations,
		'title' => $title,
        'message' => hesk_input( hesk_POST('message') ),
        'message_preview' => $message
		);

		header('Location: service_messages.php');
		exit;
	}

	// Update the service message in the database
	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."service_messages` SET
	`author` = '".intval($_SESSION['id'])."',
	`title` = '".hesk_dbEscape($title)."',
	`message` = '".hesk_dbEscape($message)."',
    `language` = ".(strlen($language) ? "'".hesk_dbEscape($language)."'" : 'NULL').",
    `location` = ".(count($locations) ? "'".implode(',', $locations)."'" : 'NULL').",
	`style` = '{$style}',
	`type` = '{$type}'
	WHERE `id`={$id}");

    $_SESSION['smord'] = $id;
    hesk_process_messages($hesklang['sm_mdf'],'service_messages.php','SUCCESS');

} // End save_sm()


function edit_sm()
{
	global $hesk_settings, $hesklang;

	// Get service messageID
	$id = intval( hesk_GET('id') ) or hesk_error($hesklang['sm_e_id']);

	// Get details from the database
	$res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."service_messages` WHERE `id`={$id} LIMIT 1");
	if ( hesk_dbNumRows($res) != 1 )
	{
    	hesk_error($hesklang['sm_not_found']);
	}
	$sm = hesk_dbFetchAssoc($res);

    // If we're in plain text mode, convert any HTML message safely to text
    if ( ! $hesk_settings['kb_wysiwyg'])
    {
            // Clean the HTML code and set the plaintext version
            require(HESK_PATH . 'inc/htmlpurifier/HeskHTMLPurifier.php');
            require(HESK_PATH . 'inc/html2text/html2text.php');
            $purifier = new HeskHTMLPurifier($hesk_settings['cache_dir']);
            $sm['message'] = $purifier->heskPurify($sm['message']);

            $sm['message'] = convert_html_to_text($sm['message']);
            $sm['message'] = fix_newlines($sm['message']);
    }

    $sm['message'] = hesk_htmlspecialchars($sm['message']);

    if (empty($sm['location'])) {
        $sm['locations'] = array();
        $sm['location'] = 0;
    } elseif ($sm['location'] == 'ALL') {
        $sm['locations'] = array('ALL');
        $sm['location'] = 1;
    } else {
        $sm['locations'] = explode(',', $sm['location']);
        $sm['location'] = 2;
    }

    $_SESSION['smord'] = $id;
	$_SESSION['new_sm'] = $sm;
	$_SESSION['edit_sm'] = true;

} // End edit_sm()


function order_sm()
{
	global $hesk_settings, $hesklang;

	// A security check
	hesk_token_check();

	// Get ID and move parameters
	$id    = intval( hesk_GET('id') ) or hesk_error($hesklang['sm_e_id']);
	$move  = intval( hesk_GET('move') );
    $_SESSION['smord'] = $id;

	// Update article details
	hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."service_messages` SET `order`=`order`+".intval($move)." WHERE `id`={$id}");

    // Update order of all service messages
    update_sm_order();

    $_SESSION['smord'] = $id;

	// Finish
	header('Location: service_messages.php');
	exit();

} // End order_sm()


function update_sm_order()
{
	global $hesk_settings, $hesklang;

	// Get list of current service messages
	$res = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."service_messages` ORDER BY `order` ASC");

	// Update database
	$i = 10;
	while ( $sm = hesk_dbFetchAssoc($res) )
	{
		hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."service_messages` SET `order`=".intval($i)." WHERE `id`='".intval($sm['id'])."'");
		$i += 10;
	}

	return true;

} // END update_sm_order()


function remove_sm()
{
	global $hesk_settings, $hesklang;

	// A security check
	hesk_token_check();

	// Get ID
	$id = intval( hesk_GET('id') ) or hesk_error($hesklang['sm_e_id']);

	// Delete the service message
    hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."service_messages` WHERE `id`={$id}");

	// Were we successful?
    if ( hesk_dbAffectedRows() == 1 )
	{
		hesk_process_messages($hesklang['sm_deleted'],'./service_messages.php','SUCCESS');
	}
	else
	{
		hesk_process_messages($hesklang['sm_not_found'],'./service_messages.php');
	}

} // End remove_sm()


function new_sm()
{
	global $hesk_settings, $hesklang, $listBox;
    global $hesk_error_buffer;

	// A security check
	hesk_token_check('POST');

    $hesk_error_buffer = array();

	$style = intval( hesk_POST('style', 0) );
	if ($style > 4 || $style < 0)
	{
    	$style = 0;
	}

    $type  = empty($_POST['type']) ? 0 : 1;
    $language = hesk_input( hesk_POST('language') );
    if ( ! isset($hesk_settings['languages'][$language]))
    {
        $language = '';
    }

    $location = intval(hesk_POST('location'));
    if ($location == 2) {
        $locations = hesk_POST_array('locations');
        foreach ($locations as $key => $page) {
            if ( ! isset($hesk_settings['sm_locations'][$page])) {
                unset($locations[$key]);
            }
        }
        if (count($locations) == 0) {
            $hesk_error_buffer[] = $hesklang['loc_selerr'];
        }
    } elseif ($location == 1) {
        $locations = array('ALL');
    } else {
        $location = 0;
        $locations = array();
    }

    $title = hesk_input( hesk_POST('title') ) or $hesk_error_buffer[] = $hesklang['sm_e_title'];
    $message = $hesk_settings['kb_wysiwyg'] ? hesk_getHTML( hesk_POST('message') ) : nl2br( hesk_input( hesk_POST('message') ) );

    // Clean the HTML code
    require(HESK_PATH . 'inc/htmlpurifier/HeskHTMLPurifier.php');
    $purifier = new HeskHTMLPurifier($hesk_settings['cache_dir']);
    $message = $purifier->heskPurify($message);

    // Any errors?
    if (count($hesk_error_buffer))
    {
		$_SESSION['new_sm'] = array(
		'style' => $style,
		'type' => $type,
        'language' => $language,
        'location' => $location,
        'locations' => $locations,
		'title' => $title,
		'message' => hesk_input( hesk_POST('message') ),
        'errors' => array('title')
		);

		$tmp = '';
		foreach ($hesk_error_buffer as $error)
		{
			$tmp .= "<li>$error</li>\n";
		}
		$hesk_error_buffer = $tmp;

    	$hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
    	hesk_process_messages($hesk_error_buffer,'service_messages.php');
    }

	// Just preview the message?
	if ( isset($_POST['sm_preview']) )
	{
    	$_SESSION['preview_sm'] = true;

		$_SESSION['new_sm'] = array(
		'style' => $style,
		'type' => $type,
        'language' => $language,
        'location' => $location,
        'locations' => $locations,
		'title' => $title,
        'message' => hesk_input( hesk_POST('message') ),
        'message_preview' => $message
		);

		header('Location: service_messages.php');
		exit;
	}

	// Get the latest service message order
	$res = hesk_dbQuery("SELECT `order` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."service_messages` ORDER BY `order` DESC LIMIT 1");
	$row = hesk_dbFetchRow($res);
	$my_order = isset($row[0]) ? intval($row[0]) + 10 : 10;

    // Insert service message into database
	hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."service_messages` (`author`,`title`,`message`,`language`,`style`,`type`,`location`,`order`) VALUES (
    '".intval($_SESSION['id'])."',
    '".hesk_dbEscape($title)."',
    '".hesk_dbEscape($message)."',
    ".(strlen($language) ? "'".hesk_dbEscape($language)."'" : 'NULL').",
    '{$style}',
    '{$type}',
    ".(count($locations) ? "'".implode(',', $locations)."'" : 'NULL').",
    '{$my_order}'
    )");

    $_SESSION['smord'] = hesk_dbInsertID();
    hesk_process_messages($hesklang['sm_added'],'service_messages.php','SUCCESS');

} // End new_sm()

show_tickets.php
wget 'https://lists2.roe3.org/hesk/admin/show_tickets.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');
hesk_load_database_functions();

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

define('CALENDAR',1);
define('AUTO_RELOAD',1);

/* Check permissions for this feature */
hesk_checkPermission('can_view_tickets');

/* Print header */
require_once(HESK_PATH . 'inc/header.inc.php');

/* Print admin navigation */
require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');
?>

<div class="main__content tickets">
<div style="margin-left: -16px; margin-right: -24px;">
<?php

/* This will handle error, success and notice messages */
hesk_handle_messages();
?>
</div>
<?php

/* Print the list of tickets */
$is_search = 1;
$href = 'show_tickets.php';
require_once(HESK_PATH . 'inc/print_tickets.inc.php');

/* Update staff default settings? */
if ( ! empty($_GET['def']))
{
	hesk_updateStaffDefaults();
}
?>

&nbsp;<br />

<?php
/* Print forms for listing and searching tickets */
require_once(HESK_PATH . 'inc/show_search_form.inc.php');
?>

<p>&nbsp;</p>
<?php

/* Print footer */
require_once(HESK_PATH . 'inc/footer.inc.php');
exit();

?>
test_connection.php
wget 'https://lists2.roe3.org/hesk/admin/test_connection.php'
View Content
<?php
/**
 *
 * This file is part of HESK - PHP Help Desk Software.
 *
 * (c) Copyright Klemen Stirn. All rights reserved.
 * https://www.hesk.com
 *
 * For the full copyright and license agreement information visit
 * https://www.hesk.com/eula.php
 *
 */

define('IN_SCRIPT',1);
define('HESK_PATH','../');

// Get all the required files and functions
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/setup_functions.inc.php');
require(HESK_PATH . 'inc/admin_functions.inc.php');

hesk_load_database_functions();
hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

// Check permissions for this feature
hesk_checkPermission('can_man_settings');

// Demo mode?
if ( defined('HESK_DEMO') )
{
	hesk_show_notice($hesklang['ddemo']);
    exit();
}

// Test type?
$test_type = hesk_POST('test');

// Test MySQL connection
if ($test_type == 'mysql')
{
	if ( hesk_testMySQL() )
	{
		hesk_show_success($hesklang['conok']);
	}
	elseif ( ! empty($mysql_log) )
	{
		hesk_show_error($mysql_error . '<br /><br /><b>' . $hesklang['mysql_said'] . ':</b> ' . $mysql_log);
	}
	else
	{
		hesk_show_error($mysql_error);
	}
}

// Test POP3 connection
elseif ($test_type == 'pop3')
{
	if ( hesk_testPOP3() )
	{
        if (is_numeric($emails_found)) {
            hesk_show_success($hesklang['conok'] . '<br><br>' . sprintf($hesklang['tst_cnt'], $emails_found) );
            if ($emails_found > 10) {
                hesk_show_notice( sprintf($hesklang['wrn_pop3'], $emails_found, $hesklang['pop3']), $hesklang['warn']);
            }
        } else {
            hesk_show_notice(sprintf($hesklang['conok_but_no_count'], 'https://www.hesk.com/knowledgebase/?article=116'), ' ', false);
        }
	}
	else
	{
		hesk_show_error( $pop3_error . '<br /><br /><textarea name="pop3_log" rows="10" cols="60">' . $pop3_log . '</textarea>' );
	}
}

// Test SMTP connection
elseif ($test_type == 'smtp')
{
	if ( hesk_testSMTP() )
	{
		// If no username/password add a notice
		if ($set['smtp_user'] == '' && $set['smtp_user'] == '' && $set['smtp_conn_type'] != 'oauth')
		{
			$hesklang['conok'] .= '<br /><br />' . $hesklang['conokn'];
		}

		hesk_show_success($hesklang['conok']);
	}
	else
	{
		hesk_show_error( $smtp_error . '<br /><br /><textarea name="smtp_log" rows="10" cols="60" style="width: 100%">' . $smtp_log . '</textarea>' );
	}
}

// Test IMAP connection
elseif ($test_type == 'imap')
{
	if ( hesk_testIMAP() )
	{
        if (is_numeric($emails_found)) {
            hesk_show_success($hesklang['conok'] . '<br><br>' . sprintf($hesklang['tst_cnt'], $emails_found) );
            if ($emails_found > 10) {
                hesk_show_notice( sprintf($hesklang['wrn_imap'], $emails_found, $hesklang['imap']), $hesklang['warn']);
            }
        } else {
            hesk_show_notice(sprintf($hesklang['conok_but_no_count'], 'https://www.hesk.com/knowledgebase/?article=116'), ' ', false);
        }
	}
	else
	{
        // Give clues about a Microsoft 365 specific issue
        if ($imap_error == 'User is authenticated but not connected.') {
            $imap_error .= '<br><br>' . sprintf($hesklang['imap_test_bad'], 'https://www.hesk.com/knowledgebase/?article=116');
        }
		hesk_show_error( $imap_error . '<br /><br /><textarea name="imap_log" rows="10" cols="60">' . $imap_log . '</textarea>' );
	}
}

// Not a valid test...
else
{
	die($hesklang['attempt']);
}

exit();
?>