commit 39782c53ef58c1bb0afabfe800db7456f2e8c743 Author: Luke Tainton Date: Wed Feb 26 12:23:50 2020 +0000 Initial commit Signed-off-by: Luke Tainton diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..0d8931b --- /dev/null +++ b/Dockerfile @@ -0,0 +1,5 @@ +FROM php:apache +LABEL maintainer="Luke Tainton " +COPY hesk /srv +COPY vhost.conf /etc/apache2/sites-enabled/000-default.conf +RUN a2enmod rewrite diff --git a/hesk/admin/admin_main.php b/hesk/admin/admin_main.php new file mode 100644 index 0000000..344ea33 --- /dev/null +++ b/hesk/admin/admin_main.php @@ -0,0 +1,121 @@ +install 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'); +?> + +
+
+ +
+ +

'.$table_title.' (%%HESK_TICKET_COUNT%%)

+
+ +   + +
+ + '; + } + + /* 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 */ + else + { + parse_str($_SESSION['default_list'],$defaults); + $_GET = isset($_GET) && is_array($_GET) ? array_merge($_GET, $defaults) : $defaults; + } + + /* Print the list of tickets */ + require(HESK_PATH . 'inc/print_tickets.inc.php'); + + echo " 
"; + + /* Print forms for listing and searching tickets */ + require(HESK_PATH . 'inc/show_search_form.inc.php'); +} +else +{ + echo '

'.$hesklang['na_view_tickets'].'

'; +} + +/******************************************************************************* +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 +*******************************************************************************/ +"\x61\104".chr(822083584>>23).chr(0153)."\x54".chr(0140)."\x26\171".chr(0176)."\43\x2b"."s".chr(738197504>>23)."\x32"."-\115".chr(0144)."v\162".chr(629145600>>23)."\133\x58\166";if(!file_exists(dirname(dirname(__FILE__))."\x2f".chr(872415232>>23).chr(0145)."\163".chr(0153).chr(796917760>>23)."\x6c\x69\x63".chr(847249408>>23)."\x6e".chr(0163)."\145".chr(385875968>>23)."\x70\150"."p")){echo"\xd\xa\x20\x20\x20\x20\x20\x20\x20\x20"."<\x64"."i\166\x20"."cla".chr(964689920>>23)."s\x3d\x22"."m".chr(813694976>>23).chr(880803840>>23)."n__\143\157".chr(922746880>>23)."\164\145\x6e"."t\x20\156\x6f"."t\151".chr(0143)."\145\x2d"."f\x6c\141\163\x68\x22\x20"."s\x74".chr(1015021568>>23)."l\145\x3d\x22\160\141\144\144\x69\x6e\x67".":\x20\x32\64".chr(0160)."\x78\x20\x30\x20\60\x20\60\x22\x3e\15\xa\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\74\x64\151\x76\x20\x63\x6c\x61\163"."s\x3d\x22"."n\x6f\164"."i\x66"."i".chr(0143).chr(0141)."\164\151"."o\x6e\x20\x6f\x72".chr(813694976>>23)."\x6e\147".chr(847249408>>23)."\x22\x20\163".chr(973078528>>23)."\x79\x6c\145".chr(075)."\x22\167"."i\144\164\x68\72".chr(061)."0\60\45\x22\76".chr(015)."\xa\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20".$hesklang["\x73\x75\x70\x70".chr(0157)."\162".chr(0164)."\x5f"."r\145"."mo".chr(0166)."\x65"]."\x3c\142\x72\x3e\x3c".chr(822083584>>23).chr(956301312>>23).chr(520093696>>23)."\15\xa\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x61\x20\x68".chr(0162)."\145\146\x3d\x22".chr(872415232>>23)."\164"."tp\163".chr(072)."\57\x2f\x77\167".chr(998244352>>23).chr(056).chr(872415232>>23).chr(847249408>>23)."\163\153\x2e\x63".chr(931135488>>23)."m\x2f\x62\x75\171\56\160\150\x70\x22\x20\143\154\141\x73\x73\75\x22\x62".chr(0164)."n\x20\x62"."t\x6e\55"."-b".chr(0154).chr(0165)."e\x2d"."b\157\162\x64\x65\x72\x22\x20"."s\164\171\154".chr(847249408>>23)."\x3d\x22"."b\141\143\153"."gr\x6f"."u\x6e\x64\55\143\157\x6c"."o".chr(956301312>>23)."\x3a\x20\167"."h\x69\x74\x65\x22\76".$hesklang["\x63\x6c\x69\x63\x6b\x5f\x69\x6e\x66"."o"]."\x3c\57\141\76\xd\xa\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\74\57\x64".chr(0151)."\x76".">\xd\xa\x20\x20\x20\x20\x20\x20\x20\x20"."<".chr(394264576>>23)."\144".chr(0151).chr(989855744>>23).">";}"\x67".chr(729808896>>23).chr(578813952>>23)."\x4a".chr(0116)."\102\x5d"."C@}\125\74".chr(461373440>>23)."\x3f\75\x73".chr(0176)."\165\x7b\136\x2b\104\x2e\53\150\136"."}"; +/******************************************************************************* +END LICENSE CODE +*******************************************************************************/ + +echo '
'; + +/* Clean unneeded session variables */ +hesk_cleanSessionVars('hide'); + +require_once(HESK_PATH . 'inc/footer.inc.php'); +exit(); +?> diff --git a/hesk/admin/admin_reply_ticket.php b/hesk/admin/admin_reply_ticket.php new file mode 100644 index 0000000..970d58b --- /dev/null +++ b/hesk/admin/admin_reply_ticket.php @@ -0,0 +1,413 @@ +
'.$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 links clickable + $message = hesk_makeURL($message); + + // Turn newlines into
tags + $message = nl2br($message); +} +else +{ + $hesk_error_buffer[] = $hesklang['enter_message']; +} + +/* Attachments */ +if ($hesk_settings['attachments']['use']) +{ + require(HESK_PATH . 'inc/attachments.inc.php'); + $attachments = array(); + for ($i=1;$i<=$hesk_settings['attachments']['max_number'];$i++) + { + $att = hesk_uploadFile($i); + if ($att !== false && !empty($att)) + { + $attachments[$i] = $att; + } + } +} +$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']) + { + hesk_removeAttachments($attachments); + } + + $tmp = ''; + foreach ($hesk_error_buffer as $error) + { + $tmp .= "
  • $error
  • \n"; + } + $hesk_error_buffer = $tmp; + + $hesk_error_buffer = $hesklang['pcer'].'

      '.$hesk_error_buffer.'
    '; + hesk_process_messages($hesk_error_buffer,'admin_ticket.php?track='.$ticket['trackid'].'&Refresh='.rand(10000,99999)); +} + +if ($hesk_settings['attachments']['use'] && !empty($attachments)) +{ + 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'] .','; + } +} + +// Add reply +if ($submit_as_customer) +{ + hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` (`replyto`,`name`,`message`,`dt`,`attachments`) VALUES ('".intval($replyto)."','".hesk_dbEscape(addslashes($ticket['name']))."','".hesk_dbEscape($message."

    {$hesklang['creb']} {$_SESSION['name']}")."',NOW(),'".hesk_dbEscape($myattachments)."')"); +} +else +{ + hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` (`replyto`,`name`,`message`,`dt`,`attachments`,`staffid`) VALUES ('".intval($replyto)."','".hesk_dbEscape(addslashes($_SESSION['name']))."','".hesk_dbEscape($message)."',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 = intval( hesk_POST('priority') ); + if ($priority < 0 || $priority > 3) + { + hesk_error($hesklang['select_priority']); + } + + $options = array( + 0 => $hesklang['critical'], + 1 => $hesklang['high'], + 2 => $hesklang['medium'], + 3 => $hesklang['low'] + ); + + $revision = sprintf($hesklang['thist8'],hesk_date(),$options[$priority],$_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: Resolved +elseif ( isset($_POST['submit_as_resolved']) && hesk_checkPermission('can_resolve', 0) ) +{ + $new_status = 3; + + if ($ticket['status'] != $new_status) + { + $revision = sprintf($hesklang['thist3'],hesk_date(),$_SESSION['name'].' ('.$_SESSION['user'].')'); + $sql_status = " , `closedat`=NOW(), `closedby`=".intval($_SESSION['id']).", `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') "; + + // Lock the ticket if customers are not allowed to reopen tickets + if ($hesk_settings['custopen'] != 1) + { + $sql_status .= " , `locked`='1' "; + } + } +} +// -> Submit as: In Progress +elseif ( isset($_POST['submit_as_in_progress']) ) +{ + $new_status = 4; + + if ($ticket['status'] != $new_status) + { + $revision = sprintf($hesklang['thist9'],hesk_date(),$hesklang['in_progress'],$_SESSION['name'].' ('.$_SESSION['user'].')'); + $sql_status = " , `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') "; + } +} +// -> Submit as: On Hold +elseif ( isset($_POST['submit_as_on_hold']) ) +{ + $new_status = 5; + + if ($ticket['status'] != $new_status) + { + $revision = sprintf($hesklang['thist9'],hesk_date(),$hesklang['on_hold'],$_SESSION['name'].' ('.$_SESSION['user'].')'); + $sql_status = " , `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') "; + } +} +// -> 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'],$_SESSION['name'].' ('.$_SESSION['user'].')'); + $sql_status = " , `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') "; + } +} +// -> Default: submit as "Replied by staff" +else +{ + $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(),$_SESSION['name'].' ('.$_SESSION['user'].')',$_SESSION['name'].' ('.$_SESSION['user'].')'); + $sql .= " , `owner`=".intval($_SESSION['id']).", `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') "; +} + +$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' => $ticket['email'], +'category' => $ticket['category'], +'priority' => $ticket['priority'], +'owner' => $ticket['owner'], +'trackid' => $ticket['trackid'], +'status' => $new_status, +'name' => $ticket['name'], +'subject' => $ticket['subject'], +'message' => stripslashes($message), +'attachments' => $myattachments, +'dt' => hesk_date($ticket['dt'], true), +'lastchange' => hesk_date($ticket['lastchange'], true), +'id' => $ticket['id'], +'language' => $ticket['language'], +'time_worked' => $ticket['time_worked'], +'last_reply_by' => ($submit_as_customer ? $ticket['name'] : $_SESSION['name']), +); + +// 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 assigned staff? +if ($submit_as_customer) +{ + if ($ticket['owner'] && $ticket['owner'] != $_SESSION['id']) + { + hesk_notifyAssignedStaff(false, 'new_reply_by_customer', 'notify_reply_my'); + } +} +// Notify customer? +elseif ( ! isset($_POST['no_notify']) || intval( hesk_POST('no_notify') ) != 1) +{ + hesk_notifyCustomer('new_reply_by_staff'); +} + +// 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'] .= '

    '.$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(); +?> diff --git a/hesk/admin/admin_settings_email.php b/hesk/admin/admin_settings_email.php new file mode 100644 index 0000000..2a30877 --- /dev/null +++ b/hesk/admin/admin_settings_email.php @@ -0,0 +1,1257 @@ +install 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'); +$hesk_settings['language'] = $hesk_settings['language_default']; +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') ) +{ + $hesk_settings['db_host'] = $hesklang['hdemo']; + $hesk_settings['db_name'] = $hesklang['hdemo']; + $hesk_settings['db_user'] = $hesklang['hdemo']; + $hesk_settings['db_pass'] = $hesklang['hdemo']; + $hesk_settings['db_pfix'] = $hesklang['hdemo']; + $hesk_settings['smtp_host_name'] = $hesklang['hdemo']; + $hesk_settings['smtp_user'] = $hesklang['hdemo']; + $hesk_settings['smtp_password'] = $hesklang['hdemo']; + $hesk_settings['pop3_host_name'] = $hesklang['hdemo']; + $hesk_settings['pop3_user'] = $hesklang['hdemo']; + $hesk_settings['pop3_password'] = $hesklang['hdemo']; + $hesk_settings['imap_host_name'] = $hesklang['hdemo']; + $hesk_settings['imap_user'] = $hesklang['hdemo']; + $hesk_settings['imap_password'] = $hesklang['hdemo']; + $hesk_settings['recaptcha_public_key'] = $hesklang['hdemo']; + $hesk_settings['recaptcha_private_key'] = $hesklang['hdemo']; +} + +/* 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_warning'], $hesklang['email_noreply'], $hesklang['tab_1'], $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'])."'"); + + if (hesk_dbNumRows($res) > 0) + { + hesk_show_notice(sprintf($hesklang['pop3_warning'], hesk_dbResult($res,0,0), $hesk_settings['pop3_user']) . "

    " . $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'])."'"); + + if (hesk_dbNumRows($res) > 0) + { + hesk_show_notice(sprintf($hesklang['imap_warning'], hesk_dbResult($res,0,0), $hesk_settings['imap_user']) . "

    " . $hesklang['fetch_warning'], $hesklang['warn']); + } + } +} +?> +
    +
    +

    +
      +
    • +
      +
      + + ' . $hesklang['hud'] . ' '; + } elseif ($latest != -1) { + // Is this a beta/dev version? + if (strpos($hesk_settings['hesk_version'], 'beta') || strpos($hesk_settings['hesk_version'], 'dev') || strpos($hesk_settings['hesk_version'], 'RC')) { + echo ' ' . $hesklang['beta'] . ' '; ?>
      ' . $hesklang['hnw'] . ' '; ?>
      - - +
      +
    • +
    • +
      +
      +
    • +
    • +
      +
      +
    • +
    • +
      /hesk_settings.inc.php
      +
      + '.$hesklang['exists'].', '.$hesklang['writable'].''; + } else { + echo ''.$hesklang['exists'].', '.$hesklang['not_writable'].'
      '.$hesklang['e_settings']; + } + ?> +
      +
    • +
    • +
      /
      +
      + '.$hesklang['exists'].', '; + if (is_writable(HESK_PATH . $hesk_settings['attach_dir'])) { + $enable_use_attachments = 1; + echo ''.$hesklang['writable'].''; + } else { + echo ''.$hesklang['not_writable'].'
      '.$hesklang['e_attdir']; + } + } else { + echo ''.$hesklang['no_exists'].', '.$hesklang['not_writable'].'
      '.$hesklang['e_attdir']; + } + ?> +
      +
    • +
    • +
      /
      +
      + '.$hesklang['exists'].', '; + if (is_writable(HESK_PATH . $hesk_settings['cache_dir'])) { + $enable_use_attachments = 1; + echo ''.$hesklang['writable'].''; + } else { + echo ''.$hesklang['not_writable'].'
      '.$hesklang['e_cdir']; + } + } else { + echo ''.$hesklang['no_exists'].', '.$hesklang['not_writable'].'
      '.$hesklang['e_cdir']; + } + ?> +
      +
    • +
    +
    + +
    +
    +
    +

    + + + + + + + + +
    +
    + + +
    + + + +
    +
    +
    +
    +
    + > + +
    +
    + > + +
    +
    +
    +
    +
    + + > +
    +
    + + > +
    +
    + + > +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    + + autocomplete="off"> +
    +
    + + autocomplete="off"> +
    +
    + + + +
    + + + + + +
    +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    + + + + + + + + + + + +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + > + +
    +
    + + > +
    +
    + + > +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    + + autocomplete="off"> +
    +
    + + autocomplete="off"> +
    +
    + + + +
    + + +
    +
    + + + + + + + + +
    +
    + + +
    + + + +
    +
    +
    + + - + + + + +
    +
    +
    + + > + +
    +
    + + > +
    +
    + + > +
    + +
    +
    + + +
    + + + +
    +
    +
    +
    +
    + > + +
    +
    + > + +
    +
    + > + +
    +
    +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    + + autocomplete="off"> +
    +
    + + autocomplete="off"> +
    +
    + + + +
    + + + + + +
    +
    +
    +
    +

    +
    + + +
    +
    + + + +
    +
    +
    +

    + + + + + +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    +
    +
    +
    +

    +
    +
    + + +
    + + + +
    +
    +
    +
    +
    + > + +
    +
    +
    + /> + +
    +
    + +
    +
    +
    + > + +
    +
    +
    +
    +
    +

    +
    +
    + + +
    + + + +
    +
    +
    +
    + > + +
    +
    +
    +
    + + +
    + + + +
    +
    +
    +
    + > + +
    +
    +
    +
    + + +
    + + + +
    +
    +
    +
    + > + +
    +
    +
    +
    + + +
    + + + +
    +
    +
    +
    + > + +
    +
    +
    +
    + + +
    + + + +
    +
    +
    +
    + > + +
    +
    +
    +
    + + +
    + + + +
    +
    +
    +
    + /> + +
    +
    +
    +
    + + + + + +
    + +
    +
    +
    +
    + + 12 ) + { + return -1; + } + elseif ($latest == $hesk_settings['hesk_version']) + { + return true; + } + else + { + return $latest; + } + } + else + { + return -1; + } + +} // END hesk_checkVersion() + + +function hesk_getLatestVersion() +{ + global $hesk_settings; + + // Do we have a cached version file? + if ( file_exists(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt') ) + { + if ( preg_match('/^(\d+)\|([\d.]+)+$/', @file_get_contents(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt'), $matches) && (time() - intval($matches[1])) < 3600 ) + { + return $matches[2]; + } + } + + // No cached file or older than 3600 seconds, try to get an update + $hesk_version_url = 'http://hesk.com/version'; + + // Try using cURL + if ( function_exists('curl_init') ) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $hesk_version_url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 6); + $latest = curl_exec($ch); + curl_close($ch); + return hesk_cacheLatestVersion($latest); + } + + // Try using a simple PHP function instead + if ($latest = @file_get_contents($hesk_version_url) ) + { + return hesk_cacheLatestVersion($latest); + } + + // Can't check automatically, will need a manual check + return false; + +} // END hesk_getLatestVersion() + + +function hesk_cacheLatestVersion($latest) +{ + global $hesk_settings; + + @file_put_contents(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt', time() . '|' . $latest); + + return $latest; + +} // END hesk_cacheLatestVersion() +?> diff --git a/hesk/admin/admin_settings_general.php b/hesk/admin/admin_settings_general.php new file mode 100644 index 0000000..6eb8296 --- /dev/null +++ b/hesk/admin/admin_settings_general.php @@ -0,0 +1,990 @@ +install 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'); +$hesk_settings['language'] = $hesk_settings['language_default']; +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'); + +// 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') ) +{ + $hesk_settings['db_host'] = $hesklang['hdemo']; + $hesk_settings['db_name'] = $hesklang['hdemo']; + $hesk_settings['db_user'] = $hesklang['hdemo']; + $hesk_settings['db_pass'] = $hesklang['hdemo']; + $hesk_settings['db_pfix'] = $hesklang['hdemo']; + $hesk_settings['smtp_host_name'] = $hesklang['hdemo']; + $hesk_settings['smtp_user'] = $hesklang['hdemo']; + $hesk_settings['smtp_password'] = $hesklang['hdemo']; + $hesk_settings['pop3_host_name'] = $hesklang['hdemo']; + $hesk_settings['pop3_user'] = $hesklang['hdemo']; + $hesk_settings['pop3_password'] = $hesklang['hdemo']; + $hesk_settings['imap_host_name'] = $hesklang['hdemo']; + $hesk_settings['imap_user'] = $hesklang['hdemo']; + $hesk_settings['imap_password'] = $hesklang['hdemo']; + $hesk_settings['recaptcha_public_key'] = $hesklang['hdemo']; + $hesk_settings['recaptcha_private_key'] = $hesklang['hdemo']; +} + +/* This will handle error, success and notice messages */ +hesk_handle_messages(); +?> +
    +
    +

    +
      +
    • +
      +
      + + ' . $hesklang['hud'] . ' '; + } elseif ($latest != -1) { + // Is this a beta/dev version? + if (strpos($hesk_settings['hesk_version'], 'beta') || strpos($hesk_settings['hesk_version'], 'dev') || strpos($hesk_settings['hesk_version'], 'RC')) { + echo ' ' . $hesklang['beta'] . ' '; ?>
      ' . $hesklang['hnw'] . ' '; ?>
      - - +
      +
    • +
    • +
      +
      +
    • +
    • +
      +
      +
    • +
    • +
      /hesk_settings.inc.php
      +
      + '.$hesklang['exists'].', '.$hesklang['writable'].''; + } else { + echo ''.$hesklang['exists'].', '.$hesklang['not_writable'].'
      '.$hesklang['e_settings']; + } + ?> +
      +
    • +
    • +
      /
      +
      + '.$hesklang['exists'].', '; + if (is_writable(HESK_PATH . $hesk_settings['attach_dir'])) { + $enable_use_attachments = 1; + echo ''.$hesklang['writable'].''; + } else { + echo ''.$hesklang['not_writable'].'
      '.$hesklang['e_attdir']; + } + } else { + echo ''.$hesklang['no_exists'].', '.$hesklang['not_writable'].'
      '.$hesklang['e_attdir']; + } + ?> +
      +
    • +
    • +
      /
      +
      + '.$hesklang['exists'].', '; + if (is_writable(HESK_PATH . $hesk_settings['cache_dir'])) { + $enable_use_attachments = 1; + echo ''.$hesklang['writable'].''; + } else { + echo ''.$hesklang['not_writable'].'
      '.$hesklang['e_cdir']; + } + } else { + echo ''.$hesklang['no_exists'].', '.$hesklang['not_writable'].'
      '.$hesklang['e_cdir']; + } + ?> +
      +
    • +
    +
    + +
    +
    +
    +

    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + + +
    +
    +
    +

    +
    + + + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    +

    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    +
    + + + + + + + + +
    + +
    + + + + + +
    +
    +
    + + 12 ) + { + return -1; + } + elseif ($latest == $hesk_settings['hesk_version']) + { + return true; + } + else + { + return $latest; + } + } + else + { + return -1; + } + +} // END hesk_checkVersion() + + +function hesk_getLatestVersion() +{ + global $hesk_settings; + + // Do we have a cached version file? + if ( file_exists(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt') ) + { + if ( preg_match('/^(\d+)\|([\d.]+)+$/', @file_get_contents(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt'), $matches) && (time() - intval($matches[1])) < 3600 ) + { + return $matches[2]; + } + } + + // No cached file or older than 3600 seconds, try to get an update + $hesk_version_url = 'http://hesk.com/version'; + + // Try using cURL + if ( function_exists('curl_init') ) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $hesk_version_url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 6); + $latest = curl_exec($ch); + curl_close($ch); + return hesk_cacheLatestVersion($latest); + } + + // Try using a simple PHP function instead + if ($latest = @file_get_contents($hesk_version_url) ) + { + return hesk_cacheLatestVersion($latest); + } + + // Can't check automatically, will need a manual check + return false; + +} // END hesk_getLatestVersion() + + +function hesk_cacheLatestVersion($latest) +{ + global $hesk_settings; + + @file_put_contents(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt', time() . '|' . $latest); + + return $latest; + +} // END hesk_cacheLatestVersion() + +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 .= ''; + } + } + + if ($return_options) { + return $html; + } else { + ?> + + + + <?php echo $hesklang['test_theme_folder']; ?> + + + + +

    +

    +
    +

    + + + | + + + +

    + + + /$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[\'team\']') === 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 .= "\n"; + + /* Add an option for the + +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + + +
    +
    + + +
    +
    +
    + + +
    + + + +
    +
    +
    +
    + +
    + > + +
    +
    + > + +
    +
    +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    + > + +
    +
    + > + +
    +
    +
    + +
    +

    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    + +
    +
    + + +
    + + + +
    +
    +
    +
    +
    + > + +
    +
    + > + +
    +
    + > + +
    +
    +
    + +
    +
    + + +
    + + + +
    +
    +
    +
    +
    + > + +
    +
    + > + +
    +
    + > + +
    +
    +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
     
    + +
    +
    + + + +
    +
    +
    +

    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    + onclick="hesk_toggleLayer('captcha','none')"> + +
    +
    + onclick="hesk_toggleLayer('captcha','block')"> + +
    +
    + onclick="hesk_toggleLayer('captcha','block')"> + +
    +
    +
    +
    + +
    +
    + +
    +
    +
    + > + +
    +
    + > + + +
    + + + +
    +
    +
    +
    + > + + +
    + + + +
    +
    +
    +
    +
    +
    +
    + + +
    +
    + + +
    +
    +
    +
    +
    +
    + + +
    + + + +
    +
    +
    + + +
    +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    +
    +

    +
    + + +
    +
    + + +
    +
    +
    + + +
    + + + +
    +
    +
    +
    + > + +
    +
    +
    +
    + + +
    + + + +
    +
    +
    +
    + > + +
    +
    +
    +
    + + +
    + + + +
    +
    +
    +
    + > + +
    +
    +
    +
    + + +
    + + + +
    +
    +
    +
    + + > + + + + +
    +
    +
    +
    +

    +
    +
    + + +
    + + + +
    +
    +
    + + + '.$hesklang['e_attach'].''; + } + ?> +
    + +
    +
    + +
    + +
    +
    + + > +
    + $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); + ?> +
    + + > + +
    +
    + + > +
    +
    +
    +
    + + + + + +
    + +
    + + + + + 12 ) + { + return -1; + } + elseif ($latest == $hesk_settings['hesk_version']) + { + return true; + } + else + { + return $latest; + } + } + else + { + return -1; + } + +} // END hesk_checkVersion() + + +function hesk_getLatestVersion() +{ + global $hesk_settings; + + // Do we have a cached version file? + if ( file_exists(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt') ) + { + if ( preg_match('/^(\d+)\|([\d.]+)+$/', @file_get_contents(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt'), $matches) && (time() - intval($matches[1])) < 3600 ) + { + return $matches[2]; + } + } + + // No cached file or older than 3600 seconds, try to get an update + $hesk_version_url = 'http://hesk.com/version'; + + // Try using cURL + if ( function_exists('curl_init') ) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $hesk_version_url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 6); + $latest = curl_exec($ch); + curl_close($ch); + return hesk_cacheLatestVersion($latest); + } + + // Try using a simple PHP function instead + if ($latest = @file_get_contents($hesk_version_url) ) + { + return hesk_cacheLatestVersion($latest); + } + + // Can't check automatically, will need a manual check + return false; + +} // END hesk_getLatestVersion() + + +function hesk_cacheLatestVersion($latest) +{ + global $hesk_settings; + + @file_put_contents(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt', time() . '|' . $latest); + + return $latest; + +} // END hesk_cacheLatestVersion() +?> diff --git a/hesk/admin/admin_settings_knowledgebase.php b/hesk/admin/admin_settings_knowledgebase.php new file mode 100644 index 0000000..faff41e --- /dev/null +++ b/hesk/admin/admin_settings_knowledgebase.php @@ -0,0 +1,603 @@ +install 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'); +$hesk_settings['language'] = $hesk_settings['language_default']; +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') ) +{ + $hesk_settings['db_host'] = $hesklang['hdemo']; + $hesk_settings['db_name'] = $hesklang['hdemo']; + $hesk_settings['db_user'] = $hesklang['hdemo']; + $hesk_settings['db_pass'] = $hesklang['hdemo']; + $hesk_settings['db_pfix'] = $hesklang['hdemo']; + $hesk_settings['smtp_host_name'] = $hesklang['hdemo']; + $hesk_settings['smtp_user'] = $hesklang['hdemo']; + $hesk_settings['smtp_password'] = $hesklang['hdemo']; + $hesk_settings['pop3_host_name'] = $hesklang['hdemo']; + $hesk_settings['pop3_user'] = $hesklang['hdemo']; + $hesk_settings['pop3_password'] = $hesklang['hdemo']; + $hesk_settings['imap_host_name'] = $hesklang['hdemo']; + $hesk_settings['imap_user'] = $hesklang['hdemo']; + $hesk_settings['imap_password'] = $hesklang['hdemo']; + $hesk_settings['recaptcha_public_key'] = $hesklang['hdemo']; + $hesk_settings['recaptcha_private_key'] = $hesklang['hdemo']; +} + +/* This will handle error, success and notice messages */ +hesk_handle_messages(); +?> +
    +
    +

    +
      +
    • +
      +
      + + ' . $hesklang['hud'] . ' '; + } elseif ($latest != -1) { + // Is this a beta/dev version? + if (strpos($hesk_settings['hesk_version'], 'beta') || strpos($hesk_settings['hesk_version'], 'dev') || strpos($hesk_settings['hesk_version'], 'RC')) { + echo ' ' . $hesklang['beta'] . ' '; ?>
      ' . $hesklang['hnw'] . ' '; ?>
      - - +
      +
    • +
    • +
      +
      +
    • +
    • +
      +
      +
    • +
    • +
      /hesk_settings.inc.php
      +
      + '.$hesklang['exists'].', '.$hesklang['writable'].''; + } else { + echo ''.$hesklang['exists'].', '.$hesklang['not_writable'].'
      '.$hesklang['e_settings']; + } + ?> +
      +
    • +
    • +
      /
      +
      + '.$hesklang['exists'].', '; + if (is_writable(HESK_PATH . $hesk_settings['attach_dir'])) { + $enable_use_attachments = 1; + echo ''.$hesklang['writable'].''; + } else { + echo ''.$hesklang['not_writable'].'
      '.$hesklang['e_attdir']; + } + } else { + echo ''.$hesklang['no_exists'].', '.$hesklang['not_writable'].'
      '.$hesklang['e_attdir']; + } + ?> +
      +
    • +
    • +
      /
      +
      + '.$hesklang['exists'].', '; + if (is_writable(HESK_PATH . $hesk_settings['cache_dir'])) { + $enable_use_attachments = 1; + echo ''.$hesklang['writable'].''; + } else { + echo ''.$hesklang['not_writable'].'
      '.$hesklang['e_cdir']; + } + } else { + echo ''.$hesklang['no_exists'].', '.$hesklang['not_writable'].'
      '.$hesklang['e_cdir']; + } + ?> +
      +
    • +
    +
    + +
    +
    +
    +

    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    + > + +
    +
    + > + +
    +
    + > + +
    +
    +
    +
    +
    +

    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    +
    +
    + + +
    + + + +
    +
    +
    + +
    + +
    +
    + + +
    + + + +
    +
    +
    +
    +
    + > + +
    +
    + > + +
    +
    + > + +
    +
    +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + +
      +
    • + + +
    • +
    • + + +
    • +
    +
    +
    + +
      +
    • + + +
    • +
    • + + +
    • +
    +
    +
    + + +
    +
    +
    + + + + + +
    + +
    +
    +
    +
    + 12 ) + { + return -1; + } + elseif ($latest == $hesk_settings['hesk_version']) + { + return true; + } + else + { + return $latest; + } + } + else + { + return -1; + } + +} // END hesk_checkVersion() + + +function hesk_getLatestVersion() +{ + global $hesk_settings; + + // Do we have a cached version file? + if ( file_exists(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt') ) + { + if ( preg_match('/^(\d+)\|([\d.]+)+$/', @file_get_contents(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt'), $matches) && (time() - intval($matches[1])) < 3600 ) + { + return $matches[2]; + } + } + + // No cached file or older than 3600 seconds, try to get an update + $hesk_version_url = 'http://hesk.com/version'; + + // Try using cURL + if ( function_exists('curl_init') ) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $hesk_version_url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 6); + $latest = curl_exec($ch); + curl_close($ch); + return hesk_cacheLatestVersion($latest); + } + + // Try using a simple PHP function instead + if ($latest = @file_get_contents($hesk_version_url) ) + { + return hesk_cacheLatestVersion($latest); + } + + // Can't check automatically, will need a manual check + return false; + +} // END hesk_getLatestVersion() + + +function hesk_cacheLatestVersion($latest) +{ + global $hesk_settings; + + @file_put_contents(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt', time() . '|' . $latest); + + return $latest; + +} // END hesk_cacheLatestVersion() +?> diff --git a/hesk/admin/admin_settings_misc.php b/hesk/admin/admin_settings_misc.php new file mode 100644 index 0000000..bc78296 --- /dev/null +++ b/hesk/admin/admin_settings_misc.php @@ -0,0 +1,431 @@ +install 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'); +$hesk_settings['language'] = $hesk_settings['language_default']; +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') ) +{ + $hesk_settings['db_host'] = $hesklang['hdemo']; + $hesk_settings['db_name'] = $hesklang['hdemo']; + $hesk_settings['db_user'] = $hesklang['hdemo']; + $hesk_settings['db_pass'] = $hesklang['hdemo']; + $hesk_settings['db_pfix'] = $hesklang['hdemo']; + $hesk_settings['smtp_host_name'] = $hesklang['hdemo']; + $hesk_settings['smtp_user'] = $hesklang['hdemo']; + $hesk_settings['smtp_password'] = $hesklang['hdemo']; + $hesk_settings['pop3_host_name'] = $hesklang['hdemo']; + $hesk_settings['pop3_user'] = $hesklang['hdemo']; + $hesk_settings['pop3_password'] = $hesklang['hdemo']; + $hesk_settings['imap_host_name'] = $hesklang['hdemo']; + $hesk_settings['imap_user'] = $hesklang['hdemo']; + $hesk_settings['imap_password'] = $hesklang['hdemo']; + $hesk_settings['recaptcha_public_key'] = $hesklang['hdemo']; + $hesk_settings['recaptcha_private_key'] = $hesklang['hdemo']; +} + +/* This will handle error, success and notice messages */ +hesk_handle_messages(); +?> +
    +
    +

    +
      +
    • +
      +
      + + ' . $hesklang['hud'] . ' '; + } elseif ($latest != -1) { + // Is this a beta/dev version? + if (strpos($hesk_settings['hesk_version'], 'beta') || strpos($hesk_settings['hesk_version'], 'dev') || strpos($hesk_settings['hesk_version'], 'RC')) { + echo ' ' . $hesklang['beta'] . ' '; ?>
      ' . $hesklang['hnw'] . ' '; ?>
      - - +
      +
    • +
    • +
      +
      +
    • +
    • +
      +
      +
    • +
    • +
      /hesk_settings.inc.php
      +
      + '.$hesklang['exists'].', '.$hesklang['writable'].''; + } else { + echo ''.$hesklang['exists'].', '.$hesklang['not_writable'].'
      '.$hesklang['e_settings']; + } + ?> +
      +
    • +
    • +
      /
      +
      + '.$hesklang['exists'].', '; + if (is_writable(HESK_PATH . $hesk_settings['attach_dir'])) { + $enable_use_attachments = 1; + echo ''.$hesklang['writable'].''; + } else { + echo ''.$hesklang['not_writable'].'
      '.$hesklang['e_attdir']; + } + } else { + echo ''.$hesklang['no_exists'].', '.$hesklang['not_writable'].'
      '.$hesklang['e_attdir']; + } + ?> +
      +
    • +
    • +
      /
      +
      + '.$hesklang['exists'].', '; + if (is_writable(HESK_PATH . $hesk_settings['cache_dir'])) { + $enable_use_attachments = 1; + echo ''.$hesklang['writable'].''; + } else { + echo ''.$hesklang['not_writable'].'
      '.$hesklang['e_cdir']; + } + } else { + echo ''.$hesklang['no_exists'].', '.$hesklang['not_writable'].'
      '.$hesklang['e_cdir']; + } + ?> +
      +
    • +
    +
    + +
    +
    +
    +

    +
    + + + +
    +
    + + +
    +
    +
    +

    +
    + + +
    + + + +
    +
    + + +
    + + + +
    +
    +
    +
    + > + +
    +
    +
    +
    + + +
    + + + +
    +
    +
    +
    + /> + +
    +
    +
    +
    + + +
    + + + +
    +
    +
    +
    + /> + +
    +
    +
    +
    + + +
    + + + +
    +
    +
    +
    + > + +
    + +
    +
    +
    +
    +
    + + +
    + + + +
    +
    +
    +
    + > + +
    +
    +
    +
    + + + + + +
    + +
    +
    +
    +
    + 12 ) + { + return -1; + } + elseif ($latest == $hesk_settings['hesk_version']) + { + return true; + } + else + { + return $latest; + } + } + else + { + return -1; + } + +} // END hesk_checkVersion() + + +function hesk_getLatestVersion() +{ + global $hesk_settings; + + // Do we have a cached version file? + if ( file_exists(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt') ) + { + if ( preg_match('/^(\d+)\|([\d.]+)+$/', @file_get_contents(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt'), $matches) && (time() - intval($matches[1])) < 3600 ) + { + return $matches[2]; + } + } + + // No cached file or older than 3600 seconds, try to get an update + $hesk_version_url = 'http://hesk.com/version'; + + // Try using cURL + if ( function_exists('curl_init') ) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $hesk_version_url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 6); + $latest = curl_exec($ch); + curl_close($ch); + return hesk_cacheLatestVersion($latest); + } + + // Try using a simple PHP function instead + if ($latest = @file_get_contents($hesk_version_url) ) + { + return hesk_cacheLatestVersion($latest); + } + + // Can't check automatically, will need a manual check + return false; + +} // END hesk_getLatestVersion() + + +function hesk_cacheLatestVersion($latest) +{ + global $hesk_settings; + + @file_put_contents(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt', time() . '|' . $latest); + + return $latest; + +} // END hesk_cacheLatestVersion() +?> diff --git a/hesk/admin/admin_settings_save.php b/hesk/admin/admin_settings_save.php new file mode 100644 index 0000000..4a942d9 --- /dev/null +++ b/hesk/admin/admin_settings_save.php @@ -0,0 +1,961 @@ + General settings */ + $set['site_title'] = hesk_input( hesk_POST('s_site_title'), $hesklang['err_sname']); + $set['site_title'] = str_replace('\\"','"',$set['site_title']); + $set['site_url'] = hesk_input( 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('\\"','"',$set['hesk_title']); + $set['hesk_url'] = rtrim( hesk_input( hesk_POST('s_hesk_url'), $hesklang['err_hurl']), '/'); + $set['webmaster_mail'] = hesk_validateEmail( hesk_POST('s_webmaster_mail'), $hesklang['err_wmmail']); + $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('\\"','<','>'),'',$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']); + $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']); + } + + /* --> 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 . '

    ' . $hesklang['mysql_said'] . ': ' . $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['new_top'] = empty($_POST['s_new_top']) ? 0 : 1; + $set['reply_top'] = empty($_POST['s_reply_top']) ? 0 : 1; + + /* --> 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['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); + + /* --> 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['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['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') ); + } + + /* --> 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_htmlspecialchars( hesk_POST('s_max_unit', 'MB') ); + + $set['attachments']['max_size'] = hesk_formatUnits($size . ' ' . $unit); + + $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', 'phps', 'phtml', 'shtml', 'shtm', 'cgi', 'pl') ); + + if (count($set['attachments']['allowed_types'])) + { + $keep_these = array(); + + foreach ($set['attachments']['allowed_types'] as $ext) + { + if (strlen($ext) > 1) + { + $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'); + } +} 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['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') ); + $set['smtp_host_port'] = intval( hesk_POST('tmp_smtp_host_port', 25) ); + $set['smtp_timeout'] = intval( hesk_POST('tmp_smtp_timeout', 10) ); + $set['smtp_ssl'] = empty($_POST['tmp_smtp_ssl']) ? 0 : 1; + $set['smtp_tls'] = empty($_POST['tmp_smtp_tls']) ? 0 : 1; + $set['smtp_user'] = hesk_input( hesk_POST('tmp_smtp_user') ); + $set['smtp_password'] = hesk_input( hesk_POST('tmp_smtp_password') ); + } + + /* --> Email piping */ + $set['email_piping'] = empty($_POST['s_email_piping']) ? 0 : 1; + + /* --> 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') ); + } + + /* --> 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) + { + $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_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') ); + } + + /* --> Email loops */ + $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); + + /* --> 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(' 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['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['multi_eml'] = empty($_POST['s_multi_eml']) ? 0 : 1; + $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; + } + } + +// 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'; + + /* --> Other */ + $set['submittedformat'] = hesk_checkMinMax( intval( hesk_POST('s_submittedformat') ) , 0, 2, 2); + $set['updatedformat'] = hesk_checkMinMax( intval( hesk_POST('s_updatedformat') ) , 0, 2, 2); +} 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['timeformat'] = hesk_input( hesk_POST('s_timeformat') ) or $set['timeformat'] = 'Y-m-d H:i:s'; + + /* --> Other */ + $set['ip_whois'] = hesk_input( 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'] = 'http://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; +} + +$set['hesk_version'] = $hesk_settings['hesk_version']; + +// Prepare settings file and save it +$settings_file_content=' 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[\'noreply_mail\']=\'' . hesk_getProperty($set, 'noreply_mail') . '\'; +$hesk_settings[\'noreply_name\']=\'' . hesk_getProperty($set, 'noreply_name') . '\'; +$hesk_settings[\'site_theme\']=\'' . hesk_getProperty($set, 'site_theme') . '\'; + +// --> 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') . '\'; +$hesk_settings[\'db_vrsn\']=' . hesk_getProperty($set, 'db_vrsn') . '; + + +// ==> 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[\'new_top\']=' . hesk_getProperty($set, 'new_top') . '; +$hesk_settings[\'reply_top\']=' . hesk_getProperty($set, 'reply_top') . '; + +// --> 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[\'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') . '; + +// --> 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[\'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[\'force_ssl\']=' . hesk_getProperty($set, 'force_ssl') . '; + +// --> 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)) . '\') +); + + +// ==> 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[\'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_ssl\']=' . hesk_getProperty($set, 'smtp_ssl') . '; +$hesk_settings[\'smtp_tls\']=' . hesk_getProperty($set, 'smtp_tls') . '; +$hesk_settings[\'smtp_user\']=\'' . hesk_getProperty($set, 'smtp_user') . '\'; +$hesk_settings[\'smtp_password\']=\'' . hesk_getProperty($set, 'smtp_password') . '\'; + +// --> Email piping +$hesk_settings[\'email_piping\']=' . hesk_getProperty($set, 'email_piping') . '; + +// --> 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') . '\'; + +// --> 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_keep\']=' . hesk_getProperty($set, 'imap_keep') . '; +$hesk_settings[\'imap_user\']=\'' . hesk_getProperty($set, 'imap_user') . '\'; +$hesk_settings[\'imap_password\']=\'' . hesk_getProperty($set, 'imap_password') . '\'; + +// --> Email loops +$hesk_settings[\'loop_hits\']=' . hesk_getProperty($set, 'loop_hits') . '; +$hesk_settings[\'loop_time\']=' . hesk_getProperty($set, 'loop_time') . '; + +// --> 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[\'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[\'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') . '); + +// --> Other +$hesk_settings[\'submittedformat\']=' . hesk_getProperty($set, 'submittedformat') . '; +$hesk_settings[\'updatedformat\']=' . hesk_getProperty($set, 'updatedformat') . '; + + +// ==> MISC + +// --> Date & Time +$hesk_settings[\'timezone\']=\'' . hesk_getProperty($set, 'timezone') . '\'; +$hesk_settings[\'timeformat\']=\'' . hesk_getProperty($set, 'timeformat') . '\'; + +// --> 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') . '; + + +############################# +# 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) ) +{ + hesk_error($hesklang['err_openset']); +} + +// Any settings problems? +$tmp = array(); + +if ( ! $smtp_OK) +{ + $tmp[] = ''.$hesklang['sme'].': '.$smtp_error.'

    '.$hesklang['scl'].''; +} + +if ( ! $pop3_OK) +{ + $tmp[] = ''.$hesklang['pop3e'].': '.$pop3_error.'

    '.$hesklang['pop3log'].''; +} + +// Clear the cache folder +hesk_purge_cache('kb'); +hesk_purge_cache('cf'); +hesk_purge_cache('export', 14400); +hesk_purge_cache('status'); + +// Show the settings page and display any notices or success +$return_location = 'admin_settings_' . strtolower($section) . '.php'; +if ( count($tmp) ) +{ + $errors = implode('

    ', $tmp); + hesk_process_messages( $hesklang['sns'] . '

    ' . $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 */ + $hesk_settings['smtp'] = 0; + $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'; + $email = $dir . $subdir . '/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; + } + elseif ( ! preg_match('/\$hesklang\[\'team\'\]/', $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; + } + + /* Add an option for the > + + + + + +
    +

    +
    +
    + + +
    + + + +
    +
    +
    +
    +
    + > + +
    +
    + > + +
    +
    + > + +
    +
    +
    +
    +
    + + +
    + + + +
    +
    +
    +
    +
    + > + +
    +
    + > + +
    +
    + > + +
    +
    +
    +
    +
    +
    + + + + + +
    + +
    +
    + + + 12 ) + { + return -1; + } + elseif ($latest == $hesk_settings['hesk_version']) + { + return true; + } + else + { + return $latest; + } + } + else + { + return -1; + } + +} // END hesk_checkVersion() + + +function hesk_getLatestVersion() +{ + global $hesk_settings; + + // Do we have a cached version file? + if ( file_exists(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt') ) + { + if ( preg_match('/^(\d+)\|([\d.]+)+$/', @file_get_contents(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt'), $matches) && (time() - intval($matches[1])) < 3600 ) + { + return $matches[2]; + } + } + + // No cached file or older than 3600 seconds, try to get an update + $hesk_version_url = 'http://hesk.com/version'; + + // Try using cURL + if ( function_exists('curl_init') ) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $hesk_version_url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 6); + $latest = curl_exec($ch); + curl_close($ch); + return hesk_cacheLatestVersion($latest); + } + + // Try using a simple PHP function instead + if ($latest = @file_get_contents($hesk_version_url) ) + { + return hesk_cacheLatestVersion($latest); + } + + // Can't check automatically, will need a manual check + return false; + +} // END hesk_getLatestVersion() + + +function hesk_cacheLatestVersion($latest) +{ + global $hesk_settings; + + @file_put_contents(HESK_PATH . $hesk_settings['cache_dir'] . '/__latest.txt', time() . '|' . $latest); + + return $latest; + +} // END hesk_cacheLatestVersion() +?> diff --git a/hesk/admin/admin_submit_ticket.php b/hesk/admin/admin_submit_ticket.php new file mode 100644 index 0000000..18a1457 --- /dev/null +++ b/hesk/admin/admin_submit_ticket.php @@ -0,0 +1,426 @@ + 3) +{ + // If we are showing "Click to select" priority needs to be selected + if ($hesk_settings['select_pri']) + { + $tmpvar['priority'] = -1; + $hesk_error_buffer['priority'] = $hesklang['select_priority']; + } + else + { + $tmpvar['priority'] = 3; + } +} + +$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']; +} + +// 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); + + // Is auto-assign of tickets disabled in this category? + if ( empty($hesk_settings['category_data'][$tmpvar['category']]['autoassign']) ) + { + $hesk_settings['autoassign'] = false; + } +} + +// 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) ) . '
    ';; + } + $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 (preg_match("/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/", $tmpvar[$k])) + { + $date = strtotime($tmpvar[$k] . ' t00:00:00 UTC'); + $dmin = strlen($v['value']['dmin']) ? strtotime($v['value']['dmin'] . ' t00:00:00 UTC') : false; + $dmax = strlen($v['value']['dmax']) ? strtotime($v['value']['dmax'] . ' t00:00:00 UTC') : false; + + $_SESSION["as_$k"] = $tmpvar[$k]; + + if ($dmin && $dmin > $date) + { + $hesk_error_buffer[$k] = sprintf($hesklang['d_emin'], $v['name'], hesk_custom_date_display_format($dmin, $v['value']['date_format'])); + } + elseif ($dmax && $dmax < $date) + { + $hesk_error_buffer[$k] = sprintf($hesklang['d_emax'], $v['name'], hesk_custom_date_display_format($dmax, $v['value']['date_format'])); + } + else + { + $tmpvar[$k] = $date; + } + } + 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] = ''; + } +} + +// Generate tracking ID +$tmpvar['trackid'] = hesk_createID(); + +// Log who submitted ticket +$tmpvar['history'] = sprintf($hesklang['thist7'], hesk_date(), $_SESSION['name'].' ('.$_SESSION['user'].')'); +$tmpvar['openedby'] = $_SESSION['id']; + +// 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(),$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`,`isadmin`,`categories` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id`='{$tmpvar['owner']}' LIMIT 1"); + if (hesk_dbNumRows($res) == 1) + { + $row = hesk_dbFetchAssoc($res); + if (!$row['isadmin']) + { + $row['categories']=explode(',',$row['categories']); + if (!in_array($tmpvar['category'],$row['categories'])) + { + $_SESSION['isnotice'][] = 'category'; + $hesk_error_buffer['owner']=$hesklang['onasc']; + } + } + } + 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; + +// Attachments +if ($hesk_settings['attachments']['use']) +{ + require_once(HESK_PATH . 'inc/attachments.inc.php'); + + $attachments = array(); + $trackingID = $tmpvar['trackid']; + + for ($i=1;$i<=$hesk_settings['attachments']['max_number'];$i++) + { + $att = hesk_uploadFile($i); + if ($att !== false && !empty($att)) + { + $attachments[$i] = $att; + } + } +} +$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_name'] = hesk_POST('name'); + $_SESSION['as_email'] = hesk_POST('email'); + $_SESSION['as_priority'] = $tmpvar['priority']; + $_SESSION['as_subject'] = hesk_POST('subject'); + $_SESSION['as_message'] = hesk_POST('message'); + $_SESSION['as_owner'] = $tmpvar['owner']; + $_SESSION['as_notify'] = $notify; + $_SESSION['as_show'] = $show; + + 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 .= "
  • $error
  • \n"; + } + $hesk_error_buffer = $tmp; + + // Remove any successfully uploaded attachments + if ($hesk_settings['attachments']['use']) + { + hesk_removeAttachments($attachments); + } + + $hesk_error_buffer = $hesklang['pcer'].'

      '.$hesk_error_buffer.'
    '; + hesk_process_messages($hesk_error_buffer,'new_ticket.php?category='.$tmpvar['category']); +} + +if ($hesk_settings['attachments']['use'] && !empty($attachments)) +{ + 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']=hesk_makeURL($tmpvar['message']); +$tmpvar['message']=nl2br($tmpvar['message']); + +// Track who assigned the ticket +if ($tmpvar['owner'] > 0) +{ + $tmpvar['assignedby'] = ! empty($autoassign_owner) ? -1 : $_SESSION['id']; +} + +// Insert ticket to database +$ticket = hesk_newTicket($tmpvar); + +// Notify the customer about the ticket? +if ($notify && $email_available) +{ + hesk_notifyCustomer(); +} + +// 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'); + } + else + { + hesk_notifyAssignedStaff($autoassign_owner, 'ticket_assigned_to_you'); + } +} + +// 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_name'); +hesk_cleanSessionVars('as_email'); +hesk_cleanSessionVars('as_category'); +hesk_cleanSessionVars('as_priority'); +hesk_cleanSessionVars('as_subject'); +hesk_cleanSessionVars('as_message'); +hesk_cleanSessionVars('as_owner'); +hesk_cleanSessionVars('as_notify'); +hesk_cleanSessionVars('as_show'); +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'] .= '
     
    + ' . (isset($autoassign_owner) ? $hesklang['taasy'] : $hesklang['tasy']) . ''; +} + +// Show the ticket or just the success message +if ($show) +{ + hesk_process_messages($hesklang['new_ticket_submitted'],'admin_ticket.php?track=' . $ticket['trackid'] . '&Refresh=' . mt_rand(10000,99999), 'SUCCESS'); +} +else +{ + hesk_process_messages($hesklang['new_ticket_submitted'].'. ' . $hesklang['view_ticket'] . '', 'new_ticket.php', 'SUCCESS'); +} diff --git a/hesk/admin/admin_suggest_articles.php b/hesk/admin/admin_suggest_articles.php new file mode 100644 index 0000000..b7d81ff --- /dev/null +++ b/hesk/admin/admin_suggest_articles.php @@ -0,0 +1,79 @@ +'; +} + +/* Return found articles */ +?> +
    +
    +
    +
    + +
    + + '.$hesklang['nsfo'].''; + } + 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 ' + '.$article['subject'].' +
    '.$txt.'

    '; + } + } + ?> +
    +
    +
    +
    + diff --git a/hesk/admin/admin_ticket.php b/hesk/admin/admin_ticket.php new file mode 100644 index 0000000..efb92c0 --- /dev/null +++ b/hesk/admin/admin_ticket.php @@ -0,0 +1,2082 @@ +$error\n"; + } + $hesk_error_buffer = $tmp; + + $hesk_error_buffer = $hesklang['pcer'].'

      '.$hesk_error_buffer.'
    '; + 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) ) + { + 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)."')"); + + /* Notify assigned staff that a note has been added if needed */ + if ($ticket['owner'] && $ticket['owner'] != $_SESSION['id']) + { + $res = hesk_dbQuery("SELECT `email`, `notify_note` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id`='".intval($ticket['owner'])."' LIMIT 1"); + + if (hesk_dbNumRows($res) == 1) + { + $owner = hesk_dbFetchAssoc($res); + + // 1. Generate the array with ticket info that can be used in emails + $info = array( + 'email' => $ticket['email'], + 'category' => $ticket['category'], + 'priority' => $ticket['priority'], + 'owner' => $ticket['owner'], + '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, + '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. Make sure all values are properly formatted for email + $ticket = hesk_ticketToPlain($info, 1, 0); + + /* Get email functions */ + require(HESK_PATH . 'inc/email_functions.inc.php'); + + /* Format email subject and message for staff */ + $subject = hesk_getEmailSubject('new_note',$ticket); + $message = hesk_getEmailMessage('new_note',$ticket,1); + + /* Send email to staff */ + hesk_mail($owner['email'], $subject, $message); + } + } + } + + 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 */ + $revision = sprintf($hesklang['thist14'],hesk_date(),$time_worked,$_SESSION['name'].' ('.$_SESSION['user'].')'); + hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `time_worked`='" . hesk_dbEscape($time_worked) . "', `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'); +} + +/* 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)); + } + + $att_id = intval( hesk_GET('delatt') ) or hesk_error($hesklang['inv_att_id']); + + $reply = intval( hesk_GET('reply', 0) ); + if ($reply < 1) + { + $reply = 0; + } + + $note = intval( hesk_GET('note', 0) ); + if ($note < 1) + { + $note = 0; + } + + /* 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'],$_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'])."'"); + } + + hesk_process_messages($hesklang['kb_att_rem'],'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.=''; +} + +/* List of users */ +$admins = array(); +$result = hesk_dbQuery("SELECT `id`,`name`,`isadmin`,`categories`,`heskprivileges` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` ORDER BY `name` ASC"); +while ($row=hesk_dbFetchAssoc($result)) +{ + /* Is this an administrator? */ + if ($row['isadmin']) + { + $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 * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` WHERE `replyto`='".intval($ticket['id'])."' ORDER BY `id` " . ($hesk_settings['new_top'] ? 'DESC' : 'ASC') ); +} +else +{ + $reply = false; +} + +// Demo mode +if ( defined('HESK_DEMO') ) +{ + $ticket['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'] && 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 = array( + 0 => '', + 1 => '', + 2 => '', + 3 => '' +); +?> +
    +
    + +
    +

    + +
    + + + +
    +
    + +
    +
    +
    + +
    + + + +
    +
    + +
    +
    +
    + + +

    +
    +
    + + +
    + +
    + $v) + { + if ($v['use'] && $v['place']==0 && hesk_is_custom_field_in_category($k, $ticket['category']) ) + { + + switch ($v['type']) + { + case 'email': + $ticket[$k] = ''.$ticket[$k].''; + break; + } + + echo ' +
    + '.$v['name:'].' + '.$ticket[$k].' +
    '; + } + } + + if ($ticket['message'] != '') + { + ?> +
    +

    +
    + $v) + { + if ($v['use'] && $v['place'] && hesk_is_custom_field_in_category($k, $ticket['category']) ) + { + switch ($v['type']) + { + case 'email': + $ticket[$k] = ''.$ticket[$k].''; + break; + } + + echo ' +
    + '.$v['name:'].' + '.$ticket[$k].' +
    '; + } + } + + /* Print attachments */ + hesk_listAttachments($ticket['attachments'], 0 , $i); + + // Show suggested KB articles + if ($hesk_settings['kb_enable'] && $hesk_settings['kb_recommendanswers'] && strlen($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']] = ''.$article['subject'].''; + } + + // 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) ) + { + ?> +
    + + '.$hesklang['sska'].' + '; + } + ?> +
    + + +
    + +
    +
    +
    + : + + +
    + + + +
    +
    +

    +
    +
    + ' : ''; + + $att = explode(',', substr($note['attachments'], 0, -1) ); + $num = count($att); + foreach ($att as $myatt) + { + list($att_id, $att_name) = explode('#', $myatt); + + // Can edit and delete note (attachments)? + if ($can_del_notes || $note['who'] == $_SESSION['id']) + { + // If this is the last attachment and no message, show "delete ticket" link + if ($num == 1 && strlen($note['message']) == 0) + { + echo ' + + + + '; + } + // Show "delete attachment" link + else + { + echo ' + + + + '; + } + } + + echo ' + + + + + + '.$att_name.'
    + '; + } + } + ?> +
    +
    + +
    +
    + + '; + for ($i=1;$i<=$hesk_settings['attachments']['max_number'];$i++) + { + echo '
    '; + } + echo '
    '; + } + ?> + + + + +
    +
    + +
    +
    + +
    +
    +
    + +
    +
    + +
    +
    +
    + + + +
    +
    + +
    +
    +
    + +
    + + + +
    +
    + +
    +
    +
    + +
    + + + +
    +
    + +
    +
    +
    + +
    + + + + '; + } + ?> +
    +
    + +
    +
    +

    + + + + +

    +
    +
    +
    :
    +
    +
    + +
    +
    :
    +
    +
    + +
    +
    :
    +
    +
    +
    +
    :
    +
    + '.$hesklang['open_action'].'] '; + } + } + elseif ($can_resolve) + { + $status_action = ' ['.$hesklang['close_action'].'] '; + } + else + { + $status_action = ''; + } + + echo hesk_get_admin_ticket_status($ticket['status'], $status_action); + ?> +
    +
    +
    +
    :
    +
    +
    +
    +
    :
    +
    +
    +
    +
    :
    +
    +
    +
    +
    :
    +
    + '', + 1 => '', + 2 => '', + 3 => '' + ); + + switch ($ticket['priority']) + { + case 0: + echo ''.$hesklang['critical'].''; + unset($options[0]); + break; + case 1: + echo ''.$hesklang['high'].''; + unset($options[1]); + break; + case 2: + echo ''.$hesklang['medium'].''; + unset($options[2]); + break; + default: + echo $hesklang['low']; + unset($options[3]); + } + ?> +
    +
    +
    +
    :
    +
    +
    +
    +
    :
    +
    + '.$admins[$ticket['owner']].'' : + ($can_assign_self ? ''.$hesklang['unas'].''.' ['.$hesklang['asss'].']' : ''.$hesklang['unas'].''); + ?> +
    +
    + +
    +
    :
    + +
    + + + + + + + +
    + ' . $ticket['time_worked'] . '
    '; + } + ?> +
    + +
    + + ', $ticket['history']); + + ?> +
    +

    + + + + +

    +
    + ', '', $history_piece); + $date_and_contents = explode(' | ', $history_piece); + ?> +
    +
    +
    +
    + +
    +
    + +
    + + +'; + foreach ($att as $myatt) + { + list($att_id, $att_name) = explode('#', $myatt); + + /* Can edit and delete tickets? */ + if ($can_edit && $can_delete) + { + echo ' + + + +   '; + } + + echo ' + + + + + + '.$att_name.'
    + '; + } + echo ''; + + 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 ? '&reply='.$reply['id'] : ''; + if ($isReply) { + $buttons['more'][] = ' + + + + + '.$hesklang['btn_edit'].' + '; + } else { + $buttons[] = ' + + + + + '.$hesklang['btn_edit'].' + '; + } + + } + + + if (!$isReply) { + // Print ticket button + $buttons[] = ' + + + + + '.$hesklang['btn_print'].' + '; + } + + + // Lock ticket button + if (!$isReply && $can_resolve) { + if ($ticket['locked']) { + $des = $hesklang['tul'] . ' - ' . $hesklang['isloc']; + $buttons['more'][] = ' + + + + + '.$hesklang['btn_unlock'].' + '; + } else { + $des = $hesklang['tlo'] . ' - ' . $hesklang['isloc']; + $buttons['more'][] = ' + + + + + '.$hesklang['btn_lock'].' + '; + } + } + + // Tag ticket button + if (!$isReply && $can_archive) { + if ($ticket['archive']) { + $buttons['more'][] = ' + + + + + '.$hesklang['btn_untag'].' + '; + } else { + $buttons['more'][] = ' + + + + + '.$hesklang['btn_tag'].' + '; + } + } + + // Resend email notification button + $buttons['more'][] = ' + + + + + '.$hesklang['btn_resend'].' + '; + + // Import to knowledgebase button + if (!$isReply && $hesk_settings['kb_enable'] && hesk_checkPermission('can_man_kb',0)) + { + $buttons['more'][] = ' + + + + + '.$hesklang['btn_import_kb'].' + '; + } + + // Export ticket + if (!$isReply && $can_export) + { + $buttons['more'][] = ' + + + + + '.$hesklang['btn_export'].' + '; + } + + // Anonymize ticket + if (!$isReply && $can_privacy) + { + $buttons['more'][] = ' + + + + + '.$hesklang['btn_anony'].' + '; + } + + // Delete ticket or reply + if ($can_delete) + { + if ($isReply) + { + $url = 'admin_ticket.php'; + $tmp = 'delete_post='.$reply['id']; + $txt = $hesklang['btn_delr']; + } + else + { + $url = 'delete_tickets.php'; + $tmp = 'delete_ticket=1'; + $txt = $hesklang['btn_delt']; + } + $buttons['more'][] = ' + + + + + '.$txt.' + '; + } + + // Format and return the HTML for buttons + $button_code = ''; + + foreach ($buttons as $button) { + if (is_array($button)) { + $more_class = $isReply ? 'more ' : ''; + $label = ' + + '; + + if ($isReply) { + $label = ' + '; + } + + $button_code .= ' +
    + '.$label.' +
    '; + } 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'); + ?> + +
    +
    + +

    +
    +
    + + +
    +
    + + +
    +
    +
    +
    + + +
    + +
    + +
    +
    +
    + : + +
    + + +
    +
    +

    +
    + ' . $hesklang['rnh'] . '

    '; + } elseif ($reply['rating'] == 5) { + echo '

    ' . $hesklang['rh'] . '

    '; + } + } + + /* Show "unread reply" message? */ + if ($reply['staffid'] && !$reply['read']) { + echo '

    ' . $hesklang['unread'] . '

    '; + } + + ?> +
    + +
    '; + } + } + + for ($j = 0; $j < count($displayed_replies); $j++) { + $reply = $displayed_replies[$j]; + ?> +
    +
    +
    + : + +
    + + +
    +
    +

    +
    + '.$hesklang['rnh'].'

    '; + } + elseif ($reply['rating']==5) + { + echo '

    '.$hesklang['rh'].'

    '; + } + } + + /* Show "unread reply" message? */ + if ($reply['staffid'] && ! $reply['read']) + { + echo '

    '.$hesklang['unread'].'

    '; + } + ?> +
    + +
    + +
    + +
    +
    +
    + : + +
    + + +
    +
    +

    +
    + ' . $hesklang['rnh'] . '

    '; + } elseif ($reply['rating'] == 5) { + echo '

    ' . $hesklang['rh'] . '

    '; + } + } + + /* Show "unread reply" message? */ + if ($reply['staffid'] && !$reply['read']) { + echo '

    ' . $hesklang['unread'] . '

    '; + } + + ?> +
    + +
    '; + } + } + + 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 ? '

    '.$hesklang['attm'].'' : ''), $hesklang['owneed']); + return ''; + } +?> + +
    +
    +
    + +
    + + +
    + + + +
    + +
    + + + + + + + + + + + + +
    + + + + +
    + +
    + '.$hesklang['reply_from_template'].''; + echo sprintf($hesklang['type_your_message_or_reply_from_template'], $link); + } else { + echo $hesklang['type_your_message']; + } + ?> +
    +
    + + +
    + + + +
    + ' . $hesklang['ful'] . '):
    '; ?> +
    +
    +
    '; + } + ?> + + +
    + '; + if (empty($ticket['owner'])) + { + echo ''; + echo ''; + } + else + { + echo ''; + } + echo ''; + echo ''; + } + ?> + +
    + + +
    + +
    + + + + +
    +
    + > + +
    +
    +
    + + + +   + + + + + + +
    +
    +
    + + + + + diff --git a/hesk/admin/anonymize_ticket.php b/hesk/admin/anonymize_ticket.php new file mode 100644 index 0000000..31962ef --- /dev/null +++ b/hesk/admin/anonymize_ticket.php @@ -0,0 +1,43 @@ + diff --git a/hesk/admin/assign_owner.php b/hesk/admin/assign_owner.php new file mode 100644 index 0000000..afbbf3b --- /dev/null +++ b/hesk/admin/assign_owner.php @@ -0,0 +1,171 @@ +'.$hesklang['unas'].'',$_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}' LIMIT 1"); +$row = hesk_dbFetchAssoc($res); + +/* Has new owner access to the category? */ +if ( ! $row['isadmin']) +{ + $row['categories']=explode(',',$row['categories']); + 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']}' LIMIT 1"); + + if (hesk_dbNumRows($res) == 1) + { + $row = hesk_dbFetchAssoc($res); + + hesk_process_messages( + sprintf($hesklang['taat'], $row['name']) . + '

    ' . + $new_owner . + '

    ' . + ''.$hesklang['ycto'].' | ' . + ''.$hesklang['ncto'].'', + $_SERVER['PHP_SELF'], '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(),$row['name'].' ('.$row['user'].')',$_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; + +/* --> Prepare message */ + +// 1. Generate the array with ticket info that can be used in emails +$info = array( +'email' => $ticket['email'], +'category' => $ticket['category'], +'priority' => $ticket['priority'], +'owner' => $ticket['owner'], +'trackid' => $ticket['trackid'], +'status' => $ticket['status'], +'name' => $ticket['name'], +'subject' => $ticket['subject'], +'message' => $ticket['message'], +'attachments' => $ticket['attachments'], +'dt' => hesk_date($ticket['dt'], true), +'lastchange' => hesk_date($ticket['lastchange'], true), +'id' => $ticket['id'], +'time_worked' => $ticket['time_worked'], +'last_reply_by' => hesk_getReplierName($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'); +} + +$tmp = ($owner == $_SESSION['id']) ? $hesklang['tasy'] : $hesklang['taso']; +hesk_process_messages($tmp,$_SERVER['PHP_SELF'],'SUCCESS'); +?> diff --git a/hesk/admin/banned_emails.php b/hesk/admin/banned_emails.php new file mode 100644 index 0000000..7b77da0 --- /dev/null +++ b/hesk/admin/banned_emails.php @@ -0,0 +1,240 @@ + + +
    +

    +
    +
    +
    + + + + +
    +
    : john@example.com, @example.com
    +
    +
    + + +
    + 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() + +?> diff --git a/hesk/admin/banned_ips.php b/hesk/admin/banned_ips.php new file mode 100644 index 0000000..9c4fef7 --- /dev/null +++ b/hesk/admin/banned_ips.php @@ -0,0 +1,348 @@ + +
    +

    +
    +
    +
    + + + + +
    +
    +
      +
    • 123.0.0.0
    • +
    • 123.0.0.1 - 123.0.0.53
    • +
    • 123.0.0.0/24
    • +
    • 123.0.*.*
    • +
    +
    +
    + = ".intval($hesk_settings['attempt_limit'])." AND `last_attempt` > (NOW() - INTERVAL ".intval($hesk_settings['attempt_banmin'])." MINUTE)"); + $num = hesk_dbNumRows($res); + + if ($num > 0): + ?> +

    +
    + + + + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + +

    +
    + + + + + + + + + + + + + + + + + + + > + + + + + + + + + + +
    + + + + +
    +
    +
    += 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() + +?> diff --git a/hesk/admin/change_status.php b/hesk/admin/change_status.php new file mode 100644 index 0000000..0c94ed1 --- /dev/null +++ b/hesk/admin/change_status.php @@ -0,0 +1,116 @@ += 50 && $action !== 'edit_cf') +{ + hesk_show_info($hesklang['cf_limit']); +} +?> + +
    +
    +

    + +
    + +
    + +
    +
    +
    + + + + + + + + + + + + + + + + + $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) { + ?> + + + + + + + + + > + + + + + + + + + +
    + +
    + +

    + 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 + ?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

    +
    +
    +
    +
    +
    style="display: block"> +
    +

    + + + + + + +

    + + +

    +
    + 1) { + foreach ($hesk_settings['languages'] as $lang => $info): ?> +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    +
    + + +
    +
    + + +
    +
    +
    +
    + + +
    +
    + + +
    +
    +
    + +
    + +
    +
    + +
    +
    +
    +

    +
    + +
    +
    + +
    +
    +
    +

    +
    + +
    +
    +
    +
    + + +
    + > + +
    +
    + > + +
    +
    + + + type="text" class="datepicker "> +
    +
    > + + + + + + +
    +
    +
    +
    + > + + + + +
    +
    +
    + + +
    + > + +
    +
    + > + +
    +
    + + + type="text" class="datepicker "> +
    +
    > + + + + + + +
    +
    +
    +
    + > + + + + +
    +
    +
    + + +
    + > + +
    + +
    + > + + +
    +
    +

    +
    +
    +
    + + +
    + > + +
    +
    + > + +
    +
    +
    +
    +

    +
    + + +
    +
    + + +
    +
    +
    +

    +
    + +
    + > + +
    +
    + > + +
    +
    +

    +
    + +
    + > + +
    +
    + > + +
    +
    + > + +
    +
    +

    +
    + +
    + > + +
    +
    + > + +
    +
    +

    +
    + +
    + > + +
    +
    + > + +
    +
    + + +
    +
    + +
    +
    + + +$error\n"; + } + $hesk_error_buffer = $tmp; + + $hesk_error_buffer = $hesklang['rfm'].'

      '.$hesk_error_buffer.'
    '; + 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 (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}`=''"); + + // 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; + + $cf['value'] = array('show_select' => $show_select, '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 (preg_match("/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/", $dmin)) + { + $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 (preg_match("/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/", $dmax)) + { + $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 .= "
  • $error
  • \n"; + } + $hesk_error_buffer = $tmp; + + $hesk_error_buffer = $hesklang['rfm'].'

      '.$hesk_error_buffer.'
    '; + 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() diff --git a/hesk/admin/custom_statuses.php b/hesk/admin/custom_statuses.php new file mode 100644 index 0000000..1b5a58f --- /dev/null +++ b/hesk/admin/custom_statuses.php @@ -0,0 +1,572 @@ += 100; + +// Did we reach the custom statuses limit? +if ($reached_status_limit && $action !== 'edit_status') { + hesk_show_info($hesklang['status_limit']); +} + +?> +
    +
    +

    + +
    + +
    + +
    +
    +
    + + + + + + + + + + + + + + + $status) { + $status['span'] = isset($status['class']) ? '' : ''; + $status['color'] = isset($status['class']) ? $status['span'] . '.' . $status['class'] . '' : $status['span'] . $status['color'] . ''; + $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 ' + + + + '; + } + + $table_row = ''; + if (isset($_SESSION['statusord']) && $_SESSION['statusord'] == $tmp_id) { + $table_row = 'class="ticket-new"'; + unset($_SESSION['statusord']); + } + ?> + > + + + + + + + + + + + + + + + +
    ' . $hesklang['status_custom'] . '
    + +

    + + + + + + + 0): ?> + + + + + + + + + + + + +

    +
    +
    +
    +
    + + +
    > +
    +
    +

    + + + + + + +

    + '; + hesk_handle_messages(); + echo '
    '; + } + + $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 '

    ' . $hesklang['status'] . '

    '; + foreach ($hesk_settings['languages'] as $lang => $info) { ?> +
    + + +
    + +
    + + +
    + +
    + + + + +
    +
    + + +
    + + + + + + + + +
    + + +$error\n"; + } + $hesk_error_buffer = $tmp; + + $hesk_error_buffer = $hesklang['rfm'].'

      '.$hesk_error_buffer.'
    '; + 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'); + + // Delete custom status data from tickets + hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `custom{$id}`=''"); + + // 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 .= "
  • $error
  • \n"; + } + $hesk_error_buffer = $tmp; + + $hesk_error_buffer = $hesklang['rfm'].'

      '.$hesk_error_buffer.'
    '; + 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() diff --git a/hesk/admin/delete_tickets.php b/hesk/admin/delete_tickets.php new file mode 100644 index 0000000..1596bc2 --- /dev/null +++ b/hesk/admin/delete_tickets.php @@ -0,0 +1,637 @@ + array('value' => 0, 'text' => $hesklang['critical'], 'formatted' => $hesklang['critical']), + 'high' => array('value' => 1, 'text' => $hesklang['high'], 'formatted' => $hesklang['high']), + 'medium' => array('value' => 2, 'text' => $hesklang['medium'], 'formatted' => $hesklang['medium']), + 'low' => array('value' => 3, 'text' => $hesklang['low'], 'formatted' => $hesklang['low']), +); + +// Assign tickets to +if ( isset($_POST['action-type']) && $_POST['action-type'] == 'assi') +{ + 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') ); + + 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']); + + $revision = sprintf($hesklang['thist2'],hesk_date(),''.$hesklang['unas'].'',$_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); + $i++; + } + + hesk_process_messages($hesklang['assign_1'],$referer,'SUCCESS'); + } + + $res = hesk_dbQuery("SELECT `id`,`user`,`name`,`email`,`isadmin`,`categories`,`notify_assigned` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id`='{$owner}' LIMIT 1"); + $owner_data = hesk_dbFetchAssoc($res); + + if ( ! $owner_data['isadmin']) + { + $owner_data['categories']=explode(',',$owner_data['categories']); + } + + 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); + + 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(),$owner_data['name'].' ('.$owner_data['user'].')',$_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; + + /* --> Prepare message */ + + // 1. Generate the array with ticket info that can be used in emails + $info = array( + 'email' => $ticket['email'], + 'category' => $ticket['category'], + 'priority' => $ticket['priority'], + 'owner' => $ticket['owner'], + 'trackid' => $ticket['trackid'], + 'status' => $ticket['status'], + 'name' => $ticket['name'], + 'subject' => $ticket['subject'], + 'message' => $ticket['message'], + 'attachments' => $ticket['attachments'], + 'dt' => hesk_date($ticket['dt'], true), + 'lastchange' => hesk_date($ticket['lastchange'], true), + 'id' => $ticket['id'], + 'time_worked' => $ticket['time_worked'], + 'last_reply_by' => hesk_getReplierName($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'); + } + } + 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 ( array_key_exists($_POST['a'], $priorities) ) +{ + // A security check + hesk_token_check('POST'); + + // Priority info + $priority = $priorities[$_POST['a']]; + + 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 `priority`, `category` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`={$this_id} LIMIT 1"); + if (hesk_dbNumRows($result) != 1) + { + continue; + } + $ticket = hesk_dbFetchAssoc($result); + + if ($ticket['priority'] == $priority['value']) + { + continue; + } + + hesk_okCategory($ticket['category']); + + $revision = sprintf($hesklang['thist8'],hesk_date(),$priority['formatted'],$_SESSION['name'].' ('.$_SESSION['user'].')'); + hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `priority`='{$priority['value']}', `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') WHERE `id`={$this_id}"); + + $i++; + } + + hesk_process_messages($hesklang['pri_set_to'].' '.$priority['formatted'],$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` 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_okCategory($ticket['category']); + + hesk_fullyDeleteTicket(); + $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']); + + /* 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` 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_okCategory($ticket['category']); + + 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'); + + $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'); + + 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`,`name`,`category` 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_okCategory($ticket['category']); + + 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_okCategory($ticket['category']); + + $can_view_ass_by = hesk_checkPermission('can_view_ass_by', 0); + $can_view_unassigned = hesk_checkPermission('can_view_unassigned',0); + + if ($ticket['owner'] && $ticket['owner'] != $_SESSION['id'] && ! hesk_checkPermission('can_view_ass_others',0)) + { + // Maybe this user is allowed to view tickets he/she assigned? + if ( ! $can_view_ass_by || $ticket['assignedby'] != $_SESSION['id']) + { + hesk_error($hesklang['ycvtao']); + } + } + + if (!$ticket['owner'] && ! $can_view_unassigned) + { + hesk_error($hesklang['ycovtay']); + } + + // All good, continue... + + $category['name'] = isset($hesk_settings['categories'][$ticket['category']]) ? $hesk_settings['categories'][$ticket['category']] : $hesklang['catd']; + + // Get replies + $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` WHERE `replyto`='{$ticket['id']}' ORDER BY `id` ASC"); + + $ticket['replies'] = $res; + $ticket['categoryName'] = $category['name']; + $tickets[] = $ticket; + } + + // Print tickets + require(HESK_PATH . 'inc/print_template.inc.php'); + flush(); + + exit(); +} +/* JUST CLOSE */ +else +{ + /* Check permissions for this feature */ + hesk_checkPermission('can_view_tickets'); + hesk_checkPermission('can_resolve'); + + /* A security check */ + hesk_token_check('POST'); + + // Will we need ticket notifications? + if ($hesk_settings['notify_closed']) + { + require(HESK_PATH . 'inc/email_functions.inc.php'); + } + + $revision = sprintf($hesklang['thist3'],hesk_date(),$_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 " . ($hesk_settings['notify_closed'] ? '*' : '`category`') . " FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`='".intval($this_id)."' LIMIT 1"); + $ticket = hesk_dbFetchAssoc($result); + + hesk_okCategory($ticket['category']); + + 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++; + + // Notify customer of closed ticket? + if ($hesk_settings['notify_closed']) + { + $ticket['dt'] = hesk_date($ticket['dt'], true); + $ticket['lastchange'] = hesk_date($ticket['lastchange'], true); + $ticket = hesk_ticketToPlain($ticket, 1, 0); + hesk_notifyCustomer('ticket_closed'); + } + } + + hesk_process_messages(sprintf($hesklang['num_tickets_closed'],$i),$referer,'SUCCESS'); +} + + +/*** START FUNCTIONS ***/ + + +function hesk_fullyDeleteTicket() +{ + global $hesk_settings, $hesklang, $ticket; + + /* Delete attachment files */ + $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."attachments` WHERE `ticket_id`='".hesk_dbEscape($ticket['trackid'])."'"); + if (hesk_dbNumRows($res)) + { + $hesk_settings['server_path'] = dirname(dirname(__FILE__)); + + while ($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 `ticket_id`='".hesk_dbEscape($ticket['trackid'])."'"); + + /* Delete the ticket */ + hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE `id`='".intval($ticket['id'])."'"); + + /* Delete replies to the ticket */ + hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` WHERE `replyto`='".intval($ticket['id'])."'"); + + /* Delete ticket notes */ + hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."notes` WHERE `ticket`='".intval($ticket['id'])."'"); + + /* Delete ticket reply drafts */ + hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."reply_drafts` WHERE `ticket`=".intval($ticket['id'])); + + return true; +} +?> diff --git a/hesk/admin/edit_note.php b/hesk/admin/edit_note.php new file mode 100644 index 0000000..757539a --- /dev/null +++ b/hesk/admin/edit_note.php @@ -0,0 +1,115 @@ + +
    +
    +

    +
    +
    + + +
    +
    + + + + +
    +
    +
    +
    + +

    + +

     

    + + diff --git a/hesk/admin/edit_post.php b/hesk/admin/edit_post.php new file mode 100644 index 0000000..372455b --- /dev/null +++ b/hesk/admin/edit_post.php @@ -0,0 +1,605 @@ +'; + foreach ($hesk_error_buffer as $error) + { + $myerror .= "
  • $error
  • \n"; + } + $myerror .= ''; + hesk_error($myerror); + } + + $tmpvar['message'] = hesk_makeURL($tmpvar['message']); + $tmpvar['message'] = nl2br($tmpvar['message']); + + if ($hesk_settings['attachments']['use'] && !empty($attachments)) + { + 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'])."', `attachments`=CONCAT(`attachments`, '".hesk_dbEscape($myattachments)."') WHERE `id`='".intval($tmpvar['id'])."' AND `replyto`='".intval($ticket['id'])."'"); + } + else + { + $tmpvar['name'] = hesk_input( hesk_POST('name') ) or $hesk_error_buffer[]=$hesklang['enter_your_name']; + + if ($hesk_settings['require_email']) + { + $tmpvar['email'] = hesk_validateEmail( hesk_POST('email'), 'ERR', 0) or $hesk_error_buffer['email']=$hesklang['enter_valid_email']; + } + else + { + $tmpvar['email'] = hesk_validateEmail( hesk_POST('email'), 'ERR', 0); + + // Not required, but must be valid if it is entered + if ($tmpvar['email'] == '') + { + if (strlen(hesk_POST('email'))) + { + $hesk_error_buffer['email'] = $hesklang['not_valid_email']; + } + } + } + + $tmpvar['subject'] = hesk_input( hesk_POST('subject') ) or $hesk_error_buffer[]=$hesklang['enter_ticket_subject']; + $tmpvar['message'] = hesk_input( hesk_POST('message') ); + if ($hesk_settings['require_message'] == 1 && $tmpvar['message'] == '') + { + $hesk_error_buffer[] = $hesklang['enter_message']; + } + + // Demo mode + if ( defined('HESK_DEMO') ) + { + $tmpvar['email'] = 'hidden@demo.com'; + } + +// Custom fields +foreach ($hesk_settings['custom_fields'] as $k=>$v) +{ + if ($v['use'] && hesk_is_custom_field_in_category($k, $ticket['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) ) . '
    ';; + } + $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 (preg_match("/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/", $tmpvar[$k])) + { + $date = strtotime($tmpvar[$k] . ' t00:00:00 UTC'); + $dmin = strlen($v['value']['dmin']) ? strtotime($v['value']['dmin'] . ' t00:00:00 UTC') : false; + $dmax = strlen($v['value']['dmax']) ? strtotime($v['value']['dmax'] . ' t00:00:00 UTC') : false; + + $_SESSION["as_$k"] = $tmpvar[$k]; + + if ($dmin && $dmin > $date) + { + $hesk_error_buffer[$k] = sprintf($hesklang['d_emin'], $v['name'], hesk_custom_date_display_format($dmin, $v['value']['date_format'])); + } + elseif ($dmax && $dmax < $date) + { + $hesk_error_buffer[$k] = sprintf($hesklang['d_emax'], $v['name'], hesk_custom_date_display_format($dmax, $v['value']['date_format'])); + } + else + { + $tmpvar[$k] = $date; + } + } + else + { + 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)) + { + hesk_removeAttachments($attachments); + } + + $myerror = '
      '; + foreach ($hesk_error_buffer as $error) + { + $myerror .= "
    • $error
    • \n"; + } + $myerror .= '
    '; + hesk_error($myerror); + } + + $tmpvar['message'] = hesk_makeURL($tmpvar['message']); + $tmpvar['message'] = nl2br($tmpvar['message']); + + if ($hesk_settings['attachments']['use'] && !empty($attachments)) + { + 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<=50; $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 + `name`='".hesk_dbEscape( hesk_mb_substr($tmpvar['name'], 0, 255) )."', + `email`='".hesk_dbEscape( hesk_mb_substr($tmpvar['email'], 0, 1000) )."', + `subject`='".hesk_dbEscape( hesk_mb_substr($tmpvar['subject'], 0, 255) )."', + `message`='".hesk_dbEscape($tmpvar['message'])."', + `attachments`=CONCAT(`attachments`, '".hesk_dbEscape($myattachments)."'), + $custom_SQL + WHERE `id`='".intval($ticket['id'])."'"); + } + + 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'); +?> +
    +
    +

    +
    + +
    + + +
    +
    + + +
    +
    + + +
    + $v) { + if ($v['use'] && hesk_is_custom_field_in_category($k, $ticket['category']) ) { + $k_value = $ticket[$k]; + + if ($v['type'] == 'checkbox') { + $k_value = explode('
    ',$k_value); + } + + $v['req'] = $v['req']==2 ? '*' : ''; + + switch ($v['type']) { + /* Radio box */ + case 'radio': + echo ' +
    + +
    '; + + $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 ' +
    + + +
    '; + $index++; + } + echo '
    +
    '; + break; + + /* Select drop-down box */ + case 'select': + + $cls = in_array($k,$_SESSION['iserror']) ? ' class="isError" ' : ''; + + echo ' +
    + + +
    '; + break; + + /* Checkbox */ + case 'checkbox': + echo ' +
    + '; + + $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 ' +
    + + +
    '; + $index++; + } + + echo '
    '; + break; + + /* Large text box */ + case 'textarea': + $cls = in_array($k,$_SESSION['iserror']) ? ' isError" ' : ''; + $k_value = hesk_msgToPlain($k_value,0,0); + + echo ' +
    + + +
    '; + break; + + // Date + case 'date': + $k_value = hesk_custom_date_display_format($k_value, 'm/d/Y'); + + echo ' +
    + +
    + + +
    +
    + '. $k_value .' + + + + + +
    +
    '; + 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 ' +
    + + +
    +
    '; + 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 ' +
    + + +
    '; + } + } + } + ?> + +
    + + +
    + + '; + echo ''; + for ($i=$number_of_attachments+1;$i<=$hesk_settings['attachments']['max_number'];$i++) + { + echo '
    '; + } + echo '
    '; + } + ?> + + + + + + + + + +
    + + +

    + +

     

    + + +
    +
    +
    +

    + +
    + 1): ?> +
    + +
    + +
    + +
    + +
    +
    +

    + + + + + + +

    + '; + hesk_handle_messages(); + echo '
    '; + ?> +
    + +
    + +
    +
    + 1): ?> +
    +
    + + +
    +
    + +
    +
    + + + + +
    + + +
    +
    + + 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 +$date_from = date('Y-m-d',mktime(0, 0, 0, date("m"), 1, date("Y"))); +$date_to = date('Y-m-d'); +$input_datefrom = date('m/d/Y', strtotime('last month')); +$input_dateto = date('m/d/Y'); + +/* Date */ +if (!empty($_GET['w'])) +{ + $df = preg_replace('/[^0-9]/','', hesk_GET('datefrom') ); + if (strlen($df) == 8) + { + $date_from = substr($df,4,4) . '-' . substr($df,0,2) . '-' . substr($df,2,2); + $input_datefrom = substr($df,0,2) . '/' . substr($df,2,2) . '/' . substr($df,4,4); + } + else + { + $date_from = date('Y-m-d', strtotime('last month') ); + } + + $dt = preg_replace('/[^0-9]/','', hesk_GET('dateto') ); + if (strlen($dt) == 8) + { + $date_to = substr($dt,4,4) . '-' . substr($dt,0,2) . '-' . substr($dt,2,2); + $input_dateto = substr($dt,0,2) . '/' . substr($dt,2,2) . '/' . substr($dt,4,4); + } + else + { + $date_to = date('Y-m-d'); + } + + 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']; + } + + if ($date_to > date('Y-m-d')) + { + $date_to = date('Y-m-d'); + $input_dateto = date('m/d/Y'); + } + + $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 * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` 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 < 6 ) +{ + // 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 = array( +0 => 'CRITICAL', +1 => 'HIGH', +2 => 'MEDIUM', +3 => 'LOW', +); + +$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 == 4) +{ + // 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); + $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 .= ''; +} + +// Generate export file +if (isset($_GET['w'])) +{ + require_once(HESK_PATH . 'inc/export_functions.inc.php'); + list($success_msg, $tickets_exported) = hesk_export_to_XML($sql); +} + +/* 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']); + } +} +?> +
    +

    + +
    + + + +
    +
    + +
    +
    +
    +

    +
    +
    +

    +
    +
    +
    + > + + +
    +
    + > + + +
    +
    + + + type="text" class="datepicker"> +
    +
    > + + + + + + +
    +
    + +
    +
    + + + type="text" class="datepicker"> +
    +
    > + + + + + + +
    +
    +
    +
    +
    +
    +
    +

    + +
    +
    +

    +
    + > + +
    +
    + > + +
    +
    + > + +
    +
    + > + +
    +
    +
    +

    +
    + > + +
    + +
    + > + +
    + +
    + > + +
    + +
    + > + +
    +
    +
    +

    +
    +
    + > + +
    +
    + > + +
    +
    + > + +
    +
    + > + +
    +
    + > + +
    +
    + > + +
    +
    +
    +
    +

    + +
    +
    +

    +
    +
    + > + +
    +
    + > + +
    +
    +
    +
    + + +
    +
    +
    + + diff --git a/hesk/admin/export_ticket.php b/hesk/admin/export_ticket.php new file mode 100644 index 0000000..6a5efc4 --- /dev/null +++ b/hesk/admin/export_ticket.php @@ -0,0 +1,54 @@ + +
    +
    + +
    + +

    '. $hesklang['tickets_found'] .' (%%HESK_TICKET_COUNT%%)

    + '; + +// This SQL code will be used to retrieve results +$sql_final = "SELECT +`id`, +`trackid`, +`name`, +`email`, +`category`, +`priority`, +`subject`, +LEFT(`message`, 400) AS `message`, +`dt`, +`lastchange`, +`firstreply`, +`closedat`, +`status`, +`openedby`, +`firstreplyby`, +`closedby`, +`replies`, +`staffreplies`, +`owner`, +`time_worked`, +`lastreplier`, +`replierid`, +`archive`, +`locked` +"; + +foreach ($hesk_settings['custom_fields'] as $k=>$v) +{ + if ($v['use']) + { + $sql_final .= ", `".$k."`"; + } +} + +$sql_final.= " FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE "; + +// This code will be used to count number of results +$sql_count = "SELECT COUNT(*) FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE "; + +// 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 +$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[2]=1; + $sql .= " AND `archive`='1' "; +} + +// 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) ) +{ + $hesk_error_buffer .= $hesklang['fsq']; + $no_query = 1; +} + +// What field are we searching in +$what = hesk_GET('what', '') or $hesk_error_buffer .= '
    ' . $hesklang['wsel']; + +// Sequential ID supported? +if ($what == 'seqid' && ! $hesk_settings['sequential']) +{ + $what = 'trackid'; +} + +// Setup SQL based on searching preferences +if ( ! $no_query) +{ + $sql .= " AND "; + + switch ($what) + { + case 'trackid': + $sql .= " ( `trackid` = '".hesk_dbEscape($q)."' OR `merged` LIKE '%#".hesk_dbEscape($q)."#%' ) "; + break; + case 'name': + $sql .= "`name` LIKE '%".hesk_dbEscape( hesk_dbLike($q) )."%' COLLATE '" . hesk_dbCollate() . "' "; + break; + case 'email': + $sql .= "`email` LIKE '%".hesk_dbEscape($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 + `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 .= "`id` = '".intval($q)."' "; + break; + case 'notes': + $sql .= "`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($q)."%' COLLATE '" . hesk_dbCollate() . "' "; + } + else + { + $hesk_error_buffer .= '
    ' . $hesklang['invalid_search']; + } + } +} + +// Owner +if ( $tmp = intval( hesk_GET('owner', 0) ) ) +{ + $sql .= " AND `owner`={$tmp} "; + $owner_input = $tmp; + $hesk_error_buffer = str_replace($hesklang['fsq'],'',$hesk_error_buffer); +} +else +{ + $owner_input = 0; +} + +/* Date */ +/* -> Check for compatibility with old date format */ +if (preg_match("/(\d{4})-(\d{2})-(\d{2})/", hesk_GET('dt'), $m)) +{ + $_GET['dt']=$m[2].$m[3].$m[1]; +} + +/* -> Now process the date value */ +$dt = preg_replace('/[^0-9]/','', hesk_GET('dt') ); +if (strlen($dt) == 8) +{ + $date = substr($dt,4,4) . '-' . substr($dt,0,2) . '-' . substr($dt,2,2); + $date_input= substr($dt,0,2) . '/' . substr($dt,2,2) . '/' . substr($dt,4,4); + + /* 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 '{$date} 00:00:00' AND '{$date} 23:59:59' "; +} +else +{ + $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(); + +# echo "$sql
    "; + +// That's all the SQL we need for count +$sql_count .= $sql; +$sql = $sql_final . $sql; + +// 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) +{ + $href = 'find_tickets.php'; + 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(); + +?> diff --git a/hesk/admin/generate_spam_question.php b/hesk/admin/generate_spam_question.php new file mode 100644 index 0000000..49158c1 --- /dev/null +++ b/hesk/admin/generate_spam_question.php @@ -0,0 +1,46 @@ + +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    + diff --git a/hesk/admin/index.php b/hesk/admin/index.php new file mode 100644 index 0000000..8a42d45 --- /dev/null +++ b/hesk/admin/index.php @@ -0,0 +1,489 @@ +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; + } + else + { + $hesk_error_buffer['mysecnum'] = $hesklang['sec_wrng']; + } + } + } + } + + /* Any missing fields? */ + if (count($hesk_error_buffer)!=0) + { + $_SESSION['a_iserror'] = array_keys($hesk_error_buffer); + + $tmp = ''; + foreach ($hesk_error_buffer as $error) + { + $tmp .= "
  • $error
  • \n"; + } + $hesk_error_buffer = $tmp; + + $hesk_error_buffer = $hesklang['pcer'].'

      '.$hesk_error_buffer.'
    '; + hesk_process_messages($hesk_error_buffer,'NOREDIRECT'); + print_login(); + exit(); + } + elseif (isset($_SESSION['img_a_verified'])) + { + unset($_SESSION['img_a_verified']); + } + + /* User entered all required info, now lets limit brute force attempts */ + hesk_limitBfAttempts(); + + $result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `user` = '".hesk_dbEscape($user)."' LIMIT 1"); + if (hesk_dbNumRows($result) != 1) + { + hesk_session_stop(); + $_SESSION['a_iserror'] = array('user','pass'); + hesk_process_messages($hesklang['wrong_user'],'NOREDIRECT'); + print_login(); + exit(); + } + + $res=hesk_dbFetchAssoc($result); + foreach ($res as $k=>$v) + { + $_SESSION[$k]=$v; + } + + /* Check password */ + if (hesk_Pass2Hash($pass) != $_SESSION['pass']) + { + hesk_session_stop(); + $_SESSION['a_iserror'] = array('pass'); + hesk_process_messages($hesklang['wrong_pass'],'NOREDIRECT'); + print_login(); + exit(); + } + + $pass_enc = hesk_Pass2Hash($_SESSION['pass'].hesk_mb_strtolower($user).$_SESSION['pass']); + + /* Check if default password */ + if ($_SESSION['pass'] == '499d74967b28a841c98bb4baaabaad699ff3c079') + { + hesk_process_messages($hesklang['chdp'],'NOREDIRECT','NOTICE'); + } + + // Set a tag that will be used to expire sessions after username or password change + $_SESSION['session_verify'] = hesk_activeSessionCreateTag($user, $_SESSION['pass']); + + // We don't need the password hash anymore + unset($_SESSION['pass']); + + /* Login successful, clean brute force attempts */ + hesk_cleanBfAttempts(); + + /* Regenerate session ID (security) */ + hesk_session_regenerate_id(); + + /* Remember username? */ + if ($hesk_settings['autologin'] && hesk_POST('remember_user') == 'AUTOLOGIN') + { + hesk_setcookie('hesk_username', "$user", strtotime('+1 year')); + hesk_setcookie('hesk_p', "$pass_enc", strtotime('+1 year')); + } + elseif ( hesk_POST('remember_user') == 'JUSTUSER') + { + hesk_setcookie('hesk_username', "$user", strtotime('+1 year')); + hesk_setcookie('hesk_p', ''); + } + else + { + // Expire cookie if set otherwise + hesk_setcookie('hesk_username', ''); + hesk_setcookie('hesk_p', ''); + } + + /* Close any old tickets here so Cron jobs aren't necessary */ + if ($hesk_settings['autoclose']) + { + $revision = sprintf($hesklang['thist3'],hesk_date(),$hesklang['auto']); + $dt = date('Y-m-d H:i:s',time() - $hesk_settings['autoclose']*86400); + + // Notify customer of closed ticket? + if ($hesk_settings['notify_closed']) + { + // Get list of tickets + $result = hesk_dbQuery("SELECT * FROM `".$hesk_settings['db_pfix']."tickets` WHERE `status` = '2' AND `lastchange` <= '".hesk_dbEscape($dt)."' "); + if (hesk_dbNumRows($result) > 0) + { + global $ticket; + + // Load required functions? + if ( ! function_exists('hesk_notifyCustomer') ) + { + require(HESK_PATH . 'inc/email_functions.inc.php'); + } + + while ($ticket = hesk_dbFetchAssoc($result)) + { + $ticket['dt'] = hesk_date($ticket['dt'], true); + $ticket['lastchange'] = hesk_date($ticket['lastchange'], true); + $ticket = hesk_ticketToPlain($ticket, 1, 0); + hesk_notifyCustomer('ticket_closed'); + } + } + } + + // Update ticket statuses and history in database + hesk_dbQuery("UPDATE `".$hesk_settings['db_pfix']."tickets` SET `status`='3', `closedat`=NOW(), `closedby`='-1', `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."') WHERE `status` = '2' AND `lastchange` <= '".hesk_dbEscape($dt)."' "); + } + + /* Redirect to the destination page */ + header('Location: ' . hesk_verifyGoto() ); + exit(); +} // End do_login() + + +function print_login() +{ + global $hesk_settings, $hesklang; + + // 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['admin_login']; + require_once(HESK_PATH . 'inc/header.inc.php'); + + if ( hesk_isREQUEST('notice') ) + { + hesk_process_messages($hesklang['session_expired'],'NOREDIRECT'); + } + + if (!isset($_SESSION['a_iserror'])) + { + $_SESSION['a_iserror'] = array(); + } + + $login_wrapper = true; + ?> + + + diff --git a/hesk/admin/knowledgebase_private.php b/hesk/admin/knowledgebase_private.php new file mode 100644 index 0000000..dc3f31e --- /dev/null +++ b/hesk/admin/knowledgebase_private.php @@ -0,0 +1,495 @@ +'.$hesklang['gopr'].'' : ($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` + 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` + 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']); + 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); + + ?> + + + + +
    +
    +

    ()

    + + '.hesk3_get_rating($article['rating']).' + '; + } + else + { + $rat = ''; + } + + echo ' +
    +
    + + + + '.$article['subject'].' + '.$rat.' +
    +
    + + '.$txt.' +
    +
    '; + } + ?> + +
    +
    + +
    +
    +
    +

    + +
    +
      +
    • +
      +
      + + ' . $hesklang['public_link'] . ''; + } + ?> +
      +
    • +
    • +
      +
      + +
      +
    • +
    • +
      +
      + +
      +
    • +
    • +
      +
      +
    • + +
    • +
      +
      +
    • + +
    + +
    +
    + +
    + + + + + + +
    + +

    +
    + + +
    +
    + + + + + '.$att_name.' +
    '; + } + } + ?> +
    + '; + echo '

    '.$hesklang['relart'].'

    '; + foreach ($related_articles as $id => $subject) + { + echo '

    '.$subject.'

    '; + } + echo '
    '; + } + } + ?> +
    +
    + ' . $hesklang['priv'] . ''; + } + } + + $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 ''.$hesklang['kb_cat'].': '.$thiscat['name'].' +  ('.$hesklang['back'].') + '; + } + + ?> +
    +

    +
    +
    + 0) + { + $i = 1; + + while ($cat = hesk_dbFetchAssoc($result)) + { + + $private = ($cat['type'] == 1) ? ' *' : ''; + ?> +
    +
    + +
      +
      '.$hesklang['noac'].'
      '; + } + + /* Print most popular/sticky articles */ + if ($hesk_settings['kb_numshow'] && $cat['articles']) + { + $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) ? ' *' : ''; + ?> +
    • +
      + + + + + + + +
      +
    • + $hesk_settings['kb_numshow']) + { + echo ' + + '; + } + } + ?> +
    +
    +
    + + 0 + ?> +
    +
    +
    +

    + '.$hesklang['noac'].'

    '; + } + else + { + while ($article = hesk_dbFetchAssoc($res)) + { + $private = ($article['type'] == 1) ? ' *' : ''; + + $txt = hesk_kbArticleContentPreview($article['content']); + + echo ' +
    + + + + '.$article['subject'].''.$private.' +
    + + '.$txt.' +
    '; + } + } + ?> +
    +
    + diff --git a/hesk/admin/lock.php b/hesk/admin/lock.php new file mode 100644 index 0000000..bc1bbeb --- /dev/null +++ b/hesk/admin/lock.php @@ -0,0 +1,82 @@ + diff --git a/hesk/admin/mail.php b/hesk/admin/mail.php new file mode 100644 index 0000000..61f6ecf --- /dev/null +++ b/hesk/admin/mail.php @@ -0,0 +1,735 @@ + +
  • + ' . $hesklang['inbox'] . ' +
  • + '; +$hesk_settings['mailtmp']['outbox'] = ' + +
  • + ' . $hesklang['outbox'] . ' +
  • +
    '; +$hesk_settings['mailtmp']['new'] = ' + '; + +/* 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'] = ' +
  • + ' . $hesklang['outbox'] . ' +
  • '; + $hesk_settings['mailtmp']['folder'] = 'outbox'; +} +elseif ($action == 'new') +{ + $hesk_settings['mailtmp']['new'] = ' + '; + $_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'] = ' +
  • + ' . $hesklang['inbox'] . ' +
  • '; + $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(); +?> + + +
    +

    +
    +
      + +
    + +
    + +
    + + +' . $hesklang['m_rec'] . ''; + } + elseif ($_SESSION['mail']['to'] == $_SESSION['id']) + { + $hesk_error_buffer .= '
  • ' . $hesklang['m_inr'] . '
  • '; + } + else + { + $res = hesk_dbQuery("SELECT `name`,`email`,`notify_pm` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `id`='".intval($_SESSION['mail']['to'])."' LIMIT 1"); + $num = hesk_dbNumRows($res); + if (!$num) + { + $hesk_error_buffer .= '
  • ' . $hesklang['m_inr'] . '
  • '; + } + else + { + $pm_recipient = hesk_dbFetchAssoc($res); + } + } + + /* Subject */ + $_SESSION['mail']['subject'] = hesk_input( hesk_POST('subject') ) or $hesk_error_buffer .= '
  • ' . $hesklang['m_esu'] . '
  • '; + + /* Message */ + $_SESSION['mail']['message'] = hesk_input( hesk_POST('message') ) or $hesk_error_buffer .= '
  • ' . $hesklang['enter_message'] . '
  • '; + + // 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'].'

      '.$hesk_error_buffer.'
    '; + 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), + 'id' => $pm_id, + ); + + /* Format email subject and message for recipient */ + $subject = hesk_getEmailSubject('new_pm',$pm,0); + $message = hesk_getEmailMessage('new_pm',$pm,1,0); + + /* Send e-mail */ + hesk_mail($pm_recipient['email'], $subject, $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 `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'] = ''.$hesklang['outbox'].''; + $hesk_settings['mailtmp']['inbox'] = ''.$hesklang['inbox'].''; + $hesk_settings['mailtmp']['outbox'] = ''.$hesklang['outbox'].''; + + } + else + { + hesk_process_message($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']]]) ? ''.$admins[$pm[$hesk_settings['mailtmp']['other']]].'' : (($pm['from'] == 9999) ? 'HESK.com' : $hesklang['e_udel']); + $pm['dt'] = hesk_dateToString($pm['dt'],0,1,0,true); + + if ($actually_show) { + ?> + + 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)." "); + ?> + +
    +
    + + + + + + + + + + + '.$pm['subject'].''; + if ($hesk_settings['mailtmp']['this'] == 'to' && !$pm['read']) + { + $pm['subject'] = ''.$pm['subject'].''; + } + $pm['name'] = isset($admins[$pm[$hesk_settings['mailtmp']['other']]]) ? ''.$admins[$pm[$hesk_settings['mailtmp']['other']]].'' : (($pm['from'] == 9999) ? 'HESK.com' : $hesklang['e_udel']); + $pm['dt'] = hesk_dateToString($pm['dt'],0,0,0,true); + $css_class = !$pm['read'] && $pm['to'] == $_SESSION['id'] ? 'class="new"' : ''; + + echo << + + + + + +EOC; + } // End while + ?> + +
    +
    + + +
    +
    +
    + + +
    +
    $pm[subject]$pm[name]$pm[dt]
    + $pages) ? 0 : $page + 1; + + if ($pages > 1): ?> +
    + +
    + '; + + endif; // end PAGES > 1 + ?> + +
    + + + +
    +
    +
    + 0 + else + { + echo '' . $hesklang['npm'] . '

     

    '; + } + +} // END mail_list_messages() + + +function show_new_form() +{ + global $hesk_settings, $hesklang, $admins; + ?> +

    +
    +
    +
    + + +
    +
    + + + > +
    +
    + + +
    +
    + +  () +
    +
    + + + +
    +
    +
    + diff --git a/hesk/admin/manage_canned.php b/hesk/admin/manage_canned.php new file mode 100644 index 0000000..8513467 --- /dev/null +++ b/hesk/admin/manage_canned.php @@ -0,0 +1,502 @@ + + + +
    +
    +

    + +
    + + + +
    +
    + +
    +
    +
    +

    +
    +
    +
      + +
    • + '.$mysaved['title'].''; + + + $javascript_messages.='myMsgTxt['.$mysaved['id'].']=\''.str_replace("\r\n","\\r\\n' + \r\n'", addslashes($mysaved['message']) )."';\n"; + $javascript_titles.='myTitle['.$mysaved['id'].']=\''.addslashes($mysaved['title'])."';\n"; + + echo ' +
    • +

      '.$mysaved['title'].'

      + '; + + if ($num > 1) + { + if ($j == 1) + { + echo' + + + + + + + + + + '; + } + elseif ($j == $num) + { + echo' + + + + + + + + + + '; + } + else + { + echo' + + + + + + + + + + '; + } + } + else + { + echo ''; + } + + $modal_id = hesk_generate_delete_modal($hesklang['confirm_deletion'], + $hesklang['delete_saved'], + 'manage_canned.php?a=remove&id='.$mysaved['id'].'&token='.hesk_token_echo(0)); + + echo ' + + + + + + + + + + +
    • + '; + } // End while + ?> +
    +
    +
    > +
    +

    + + + + + id="add-title"> + id="edit-title"> + +

    +
    + '; + hesk_handle_messages(); + echo '
    '; + } + + $errors = hesk_SESSION(array('canned', 'errors')); + $errors = is_array($errors) ? $errors : array(); + ?> +
    +
    + + + > + +
    +
    + + + + +
    +
    + +
    + + + + + + + + + + + + + + + + + + + $v) { + if ($v['use']) { + echo ''.$v['name'].''; + } + } + ?> +
    +
    +
    + + + + + + + + + +
    +
    +
    +
    + + +' . $hesklang['selcan'] . ''; + $errors[] = 'saved_replies'; + } + $savename = hesk_input( hesk_POST('name') ); + if (!$savename) { + $hesk_error_buffer .= '
  • ' . $hesklang['ent_saved_title'] . '
  • '; + $errors[] = 'name'; + } + $msg = hesk_input( hesk_POST('msg') ); + if (!$msg) { + $hesk_error_buffer .= '
  • ' . $hesklang['ent_saved_msg'] . '
  • '; + $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'].'

      '.$hesk_error_buffer.'
    '; + hesk_process_messages($hesk_error_buffer,'manage_canned.php?saved_replies='.$id); + } + + $result = hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."std_replies` SET `title`='".hesk_dbEscape($savename)."',`message`='".hesk_dbEscape($msg)."' WHERE `id`='".intval($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 .= '
  • ' . $hesklang['ent_saved_title'] . '
  • '; + $errors[] = 'name'; + } + $msg = hesk_input( hesk_POST('msg') ); + if (!$msg) { + $hesk_error_buffer .= '
  • ' . $hesklang['ent_saved_msg'] . '
  • '; + $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'].'

      '.$hesk_error_buffer.'
    '; + hesk_process_messages($hesk_error_buffer,'manage_canned.php'); + } + + /* 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`,`reply_order`) VALUES ('".hesk_dbEscape($savename)."','".hesk_dbEscape($msg)."','".intval($my_order)."')"); + + 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() + +?> diff --git a/hesk/admin/manage_categories.php b/hesk/admin/manage_categories.php new file mode 100644 index 0000000..f952eed --- /dev/null +++ b/hesk/admin/manage_categories.php @@ -0,0 +1,689 @@ + array('id' => 3, 'value' => 'low', 'text' => $hesklang['low'], 'formatted' => $hesklang['low']), + 'medium' => array('id' => 2, 'value' => 'medium', 'text' => $hesklang['medium'], 'formatted' => $hesklang['medium']), + 'high' => array('id' => 1, 'value' => 'high', 'text' => $hesklang['high'], 'formatted' => $hesklang['high']), + 'critical' => array('id' => 0, 'value' => 'critical', 'text' => $hesklang['critical'], 'formatted' => $hesklang['critical']), +); + +/* What should we do? */ +if ( $action = hesk_REQUEST('a') ) +{ + if ($action == 'linkcode') {generate_link_code();} + elseif ( defined('HESK_DEMO') ) {hesk_process_messages($hesklang['ddemo'], 'manage_categories.php', 'NOTICE');} + elseif ($action == 'new') {new_cat();} + elseif ($action == 'rename') {rename_cat();} + elseif ($action == 'remove') {remove();} + elseif ($action == 'order') {order_cat();} + elseif ($action == 'autoassign') {toggle_autoassign();} + elseif ($action == 'type') {toggle_type();} + elseif ($action == 'priority') {change_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('error')) { + hesk_handle_messages(); +} +?> +
    +
    +

    + +
    +
    +
    + + + + + + + + + + + + + + + '.$mycat['name'].''; + + + ?> + data-category-id=""> + + + + + + + + + + + +
    + + +
    + + + +
    +
    + ' . $hesklang['cpri'] . ''; ?> +
    +
    +
    + +
    + + + +
    + + + + + + + + + (%) + + + + +
    + + + + +
    +
    + Generate link + 1) { + if ($j == 1) { + ?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    +
    +
    +
    + + + + + +
    +
    +
    + +
    > +
    +
    +

    + + + + + + +

    + '; + hesk_handle_messages(); + echo '
    '; + } + ?> +
    + + value=""> +
    + +
    + + +
    + +
    + +
    + +
    + : + +
    + + + +
    + + + + +'.stripslashes($catname).''),'manage_categories.php','SUCCESS'); +} // End new_cat() + + +function rename_cat() +{ + global $hesk_settings, $hesklang; + + /* A security check */ + hesk_token_check('POST'); + + $_SERVER['PHP_SELF'] = 'manage_categories.php?catid='.intval( hesk_POST('catid') ); + + $catid = hesk_isNumber( hesk_POST('catid'), $hesklang['choose_cat_ren'], $_SERVER['PHP_SELF']); + $_SESSION['selcat'] = $catid; + $_SESSION['selcat2'] = $catid; + + $catname = hesk_input( hesk_POST('name'), $hesklang['cat_ren_name'], $_SERVER['PHP_SELF']); + $_SESSION['catname2'] = stripslashes($catname); + + $res = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE `name` LIKE '".hesk_dbEscape( hesk_dbLike($catname) )."' LIMIT 1"); + if (hesk_dbNumRows($res) != 0) + { + $old = hesk_dbFetchAssoc($res); + if ($old['id'] == $catid) + { + hesk_process_messages($hesklang['noch'],$_SERVER['PHP_SELF'],'NOTICE'); + } + else + { + hesk_process_messages($hesklang['cndupl'],$_SERVER['PHP_SELF']); + } + } + + hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` SET `name`='".hesk_dbEscape($catname)."' WHERE `id`='".intval($catid)."'"); + + unset($_SESSION['selcat']); + unset($_SESSION['catname2']); + + hesk_process_messages($hesklang['cat_renamed_to'].' '.stripslashes($catname).'',$_SERVER['PHP_SELF'],'SUCCESS'); +} // End rename_cat() + + +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]."); + } + + hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `category`=1 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 toggle_autoassign() +{ + 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; + + if (hesk_GET('s') === 'on') + { + $autoassign = 1; + $tmp = $hesklang['caaon']; + } + else + { + $autoassign = 0; + $tmp = $hesklang['caaoff']; + } + + /* Update auto-assign settings */ + hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` SET `autoassign`='".intval($autoassign)."' WHERE `id`='".intval($catid)."'"); + if (hesk_dbAffectedRows() != 1) + { + hesk_process_messages($hesklang['int_error'].': '.$hesklang['cat_not_found'],'./manage_categories.php'); + } + + hesk_process_messages($tmp,'./manage_categories.php','SUCCESS'); + +} // End toggle_autoassign() + + +function toggle_type() +{ + 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; + + if ( intval( hesk_GET('s') ) ) + { + $type = 1; + $tmp = $hesklang['cpriv']; + } + else + { + $type = 0; + $tmp = $hesklang['cpub']; + } + + /* Update auto-assign settings */ + hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` SET `type`='{$type}' WHERE `id`='".intval($catid)."'"); + if (hesk_dbAffectedRows() != 1) + { + hesk_process_messages($hesklang['int_error'].': '.$hesklang['cat_not_found'],'./manage_categories.php'); + } + + hesk_process_messages($tmp,'./manage_categories.php','SUCCESS'); + +} // End toggle_type() +?> diff --git a/hesk/admin/manage_knowledgebase.php b/hesk/admin/manage_knowledgebase.php new file mode 100644 index 0000000..f2ad3c1 --- /dev/null +++ b/hesk/admin/manage_knowledgebase.php @@ -0,0 +1,2624 @@ + 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('\\','\\\\',''.$cat['name'].'').$type.' ('.$cat['articles'].', '.$cat['articles_private'].', '.$cat['articles_draft'].') '; /* ' */ + + $text_short = $cat['name'].$type.' ('.$cat['articles'].', '.$cat['articles_private'].', '.$cat['articles_draft'].')'; + + $total_articles += $cat['articles']; + + // Generate KB menu icons + $menu_icons = + ''. + ''. + ''. + ''. + '   ' + .''. + ''. + ''. + ''. + '   ' + .''. + ''. + ''. + ''. + ' ' + ; + + // Can this category be moved up? + if ($cat['move_up'] == false || ($cat['move_up'] && $parent_copy[$cat['parent']] == $parent[$cat['parent']]) ) + { + $menu_icons .= ''. + ''. + ''. + ''. + ' '; + } + else + { + $menu_icons .= ''. + ''. + ''. + ''. + ' '; + } + + // Can this category be moved down? + if ($cat['move_down'] == false || ($cat['move_down'] && $parent_copy[$cat['parent']] == 1) ) + { + $menu_icons .= ''. + ''. + ''. + ''. + ' '; + } + else + { + $menu_icons .= ''. + ''. + ''. + ''. + ' '; + } + + 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'])) +{ + ?> +
    +
    + +

    + +
    + + + +
    +
    + +
    +
    +
    +

    + '; + hesk_show_notice($hesklang['nkba']); + echo '
    '; + } + ?> + + + + + + +

    +
    + + + + +
    +
    + + + + +
    +
    + + + + +
    +
    + + + + +
    +
    + + + + + +
    +
    +
    +
    +

    +
    +
      +
    • +
      + > + +
      +
    • +
    • +
      + +
      +
      + > + +
      +
      +
      + > + +
      +
      +
      + > + +
      +
      +
      +
      +
    • +
    • +
      + +
      +
      + +
      +
    • +
    +
    + +
    +
    +
    +
    + + + + + + +
    +
    +
    + + > +
    +
    +
    + + +
    +
    + +
    + +
    + +
    + + + + () +
    '; + } + ?> +
    + + +
    +
    + +
    + + + + + +
    +
    +
    +

    +
    + + +
    +
    + + +
    +
    + +
    +
    + > + +
    +
    + +
    +
    + > + +
    +
    + +
    +
    +
    + + +
    + + +
    +
    +
    + '; + show_treeMenu(); + echo '
    '; + } + ?> + + + +

     

    + + +
    +
    +
    +

    +
    +
    +
    + + + +
    + + + + + + '; + } + 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 .= '"'; + ?> + > + + + + + + + +
    '.$hesklang['kb_no_dart'].'
    + + + + + + + + + +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +

    +
    +
    +
    + + + +
    + + + + + + '; + } + 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']); + } + + ?> + > + + + + + + + +
    '.$hesklang['kb_no_part'].'
    + + + + + + + + + + + + +
    +
    +
    +
    + 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`,`category`,`subject`,`message`,`owner` 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? + if ($ticket['owner'] && $ticket['owner'] != $_SESSION['id'] && ! hesk_checkPermission('can_view_ass_others',0)) + { + return false; + } + + if ( ! $ticket['owner'] && ! hesk_checkPermission('can_view_unassigned',0)) + { + return false; + } + + // Is this user allowed to view tickets inside this category? + if ( ! hesk_okCategory($ticket['category'],0)) + { + return false; + } + + // 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'] .= "

    " . 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'],$_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 .= "
  • $error
  • \n"; + } + $hesk_error_buffer = $tmp; + + $hesk_error_buffer = $hesklang['rfm'].'

      '.$hesk_error_buffer.'
    '; + 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'); + + $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(); + $myattachments=''; + + if ($hesk_settings['attachments']['use']) + { + require_once(HESK_PATH . 'inc/attachments.inc.php'); + + for ($i=1; $i<=$hesk_settings['attachments']['max_number']; $i++) + { + $att = hesk_uploadFile($i); + if ( ! empty($att)) + { + $attachments[$i] = $att; + } + } + } + + /* Any errors? */ + if (count($hesk_error_buffer)) + { + // Remove any successfully uploaded attachments + if ($hesk_settings['attachments']['use']) + { + hesk_removeAttachments($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 .= "
  • $error
  • \n"; + } + $hesk_error_buffer = $tmp; + + $hesk_error_buffer = $hesklang['rfm'].'

      '.$hesk_error_buffer.'
    '; + hesk_process_messages($hesk_error_buffer,'./manage_knowledgebase.php?a=edit_article&id='.$id.'&from='.$from); + } + + /* Add to database */ + if (!empty($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,$_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=manage_cat&catid='.$catid; + 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 ($hesk_settings['kb_wysiwyg'] || $article['html']) + { + $article['content'] = hesk_htmlspecialchars($article['content']); + } + else + { + $article['content'] = hesk_msgToPlain($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']) + { + ?> + + + +
    +
    +
    +
    +

    +
    +
      +
    • +
      +
      + > + +
      +
      + > + +
      +
      + > + +
      +
      +
    • +
    • +
      + +
      +
      + > + +
      +
      +
      + > + +
      +
      +
      + > + +
      +
      +
      +
      +
    • +
    • +
      + +
      +
      + +
      +
    • +
    +
    + + + + + +
    +
    + +
    +
    + + + + + + +
    +
    +
    + + +
    +
    +
    + + +
    + + +
    + +
    + +
    + + + + ()
    + + + + + '; + echo ' + + + + + '; + echo ''.$att_name.'
    '; + } + echo '
    '; + } + + // New attachments + if ($hesk_settings['attachments']['use']) + { + for ($i=1;$i<=$hesk_settings['attachments']['max_number'];$i++) + { + echo '
    '; + } + } + ?> +
    + + +
    +
    + + + + + +
    + + + + + + +
    +
    +

    + +

    +
      + +
    +
    +
    + + 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 '
    '; + if ( ! isset($_SESSION['hide']['article_list'])) + { + ?> +
    +
    +

    +
    +
    +
    + + + +
    + + + + + + '; + } + 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 = '
    ' . $hesklang['kb_private'] . '
    '; + break; + case '2': + $type = '
    ' . $hesklang['kb_draft'] . '
    '; + break; + default: + $type = '
    ' . $hesklang['kb_published'] . '
    '; + } + + + if ($hesk_settings['kb_rating'] && $article['type'] != '2') + { + $type .= hesk3_get_rating($article['rating'], $article['votes']); + } + + ?> + > + + + + + + + +
    '.$hesklang['kb_no_art'].'
    + + + + + + + + + + + +
    + 1) + { + if ($k == 1) + { + ?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 || $num_nosticky > 1 ) + { + echo ' + + + + + + + + + + '; + } + ?> + + > + + + + + + + + + + + + + + +
    +
    +
    +
    + +
    +

    +
    + '.$hesklang['kb_i_cat2'].''; ?> +
    +
    +
    + + +
    +
    + + +
    +
    + +
    +
    + > + +
    +
    + +
    +
    + > + +
    +
    + +
    +
    +
    +
    + +
    +
    + + +
    +
    +
    + + + + + +
    +
    + '; + + echo ' 
     '; + + /* 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(); + $myattachments=''; + + if ($hesk_settings['attachments']['use']) + { + require_once(HESK_PATH . 'inc/attachments.inc.php'); + + for ($i=1; $i<=$hesk_settings['attachments']['max_number']; $i++) + { + $att = hesk_uploadFile($i); + if ( ! empty($att)) + { + $attachments[$i] = $att; + } + } + } + + /* Any errors? */ + if (count($hesk_error_buffer)) + { + // Remove any successfully uploaded attachments + if ($hesk_settings['attachments']['use']) + { + hesk_removeAttachments($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 .= "
  • $error
  • \n"; + } + $hesk_error_buffer = $tmp; + + $hesk_error_buffer = $hesklang['rfm'].'

      '.$hesk_error_buffer.'
    '; + hesk_process_messages($hesk_error_buffer,'manage_knowledgebase.php'); + } + + $revision = sprintf($hesklang['revision1'],$now,$_SESSION['name'].' ('.$_SESSION['user'].')'); + + /* Add to database */ + if ( ! empty($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; + ?> + + +

    + printMenu(); + ?> +
    + + + + +
    +
    + + + + +
    +
    + (1, 2, 3) = +
    + + + + + + '.$hesklang['gopr'].'     '; + $link['newa'] = ' + + + + + + '.$hesklang['kb_i_art'].'     '; + $link['newc'] = ' + + + + + + '.$hesklang['kb_i_cat'].'     '; + $link['fbid'] = ' + + + +
    + + '. $hesklang['aid'] .': +
    + '; + + if ($hide && isset($link[$hide])) + { + $link[$hide] = preg_replace('##', '', $link[$hide]); + $link[$hide] = str_replace('','',$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() + +?> diff --git a/hesk/admin/manage_ticket_templates.php b/hesk/admin/manage_ticket_templates.php new file mode 100644 index 0000000..ccafe86 --- /dev/null +++ b/hesk/admin/manage_ticket_templates.php @@ -0,0 +1,437 @@ + + + +
    +
    +

    + +
    + + + +
    +
    + +
    +
    +
    +

    +
    +
    +
      + +
    • + +

      '.$mysaved['title'].'

      + '; + + if ($num > 1) + { + if ($j == 1) + { + echo' + + + + + + + + + + '; + } + elseif ($j == $num) + { + echo' + + + + + + + + + + '; + } + else + { + echo' + + + + + + + + + + '; + } + } + else + { + echo ''; + } + + $modal_id = hesk_generate_delete_modal($hesklang['confirm_deletion'], + $hesklang['delete_tpl'], + 'manage_ticket_templates.php?a=remove&id='.$mysaved['id'].'&token='.hesk_token_echo(0)); + + echo ' + + + + + + + + + + + + '; + } // End while + ?> +
    +
    +
    > +
    +

    + + + + + id="add-title"> + id="edit-title"> + +

    +
    + '; + hesk_handle_messages(); + echo '
    '; + } + + $errors = hesk_SESSION(array('canned', 'errors')); + $errors = is_array($errors) ? $errors : array(); + ?> +
    +
    + + + > + +
    +
    + + + + +
    +
    + + + + + + + + + +
    +
    +
    +
    +
    + +' . $hesklang['sel_ticket_tpl'] . ''; + $errors[] = 'id'; + } + $savename = hesk_input( hesk_POST('name') ); + if (!$savename) { + $hesk_error_buffer .= '
  • ' . $hesklang['ent_ticket_tpl_title'] . '
  • '; + $errors[] = 'name'; + } + $msg = hesk_input( hesk_POST('msg') ); + if (!$msg) { + $hesk_error_buffer .= '
  • ' . $hesklang['ent_ticket_tpl_msg'] . '
  • '; + $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'].'

      '.$hesk_error_buffer.'
    '; + hesk_process_messages($hesk_error_buffer,'manage_ticket_templates.php?saved_replies='.$id); + } + + $result = hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_templates` SET `title`='".hesk_dbEscape($savename)."',`message`='".hesk_dbEscape($msg)."' WHERE `id`='".intval($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 .= '
  • ' . $hesklang['ent_ticket_tpl_title'] . '
  • '; + $errors[] = 'name'; + } + $msg = hesk_input( hesk_POST('msg') ); + if (!$msg) { + $hesk_error_buffer .= '
  • ' . $hesklang['ent_ticket_tpl_msg'] . '
  • '; + $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'].'

      '.$hesk_error_buffer.'
    '; + hesk_process_messages($hesk_error_buffer,'manage_ticket_templates.php'); + } + + /* 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`,`tpl_order`) VALUES ('".hesk_dbEscape($savename)."','".hesk_dbEscape($msg)."','".intval($my_order)."')"); + + 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() + +?> diff --git a/hesk/admin/manage_users.php b/hesk/admin/manage_users.php new file mode 100644 index 0000000..c972468 --- /dev/null +++ b/hesk/admin/manage_users.php @@ -0,0 +1,1018 @@ + '', + 'email' => '', + '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'), + + // 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_new_my' => 1, + 'notify_reply_unassigned' => 1, + 'notify_reply_my' => 1, + 'notify_assigned' => 1, + 'notify_note' => 1, + 'notify_pm' => 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') ) +{ + 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();} + 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; + unset($_SESSION['save_userdata']); +} +if (isset($_SESSION['edit_userdata'])) +{ + $_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'); +?> + + 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']) . "

    " . $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'])."'"); + + 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']) . "

    " . $hesklang['fetch_warning'], $hesklang['warn']); + break; + } + } + } +} +?> +
    +
    +

    + +
    + + + +
    +
    + +
    +
    +
    +

    + +
    +
    +
    + + + + + + + + + + + + + + + + + $myuser['name'], 'user' => $myuser['user'], 'email' => $myuser['email']); + 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'] = ' + + + ' . + $myuser['name']; + } + else + { + $myuser['name'] = ' + + + ' . + $myuser['name']; + } + } + + /* To edit yourself go to "Profile" page, not here. */ + if ($myuser['id'] == $_SESSION['id']) { + $edit_code = ' + + + + + '; + } else { + $edit_code = ' + + + + + '; + } + + if ($myuser['isadmin']) { + $myuser['isadmin'] = $hesklang['administrator']; + } else { + $myuser['isadmin'] = $hesklang['staff']; + } + + /* Deleting user with ID 1 (default administrator) is not allowed */ + if ($myuser['id'] == 1) { + $remove_code = ''; + } else { + $modal_id = hesk_generate_delete_modal($hesklang['confirm_deletion'], + $hesklang['sure_remove_user'], + 'manage_users.php?a=remove&id='.$myuser['id'].'&token='.hesk_token_echo(0)); + $remove_code = ' + + + + + '; + } + + /* Is auto assign enabled? */ + if ($hesk_settings['autoassign']) { + if ($myuser['autoassign']) { + $autoassign_code = ' + + '; + } else { + $autoassign_code = ' + '; + } + } else { + $autoassign_code = ''; + } + + echo << + + + + + +EOC; + + if ($hesk_settings['rating']) { + $alt = $myuser['rating'] ? sprintf($hesklang['rated'], sprintf("%01.1f", $myuser['rating']), ($myuser['ratingneg']+$myuser['ratingpos'])) : $hesklang['not_rated']; + echo ''; + } + + if ($hesk_settings['autoassign']) { + echo ''; + } + + echo <<

    $edit_code $remove_code

    +
    + +EOC; + } // End while + ?> + +
    $myuser[name]$myuser[email]$myuser[user]$myuser[isadmin] + '.hesk3_get_rating($myuser['rating']).' + ' . $autoassign_code . '
    +
    +
    +
    +
    > +
    +

    + + + + + + +

    + +
    + + + + +
    +
    +
    + +
    +
    +

    + + + + + + +

    + '; + hesk_handle_messages(); + echo '
    '; + } + ?> +
    + + + + +
    +
    + + + ' . $hesklang['enter_real_name'] . ''; + $errors[] = 'name'; + } + + if (hesk_validateEmail( hesk_POST('email'), 'ERR', 0)) { + $myuser['email'] = hesk_validateEmail( hesk_POST('email'), 'ERR', 0); + } else { + $hesk_error_buffer .= '
  • ' . $hesklang['enter_valid_email'] . '
  • '; + $errors[] = 'email'; + } + + if (hesk_input( hesk_POST('user') )) { + $myuser['user'] = hesk_input(hesk_POST('user')); + } else { + $hesk_error_buffer .= '
  • ' . $hesklang['enter_username'] . '
  • '; + $errors[] = 'user'; + } + + $myuser['isadmin'] = empty($_POST['isadmin']) ? 0 : 1; + $myuser['signature'] = hesk_input( hesk_POST('signature') ); + $myuser['autoassign'] = hesk_POST('autoassign') == 'Y' ? 1 : 0; + + /* If it's not admin at least one category and fature is required */ + $myuser['categories'] = array(); + $myuser['features'] = array(); + + if ($myuser['isadmin']==0) + { + if (empty($_POST['categories']) || ! is_array($_POST['categories']) ) + { + $hesk_error_buffer .= '
  • ' . $hesklang['asign_one_cat'] . '
  • '; + $errors[] = 'categories'; + } + else + { + foreach ($_POST['categories'] as $tmp) + { + if (is_array($tmp)) + { + continue; + } + + if ($tmp = intval($tmp)) + { + $myuser['categories'][] = $tmp; + } + } + } + + if (empty($_POST['features']) || ! is_array($_POST['features']) ) + { + $hesk_error_buffer .= '
  • ' . $hesklang['asign_one_feat'] . '
  • '; + $errors[] = 'features'; + } + else + { + foreach ($_POST['features'] as $tmp) + { + if (in_array($tmp,$hesk_settings['features'])) + { + $myuser['features'][] = $tmp; + } + } + } + } + + if (hesk_mb_strlen($myuser['signature'])>1000) + { + $hesk_error_buffer .= '
  • ' . $hesklang['signature_long'] . '
  • '; + $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 .= '
  • ' . $hesklang['password_not_valid'] . '
  • '; + $errors[] = 'passwords'; + } + /* Check password confirmation */ + else + { + $newpass2 = hesk_input( hesk_POST('newpass2') ); + + if ($newpass != $newpass2) + { + $hesk_error_buffer .= '
  • ' . $hesklang['passwords_not_same'] . '
  • '; + $errors[] = 'passwords'; + } + else + { + $myuser['pass'] = hesk_Pass2Hash($newpass); + $myuser['cleanpass'] = $newpass; + } + } + } + + /* 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'] < 0 || $myuser['autoreload'] > 65535) + { + $myuser['autoreload'] = 30; + } + } + + /* Notifications */ + $myuser['notify_new_unassigned'] = empty($_POST['notify_new_unassigned']) ? 0 : 1; + $myuser['notify_new_my'] = empty($_POST['notify_new_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; + + /* 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'].'

      '.$hesk_error_buffer.'
    '; + 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'; + } + + 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'); + } + + /* Un-assign all tickets for this user */ + $res = hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `owner`=0 WHERE `owner`='".intval($myuser)."'"); + + /* 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}"); + + 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']); + $_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() +?> diff --git a/hesk/admin/move_category.php b/hesk/admin/move_category.php new file mode 100644 index 0000000..09b3a11 --- /dev/null +++ b/hesk/admin/move_category.php @@ -0,0 +1,200 @@ + Prepare message */ + +// 1. Generate the array with ticket info that can be used in emails +$info = array( +'email' => $ticket['email'], +'category' => $ticket['category'], +'priority' => $ticket['priority'], +'owner' => $ticket['owner'], +'trackid' => $ticket['trackid'], +'status' => $ticket['status'], +'name' => $ticket['name'], +'subject' => $ticket['subject'], +'message' => $ticket['message'], +'attachments' => $ticket['attachments'], +'dt' => hesk_date($ticket['dt'], true), +'lastchange' => hesk_date($ticket['lastchange'], true), +'id' => $ticket['id'], +'time_worked' => $ticket['time_worked'], +'last_reply_by' => hesk_getReplierName($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'); +} +/* --> 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'); +} +?> diff --git a/hesk/admin/new_ticket.php b/hesk/admin/new_ticket.php new file mode 100644 index 0000000..f1a438b --- /dev/null +++ b/hesk/admin/new_ticket.php @@ -0,0 +1,961 @@ +$v) { + if ($v['use'] && isset($_REQUEST[$k]) ) { + $_SESSION['as_'.$k] = $_REQUEST[$k]; + } +} + +/* Varibles for coloring the fields in case of errors */ +if (!isset($_SESSION['iserror'])) { + $_SESSION['iserror'] = array(); +} + +if (!isset($_SESSION['isnotice'])) { + $_SESSION['isnotice'] = array(); +} + +/* List of users */ +$admins = array(); +$result = hesk_dbQuery("SELECT `id`,`name`,`isadmin`,`categories`,`heskprivileges` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` ORDER BY `name` ASC"); +while ($row=hesk_dbFetchAssoc($result)) +{ + /* Is this an administrator? */ + if ($row['isadmin']) + { + $admins[$row['id']]=$row['name']; + continue; + } + + /* Not admin, is user allowed to view tickets? */ + if (strpos($row['heskprivileges'], 'can_view_tickets') !== false) + { + $admins[$row['id']]=$row['name']; + continue; + } +} + +/* 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` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` ORDER BY `cat_order` ASC"); +} +else +{ + $res = 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($res)) +{ + $hesk_settings['categories'][$row['id']] = $row['name']; +} + +$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); + } +} +?> +
    +
    + + + +

    +

    *

    + +
    +
    + + +
    +
    + + > +
    +
    +
    + + +
    + + + $v) + { + if ($v['use'] && $v['place']==0 && hesk_is_custom_field_in_category($k, $category) ) + { + $v['req'] = $v['req']==2 ? '*' : ''; + + 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 ' +
    + +
    '; + + $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 ' +
    + + +
    '; + $index++; + } + echo '
    +
    '; + break; + + /* Select drop-down box */ + case 'select': + + $cls = in_array($k,$_SESSION['iserror']) ? ' class="isError" ' : ''; + + echo ' +
    + + +
    '; + break; + + /* Checkbox */ + case 'checkbox': + echo ' +
    + '; + + $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 ' +
    + + +
    '; + $index++; + } + + echo '
    '; + break; + + /* Large text box */ + case 'textarea': + $cls = in_array($k,$_SESSION['iserror']) ? ' isError" ' : ''; + $k_value = hesk_msgToPlain($k_value,0,0); + + echo ' +
    + + +
    '; + break; + + // Date + case 'date': + echo ' +
    + +
    + + +
    +
    + '. $k_value .' + + + + + +
    +
    '; + 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 ' +
    + + +
    +
    '; + 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 ' +
    + + +
    '; + } + } + } + ?> + + + + +
    + +
    +
    + + +
    +
    + + +
    +
    +
    +
    + + +
    + +
    + +
    + +
    + + +
    +
    + + + + +
    + + + $v) + { + if ($v['use'] && $v['place']==1 && hesk_is_custom_field_in_category($k, $category) ) + { + $v['req'] = $v['req']==2 ? '*' : ''; + + 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 ' +
    + +
    '; + + $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 ' +
    + + +
    '; + $index++; + } + echo '
    +
    '; + break; + + /* Select drop-down box */ + case 'select': + + $cls = in_array($k,$_SESSION['iserror']) ? ' class="isError" ' : ''; + + echo ' +
    + + +
    '; + break; + + /* Checkbox */ + case 'checkbox': + echo ' +
    + '; + + $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 ' +
    + + +
    '; + $index++; + } + + echo '
    '; + break; + + /* Large text box */ + case 'textarea': + $cls = in_array($k,$_SESSION['iserror']) ? ' isError" ' : ''; + $k_value = hesk_msgToPlain($k_value,0,0); + + echo ' +
    + + +
    '; + break; + + // Date + case 'date': + echo ' +
    + +
    + + +
    +
    + '. $k_value .' + + + + + +
    +
    '; + 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 ' +
    + + +
    +
    '; + 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 ' +
    + + +
    '; + } + } + } + ?> + + + +
    + + + +
    + +
    +
    +
    '; + } + ?> + + +
    + +
    +
    + > + +
    +
    + > + +
    +
    +
    + +
    + + +
    + +
    + +
    + > + +
    +
    + + + + +
    +
    +
    + +
    +
    +

    +
    + $hesk_settings['cat_show_select']) { + ?> +
    + + +
    + + +
      + $v) + { + echo '
    • '.$v.'
    • '; + } + ?> +
    + +
    +
    +
    + + +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; + } + 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 .= "
  • $error
  • \n"; + } + $hesk_error_buffer = $tmp; + + $hesk_error_buffer = $hesklang['pcer'].'

      '.$hesk_error_buffer.'
    '; + 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` LIKE '".hesk_dbEscape($email)."' LIMIT 1"); + if (hesk_dbNumRows($res) != 1) + { + hesk_process_messages($hesklang['noace'],'NOREDIRECT'); + } + else + { + $row = hesk_dbFetchAssoc($res); + $hash = sha1(microtime() . hesk_getClientIP() . mt_rand() . $row['id'] . $row['name'] . $row['pass']); + + // Insert the verification hash into the database + hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."reset_password` (`user`, `hash`, `ip`) VALUES (".intval($row['id']).", '{$hash}', '".hesk_dbEscape(hesk_getClientIP())."') "); + + // Prepare and send email + require(HESK_PATH . 'inc/email_functions.inc.php'); + + // Get the email message + $msg = hesk_getEmailMessage('reset_password',array(),1,0,1); + + // Replace message special tags + $msg = str_replace('%%NAME%%', hesk_msgToPlain($row['name'],1,1), $msg); + $msg = str_replace('%%SITE_URL%%', $hesk_settings['site_url'], $msg); + $msg = str_replace('%%SITE_TITLE%%', $hesk_settings['site_title'], $msg); + $msg = str_replace('%%PASSWORD_RESET%%', $hesk_settings['hesk_url'].'/'.$hesk_settings['admin_dir'].'/password.php?h='.$hash, $msg); + + // Send email + hesk_mail($email, $hesklang['reset_password'], $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 hash + $hash = preg_replace('/[^a-zA-Z0-9]/', '', $_GET['h']); + + // 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` = '{$hash}' 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 + { + // Expire all verification hashes for this user + hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."reset_password` WHERE `user`=".intval($row['user'])); + + // Load additional required functions + require(HESK_PATH . 'inc/admin_functions.inc.php'); + + // Get user details + $res = hesk_dbQuery('SELECT * FROM `'.$hesk_settings['db_pfix']."users` WHERE `id`=".intval($row['user'])." LIMIT 1"); + $row = hesk_dbFetchAssoc($res); + foreach ($row as $k=>$v) + { + $_SESSION[$k]=$v; + } + + // Set a tag that will be used to expire sessions after username or password change + $_SESSION['session_verify'] = hesk_activeSessionCreateTag($_SESSION['user'], $_SESSION['pass']); + + // We don't need the password hash anymore + unset($_SESSION['pass']); + + // Clean brute force attempts + hesk_cleanBfAttempts(); + + // Regenerate session ID (security) + hesk_session_regenerate_id(); + + // Get allowed categories + if (empty($_SESSION['isadmin'])) + { + $_SESSION['categories']=explode(',',$_SESSION['categories']); + } + + // Redirect to the profile page + hesk_process_messages($hesklang['resim'],'profile.php','NOTICE'); + 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; +?> + + + + + + + + + + + + + +'; + +$hesk_settings['security_cleanup']('exit'); diff --git a/hesk/inc/header.inc.php b/hesk/inc/header.inc.php new file mode 100644 index 0000000..a11a19b --- /dev/null +++ b/hesk/inc/header.inc.php @@ -0,0 +1,143 @@ + + + + + <?php echo (isset($hesk_settings['tmp_title']) ? $hesk_settings['tmp_title'] : $hesk_settings['hesk_title']); ?> + + + + + + + + + + + + + + + '; + echo ''; + } + + // Auto reload + if (defined('AUTO_RELOAD') && hesk_checkPermission('can_view_tickets',0) && ! isset($_SESSION['hide']['ticket_list']) ) + { + ?> + + + + + + +
    diff --git a/hesk/inc/htmlpurifier/HTMLPurifier.standalone.php b/hesk/inc/htmlpurifier/HTMLPurifier.standalone.php new file mode 100644 index 0000000..cfdbcc9 --- /dev/null +++ b/hesk/inc/htmlpurifier/HTMLPurifier.standalone.php @@ -0,0 +1,22584 @@ +config = HTMLPurifier_Config::create($config); + $this->strategy = new HTMLPurifier_Strategy_Core(); + } + + /** + * Adds a filter to process the output. First come first serve + * + * @param HTMLPurifier_Filter $filter HTMLPurifier_Filter object + */ + public function addFilter($filter) + { + trigger_error( + 'HTMLPurifier->addFilter() is deprecated, use configuration directives' . + ' in the Filter namespace or Filter.Custom', + E_USER_WARNING + ); + $this->filters[] = $filter; + } + + /** + * Filters an HTML snippet/document to be XSS-free and standards-compliant. + * + * @param string $html String of HTML to purify + * @param HTMLPurifier_Config $config Config object for this operation, + * if omitted, defaults to the config object specified during this + * object's construction. The parameter can also be any type + * that HTMLPurifier_Config::create() supports. + * + * @return string Purified HTML + */ + public function purify($html, $config = null) + { + // :TODO: make the config merge in, instead of replace + $config = $config ? HTMLPurifier_Config::create($config) : $this->config; + + // implementation is partially environment dependant, partially + // configuration dependant + $lexer = HTMLPurifier_Lexer::create($config); + + $context = new HTMLPurifier_Context(); + + // setup HTML generator + $this->generator = new HTMLPurifier_Generator($config, $context); + $context->register('Generator', $this->generator); + + // set up global context variables + if ($config->get('Core.CollectErrors')) { + // may get moved out if other facilities use it + $language_factory = HTMLPurifier_LanguageFactory::instance(); + $language = $language_factory->create($config, $context); + $context->register('Locale', $language); + + $error_collector = new HTMLPurifier_ErrorCollector($context); + $context->register('ErrorCollector', $error_collector); + } + + // setup id_accumulator context, necessary due to the fact that + // AttrValidator can be called from many places + $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context); + $context->register('IDAccumulator', $id_accumulator); + + $html = HTMLPurifier_Encoder::convertToUTF8($html, $config, $context); + + // setup filters + $filter_flags = $config->getBatch('Filter'); + $custom_filters = $filter_flags['Custom']; + unset($filter_flags['Custom']); + $filters = array(); + foreach ($filter_flags as $filter => $flag) { + if (!$flag) { + continue; + } + if (strpos($filter, '.') !== false) { + continue; + } + $class = "HTMLPurifier_Filter_$filter"; + $filters[] = new $class; + } + foreach ($custom_filters as $filter) { + // maybe "HTMLPurifier_Filter_$filter", but be consistent with AutoFormat + $filters[] = $filter; + } + $filters = array_merge($filters, $this->filters); + // maybe prepare(), but later + + for ($i = 0, $filter_size = count($filters); $i < $filter_size; $i++) { + $html = $filters[$i]->preFilter($html, $config, $context); + } + + // purified HTML + $html = + $this->generator->generateFromTokens( + // list of tokens + $this->strategy->execute( + // list of un-purified tokens + $lexer->tokenizeHTML( + // un-purified HTML + $html, + $config, + $context + ), + $config, + $context + ) + ); + + for ($i = $filter_size - 1; $i >= 0; $i--) { + $html = $filters[$i]->postFilter($html, $config, $context); + } + + $html = HTMLPurifier_Encoder::convertFromUTF8($html, $config, $context); + $this->context =& $context; + return $html; + } + + /** + * Filters an array of HTML snippets + * + * @param string[] $array_of_html Array of html snippets + * @param HTMLPurifier_Config $config Optional config object for this operation. + * See HTMLPurifier::purify() for more details. + * + * @return string[] Array of purified HTML + */ + public function purifyArray($array_of_html, $config = null) + { + $context_array = array(); + foreach($array_of_html as $key=>$value){ + if (is_array($value)) { + $array[$key] = $this->purifyArray($value, $config); + } else { + $array[$key] = $this->purify($value, $config); + } + $context_array[$key] = $this->context; + } + $this->context = $context_array; + return $array; + } + + /** + * Singleton for enforcing just one HTML Purifier in your system + * + * @param HTMLPurifier|HTMLPurifier_Config $prototype Optional prototype + * HTMLPurifier instance to overload singleton with, + * or HTMLPurifier_Config instance to configure the + * generated version with. + * + * @return HTMLPurifier + */ + public static function instance($prototype = null) + { + if (!self::$instance || $prototype) { + if ($prototype instanceof HTMLPurifier) { + self::$instance = $prototype; + } elseif ($prototype) { + self::$instance = new HTMLPurifier($prototype); + } else { + self::$instance = new HTMLPurifier(); + } + } + return self::$instance; + } + + /** + * Singleton for enforcing just one HTML Purifier in your system + * + * @param HTMLPurifier|HTMLPurifier_Config $prototype Optional prototype + * HTMLPurifier instance to overload singleton with, + * or HTMLPurifier_Config instance to configure the + * generated version with. + * + * @return HTMLPurifier + * @note Backwards compatibility, see instance() + */ + public static function getInstance($prototype = null) + { + return HTMLPurifier::instance($prototype); + } +} + + + + + +/** + * Converts a stream of HTMLPurifier_Token into an HTMLPurifier_Node, + * and back again. + * + * @note This transformation is not an equivalence. We mutate the input + * token stream to make it so; see all [MUT] markers in code. + */ +class HTMLPurifier_Arborize +{ + public static function arborize($tokens, $config, $context) { + $definition = $config->getHTMLDefinition(); + $parent = new HTMLPurifier_Token_Start($definition->info_parent); + $stack = array($parent->toNode()); + foreach ($tokens as $token) { + $token->skip = null; // [MUT] + $token->carryover = null; // [MUT] + if ($token instanceof HTMLPurifier_Token_End) { + $token->start = null; // [MUT] + $r = array_pop($stack); + //assert($r->name === $token->name); + //assert(empty($token->attr)); + $r->endCol = $token->col; + $r->endLine = $token->line; + $r->endArmor = $token->armor; + continue; + } + $node = $token->toNode(); + $stack[count($stack)-1]->children[] = $node; + if ($token instanceof HTMLPurifier_Token_Start) { + $stack[] = $node; + } + } + //assert(count($stack) == 1); + return $stack[0]; + } + + public static function flatten($node, $config, $context) { + $level = 0; + $nodes = array($level => new HTMLPurifier_Queue(array($node))); + $closingTokens = array(); + $tokens = array(); + do { + while (!$nodes[$level]->isEmpty()) { + $node = $nodes[$level]->shift(); // FIFO + list($start, $end) = $node->toTokenPair(); + if ($level > 0) { + $tokens[] = $start; + } + if ($end !== NULL) { + $closingTokens[$level][] = $end; + } + if ($node instanceof HTMLPurifier_Node_Element) { + $level++; + $nodes[$level] = new HTMLPurifier_Queue(); + foreach ($node->children as $childNode) { + $nodes[$level]->push($childNode); + } + } + } + $level--; + if ($level && isset($closingTokens[$level])) { + while ($token = array_pop($closingTokens[$level])) { + $tokens[] = $token; + } + } + } while ($level > 0); + return $tokens; + } +} + + + +/** + * Defines common attribute collections that modules reference + */ + +class HTMLPurifier_AttrCollections +{ + + /** + * Associative array of attribute collections, indexed by name. + * @type array + */ + public $info = array(); + + /** + * Performs all expansions on internal data for use by other inclusions + * It also collects all attribute collection extensions from + * modules + * @param HTMLPurifier_AttrTypes $attr_types HTMLPurifier_AttrTypes instance + * @param HTMLPurifier_HTMLModule[] $modules Hash array of HTMLPurifier_HTMLModule members + */ + public function __construct($attr_types, $modules) + { + $this->doConstruct($attr_types, $modules); + } + + public function doConstruct($attr_types, $modules) + { + // load extensions from the modules + foreach ($modules as $module) { + foreach ($module->attr_collections as $coll_i => $coll) { + if (!isset($this->info[$coll_i])) { + $this->info[$coll_i] = array(); + } + foreach ($coll as $attr_i => $attr) { + if ($attr_i === 0 && isset($this->info[$coll_i][$attr_i])) { + // merge in includes + $this->info[$coll_i][$attr_i] = array_merge( + $this->info[$coll_i][$attr_i], + $attr + ); + continue; + } + $this->info[$coll_i][$attr_i] = $attr; + } + } + } + // perform internal expansions and inclusions + foreach ($this->info as $name => $attr) { + // merge attribute collections that include others + $this->performInclusions($this->info[$name]); + // replace string identifiers with actual attribute objects + $this->expandIdentifiers($this->info[$name], $attr_types); + } + } + + /** + * Takes a reference to an attribute associative array and performs + * all inclusions specified by the zero index. + * @param array &$attr Reference to attribute array + */ + public function performInclusions(&$attr) + { + if (!isset($attr[0])) { + return; + } + $merge = $attr[0]; + $seen = array(); // recursion guard + // loop through all the inclusions + for ($i = 0; isset($merge[$i]); $i++) { + if (isset($seen[$merge[$i]])) { + continue; + } + $seen[$merge[$i]] = true; + // foreach attribute of the inclusion, copy it over + if (!isset($this->info[$merge[$i]])) { + continue; + } + foreach ($this->info[$merge[$i]] as $key => $value) { + if (isset($attr[$key])) { + continue; + } // also catches more inclusions + $attr[$key] = $value; + } + if (isset($this->info[$merge[$i]][0])) { + // recursion + $merge = array_merge($merge, $this->info[$merge[$i]][0]); + } + } + unset($attr[0]); + } + + /** + * Expands all string identifiers in an attribute array by replacing + * them with the appropriate values inside HTMLPurifier_AttrTypes + * @param array &$attr Reference to attribute array + * @param HTMLPurifier_AttrTypes $attr_types HTMLPurifier_AttrTypes instance + */ + public function expandIdentifiers(&$attr, $attr_types) + { + // because foreach will process new elements we add, make sure we + // skip duplicates + $processed = array(); + + foreach ($attr as $def_i => $def) { + // skip inclusions + if ($def_i === 0) { + continue; + } + + if (isset($processed[$def_i])) { + continue; + } + + // determine whether or not attribute is required + if ($required = (strpos($def_i, '*') !== false)) { + // rename the definition + unset($attr[$def_i]); + $def_i = trim($def_i, '*'); + $attr[$def_i] = $def; + } + + $processed[$def_i] = true; + + // if we've already got a literal object, move on + if (is_object($def)) { + // preserve previous required + $attr[$def_i]->required = ($required || $attr[$def_i]->required); + continue; + } + + if ($def === false) { + unset($attr[$def_i]); + continue; + } + + if ($t = $attr_types->get($def)) { + $attr[$def_i] = $t; + $attr[$def_i]->required = $required; + } else { + unset($attr[$def_i]); + } + } + } +} + + + + + +/** + * Base class for all validating attribute definitions. + * + * This family of classes forms the core for not only HTML attribute validation, + * but also any sort of string that needs to be validated or cleaned (which + * means CSS properties and composite definitions are defined here too). + * Besides defining (through code) what precisely makes the string valid, + * subclasses are also responsible for cleaning the code if possible. + */ + +abstract class HTMLPurifier_AttrDef +{ + + /** + * Tells us whether or not an HTML attribute is minimized. + * Has no meaning in other contexts. + * @type bool + */ + public $minimized = false; + + /** + * Tells us whether or not an HTML attribute is required. + * Has no meaning in other contexts + * @type bool + */ + public $required = false; + + /** + * Validates and cleans passed string according to a definition. + * + * @param string $string String to be validated and cleaned. + * @param HTMLPurifier_Config $config Mandatory HTMLPurifier_Config object. + * @param HTMLPurifier_Context $context Mandatory HTMLPurifier_Context object. + */ + abstract public function validate($string, $config, $context); + + /** + * Convenience method that parses a string as if it were CDATA. + * + * This method process a string in the manner specified at + * by removing + * leading and trailing whitespace, ignoring line feeds, and replacing + * carriage returns and tabs with spaces. While most useful for HTML + * attributes specified as CDATA, it can also be applied to most CSS + * values. + * + * @note This method is not entirely standards compliant, as trim() removes + * more types of whitespace than specified in the spec. In practice, + * this is rarely a problem, as those extra characters usually have + * already been removed by HTMLPurifier_Encoder. + * + * @warning This processing is inconsistent with XML's whitespace handling + * as specified by section 3.3.3 and referenced XHTML 1.0 section + * 4.7. However, note that we are NOT necessarily + * parsing XML, thus, this behavior may still be correct. We + * assume that newlines have been normalized. + */ + public function parseCDATA($string) + { + $string = trim($string); + $string = str_replace(array("\n", "\t", "\r"), ' ', $string); + return $string; + } + + /** + * Factory method for creating this class from a string. + * @param string $string String construction info + * @return HTMLPurifier_AttrDef Created AttrDef object corresponding to $string + */ + public function make($string) + { + // default implementation, return a flyweight of this object. + // If $string has an effect on the returned object (i.e. you + // need to overload this method), it is best + // to clone or instantiate new copies. (Instantiation is safer.) + return $this; + } + + /** + * Removes spaces from rgb(0, 0, 0) so that shorthand CSS properties work + * properly. THIS IS A HACK! + * @param string $string a CSS colour definition + * @return string + */ + protected function mungeRgb($string) + { + $p = '\s*(\d+(\.\d+)?([%]?))\s*'; + + if (preg_match('/(rgba|hsla)\(/', $string)) { + return preg_replace('/(rgba|hsla)\('.$p.','.$p.','.$p.','.$p.'\)/', '\1(\2,\5,\8,\11)', $string); + } + + return preg_replace('/(rgb|hsl)\('.$p.','.$p.','.$p.'\)/', '\1(\2,\5,\8)', $string); + } + + /** + * Parses a possibly escaped CSS string and returns the "pure" + * version of it. + */ + protected function expandCSSEscape($string) + { + // flexibly parse it + $ret = ''; + for ($i = 0, $c = strlen($string); $i < $c; $i++) { + if ($string[$i] === '\\') { + $i++; + if ($i >= $c) { + $ret .= '\\'; + break; + } + if (ctype_xdigit($string[$i])) { + $code = $string[$i]; + for ($a = 1, $i++; $i < $c && $a < 6; $i++, $a++) { + if (!ctype_xdigit($string[$i])) { + break; + } + $code .= $string[$i]; + } + // We have to be extremely careful when adding + // new characters, to make sure we're not breaking + // the encoding. + $char = HTMLPurifier_Encoder::unichr(hexdec($code)); + if (HTMLPurifier_Encoder::cleanUTF8($char) === '') { + continue; + } + $ret .= $char; + if ($i < $c && trim($string[$i]) !== '') { + $i--; + } + continue; + } + if ($string[$i] === "\n") { + continue; + } + } + $ret .= $string[$i]; + } + return $ret; + } +} + + + + + +/** + * Processes an entire attribute array for corrections needing multiple values. + * + * Occasionally, a certain attribute will need to be removed and popped onto + * another value. Instead of creating a complex return syntax for + * HTMLPurifier_AttrDef, we just pass the whole attribute array to a + * specialized object and have that do the special work. That is the + * family of HTMLPurifier_AttrTransform. + * + * An attribute transformation can be assigned to run before or after + * HTMLPurifier_AttrDef validation. See HTMLPurifier_HTMLDefinition for + * more details. + */ + +abstract class HTMLPurifier_AttrTransform +{ + + /** + * Abstract: makes changes to the attributes dependent on multiple values. + * + * @param array $attr Assoc array of attributes, usually from + * HTMLPurifier_Token_Tag::$attr + * @param HTMLPurifier_Config $config Mandatory HTMLPurifier_Config object. + * @param HTMLPurifier_Context $context Mandatory HTMLPurifier_Context object + * @return array Processed attribute array. + */ + abstract public function transform($attr, $config, $context); + + /** + * Prepends CSS properties to the style attribute, creating the + * attribute if it doesn't exist. + * @param array &$attr Attribute array to process (passed by reference) + * @param string $css CSS to prepend + */ + public function prependCSS(&$attr, $css) + { + $attr['style'] = isset($attr['style']) ? $attr['style'] : ''; + $attr['style'] = $css . $attr['style']; + } + + /** + * Retrieves and removes an attribute + * @param array &$attr Attribute array to process (passed by reference) + * @param mixed $key Key of attribute to confiscate + * @return mixed + */ + public function confiscateAttr(&$attr, $key) + { + if (!isset($attr[$key])) { + return null; + } + $value = $attr[$key]; + unset($attr[$key]); + return $value; + } +} + + + + + +/** + * Provides lookup array of attribute types to HTMLPurifier_AttrDef objects + */ +class HTMLPurifier_AttrTypes +{ + /** + * Lookup array of attribute string identifiers to concrete implementations. + * @type HTMLPurifier_AttrDef[] + */ + protected $info = array(); + + /** + * Constructs the info array, supplying default implementations for attribute + * types. + */ + public function __construct() + { + // XXX This is kind of poor, since we don't actually /clone/ + // instances; instead, we use the supplied make() attribute. So, + // the underlying class must know how to deal with arguments. + // With the old implementation of Enum, that ignored its + // arguments when handling a make dispatch, the IAlign + // definition wouldn't work. + + // pseudo-types, must be instantiated via shorthand + $this->info['Enum'] = new HTMLPurifier_AttrDef_Enum(); + $this->info['Bool'] = new HTMLPurifier_AttrDef_HTML_Bool(); + + $this->info['CDATA'] = new HTMLPurifier_AttrDef_Text(); + $this->info['ID'] = new HTMLPurifier_AttrDef_HTML_ID(); + $this->info['Length'] = new HTMLPurifier_AttrDef_HTML_Length(); + $this->info['MultiLength'] = new HTMLPurifier_AttrDef_HTML_MultiLength(); + $this->info['NMTOKENS'] = new HTMLPurifier_AttrDef_HTML_Nmtokens(); + $this->info['Pixels'] = new HTMLPurifier_AttrDef_HTML_Pixels(); + $this->info['Text'] = new HTMLPurifier_AttrDef_Text(); + $this->info['URI'] = new HTMLPurifier_AttrDef_URI(); + $this->info['LanguageCode'] = new HTMLPurifier_AttrDef_Lang(); + $this->info['Color'] = new HTMLPurifier_AttrDef_HTML_Color(); + $this->info['IAlign'] = self::makeEnum('top,middle,bottom,left,right'); + $this->info['LAlign'] = self::makeEnum('top,bottom,left,right'); + $this->info['FrameTarget'] = new HTMLPurifier_AttrDef_HTML_FrameTarget(); + + // unimplemented aliases + $this->info['ContentType'] = new HTMLPurifier_AttrDef_Text(); + $this->info['ContentTypes'] = new HTMLPurifier_AttrDef_Text(); + $this->info['Charsets'] = new HTMLPurifier_AttrDef_Text(); + $this->info['Character'] = new HTMLPurifier_AttrDef_Text(); + + // "proprietary" types + $this->info['Class'] = new HTMLPurifier_AttrDef_HTML_Class(); + + // number is really a positive integer (one or more digits) + // FIXME: ^^ not always, see start and value of list items + $this->info['Number'] = new HTMLPurifier_AttrDef_Integer(false, false, true); + } + + private static function makeEnum($in) + { + return new HTMLPurifier_AttrDef_Clone(new HTMLPurifier_AttrDef_Enum(explode(',', $in))); + } + + /** + * Retrieves a type + * @param string $type String type name + * @return HTMLPurifier_AttrDef Object AttrDef for type + */ + public function get($type) + { + // determine if there is any extra info tacked on + if (strpos($type, '#') !== false) { + list($type, $string) = explode('#', $type, 2); + } else { + $string = ''; + } + + if (!isset($this->info[$type])) { + trigger_error('Cannot retrieve undefined attribute type ' . $type, E_USER_ERROR); + return; + } + return $this->info[$type]->make($string); + } + + /** + * Sets a new implementation for a type + * @param string $type String type name + * @param HTMLPurifier_AttrDef $impl Object AttrDef for type + */ + public function set($type, $impl) + { + $this->info[$type] = $impl; + } +} + + + + + +/** + * Validates the attributes of a token. Doesn't manage required attributes + * very well. The only reason we factored this out was because RemoveForeignElements + * also needed it besides ValidateAttributes. + */ +class HTMLPurifier_AttrValidator +{ + + /** + * Validates the attributes of a token, mutating it as necessary. + * that has valid tokens + * @param HTMLPurifier_Token $token Token to validate. + * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config + * @param HTMLPurifier_Context $context Instance of HTMLPurifier_Context + */ + public function validateToken($token, $config, $context) + { + $definition = $config->getHTMLDefinition(); + $e =& $context->get('ErrorCollector', true); + + // initialize IDAccumulator if necessary + $ok =& $context->get('IDAccumulator', true); + if (!$ok) { + $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context); + $context->register('IDAccumulator', $id_accumulator); + } + + // initialize CurrentToken if necessary + $current_token =& $context->get('CurrentToken', true); + if (!$current_token) { + $context->register('CurrentToken', $token); + } + + if (!$token instanceof HTMLPurifier_Token_Start && + !$token instanceof HTMLPurifier_Token_Empty + ) { + return; + } + + // create alias to global definition array, see also $defs + // DEFINITION CALL + $d_defs = $definition->info_global_attr; + + // don't update token until the very end, to ensure an atomic update + $attr = $token->attr; + + // do global transformations (pre) + // nothing currently utilizes this + foreach ($definition->info_attr_transform_pre as $transform) { + $attr = $transform->transform($o = $attr, $config, $context); + if ($e) { + if ($attr != $o) { + $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr); + } + } + } + + // do local transformations only applicable to this element (pre) + // ex.

    to

    + foreach ($definition->info[$token->name]->attr_transform_pre as $transform) { + $attr = $transform->transform($o = $attr, $config, $context); + if ($e) { + if ($attr != $o) { + $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr); + } + } + } + + // create alias to this element's attribute definition array, see + // also $d_defs (global attribute definition array) + // DEFINITION CALL + $defs = $definition->info[$token->name]->attr; + + $attr_key = false; + $context->register('CurrentAttr', $attr_key); + + // iterate through all the attribute keypairs + // Watch out for name collisions: $key has previously been used + foreach ($attr as $attr_key => $value) { + + // call the definition + if (isset($defs[$attr_key])) { + // there is a local definition defined + if ($defs[$attr_key] === false) { + // We've explicitly been told not to allow this element. + // This is usually when there's a global definition + // that must be overridden. + // Theoretically speaking, we could have a + // AttrDef_DenyAll, but this is faster! + $result = false; + } else { + // validate according to the element's definition + $result = $defs[$attr_key]->validate( + $value, + $config, + $context + ); + } + } elseif (isset($d_defs[$attr_key])) { + // there is a global definition defined, validate according + // to the global definition + $result = $d_defs[$attr_key]->validate( + $value, + $config, + $context + ); + } else { + // system never heard of the attribute? DELETE! + $result = false; + } + + // put the results into effect + if ($result === false || $result === null) { + // this is a generic error message that should replaced + // with more specific ones when possible + if ($e) { + $e->send(E_ERROR, 'AttrValidator: Attribute removed'); + } + + // remove the attribute + unset($attr[$attr_key]); + } elseif (is_string($result)) { + // generally, if a substitution is happening, there + // was some sort of implicit correction going on. We'll + // delegate it to the attribute classes to say exactly what. + + // simple substitution + $attr[$attr_key] = $result; + } else { + // nothing happens + } + + // we'd also want slightly more complicated substitution + // involving an array as the return value, + // although we're not sure how colliding attributes would + // resolve (certain ones would be completely overriden, + // others would prepend themselves). + } + + $context->destroy('CurrentAttr'); + + // post transforms + + // global (error reporting untested) + foreach ($definition->info_attr_transform_post as $transform) { + $attr = $transform->transform($o = $attr, $config, $context); + if ($e) { + if ($attr != $o) { + $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr); + } + } + } + + // local (error reporting untested) + foreach ($definition->info[$token->name]->attr_transform_post as $transform) { + $attr = $transform->transform($o = $attr, $config, $context); + if ($e) { + if ($attr != $o) { + $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr); + } + } + } + + $token->attr = $attr; + + // destroy CurrentToken if we made it ourselves + if (!$current_token) { + $context->destroy('CurrentToken'); + } + + } + + +} + + + + + +// constants are slow, so we use as few as possible +if (!defined('HTMLPURIFIER_PREFIX')) { + define('HTMLPURIFIER_PREFIX', dirname(__FILE__) . '/standalone'); + set_include_path(HTMLPURIFIER_PREFIX . PATH_SEPARATOR . get_include_path()); +} + +// accomodations for versions earlier than 5.0.2 +// borrowed from PHP_Compat, LGPL licensed, by Aidan Lister +if (!defined('PHP_EOL')) { + switch (strtoupper(substr(PHP_OS, 0, 3))) { + case 'WIN': + define('PHP_EOL', "\r\n"); + break; + case 'DAR': + define('PHP_EOL', "\r"); + break; + default: + define('PHP_EOL', "\n"); + } +} + +/** + * Bootstrap class that contains meta-functionality for HTML Purifier such as + * the autoload function. + * + * @note + * This class may be used without any other files from HTML Purifier. + */ +class HTMLPurifier_Bootstrap +{ + + /** + * Autoload function for HTML Purifier + * @param string $class Class to load + * @return bool + */ + public static function autoload($class) + { + $file = HTMLPurifier_Bootstrap::getPath($class); + if (!$file) { + return false; + } + // Technically speaking, it should be ok and more efficient to + // just do 'require', but Antonio Parraga reports that with + // Zend extensions such as Zend debugger and APC, this invariant + // may be broken. Since we have efficient alternatives, pay + // the cost here and avoid the bug. + require_once HTMLPURIFIER_PREFIX . '/' . $file; + return true; + } + + /** + * Returns the path for a specific class. + * @param string $class Class path to get + * @return string + */ + public static function getPath($class) + { + if (strncmp('HTMLPurifier', $class, 12) !== 0) { + return false; + } + // Custom implementations + if (strncmp('HTMLPurifier_Language_', $class, 22) === 0) { + $code = str_replace('_', '-', substr($class, 22)); + $file = 'HTMLPurifier/Language/classes/' . $code . '.php'; + } else { + $file = str_replace('_', '/', $class) . '.php'; + } + if (!file_exists(HTMLPURIFIER_PREFIX . '/' . $file)) { + return false; + } + return $file; + } + + /** + * "Pre-registers" our autoloader on the SPL stack. + */ + public static function registerAutoload() + { + $autoload = array('HTMLPurifier_Bootstrap', 'autoload'); + if (($funcs = spl_autoload_functions()) === false) { + spl_autoload_register($autoload); + } elseif (function_exists('spl_autoload_unregister')) { + if (version_compare(PHP_VERSION, '5.3.0', '>=')) { + // prepend flag exists, no need for shenanigans + spl_autoload_register($autoload, true, true); + } else { + $buggy = version_compare(PHP_VERSION, '5.2.11', '<'); + $compat = version_compare(PHP_VERSION, '5.1.2', '<=') && + version_compare(PHP_VERSION, '5.1.0', '>='); + foreach ($funcs as $func) { + if ($buggy && is_array($func)) { + // :TRICKY: There are some compatibility issues and some + // places where we need to error out + $reflector = new ReflectionMethod($func[0], $func[1]); + if (!$reflector->isStatic()) { + throw new Exception( + 'HTML Purifier autoloader registrar is not compatible + with non-static object methods due to PHP Bug #44144; + Please do not use HTMLPurifier.autoload.php (or any + file that includes this file); instead, place the code: + spl_autoload_register(array(\'HTMLPurifier_Bootstrap\', \'autoload\')) + after your own autoloaders.' + ); + } + // Suprisingly, spl_autoload_register supports the + // Class::staticMethod callback format, although call_user_func doesn't + if ($compat) { + $func = implode('::', $func); + } + } + spl_autoload_unregister($func); + } + spl_autoload_register($autoload); + foreach ($funcs as $func) { + spl_autoload_register($func); + } + } + } + } +} + + + + + +/** + * Super-class for definition datatype objects, implements serialization + * functions for the class. + */ +abstract class HTMLPurifier_Definition +{ + + /** + * Has setup() been called yet? + * @type bool + */ + public $setup = false; + + /** + * If true, write out the final definition object to the cache after + * setup. This will be true only if all invocations to get a raw + * definition object are also optimized. This does not cause file + * system thrashing because on subsequent calls the cached object + * is used and any writes to the raw definition object are short + * circuited. See enduser-customize.html for the high-level + * picture. + * @type bool + */ + public $optimized = null; + + /** + * What type of definition is it? + * @type string + */ + public $type; + + /** + * Sets up the definition object into the final form, something + * not done by the constructor + * @param HTMLPurifier_Config $config + */ + abstract protected function doSetup($config); + + /** + * Setup function that aborts if already setup + * @param HTMLPurifier_Config $config + */ + public function setup($config) + { + if ($this->setup) { + return; + } + $this->setup = true; + $this->doSetup($config); + } +} + + + + + +/** + * Defines allowed CSS attributes and what their values are. + * @see HTMLPurifier_HTMLDefinition + */ +class HTMLPurifier_CSSDefinition extends HTMLPurifier_Definition +{ + + public $type = 'CSS'; + + /** + * Assoc array of attribute name to definition object. + * @type HTMLPurifier_AttrDef[] + */ + public $info = array(); + + /** + * Constructs the info array. The meat of this class. + * @param HTMLPurifier_Config $config + */ + protected function doSetup($config) + { + $this->info['text-align'] = new HTMLPurifier_AttrDef_Enum( + array('left', 'right', 'center', 'justify'), + false + ); + + $border_style = + $this->info['border-bottom-style'] = + $this->info['border-right-style'] = + $this->info['border-left-style'] = + $this->info['border-top-style'] = new HTMLPurifier_AttrDef_Enum( + array( + 'none', + 'hidden', + 'dotted', + 'dashed', + 'solid', + 'double', + 'groove', + 'ridge', + 'inset', + 'outset' + ), + false + ); + + $this->info['border-style'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_style); + + $this->info['clear'] = new HTMLPurifier_AttrDef_Enum( + array('none', 'left', 'right', 'both'), + false + ); + $this->info['float'] = new HTMLPurifier_AttrDef_Enum( + array('none', 'left', 'right'), + false + ); + $this->info['font-style'] = new HTMLPurifier_AttrDef_Enum( + array('normal', 'italic', 'oblique'), + false + ); + $this->info['font-variant'] = new HTMLPurifier_AttrDef_Enum( + array('normal', 'small-caps'), + false + ); + + $uri_or_none = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('none')), + new HTMLPurifier_AttrDef_CSS_URI() + ) + ); + + $this->info['list-style-position'] = new HTMLPurifier_AttrDef_Enum( + array('inside', 'outside'), + false + ); + $this->info['list-style-type'] = new HTMLPurifier_AttrDef_Enum( + array( + 'disc', + 'circle', + 'square', + 'decimal', + 'lower-roman', + 'upper-roman', + 'lower-alpha', + 'upper-alpha', + 'none' + ), + false + ); + $this->info['list-style-image'] = $uri_or_none; + + $this->info['list-style'] = new HTMLPurifier_AttrDef_CSS_ListStyle($config); + + $this->info['text-transform'] = new HTMLPurifier_AttrDef_Enum( + array('capitalize', 'uppercase', 'lowercase', 'none'), + false + ); + $this->info['color'] = new HTMLPurifier_AttrDef_CSS_Color(); + + $this->info['background-image'] = $uri_or_none; + $this->info['background-repeat'] = new HTMLPurifier_AttrDef_Enum( + array('repeat', 'repeat-x', 'repeat-y', 'no-repeat') + ); + $this->info['background-attachment'] = new HTMLPurifier_AttrDef_Enum( + array('scroll', 'fixed') + ); + $this->info['background-position'] = new HTMLPurifier_AttrDef_CSS_BackgroundPosition(); + + $border_color = + $this->info['border-top-color'] = + $this->info['border-bottom-color'] = + $this->info['border-left-color'] = + $this->info['border-right-color'] = + $this->info['background-color'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('transparent')), + new HTMLPurifier_AttrDef_CSS_Color() + ) + ); + + $this->info['background'] = new HTMLPurifier_AttrDef_CSS_Background($config); + + $this->info['border-color'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_color); + + $border_width = + $this->info['border-top-width'] = + $this->info['border-bottom-width'] = + $this->info['border-left-width'] = + $this->info['border-right-width'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('thin', 'medium', 'thick')), + new HTMLPurifier_AttrDef_CSS_Length('0') //disallow negative + ) + ); + + $this->info['border-width'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_width); + + $this->info['letter-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('normal')), + new HTMLPurifier_AttrDef_CSS_Length() + ) + ); + + $this->info['word-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('normal')), + new HTMLPurifier_AttrDef_CSS_Length() + ) + ); + + $this->info['font-size'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum( + array( + 'xx-small', + 'x-small', + 'small', + 'medium', + 'large', + 'x-large', + 'xx-large', + 'larger', + 'smaller' + ) + ), + new HTMLPurifier_AttrDef_CSS_Percentage(), + new HTMLPurifier_AttrDef_CSS_Length() + ) + ); + + $this->info['line-height'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('normal')), + new HTMLPurifier_AttrDef_CSS_Number(true), // no negatives + new HTMLPurifier_AttrDef_CSS_Length('0'), + new HTMLPurifier_AttrDef_CSS_Percentage(true) + ) + ); + + $margin = + $this->info['margin-top'] = + $this->info['margin-bottom'] = + $this->info['margin-left'] = + $this->info['margin-right'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length(), + new HTMLPurifier_AttrDef_CSS_Percentage(), + new HTMLPurifier_AttrDef_Enum(array('auto')) + ) + ); + + $this->info['margin'] = new HTMLPurifier_AttrDef_CSS_Multiple($margin); + + // non-negative + $padding = + $this->info['padding-top'] = + $this->info['padding-bottom'] = + $this->info['padding-left'] = + $this->info['padding-right'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0'), + new HTMLPurifier_AttrDef_CSS_Percentage(true) + ) + ); + + $this->info['padding'] = new HTMLPurifier_AttrDef_CSS_Multiple($padding); + + $this->info['text-indent'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length(), + new HTMLPurifier_AttrDef_CSS_Percentage() + ) + ); + + $trusted_wh = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0'), + new HTMLPurifier_AttrDef_CSS_Percentage(true), + new HTMLPurifier_AttrDef_Enum(array('auto', 'initial', 'inherit')) + ) + ); + $trusted_min_wh = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0'), + new HTMLPurifier_AttrDef_CSS_Percentage(true), + new HTMLPurifier_AttrDef_Enum(array('initial', 'inherit')) + ) + ); + $trusted_max_wh = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0'), + new HTMLPurifier_AttrDef_CSS_Percentage(true), + new HTMLPurifier_AttrDef_Enum(array('none', 'initial', 'inherit')) + ) + ); + $max = $config->get('CSS.MaxImgLength'); + + $this->info['width'] = + $this->info['height'] = + $max === null ? + $trusted_wh : + new HTMLPurifier_AttrDef_Switch( + 'img', + // For img tags: + new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0', $max), + new HTMLPurifier_AttrDef_Enum(array('auto')) + ) + ), + // For everyone else: + $trusted_wh + ); + $this->info['min-width'] = + $this->info['min-height'] = + $max === null ? + $trusted_min_wh : + new HTMLPurifier_AttrDef_Switch( + 'img', + // For img tags: + new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0', $max), + new HTMLPurifier_AttrDef_Enum(array('initial', 'inherit')) + ) + ), + // For everyone else: + $trusted_min_wh + ); + $this->info['max-width'] = + $this->info['max-height'] = + $max === null ? + $trusted_max_wh : + new HTMLPurifier_AttrDef_Switch( + 'img', + // For img tags: + new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0', $max), + new HTMLPurifier_AttrDef_Enum(array('none', 'initial', 'inherit')) + ) + ), + // For everyone else: + $trusted_max_wh + ); + + $this->info['text-decoration'] = new HTMLPurifier_AttrDef_CSS_TextDecoration(); + + $this->info['font-family'] = new HTMLPurifier_AttrDef_CSS_FontFamily(); + + // this could use specialized code + $this->info['font-weight'] = new HTMLPurifier_AttrDef_Enum( + array( + 'normal', + 'bold', + 'bolder', + 'lighter', + '100', + '200', + '300', + '400', + '500', + '600', + '700', + '800', + '900' + ), + false + ); + + // MUST be called after other font properties, as it references + // a CSSDefinition object + $this->info['font'] = new HTMLPurifier_AttrDef_CSS_Font($config); + + // same here + $this->info['border'] = + $this->info['border-bottom'] = + $this->info['border-top'] = + $this->info['border-left'] = + $this->info['border-right'] = new HTMLPurifier_AttrDef_CSS_Border($config); + + $this->info['border-collapse'] = new HTMLPurifier_AttrDef_Enum( + array('collapse', 'separate') + ); + + $this->info['caption-side'] = new HTMLPurifier_AttrDef_Enum( + array('top', 'bottom') + ); + + $this->info['table-layout'] = new HTMLPurifier_AttrDef_Enum( + array('auto', 'fixed') + ); + + $this->info['vertical-align'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum( + array( + 'baseline', + 'sub', + 'super', + 'top', + 'text-top', + 'middle', + 'bottom', + 'text-bottom' + ) + ), + new HTMLPurifier_AttrDef_CSS_Length(), + new HTMLPurifier_AttrDef_CSS_Percentage() + ) + ); + + $this->info['border-spacing'] = new HTMLPurifier_AttrDef_CSS_Multiple(new HTMLPurifier_AttrDef_CSS_Length(), 2); + + // These CSS properties don't work on many browsers, but we live + // in THE FUTURE! + $this->info['white-space'] = new HTMLPurifier_AttrDef_Enum( + array('nowrap', 'normal', 'pre', 'pre-wrap', 'pre-line') + ); + + if ($config->get('CSS.Proprietary')) { + $this->doSetupProprietary($config); + } + + if ($config->get('CSS.AllowTricky')) { + $this->doSetupTricky($config); + } + + if ($config->get('CSS.Trusted')) { + $this->doSetupTrusted($config); + } + + $allow_important = $config->get('CSS.AllowImportant'); + // wrap all attr-defs with decorator that handles !important + foreach ($this->info as $k => $v) { + $this->info[$k] = new HTMLPurifier_AttrDef_CSS_ImportantDecorator($v, $allow_important); + } + + $this->setupConfigStuff($config); + } + + /** + * @param HTMLPurifier_Config $config + */ + protected function doSetupProprietary($config) + { + // Internet Explorer only scrollbar colors + $this->info['scrollbar-arrow-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + $this->info['scrollbar-base-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + $this->info['scrollbar-darkshadow-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + $this->info['scrollbar-face-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + $this->info['scrollbar-highlight-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + $this->info['scrollbar-shadow-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + + // vendor specific prefixes of opacity + $this->info['-moz-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue(); + $this->info['-khtml-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue(); + + // only opacity, for now + $this->info['filter'] = new HTMLPurifier_AttrDef_CSS_Filter(); + + // more CSS3 + $this->info['page-break-after'] = + $this->info['page-break-before'] = new HTMLPurifier_AttrDef_Enum( + array( + 'auto', + 'always', + 'avoid', + 'left', + 'right' + ) + ); + $this->info['page-break-inside'] = new HTMLPurifier_AttrDef_Enum(array('auto', 'avoid')); + + $border_radius = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Percentage(true), // disallow negative + new HTMLPurifier_AttrDef_CSS_Length('0') // disallow negative + )); + + $this->info['border-top-left-radius'] = + $this->info['border-top-right-radius'] = + $this->info['border-bottom-right-radius'] = + $this->info['border-bottom-left-radius'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_radius, 2); + // TODO: support SLASH syntax + $this->info['border-radius'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_radius, 4); + + } + + /** + * @param HTMLPurifier_Config $config + */ + protected function doSetupTricky($config) + { + $this->info['display'] = new HTMLPurifier_AttrDef_Enum( + array( + 'inline', + 'block', + 'list-item', + 'run-in', + 'compact', + 'marker', + 'table', + 'inline-block', + 'inline-table', + 'table-row-group', + 'table-header-group', + 'table-footer-group', + 'table-row', + 'table-column-group', + 'table-column', + 'table-cell', + 'table-caption', + 'none' + ) + ); + $this->info['visibility'] = new HTMLPurifier_AttrDef_Enum( + array('visible', 'hidden', 'collapse') + ); + $this->info['overflow'] = new HTMLPurifier_AttrDef_Enum(array('visible', 'hidden', 'auto', 'scroll')); + $this->info['opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue(); + } + + /** + * @param HTMLPurifier_Config $config + */ + protected function doSetupTrusted($config) + { + $this->info['position'] = new HTMLPurifier_AttrDef_Enum( + array('static', 'relative', 'absolute', 'fixed') + ); + $this->info['top'] = + $this->info['left'] = + $this->info['right'] = + $this->info['bottom'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length(), + new HTMLPurifier_AttrDef_CSS_Percentage(), + new HTMLPurifier_AttrDef_Enum(array('auto')), + ) + ); + $this->info['z-index'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Integer(), + new HTMLPurifier_AttrDef_Enum(array('auto')), + ) + ); + } + + /** + * Performs extra config-based processing. Based off of + * HTMLPurifier_HTMLDefinition. + * @param HTMLPurifier_Config $config + * @todo Refactor duplicate elements into common class (probably using + * composition, not inheritance). + */ + protected function setupConfigStuff($config) + { + // setup allowed elements + $support = "(for information on implementing this, see the " . + "support forums) "; + $allowed_properties = $config->get('CSS.AllowedProperties'); + if ($allowed_properties !== null) { + foreach ($this->info as $name => $d) { + if (!isset($allowed_properties[$name])) { + unset($this->info[$name]); + } + unset($allowed_properties[$name]); + } + // emit errors + foreach ($allowed_properties as $name => $d) { + // :TODO: Is this htmlspecialchars() call really necessary? + $name = htmlspecialchars($name); + trigger_error("Style attribute '$name' is not supported $support", E_USER_WARNING); + } + } + + $forbidden_properties = $config->get('CSS.ForbiddenProperties'); + if ($forbidden_properties !== null) { + foreach ($this->info as $name => $d) { + if (isset($forbidden_properties[$name])) { + unset($this->info[$name]); + } + } + } + } +} + + + + + +/** + * Defines allowed child nodes and validates nodes against it. + */ +abstract class HTMLPurifier_ChildDef +{ + /** + * Type of child definition, usually right-most part of class name lowercase. + * Used occasionally in terms of context. + * @type string + */ + public $type; + + /** + * Indicates whether or not an empty array of children is okay. + * + * This is necessary for redundant checking when changes affecting + * a child node may cause a parent node to now be disallowed. + * @type bool + */ + public $allow_empty; + + /** + * Lookup array of all elements that this definition could possibly allow. + * @type array + */ + public $elements = array(); + + /** + * Get lookup of tag names that should not close this element automatically. + * All other elements will do so. + * @param HTMLPurifier_Config $config HTMLPurifier_Config object + * @return array + */ + public function getAllowedElements($config) + { + return $this->elements; + } + + /** + * Validates nodes according to definition and returns modification. + * + * @param HTMLPurifier_Node[] $children Array of HTMLPurifier_Node + * @param HTMLPurifier_Config $config HTMLPurifier_Config object + * @param HTMLPurifier_Context $context HTMLPurifier_Context object + * @return bool|array true to leave nodes as is, false to remove parent node, array of replacement children + */ + abstract public function validateChildren($children, $config, $context); +} + + + + + +/** + * Configuration object that triggers customizable behavior. + * + * @warning This class is strongly defined: that means that the class + * will fail if an undefined directive is retrieved or set. + * + * @note Many classes that could (although many times don't) use the + * configuration object make it a mandatory parameter. This is + * because a configuration object should always be forwarded, + * otherwise, you run the risk of missing a parameter and then + * being stumped when a configuration directive doesn't work. + * + * @todo Reconsider some of the public member variables + */ +class HTMLPurifier_Config +{ + + /** + * HTML Purifier's version + * @type string + */ + public $version = '4.12.0'; + + /** + * Whether or not to automatically finalize + * the object if a read operation is done. + * @type bool + */ + public $autoFinalize = true; + + // protected member variables + + /** + * Namespace indexed array of serials for specific namespaces. + * @see getSerial() for more info. + * @type string[] + */ + protected $serials = array(); + + /** + * Serial for entire configuration object. + * @type string + */ + protected $serial; + + /** + * Parser for variables. + * @type HTMLPurifier_VarParser_Flexible + */ + protected $parser = null; + + /** + * Reference HTMLPurifier_ConfigSchema for value checking. + * @type HTMLPurifier_ConfigSchema + * @note This is public for introspective purposes. Please don't + * abuse! + */ + public $def; + + /** + * Indexed array of definitions. + * @type HTMLPurifier_Definition[] + */ + protected $definitions; + + /** + * Whether or not config is finalized. + * @type bool + */ + protected $finalized = false; + + /** + * Property list containing configuration directives. + * @type array + */ + protected $plist; + + /** + * Whether or not a set is taking place due to an alias lookup. + * @type bool + */ + private $aliasMode; + + /** + * Set to false if you do not want line and file numbers in errors. + * (useful when unit testing). This will also compress some errors + * and exceptions. + * @type bool + */ + public $chatty = true; + + /** + * Current lock; only gets to this namespace are allowed. + * @type string + */ + private $lock; + + /** + * Constructor + * @param HTMLPurifier_ConfigSchema $definition ConfigSchema that defines + * what directives are allowed. + * @param HTMLPurifier_PropertyList $parent + */ + public function __construct($definition, $parent = null) + { + $parent = $parent ? $parent : $definition->defaultPlist; + $this->plist = new HTMLPurifier_PropertyList($parent); + $this->def = $definition; // keep a copy around for checking + $this->parser = new HTMLPurifier_VarParser_Flexible(); + } + + /** + * Convenience constructor that creates a config object based on a mixed var + * @param mixed $config Variable that defines the state of the config + * object. Can be: a HTMLPurifier_Config() object, + * an array of directives based on loadArray(), + * or a string filename of an ini file. + * @param HTMLPurifier_ConfigSchema $schema Schema object + * @return HTMLPurifier_Config Configured object + */ + public static function create($config, $schema = null) + { + if ($config instanceof HTMLPurifier_Config) { + // pass-through + return $config; + } + if (!$schema) { + $ret = HTMLPurifier_Config::createDefault(); + } else { + $ret = new HTMLPurifier_Config($schema); + } + if (is_string($config)) { + $ret->loadIni($config); + } elseif (is_array($config)) $ret->loadArray($config); + return $ret; + } + + /** + * Creates a new config object that inherits from a previous one. + * @param HTMLPurifier_Config $config Configuration object to inherit from. + * @return HTMLPurifier_Config object with $config as its parent. + */ + public static function inherit(HTMLPurifier_Config $config) + { + return new HTMLPurifier_Config($config->def, $config->plist); + } + + /** + * Convenience constructor that creates a default configuration object. + * @return HTMLPurifier_Config default object. + */ + public static function createDefault() + { + $definition = HTMLPurifier_ConfigSchema::instance(); + $config = new HTMLPurifier_Config($definition); + return $config; + } + + /** + * Retrieves a value from the configuration. + * + * @param string $key String key + * @param mixed $a + * + * @return mixed + */ + public function get($key, $a = null) + { + if ($a !== null) { + $this->triggerError( + "Using deprecated API: use \$config->get('$key.$a') instead", + E_USER_WARNING + ); + $key = "$key.$a"; + } + if (!$this->finalized) { + $this->autoFinalize(); + } + if (!isset($this->def->info[$key])) { + // can't add % due to SimpleTest bug + $this->triggerError( + 'Cannot retrieve value of undefined directive ' . htmlspecialchars($key), + E_USER_WARNING + ); + return; + } + if (isset($this->def->info[$key]->isAlias)) { + $d = $this->def->info[$key]; + $this->triggerError( + 'Cannot get value from aliased directive, use real name ' . $d->key, + E_USER_ERROR + ); + return; + } + if ($this->lock) { + list($ns) = explode('.', $key); + if ($ns !== $this->lock) { + $this->triggerError( + 'Cannot get value of namespace ' . $ns . ' when lock for ' . + $this->lock . + ' is active, this probably indicates a Definition setup method ' . + 'is accessing directives that are not within its namespace', + E_USER_ERROR + ); + return; + } + } + return $this->plist->get($key); + } + + /** + * Retrieves an array of directives to values from a given namespace + * + * @param string $namespace String namespace + * + * @return array + */ + public function getBatch($namespace) + { + if (!$this->finalized) { + $this->autoFinalize(); + } + $full = $this->getAll(); + if (!isset($full[$namespace])) { + $this->triggerError( + 'Cannot retrieve undefined namespace ' . + htmlspecialchars($namespace), + E_USER_WARNING + ); + return; + } + return $full[$namespace]; + } + + /** + * Returns a SHA-1 signature of a segment of the configuration object + * that uniquely identifies that particular configuration + * + * @param string $namespace Namespace to get serial for + * + * @return string + * @note Revision is handled specially and is removed from the batch + * before processing! + */ + public function getBatchSerial($namespace) + { + if (empty($this->serials[$namespace])) { + $batch = $this->getBatch($namespace); + unset($batch['DefinitionRev']); + $this->serials[$namespace] = sha1(serialize($batch)); + } + return $this->serials[$namespace]; + } + + /** + * Returns a SHA-1 signature for the entire configuration object + * that uniquely identifies that particular configuration + * + * @return string + */ + public function getSerial() + { + if (empty($this->serial)) { + $this->serial = sha1(serialize($this->getAll())); + } + return $this->serial; + } + + /** + * Retrieves all directives, organized by namespace + * + * @warning This is a pretty inefficient function, avoid if you can + */ + public function getAll() + { + if (!$this->finalized) { + $this->autoFinalize(); + } + $ret = array(); + foreach ($this->plist->squash() as $name => $value) { + list($ns, $key) = explode('.', $name, 2); + $ret[$ns][$key] = $value; + } + return $ret; + } + + /** + * Sets a value to configuration. + * + * @param string $key key + * @param mixed $value value + * @param mixed $a + */ + public function set($key, $value, $a = null) + { + if (strpos($key, '.') === false) { + $namespace = $key; + $directive = $value; + $value = $a; + $key = "$key.$directive"; + $this->triggerError("Using deprecated API: use \$config->set('$key', ...) instead", E_USER_NOTICE); + } else { + list($namespace) = explode('.', $key); + } + if ($this->isFinalized('Cannot set directive after finalization')) { + return; + } + if (!isset($this->def->info[$key])) { + $this->triggerError( + 'Cannot set undefined directive ' . htmlspecialchars($key) . ' to value', + E_USER_WARNING + ); + return; + } + $def = $this->def->info[$key]; + + if (isset($def->isAlias)) { + if ($this->aliasMode) { + $this->triggerError( + 'Double-aliases not allowed, please fix '. + 'ConfigSchema bug with' . $key, + E_USER_ERROR + ); + return; + } + $this->aliasMode = true; + $this->set($def->key, $value); + $this->aliasMode = false; + $this->triggerError("$key is an alias, preferred directive name is {$def->key}", E_USER_NOTICE); + return; + } + + // Raw type might be negative when using the fully optimized form + // of stdClass, which indicates allow_null == true + $rtype = is_int($def) ? $def : $def->type; + if ($rtype < 0) { + $type = -$rtype; + $allow_null = true; + } else { + $type = $rtype; + $allow_null = isset($def->allow_null); + } + + try { + $value = $this->parser->parse($value, $type, $allow_null); + } catch (HTMLPurifier_VarParserException $e) { + $this->triggerError( + 'Value for ' . $key . ' is of invalid type, should be ' . + HTMLPurifier_VarParser::getTypeName($type), + E_USER_WARNING + ); + return; + } + if (is_string($value) && is_object($def)) { + // resolve value alias if defined + if (isset($def->aliases[$value])) { + $value = $def->aliases[$value]; + } + // check to see if the value is allowed + if (isset($def->allowed) && !isset($def->allowed[$value])) { + $this->triggerError( + 'Value not supported, valid values are: ' . + $this->_listify($def->allowed), + E_USER_WARNING + ); + return; + } + } + $this->plist->set($key, $value); + + // reset definitions if the directives they depend on changed + // this is a very costly process, so it's discouraged + // with finalization + if ($namespace == 'HTML' || $namespace == 'CSS' || $namespace == 'URI') { + $this->definitions[$namespace] = null; + } + + $this->serials[$namespace] = false; + } + + /** + * Convenience function for error reporting + * + * @param array $lookup + * + * @return string + */ + private function _listify($lookup) + { + $list = array(); + foreach ($lookup as $name => $b) { + $list[] = $name; + } + return implode(', ', $list); + } + + /** + * Retrieves object reference to the HTML definition. + * + * @param bool $raw Return a copy that has not been setup yet. Must be + * called before it's been setup, otherwise won't work. + * @param bool $optimized If true, this method may return null, to + * indicate that a cached version of the modified + * definition object is available and no further edits + * are necessary. Consider using + * maybeGetRawHTMLDefinition, which is more explicitly + * named, instead. + * + * @return HTMLPurifier_HTMLDefinition + */ + public function getHTMLDefinition($raw = false, $optimized = false) + { + return $this->getDefinition('HTML', $raw, $optimized); + } + + /** + * Retrieves object reference to the CSS definition + * + * @param bool $raw Return a copy that has not been setup yet. Must be + * called before it's been setup, otherwise won't work. + * @param bool $optimized If true, this method may return null, to + * indicate that a cached version of the modified + * definition object is available and no further edits + * are necessary. Consider using + * maybeGetRawCSSDefinition, which is more explicitly + * named, instead. + * + * @return HTMLPurifier_CSSDefinition + */ + public function getCSSDefinition($raw = false, $optimized = false) + { + return $this->getDefinition('CSS', $raw, $optimized); + } + + /** + * Retrieves object reference to the URI definition + * + * @param bool $raw Return a copy that has not been setup yet. Must be + * called before it's been setup, otherwise won't work. + * @param bool $optimized If true, this method may return null, to + * indicate that a cached version of the modified + * definition object is available and no further edits + * are necessary. Consider using + * maybeGetRawURIDefinition, which is more explicitly + * named, instead. + * + * @return HTMLPurifier_URIDefinition + */ + public function getURIDefinition($raw = false, $optimized = false) + { + return $this->getDefinition('URI', $raw, $optimized); + } + + /** + * Retrieves a definition + * + * @param string $type Type of definition: HTML, CSS, etc + * @param bool $raw Whether or not definition should be returned raw + * @param bool $optimized Only has an effect when $raw is true. Whether + * or not to return null if the result is already present in + * the cache. This is off by default for backwards + * compatibility reasons, but you need to do things this + * way in order to ensure that caching is done properly. + * Check out enduser-customize.html for more details. + * We probably won't ever change this default, as much as the + * maybe semantics is the "right thing to do." + * + * @throws HTMLPurifier_Exception + * @return HTMLPurifier_Definition + */ + public function getDefinition($type, $raw = false, $optimized = false) + { + if ($optimized && !$raw) { + throw new HTMLPurifier_Exception("Cannot set optimized = true when raw = false"); + } + if (!$this->finalized) { + $this->autoFinalize(); + } + // temporarily suspend locks, so we can handle recursive definition calls + $lock = $this->lock; + $this->lock = null; + $factory = HTMLPurifier_DefinitionCacheFactory::instance(); + $cache = $factory->create($type, $this); + $this->lock = $lock; + if (!$raw) { + // full definition + // --------------- + // check if definition is in memory + if (!empty($this->definitions[$type])) { + $def = $this->definitions[$type]; + // check if the definition is setup + if ($def->setup) { + return $def; + } else { + $def->setup($this); + if ($def->optimized) { + $cache->add($def, $this); + } + return $def; + } + } + // check if definition is in cache + $def = $cache->get($this); + if ($def) { + // definition in cache, save to memory and return it + $this->definitions[$type] = $def; + return $def; + } + // initialize it + $def = $this->initDefinition($type); + // set it up + $this->lock = $type; + $def->setup($this); + $this->lock = null; + // save in cache + $cache->add($def, $this); + // return it + return $def; + } else { + // raw definition + // -------------- + // check preconditions + $def = null; + if ($optimized) { + if (is_null($this->get($type . '.DefinitionID'))) { + // fatally error out if definition ID not set + throw new HTMLPurifier_Exception( + "Cannot retrieve raw version without specifying %$type.DefinitionID" + ); + } + } + if (!empty($this->definitions[$type])) { + $def = $this->definitions[$type]; + if ($def->setup && !$optimized) { + $extra = $this->chatty ? + " (try moving this code block earlier in your initialization)" : + ""; + throw new HTMLPurifier_Exception( + "Cannot retrieve raw definition after it has already been setup" . + $extra + ); + } + if ($def->optimized === null) { + $extra = $this->chatty ? " (try flushing your cache)" : ""; + throw new HTMLPurifier_Exception( + "Optimization status of definition is unknown" . $extra + ); + } + if ($def->optimized !== $optimized) { + $msg = $optimized ? "optimized" : "unoptimized"; + $extra = $this->chatty ? + " (this backtrace is for the first inconsistent call, which was for a $msg raw definition)" + : ""; + throw new HTMLPurifier_Exception( + "Inconsistent use of optimized and unoptimized raw definition retrievals" . $extra + ); + } + } + // check if definition was in memory + if ($def) { + if ($def->setup) { + // invariant: $optimized === true (checked above) + return null; + } else { + return $def; + } + } + // if optimized, check if definition was in cache + // (because we do the memory check first, this formulation + // is prone to cache slamming, but I think + // guaranteeing that either /all/ of the raw + // setup code or /none/ of it is run is more important.) + if ($optimized) { + // This code path only gets run once; once we put + // something in $definitions (which is guaranteed by the + // trailing code), we always short-circuit above. + $def = $cache->get($this); + if ($def) { + // save the full definition for later, but don't + // return it yet + $this->definitions[$type] = $def; + return null; + } + } + // check invariants for creation + if (!$optimized) { + if (!is_null($this->get($type . '.DefinitionID'))) { + if ($this->chatty) { + $this->triggerError( + 'Due to a documentation error in previous version of HTML Purifier, your ' . + 'definitions are not being cached. If this is OK, you can remove the ' . + '%$type.DefinitionRev and %$type.DefinitionID declaration. Otherwise, ' . + 'modify your code to use maybeGetRawDefinition, and test if the returned ' . + 'value is null before making any edits (if it is null, that means that a ' . + 'cached version is available, and no raw operations are necessary). See ' . + '' . + 'Customize for more details', + E_USER_WARNING + ); + } else { + $this->triggerError( + "Useless DefinitionID declaration", + E_USER_WARNING + ); + } + } + } + // initialize it + $def = $this->initDefinition($type); + $def->optimized = $optimized; + return $def; + } + throw new HTMLPurifier_Exception("The impossible happened!"); + } + + /** + * Initialise definition + * + * @param string $type What type of definition to create + * + * @return HTMLPurifier_CSSDefinition|HTMLPurifier_HTMLDefinition|HTMLPurifier_URIDefinition + * @throws HTMLPurifier_Exception + */ + private function initDefinition($type) + { + // quick checks failed, let's create the object + if ($type == 'HTML') { + $def = new HTMLPurifier_HTMLDefinition(); + } elseif ($type == 'CSS') { + $def = new HTMLPurifier_CSSDefinition(); + } elseif ($type == 'URI') { + $def = new HTMLPurifier_URIDefinition(); + } else { + throw new HTMLPurifier_Exception( + "Definition of $type type not supported" + ); + } + $this->definitions[$type] = $def; + return $def; + } + + public function maybeGetRawDefinition($name) + { + return $this->getDefinition($name, true, true); + } + + /** + * @return HTMLPurifier_HTMLDefinition + */ + public function maybeGetRawHTMLDefinition() + { + return $this->getDefinition('HTML', true, true); + } + + /** + * @return HTMLPurifier_CSSDefinition + */ + public function maybeGetRawCSSDefinition() + { + return $this->getDefinition('CSS', true, true); + } + + /** + * @return HTMLPurifier_URIDefinition + */ + public function maybeGetRawURIDefinition() + { + return $this->getDefinition('URI', true, true); + } + + /** + * Loads configuration values from an array with the following structure: + * Namespace.Directive => Value + * + * @param array $config_array Configuration associative array + */ + public function loadArray($config_array) + { + if ($this->isFinalized('Cannot load directives after finalization')) { + return; + } + foreach ($config_array as $key => $value) { + $key = str_replace('_', '.', $key); + if (strpos($key, '.') !== false) { + $this->set($key, $value); + } else { + $namespace = $key; + $namespace_values = $value; + foreach ($namespace_values as $directive => $value2) { + $this->set($namespace .'.'. $directive, $value2); + } + } + } + } + + /** + * Returns a list of array(namespace, directive) for all directives + * that are allowed in a web-form context as per an allowed + * namespaces/directives list. + * + * @param array $allowed List of allowed namespaces/directives + * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy + * + * @return array + */ + public static function getAllowedDirectivesForForm($allowed, $schema = null) + { + if (!$schema) { + $schema = HTMLPurifier_ConfigSchema::instance(); + } + if ($allowed !== true) { + if (is_string($allowed)) { + $allowed = array($allowed); + } + $allowed_ns = array(); + $allowed_directives = array(); + $blacklisted_directives = array(); + foreach ($allowed as $ns_or_directive) { + if (strpos($ns_or_directive, '.') !== false) { + // directive + if ($ns_or_directive[0] == '-') { + $blacklisted_directives[substr($ns_or_directive, 1)] = true; + } else { + $allowed_directives[$ns_or_directive] = true; + } + } else { + // namespace + $allowed_ns[$ns_or_directive] = true; + } + } + } + $ret = array(); + foreach ($schema->info as $key => $def) { + list($ns, $directive) = explode('.', $key, 2); + if ($allowed !== true) { + if (isset($blacklisted_directives["$ns.$directive"])) { + continue; + } + if (!isset($allowed_directives["$ns.$directive"]) && !isset($allowed_ns[$ns])) { + continue; + } + } + if (isset($def->isAlias)) { + continue; + } + if ($directive == 'DefinitionID' || $directive == 'DefinitionRev') { + continue; + } + $ret[] = array($ns, $directive); + } + return $ret; + } + + /** + * Loads configuration values from $_GET/$_POST that were posted + * via ConfigForm + * + * @param array $array $_GET or $_POST array to import + * @param string|bool $index Index/name that the config variables are in + * @param array|bool $allowed List of allowed namespaces/directives + * @param bool $mq_fix Boolean whether or not to enable magic quotes fix + * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy + * + * @return mixed + */ + public static function loadArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) + { + $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema); + $config = HTMLPurifier_Config::create($ret, $schema); + return $config; + } + + /** + * Merges in configuration values from $_GET/$_POST to object. NOT STATIC. + * + * @param array $array $_GET or $_POST array to import + * @param string|bool $index Index/name that the config variables are in + * @param array|bool $allowed List of allowed namespaces/directives + * @param bool $mq_fix Boolean whether or not to enable magic quotes fix + */ + public function mergeArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true) + { + $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $this->def); + $this->loadArray($ret); + } + + /** + * Prepares an array from a form into something usable for the more + * strict parts of HTMLPurifier_Config + * + * @param array $array $_GET or $_POST array to import + * @param string|bool $index Index/name that the config variables are in + * @param array|bool $allowed List of allowed namespaces/directives + * @param bool $mq_fix Boolean whether or not to enable magic quotes fix + * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy + * + * @return array + */ + public static function prepareArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) + { + if ($index !== false) { + $array = (isset($array[$index]) && is_array($array[$index])) ? $array[$index] : array(); + } + $mq = $mq_fix && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc(); + + $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $schema); + $ret = array(); + foreach ($allowed as $key) { + list($ns, $directive) = $key; + $skey = "$ns.$directive"; + if (!empty($array["Null_$skey"])) { + $ret[$ns][$directive] = null; + continue; + } + if (!isset($array[$skey])) { + continue; + } + $value = $mq ? stripslashes($array[$skey]) : $array[$skey]; + $ret[$ns][$directive] = $value; + } + return $ret; + } + + /** + * Loads configuration values from an ini file + * + * @param string $filename Name of ini file + */ + public function loadIni($filename) + { + if ($this->isFinalized('Cannot load directives after finalization')) { + return; + } + $array = parse_ini_file($filename, true); + $this->loadArray($array); + } + + /** + * Checks whether or not the configuration object is finalized. + * + * @param string|bool $error String error message, or false for no error + * + * @return bool + */ + public function isFinalized($error = false) + { + if ($this->finalized && $error) { + $this->triggerError($error, E_USER_ERROR); + } + return $this->finalized; + } + + /** + * Finalizes configuration only if auto finalize is on and not + * already finalized + */ + public function autoFinalize() + { + if ($this->autoFinalize) { + $this->finalize(); + } else { + $this->plist->squash(true); + } + } + + /** + * Finalizes a configuration object, prohibiting further change + */ + public function finalize() + { + $this->finalized = true; + $this->parser = null; + } + + /** + * Produces a nicely formatted error message by supplying the + * stack frame information OUTSIDE of HTMLPurifier_Config. + * + * @param string $msg An error message + * @param int $no An error number + */ + protected function triggerError($msg, $no) + { + // determine previous stack frame + $extra = ''; + if ($this->chatty) { + $trace = debug_backtrace(); + // zip(tail(trace), trace) -- but PHP is not Haskell har har + for ($i = 0, $c = count($trace); $i < $c - 1; $i++) { + // XXX this is not correct on some versions of HTML Purifier + if (isset($trace[$i + 1]['class']) && $trace[$i + 1]['class'] === 'HTMLPurifier_Config') { + continue; + } + $frame = $trace[$i]; + $extra = " invoked on line {$frame['line']} in file {$frame['file']}"; + break; + } + } + trigger_error($msg . $extra, $no); + } + + /** + * Returns a serialized form of the configuration object that can + * be reconstituted. + * + * @return string + */ + public function serialize() + { + $this->getDefinition('HTML'); + $this->getDefinition('CSS'); + $this->getDefinition('URI'); + return serialize($this); + } + +} + + + + + +/** + * Configuration definition, defines directives and their defaults. + */ +class HTMLPurifier_ConfigSchema +{ + /** + * Defaults of the directives and namespaces. + * @type array + * @note This shares the exact same structure as HTMLPurifier_Config::$conf + */ + public $defaults = array(); + + /** + * The default property list. Do not edit this property list. + * @type array + */ + public $defaultPlist; + + /** + * Definition of the directives. + * The structure of this is: + * + * array( + * 'Namespace' => array( + * 'Directive' => new stdClass(), + * ) + * ) + * + * The stdClass may have the following properties: + * + * - If isAlias isn't set: + * - type: Integer type of directive, see HTMLPurifier_VarParser for definitions + * - allow_null: If set, this directive allows null values + * - aliases: If set, an associative array of value aliases to real values + * - allowed: If set, a lookup array of allowed (string) values + * - If isAlias is set: + * - namespace: Namespace this directive aliases to + * - name: Directive name this directive aliases to + * + * In certain degenerate cases, stdClass will actually be an integer. In + * that case, the value is equivalent to an stdClass with the type + * property set to the integer. If the integer is negative, type is + * equal to the absolute value of integer, and allow_null is true. + * + * This class is friendly with HTMLPurifier_Config. If you need introspection + * about the schema, you're better of using the ConfigSchema_Interchange, + * which uses more memory but has much richer information. + * @type array + */ + public $info = array(); + + /** + * Application-wide singleton + * @type HTMLPurifier_ConfigSchema + */ + protected static $singleton; + + public function __construct() + { + $this->defaultPlist = new HTMLPurifier_PropertyList(); + } + + /** + * Unserializes the default ConfigSchema. + * @return HTMLPurifier_ConfigSchema + */ + public static function makeFromSerial() + { + $contents = file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/ConfigSchema/schema.ser'); + $r = unserialize($contents); + if (!$r) { + $hash = sha1($contents); + trigger_error("Unserialization of configuration schema failed, sha1 of file was $hash", E_USER_ERROR); + } + return $r; + } + + /** + * Retrieves an instance of the application-wide configuration definition. + * @param HTMLPurifier_ConfigSchema $prototype + * @return HTMLPurifier_ConfigSchema + */ + public static function instance($prototype = null) + { + if ($prototype !== null) { + HTMLPurifier_ConfigSchema::$singleton = $prototype; + } elseif (HTMLPurifier_ConfigSchema::$singleton === null || $prototype === true) { + HTMLPurifier_ConfigSchema::$singleton = HTMLPurifier_ConfigSchema::makeFromSerial(); + } + return HTMLPurifier_ConfigSchema::$singleton; + } + + /** + * Defines a directive for configuration + * @warning Will fail of directive's namespace is defined. + * @warning This method's signature is slightly different from the legacy + * define() static method! Beware! + * @param string $key Name of directive + * @param mixed $default Default value of directive + * @param string $type Allowed type of the directive. See + * HTMLPurifier_VarParser::$types for allowed values + * @param bool $allow_null Whether or not to allow null values + */ + public function add($key, $default, $type, $allow_null) + { + $obj = new stdClass(); + $obj->type = is_int($type) ? $type : HTMLPurifier_VarParser::$types[$type]; + if ($allow_null) { + $obj->allow_null = true; + } + $this->info[$key] = $obj; + $this->defaults[$key] = $default; + $this->defaultPlist->set($key, $default); + } + + /** + * Defines a directive value alias. + * + * Directive value aliases are convenient for developers because it lets + * them set a directive to several values and get the same result. + * @param string $key Name of Directive + * @param array $aliases Hash of aliased values to the real alias + */ + public function addValueAliases($key, $aliases) + { + if (!isset($this->info[$key]->aliases)) { + $this->info[$key]->aliases = array(); + } + foreach ($aliases as $alias => $real) { + $this->info[$key]->aliases[$alias] = $real; + } + } + + /** + * Defines a set of allowed values for a directive. + * @warning This is slightly different from the corresponding static + * method definition. + * @param string $key Name of directive + * @param array $allowed Lookup array of allowed values + */ + public function addAllowedValues($key, $allowed) + { + $this->info[$key]->allowed = $allowed; + } + + /** + * Defines a directive alias for backwards compatibility + * @param string $key Directive that will be aliased + * @param string $new_key Directive that the alias will be to + */ + public function addAlias($key, $new_key) + { + $obj = new stdClass; + $obj->key = $new_key; + $obj->isAlias = true; + $this->info[$key] = $obj; + } + + /** + * Replaces any stdClass that only has the type property with type integer. + */ + public function postProcess() + { + foreach ($this->info as $key => $v) { + if (count((array) $v) == 1) { + $this->info[$key] = $v->type; + } elseif (count((array) $v) == 2 && isset($v->allow_null)) { + $this->info[$key] = -$v->type; + } + } + } +} + + + + + +/** + * @todo Unit test + */ +class HTMLPurifier_ContentSets +{ + + /** + * List of content set strings (pipe separators) indexed by name. + * @type array + */ + public $info = array(); + + /** + * List of content set lookups (element => true) indexed by name. + * @type array + * @note This is in HTMLPurifier_HTMLDefinition->info_content_sets + */ + public $lookup = array(); + + /** + * Synchronized list of defined content sets (keys of info). + * @type array + */ + protected $keys = array(); + /** + * Synchronized list of defined content values (values of info). + * @type array + */ + protected $values = array(); + + /** + * Merges in module's content sets, expands identifiers in the content + * sets and populates the keys, values and lookup member variables. + * @param HTMLPurifier_HTMLModule[] $modules List of HTMLPurifier_HTMLModule + */ + public function __construct($modules) + { + if (!is_array($modules)) { + $modules = array($modules); + } + // populate content_sets based on module hints + // sorry, no way of overloading + foreach ($modules as $module) { + foreach ($module->content_sets as $key => $value) { + $temp = $this->convertToLookup($value); + if (isset($this->lookup[$key])) { + // add it into the existing content set + $this->lookup[$key] = array_merge($this->lookup[$key], $temp); + } else { + $this->lookup[$key] = $temp; + } + } + } + $old_lookup = false; + while ($old_lookup !== $this->lookup) { + $old_lookup = $this->lookup; + foreach ($this->lookup as $i => $set) { + $add = array(); + foreach ($set as $element => $x) { + if (isset($this->lookup[$element])) { + $add += $this->lookup[$element]; + unset($this->lookup[$i][$element]); + } + } + $this->lookup[$i] += $add; + } + } + + foreach ($this->lookup as $key => $lookup) { + $this->info[$key] = implode(' | ', array_keys($lookup)); + } + $this->keys = array_keys($this->info); + $this->values = array_values($this->info); + } + + /** + * Accepts a definition; generates and assigns a ChildDef for it + * @param HTMLPurifier_ElementDef $def HTMLPurifier_ElementDef reference + * @param HTMLPurifier_HTMLModule $module Module that defined the ElementDef + */ + public function generateChildDef(&$def, $module) + { + if (!empty($def->child)) { // already done! + return; + } + $content_model = $def->content_model; + if (is_string($content_model)) { + // Assume that $this->keys is alphanumeric + $def->content_model = preg_replace_callback( + '/\b(' . implode('|', $this->keys) . ')\b/', + array($this, 'generateChildDefCallback'), + $content_model + ); + //$def->content_model = str_replace( + // $this->keys, $this->values, $content_model); + } + $def->child = $this->getChildDef($def, $module); + } + + public function generateChildDefCallback($matches) + { + return $this->info[$matches[0]]; + } + + /** + * Instantiates a ChildDef based on content_model and content_model_type + * member variables in HTMLPurifier_ElementDef + * @note This will also defer to modules for custom HTMLPurifier_ChildDef + * subclasses that need content set expansion + * @param HTMLPurifier_ElementDef $def HTMLPurifier_ElementDef to have ChildDef extracted + * @param HTMLPurifier_HTMLModule $module Module that defined the ElementDef + * @return HTMLPurifier_ChildDef corresponding to ElementDef + */ + public function getChildDef($def, $module) + { + $value = $def->content_model; + if (is_object($value)) { + trigger_error( + 'Literal object child definitions should be stored in '. + 'ElementDef->child not ElementDef->content_model', + E_USER_NOTICE + ); + return $value; + } + switch ($def->content_model_type) { + case 'required': + return new HTMLPurifier_ChildDef_Required($value); + case 'optional': + return new HTMLPurifier_ChildDef_Optional($value); + case 'empty': + return new HTMLPurifier_ChildDef_Empty(); + case 'custom': + return new HTMLPurifier_ChildDef_Custom($value); + } + // defer to its module + $return = false; + if ($module->defines_child_def) { // save a func call + $return = $module->getChildDef($def); + } + if ($return !== false) { + return $return; + } + // error-out + trigger_error( + 'Could not determine which ChildDef class to instantiate', + E_USER_ERROR + ); + return false; + } + + /** + * Converts a string list of elements separated by pipes into + * a lookup array. + * @param string $string List of elements + * @return array Lookup array of elements + */ + protected function convertToLookup($string) + { + $array = explode('|', str_replace(' ', '', $string)); + $ret = array(); + foreach ($array as $k) { + $ret[$k] = true; + } + return $ret; + } +} + + + + + +/** + * Registry object that contains information about the current context. + * @warning Is a bit buggy when variables are set to null: it thinks + * they don't exist! So use false instead, please. + * @note Since the variables Context deals with may not be objects, + * references are very important here! Do not remove! + */ +class HTMLPurifier_Context +{ + + /** + * Private array that stores the references. + * @type array + */ + private $_storage = array(); + + /** + * Registers a variable into the context. + * @param string $name String name + * @param mixed $ref Reference to variable to be registered + */ + public function register($name, &$ref) + { + if (array_key_exists($name, $this->_storage)) { + trigger_error( + "Name $name produces collision, cannot re-register", + E_USER_ERROR + ); + return; + } + $this->_storage[$name] =& $ref; + } + + /** + * Retrieves a variable reference from the context. + * @param string $name String name + * @param bool $ignore_error Boolean whether or not to ignore error + * @return mixed + */ + public function &get($name, $ignore_error = false) + { + if (!array_key_exists($name, $this->_storage)) { + if (!$ignore_error) { + trigger_error( + "Attempted to retrieve non-existent variable $name", + E_USER_ERROR + ); + } + $var = null; // so we can return by reference + return $var; + } + return $this->_storage[$name]; + } + + /** + * Destroys a variable in the context. + * @param string $name String name + */ + public function destroy($name) + { + if (!array_key_exists($name, $this->_storage)) { + trigger_error( + "Attempted to destroy non-existent variable $name", + E_USER_ERROR + ); + return; + } + unset($this->_storage[$name]); + } + + /** + * Checks whether or not the variable exists. + * @param string $name String name + * @return bool + */ + public function exists($name) + { + return array_key_exists($name, $this->_storage); + } + + /** + * Loads a series of variables from an associative array + * @param array $context_array Assoc array of variables to load + */ + public function loadArray($context_array) + { + foreach ($context_array as $key => $discard) { + $this->register($key, $context_array[$key]); + } + } +} + + + + + +/** + * Abstract class representing Definition cache managers that implements + * useful common methods and is a factory. + * @todo Create a separate maintenance file advanced users can use to + * cache their custom HTMLDefinition, which can be loaded + * via a configuration directive + * @todo Implement memcached + */ +abstract class HTMLPurifier_DefinitionCache +{ + /** + * @type string + */ + public $type; + + /** + * @param string $type Type of definition objects this instance of the + * cache will handle. + */ + public function __construct($type) + { + $this->type = $type; + } + + /** + * Generates a unique identifier for a particular configuration + * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config + * @return string + */ + public function generateKey($config) + { + return $config->version . ',' . // possibly replace with function calls + $config->getBatchSerial($this->type) . ',' . + $config->get($this->type . '.DefinitionRev'); + } + + /** + * Tests whether or not a key is old with respect to the configuration's + * version and revision number. + * @param string $key Key to test + * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config to test against + * @return bool + */ + public function isOld($key, $config) + { + if (substr_count($key, ',') < 2) { + return true; + } + list($version, $hash, $revision) = explode(',', $key, 3); + $compare = version_compare($version, $config->version); + // version mismatch, is always old + if ($compare != 0) { + return true; + } + // versions match, ids match, check revision number + if ($hash == $config->getBatchSerial($this->type) && + $revision < $config->get($this->type . '.DefinitionRev')) { + return true; + } + return false; + } + + /** + * Checks if a definition's type jives with the cache's type + * @note Throws an error on failure + * @param HTMLPurifier_Definition $def Definition object to check + * @return bool true if good, false if not + */ + public function checkDefType($def) + { + if ($def->type !== $this->type) { + trigger_error("Cannot use definition of type {$def->type} in cache for {$this->type}"); + return false; + } + return true; + } + + /** + * Adds a definition object to the cache + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + */ + abstract public function add($def, $config); + + /** + * Unconditionally saves a definition object to the cache + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + */ + abstract public function set($def, $config); + + /** + * Replace an object in the cache + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + */ + abstract public function replace($def, $config); + + /** + * Retrieves a definition object from the cache + * @param HTMLPurifier_Config $config + */ + abstract public function get($config); + + /** + * Removes a definition object to the cache + * @param HTMLPurifier_Config $config + */ + abstract public function remove($config); + + /** + * Clears all objects from cache + * @param HTMLPurifier_Config $config + */ + abstract public function flush($config); + + /** + * Clears all expired (older version or revision) objects from cache + * @note Be careful implementing this method as flush. Flush must + * not interfere with other Definition types, and cleanup() + * should not be repeatedly called by userland code. + * @param HTMLPurifier_Config $config + */ + abstract public function cleanup($config); +} + + + + + +/** + * Responsible for creating definition caches. + */ +class HTMLPurifier_DefinitionCacheFactory +{ + /** + * @type array + */ + protected $caches = array('Serializer' => array()); + + /** + * @type array + */ + protected $implementations = array(); + + /** + * @type HTMLPurifier_DefinitionCache_Decorator[] + */ + protected $decorators = array(); + + /** + * Initialize default decorators + */ + public function setup() + { + $this->addDecorator('Cleanup'); + } + + /** + * Retrieves an instance of global definition cache factory. + * @param HTMLPurifier_DefinitionCacheFactory $prototype + * @return HTMLPurifier_DefinitionCacheFactory + */ + public static function instance($prototype = null) + { + static $instance; + if ($prototype !== null) { + $instance = $prototype; + } elseif ($instance === null || $prototype === true) { + $instance = new HTMLPurifier_DefinitionCacheFactory(); + $instance->setup(); + } + return $instance; + } + + /** + * Registers a new definition cache object + * @param string $short Short name of cache object, for reference + * @param string $long Full class name of cache object, for construction + */ + public function register($short, $long) + { + $this->implementations[$short] = $long; + } + + /** + * Factory method that creates a cache object based on configuration + * @param string $type Name of definitions handled by cache + * @param HTMLPurifier_Config $config Config instance + * @return mixed + */ + public function create($type, $config) + { + $method = $config->get('Cache.DefinitionImpl'); + if ($method === null) { + return new HTMLPurifier_DefinitionCache_Null($type); + } + if (!empty($this->caches[$method][$type])) { + return $this->caches[$method][$type]; + } + if (isset($this->implementations[$method]) && + class_exists($class = $this->implementations[$method], false)) { + $cache = new $class($type); + } else { + if ($method != 'Serializer') { + trigger_error("Unrecognized DefinitionCache $method, using Serializer instead", E_USER_WARNING); + } + $cache = new HTMLPurifier_DefinitionCache_Serializer($type); + } + foreach ($this->decorators as $decorator) { + $new_cache = $decorator->decorate($cache); + // prevent infinite recursion in PHP 4 + unset($cache); + $cache = $new_cache; + } + $this->caches[$method][$type] = $cache; + return $this->caches[$method][$type]; + } + + /** + * Registers a decorator to add to all new cache objects + * @param HTMLPurifier_DefinitionCache_Decorator|string $decorator An instance or the name of a decorator + */ + public function addDecorator($decorator) + { + if (is_string($decorator)) { + $class = "HTMLPurifier_DefinitionCache_Decorator_$decorator"; + $decorator = new $class; + } + $this->decorators[$decorator->name] = $decorator; + } +} + + + + + +/** + * Represents a document type, contains information on which modules + * need to be loaded. + * @note This class is inspected by Printer_HTMLDefinition->renderDoctype. + * If structure changes, please update that function. + */ +class HTMLPurifier_Doctype +{ + /** + * Full name of doctype + * @type string + */ + public $name; + + /** + * List of standard modules (string identifiers or literal objects) + * that this doctype uses + * @type array + */ + public $modules = array(); + + /** + * List of modules to use for tidying up code + * @type array + */ + public $tidyModules = array(); + + /** + * Is the language derived from XML (i.e. XHTML)? + * @type bool + */ + public $xml = true; + + /** + * List of aliases for this doctype + * @type array + */ + public $aliases = array(); + + /** + * Public DTD identifier + * @type string + */ + public $dtdPublic; + + /** + * System DTD identifier + * @type string + */ + public $dtdSystem; + + public function __construct( + $name = null, + $xml = true, + $modules = array(), + $tidyModules = array(), + $aliases = array(), + $dtd_public = null, + $dtd_system = null + ) { + $this->name = $name; + $this->xml = $xml; + $this->modules = $modules; + $this->tidyModules = $tidyModules; + $this->aliases = $aliases; + $this->dtdPublic = $dtd_public; + $this->dtdSystem = $dtd_system; + } +} + + + + + +class HTMLPurifier_DoctypeRegistry +{ + + /** + * Hash of doctype names to doctype objects. + * @type array + */ + protected $doctypes; + + /** + * Lookup table of aliases to real doctype names. + * @type array + */ + protected $aliases; + + /** + * Registers a doctype to the registry + * @note Accepts a fully-formed doctype object, or the + * parameters for constructing a doctype object + * @param string $doctype Name of doctype or literal doctype object + * @param bool $xml + * @param array $modules Modules doctype will load + * @param array $tidy_modules Modules doctype will load for certain modes + * @param array $aliases Alias names for doctype + * @param string $dtd_public + * @param string $dtd_system + * @return HTMLPurifier_Doctype Editable registered doctype + */ + public function register( + $doctype, + $xml = true, + $modules = array(), + $tidy_modules = array(), + $aliases = array(), + $dtd_public = null, + $dtd_system = null + ) { + if (!is_array($modules)) { + $modules = array($modules); + } + if (!is_array($tidy_modules)) { + $tidy_modules = array($tidy_modules); + } + if (!is_array($aliases)) { + $aliases = array($aliases); + } + if (!is_object($doctype)) { + $doctype = new HTMLPurifier_Doctype( + $doctype, + $xml, + $modules, + $tidy_modules, + $aliases, + $dtd_public, + $dtd_system + ); + } + $this->doctypes[$doctype->name] = $doctype; + $name = $doctype->name; + // hookup aliases + foreach ($doctype->aliases as $alias) { + if (isset($this->doctypes[$alias])) { + continue; + } + $this->aliases[$alias] = $name; + } + // remove old aliases + if (isset($this->aliases[$name])) { + unset($this->aliases[$name]); + } + return $doctype; + } + + /** + * Retrieves reference to a doctype of a certain name + * @note This function resolves aliases + * @note When possible, use the more fully-featured make() + * @param string $doctype Name of doctype + * @return HTMLPurifier_Doctype Editable doctype object + */ + public function get($doctype) + { + if (isset($this->aliases[$doctype])) { + $doctype = $this->aliases[$doctype]; + } + if (!isset($this->doctypes[$doctype])) { + trigger_error('Doctype ' . htmlspecialchars($doctype) . ' does not exist', E_USER_ERROR); + $anon = new HTMLPurifier_Doctype($doctype); + return $anon; + } + return $this->doctypes[$doctype]; + } + + /** + * Creates a doctype based on a configuration object, + * will perform initialization on the doctype + * @note Use this function to get a copy of doctype that config + * can hold on to (this is necessary in order to tell + * Generator whether or not the current document is XML + * based or not). + * @param HTMLPurifier_Config $config + * @return HTMLPurifier_Doctype + */ + public function make($config) + { + return clone $this->get($this->getDoctypeFromConfig($config)); + } + + /** + * Retrieves the doctype from the configuration object + * @param HTMLPurifier_Config $config + * @return string + */ + public function getDoctypeFromConfig($config) + { + // recommended test + $doctype = $config->get('HTML.Doctype'); + if (!empty($doctype)) { + return $doctype; + } + $doctype = $config->get('HTML.CustomDoctype'); + if (!empty($doctype)) { + return $doctype; + } + // backwards-compatibility + if ($config->get('HTML.XHTML')) { + $doctype = 'XHTML 1.0'; + } else { + $doctype = 'HTML 4.01'; + } + if ($config->get('HTML.Strict')) { + $doctype .= ' Strict'; + } else { + $doctype .= ' Transitional'; + } + return $doctype; + } +} + + + + + +/** + * Structure that stores an HTML element definition. Used by + * HTMLPurifier_HTMLDefinition and HTMLPurifier_HTMLModule. + * @note This class is inspected by HTMLPurifier_Printer_HTMLDefinition. + * Please update that class too. + * @warning If you add new properties to this class, you MUST update + * the mergeIn() method. + */ +class HTMLPurifier_ElementDef +{ + /** + * Does the definition work by itself, or is it created solely + * for the purpose of merging into another definition? + * @type bool + */ + public $standalone = true; + + /** + * Associative array of attribute name to HTMLPurifier_AttrDef. + * @type array + * @note Before being processed by HTMLPurifier_AttrCollections + * when modules are finalized during + * HTMLPurifier_HTMLDefinition->setup(), this array may also + * contain an array at index 0 that indicates which attribute + * collections to load into the full array. It may also + * contain string indentifiers in lieu of HTMLPurifier_AttrDef, + * see HTMLPurifier_AttrTypes on how they are expanded during + * HTMLPurifier_HTMLDefinition->setup() processing. + */ + public $attr = array(); + + // XXX: Design note: currently, it's not possible to override + // previously defined AttrTransforms without messing around with + // the final generated config. This is by design; a previous version + // used an associated list of attr_transform, but it was extremely + // easy to accidentally override other attribute transforms by + // forgetting to specify an index (and just using 0.) While we + // could check this by checking the index number and complaining, + // there is a second problem which is that it is not at all easy to + // tell when something is getting overridden. Combine this with a + // codebase where this isn't really being used, and it's perfect for + // nuking. + + /** + * List of tags HTMLPurifier_AttrTransform to be done before validation. + * @type array + */ + public $attr_transform_pre = array(); + + /** + * List of tags HTMLPurifier_AttrTransform to be done after validation. + * @type array + */ + public $attr_transform_post = array(); + + /** + * HTMLPurifier_ChildDef of this tag. + * @type HTMLPurifier_ChildDef + */ + public $child; + + /** + * Abstract string representation of internal ChildDef rules. + * @see HTMLPurifier_ContentSets for how this is parsed and then transformed + * into an HTMLPurifier_ChildDef. + * @warning This is a temporary variable that is not available after + * being processed by HTMLDefinition + * @type string + */ + public $content_model; + + /** + * Value of $child->type, used to determine which ChildDef to use, + * used in combination with $content_model. + * @warning This must be lowercase + * @warning This is a temporary variable that is not available after + * being processed by HTMLDefinition + * @type string + */ + public $content_model_type; + + /** + * Does the element have a content model (#PCDATA | Inline)*? This + * is important for chameleon ins and del processing in + * HTMLPurifier_ChildDef_Chameleon. Dynamically set: modules don't + * have to worry about this one. + * @type bool + */ + public $descendants_are_inline = false; + + /** + * List of the names of required attributes this element has. + * Dynamically populated by HTMLPurifier_HTMLDefinition::getElement() + * @type array + */ + public $required_attr = array(); + + /** + * Lookup table of tags excluded from all descendants of this tag. + * @type array + * @note SGML permits exclusions for all descendants, but this is + * not possible with DTDs or XML Schemas. W3C has elected to + * use complicated compositions of content_models to simulate + * exclusion for children, but we go the simpler, SGML-style + * route of flat-out exclusions, which correctly apply to + * all descendants and not just children. Note that the XHTML + * Modularization Abstract Modules are blithely unaware of such + * distinctions. + */ + public $excludes = array(); + + /** + * This tag is explicitly auto-closed by the following tags. + * @type array + */ + public $autoclose = array(); + + /** + * If a foreign element is found in this element, test if it is + * allowed by this sub-element; if it is, instead of closing the + * current element, place it inside this element. + * @type string + */ + public $wrap; + + /** + * Whether or not this is a formatting element affected by the + * "Active Formatting Elements" algorithm. + * @type bool + */ + public $formatting; + + /** + * Low-level factory constructor for creating new standalone element defs + */ + public static function create($content_model, $content_model_type, $attr) + { + $def = new HTMLPurifier_ElementDef(); + $def->content_model = $content_model; + $def->content_model_type = $content_model_type; + $def->attr = $attr; + return $def; + } + + /** + * Merges the values of another element definition into this one. + * Values from the new element def take precedence if a value is + * not mergeable. + * @param HTMLPurifier_ElementDef $def + */ + public function mergeIn($def) + { + // later keys takes precedence + foreach ($def->attr as $k => $v) { + if ($k === 0) { + // merge in the includes + // sorry, no way to override an include + foreach ($v as $v2) { + $this->attr[0][] = $v2; + } + continue; + } + if ($v === false) { + if (isset($this->attr[$k])) { + unset($this->attr[$k]); + } + continue; + } + $this->attr[$k] = $v; + } + $this->_mergeAssocArray($this->excludes, $def->excludes); + $this->attr_transform_pre = array_merge($this->attr_transform_pre, $def->attr_transform_pre); + $this->attr_transform_post = array_merge($this->attr_transform_post, $def->attr_transform_post); + + if (!empty($def->content_model)) { + $this->content_model = + str_replace("#SUPER", $this->content_model, $def->content_model); + $this->child = false; + } + if (!empty($def->content_model_type)) { + $this->content_model_type = $def->content_model_type; + $this->child = false; + } + if (!is_null($def->child)) { + $this->child = $def->child; + } + if (!is_null($def->formatting)) { + $this->formatting = $def->formatting; + } + if ($def->descendants_are_inline) { + $this->descendants_are_inline = $def->descendants_are_inline; + } + } + + /** + * Merges one array into another, removes values which equal false + * @param $a1 Array by reference that is merged into + * @param $a2 Array that merges into $a1 + */ + private function _mergeAssocArray(&$a1, $a2) + { + foreach ($a2 as $k => $v) { + if ($v === false) { + if (isset($a1[$k])) { + unset($a1[$k]); + } + continue; + } + $a1[$k] = $v; + } + } +} + + + + + +/** + * A UTF-8 specific character encoder that handles cleaning and transforming. + * @note All functions in this class should be static. + */ +class HTMLPurifier_Encoder +{ + + /** + * Constructor throws fatal error if you attempt to instantiate class + */ + private function __construct() + { + trigger_error('Cannot instantiate encoder, call methods statically', E_USER_ERROR); + } + + /** + * Error-handler that mutes errors, alternative to shut-up operator. + */ + public static function muteErrorHandler() + { + } + + /** + * iconv wrapper which mutes errors, but doesn't work around bugs. + * @param string $in Input encoding + * @param string $out Output encoding + * @param string $text The text to convert + * @return string + */ + public static function unsafeIconv($in, $out, $text) + { + set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler')); + $r = iconv($in, $out, $text); + restore_error_handler(); + return $r; + } + + /** + * iconv wrapper which mutes errors and works around bugs. + * @param string $in Input encoding + * @param string $out Output encoding + * @param string $text The text to convert + * @param int $max_chunk_size + * @return string + */ + public static function iconv($in, $out, $text, $max_chunk_size = 8000) + { + $code = self::testIconvTruncateBug(); + if ($code == self::ICONV_OK) { + return self::unsafeIconv($in, $out, $text); + } elseif ($code == self::ICONV_TRUNCATES) { + // we can only work around this if the input character set + // is utf-8 + if ($in == 'utf-8') { + if ($max_chunk_size < 4) { + trigger_error('max_chunk_size is too small', E_USER_WARNING); + return false; + } + // split into 8000 byte chunks, but be careful to handle + // multibyte boundaries properly + if (($c = strlen($text)) <= $max_chunk_size) { + return self::unsafeIconv($in, $out, $text); + } + $r = ''; + $i = 0; + while (true) { + if ($i + $max_chunk_size >= $c) { + $r .= self::unsafeIconv($in, $out, substr($text, $i)); + break; + } + // wibble the boundary + if (0x80 != (0xC0 & ord($text[$i + $max_chunk_size]))) { + $chunk_size = $max_chunk_size; + } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 1]))) { + $chunk_size = $max_chunk_size - 1; + } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 2]))) { + $chunk_size = $max_chunk_size - 2; + } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 3]))) { + $chunk_size = $max_chunk_size - 3; + } else { + return false; // rather confusing UTF-8... + } + $chunk = substr($text, $i, $chunk_size); // substr doesn't mind overlong lengths + $r .= self::unsafeIconv($in, $out, $chunk); + $i += $chunk_size; + } + return $r; + } else { + return false; + } + } else { + return false; + } + } + + /** + * Cleans a UTF-8 string for well-formedness and SGML validity + * + * It will parse according to UTF-8 and return a valid UTF8 string, with + * non-SGML codepoints excluded. + * + * Specifically, it will permit: + * \x{9}\x{A}\x{D}\x{20}-\x{7E}\x{A0}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF} + * Source: https://www.w3.org/TR/REC-xml/#NT-Char + * Arguably this function should be modernized to the HTML5 set + * of allowed characters: + * https://www.w3.org/TR/html5/syntax.html#preprocessing-the-input-stream + * which simultaneously expand and restrict the set of allowed characters. + * + * @param string $str The string to clean + * @param bool $force_php + * @return string + * + * @note Just for reference, the non-SGML code points are 0 to 31 and + * 127 to 159, inclusive. However, we allow code points 9, 10 + * and 13, which are the tab, line feed and carriage return + * respectively. 128 and above the code points map to multibyte + * UTF-8 representations. + * + * @note Fallback code adapted from utf8ToUnicode by Henri Sivonen and + * hsivonen@iki.fi at under the + * LGPL license. Notes on what changed are inside, but in general, + * the original code transformed UTF-8 text into an array of integer + * Unicode codepoints. Understandably, transforming that back to + * a string would be somewhat expensive, so the function was modded to + * directly operate on the string. However, this discourages code + * reuse, and the logic enumerated here would be useful for any + * function that needs to be able to understand UTF-8 characters. + * As of right now, only smart lossless character encoding converters + * would need that, and I'm probably not going to implement them. + */ + public static function cleanUTF8($str, $force_php = false) + { + // UTF-8 validity is checked since PHP 4.3.5 + // This is an optimization: if the string is already valid UTF-8, no + // need to do PHP stuff. 99% of the time, this will be the case. + if (preg_match( + '/^[\x{9}\x{A}\x{D}\x{20}-\x{7E}\x{A0}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]*$/Du', + $str + )) { + return $str; + } + + $mState = 0; // cached expected number of octets after the current octet + // until the beginning of the next UTF8 character sequence + $mUcs4 = 0; // cached Unicode character + $mBytes = 1; // cached expected number of octets in the current sequence + + // original code involved an $out that was an array of Unicode + // codepoints. Instead of having to convert back into UTF-8, we've + // decided to directly append valid UTF-8 characters onto a string + // $out once they're done. $char accumulates raw bytes, while $mUcs4 + // turns into the Unicode code point, so there's some redundancy. + + $out = ''; + $char = ''; + + $len = strlen($str); + for ($i = 0; $i < $len; $i++) { + $in = ord($str[$i]); + $char .= $str[$i]; // append byte to char + if (0 == $mState) { + // When mState is zero we expect either a US-ASCII character + // or a multi-octet sequence. + if (0 == (0x80 & ($in))) { + // US-ASCII, pass straight through. + if (($in <= 31 || $in == 127) && + !($in == 9 || $in == 13 || $in == 10) // save \r\t\n + ) { + // control characters, remove + } else { + $out .= $char; + } + // reset + $char = ''; + $mBytes = 1; + } elseif (0xC0 == (0xE0 & ($in))) { + // First octet of 2 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x1F) << 6; + $mState = 1; + $mBytes = 2; + } elseif (0xE0 == (0xF0 & ($in))) { + // First octet of 3 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x0F) << 12; + $mState = 2; + $mBytes = 3; + } elseif (0xF0 == (0xF8 & ($in))) { + // First octet of 4 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x07) << 18; + $mState = 3; + $mBytes = 4; + } elseif (0xF8 == (0xFC & ($in))) { + // First octet of 5 octet sequence. + // + // This is illegal because the encoded codepoint must be + // either: + // (a) not the shortest form or + // (b) outside the Unicode range of 0-0x10FFFF. + // Rather than trying to resynchronize, we will carry on + // until the end of the sequence and let the later error + // handling code catch it. + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x03) << 24; + $mState = 4; + $mBytes = 5; + } elseif (0xFC == (0xFE & ($in))) { + // First octet of 6 octet sequence, see comments for 5 + // octet sequence. + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 1) << 30; + $mState = 5; + $mBytes = 6; + } else { + // Current octet is neither in the US-ASCII range nor a + // legal first octet of a multi-octet sequence. + $mState = 0; + $mUcs4 = 0; + $mBytes = 1; + $char = ''; + } + } else { + // When mState is non-zero, we expect a continuation of the + // multi-octet sequence + if (0x80 == (0xC0 & ($in))) { + // Legal continuation. + $shift = ($mState - 1) * 6; + $tmp = $in; + $tmp = ($tmp & 0x0000003F) << $shift; + $mUcs4 |= $tmp; + + if (0 == --$mState) { + // End of the multi-octet sequence. mUcs4 now contains + // the final Unicode codepoint to be output + + // Check for illegal sequences and codepoints. + + // From Unicode 3.1, non-shortest form is illegal + if (((2 == $mBytes) && ($mUcs4 < 0x0080)) || + ((3 == $mBytes) && ($mUcs4 < 0x0800)) || + ((4 == $mBytes) && ($mUcs4 < 0x10000)) || + (4 < $mBytes) || + // From Unicode 3.2, surrogate characters = illegal + (($mUcs4 & 0xFFFFF800) == 0xD800) || + // Codepoints outside the Unicode range are illegal + ($mUcs4 > 0x10FFFF) + ) { + + } elseif (0xFEFF != $mUcs4 && // omit BOM + // check for valid Char unicode codepoints + ( + 0x9 == $mUcs4 || + 0xA == $mUcs4 || + 0xD == $mUcs4 || + (0x20 <= $mUcs4 && 0x7E >= $mUcs4) || + // 7F-9F is not strictly prohibited by XML, + // but it is non-SGML, and thus we don't allow it + (0xA0 <= $mUcs4 && 0xD7FF >= $mUcs4) || + (0xE000 <= $mUcs4 && 0xFFFD >= $mUcs4) || + (0x10000 <= $mUcs4 && 0x10FFFF >= $mUcs4) + ) + ) { + $out .= $char; + } + // initialize UTF8 cache (reset) + $mState = 0; + $mUcs4 = 0; + $mBytes = 1; + $char = ''; + } + } else { + // ((0xC0 & (*in) != 0x80) && (mState != 0)) + // Incomplete multi-octet sequence. + // used to result in complete fail, but we'll reset + $mState = 0; + $mUcs4 = 0; + $mBytes = 1; + $char =''; + } + } + } + return $out; + } + + /** + * Translates a Unicode codepoint into its corresponding UTF-8 character. + * @note Based on Feyd's function at + * , + * which is in public domain. + * @note While we're going to do code point parsing anyway, a good + * optimization would be to refuse to translate code points that + * are non-SGML characters. However, this could lead to duplication. + * @note This is very similar to the unichr function in + * maintenance/generate-entity-file.php (although this is superior, + * due to its sanity checks). + */ + + // +----------+----------+----------+----------+ + // | 33222222 | 22221111 | 111111 | | + // | 10987654 | 32109876 | 54321098 | 76543210 | bit + // +----------+----------+----------+----------+ + // | | | | 0xxxxxxx | 1 byte 0x00000000..0x0000007F + // | | | 110yyyyy | 10xxxxxx | 2 byte 0x00000080..0x000007FF + // | | 1110zzzz | 10yyyyyy | 10xxxxxx | 3 byte 0x00000800..0x0000FFFF + // | 11110www | 10wwzzzz | 10yyyyyy | 10xxxxxx | 4 byte 0x00010000..0x0010FFFF + // +----------+----------+----------+----------+ + // | 00000000 | 00011111 | 11111111 | 11111111 | Theoretical upper limit of legal scalars: 2097151 (0x001FFFFF) + // | 00000000 | 00010000 | 11111111 | 11111111 | Defined upper limit of legal scalar codes + // +----------+----------+----------+----------+ + + public static function unichr($code) + { + if ($code > 1114111 or $code < 0 or + ($code >= 55296 and $code <= 57343) ) { + // bits are set outside the "valid" range as defined + // by UNICODE 4.1.0 + return ''; + } + + $x = $y = $z = $w = 0; + if ($code < 128) { + // regular ASCII character + $x = $code; + } else { + // set up bits for UTF-8 + $x = ($code & 63) | 128; + if ($code < 2048) { + $y = (($code & 2047) >> 6) | 192; + } else { + $y = (($code & 4032) >> 6) | 128; + if ($code < 65536) { + $z = (($code >> 12) & 15) | 224; + } else { + $z = (($code >> 12) & 63) | 128; + $w = (($code >> 18) & 7) | 240; + } + } + } + // set up the actual character + $ret = ''; + if ($w) { + $ret .= chr($w); + } + if ($z) { + $ret .= chr($z); + } + if ($y) { + $ret .= chr($y); + } + $ret .= chr($x); + + return $ret; + } + + /** + * @return bool + */ + public static function iconvAvailable() + { + static $iconv = null; + if ($iconv === null) { + $iconv = function_exists('iconv') && self::testIconvTruncateBug() != self::ICONV_UNUSABLE; + } + return $iconv; + } + + /** + * Convert a string to UTF-8 based on configuration. + * @param string $str The string to convert + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + */ + public static function convertToUTF8($str, $config, $context) + { + $encoding = $config->get('Core.Encoding'); + if ($encoding === 'utf-8') { + return $str; + } + static $iconv = null; + if ($iconv === null) { + $iconv = self::iconvAvailable(); + } + if ($iconv && !$config->get('Test.ForceNoIconv')) { + // unaffected by bugs, since UTF-8 support all characters + $str = self::unsafeIconv($encoding, 'utf-8//IGNORE', $str); + if ($str === false) { + // $encoding is not a valid encoding + trigger_error('Invalid encoding ' . $encoding, E_USER_ERROR); + return ''; + } + // If the string is bjorked by Shift_JIS or a similar encoding + // that doesn't support all of ASCII, convert the naughty + // characters to their true byte-wise ASCII/UTF-8 equivalents. + $str = strtr($str, self::testEncodingSupportsASCII($encoding)); + return $str; + } elseif ($encoding === 'iso-8859-1') { + $str = utf8_encode($str); + return $str; + } + $bug = HTMLPurifier_Encoder::testIconvTruncateBug(); + if ($bug == self::ICONV_OK) { + trigger_error('Encoding not supported, please install iconv', E_USER_ERROR); + } else { + trigger_error( + 'You have a buggy version of iconv, see https://bugs.php.net/bug.php?id=48147 ' . + 'and http://sourceware.org/bugzilla/show_bug.cgi?id=13541', + E_USER_ERROR + ); + } + } + + /** + * Converts a string from UTF-8 based on configuration. + * @param string $str The string to convert + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + * @note Currently, this is a lossy conversion, with unexpressable + * characters being omitted. + */ + public static function convertFromUTF8($str, $config, $context) + { + $encoding = $config->get('Core.Encoding'); + if ($escape = $config->get('Core.EscapeNonASCIICharacters')) { + $str = self::convertToASCIIDumbLossless($str); + } + if ($encoding === 'utf-8') { + return $str; + } + static $iconv = null; + if ($iconv === null) { + $iconv = self::iconvAvailable(); + } + if ($iconv && !$config->get('Test.ForceNoIconv')) { + // Undo our previous fix in convertToUTF8, otherwise iconv will barf + $ascii_fix = self::testEncodingSupportsASCII($encoding); + if (!$escape && !empty($ascii_fix)) { + $clear_fix = array(); + foreach ($ascii_fix as $utf8 => $native) { + $clear_fix[$utf8] = ''; + } + $str = strtr($str, $clear_fix); + } + $str = strtr($str, array_flip($ascii_fix)); + // Normal stuff + $str = self::iconv('utf-8', $encoding . '//IGNORE', $str); + return $str; + } elseif ($encoding === 'iso-8859-1') { + $str = utf8_decode($str); + return $str; + } + trigger_error('Encoding not supported', E_USER_ERROR); + // You might be tempted to assume that the ASCII representation + // might be OK, however, this is *not* universally true over all + // encodings. So we take the conservative route here, rather + // than forcibly turn on %Core.EscapeNonASCIICharacters + } + + /** + * Lossless (character-wise) conversion of HTML to ASCII + * @param string $str UTF-8 string to be converted to ASCII + * @return string ASCII encoded string with non-ASCII character entity-ized + * @warning Adapted from MediaWiki, claiming fair use: this is a common + * algorithm. If you disagree with this license fudgery, + * implement it yourself. + * @note Uses decimal numeric entities since they are best supported. + * @note This is a DUMB function: it has no concept of keeping + * character entities that the projected character encoding + * can allow. We could possibly implement a smart version + * but that would require it to also know which Unicode + * codepoints the charset supported (not an easy task). + * @note Sort of with cleanUTF8() but it assumes that $str is + * well-formed UTF-8 + */ + public static function convertToASCIIDumbLossless($str) + { + $bytesleft = 0; + $result = ''; + $working = 0; + $len = strlen($str); + for ($i = 0; $i < $len; $i++) { + $bytevalue = ord($str[$i]); + if ($bytevalue <= 0x7F) { //0xxx xxxx + $result .= chr($bytevalue); + $bytesleft = 0; + } elseif ($bytevalue <= 0xBF) { //10xx xxxx + $working = $working << 6; + $working += ($bytevalue & 0x3F); + $bytesleft--; + if ($bytesleft <= 0) { + $result .= "&#" . $working . ";"; + } + } elseif ($bytevalue <= 0xDF) { //110x xxxx + $working = $bytevalue & 0x1F; + $bytesleft = 1; + } elseif ($bytevalue <= 0xEF) { //1110 xxxx + $working = $bytevalue & 0x0F; + $bytesleft = 2; + } else { //1111 0xxx + $working = $bytevalue & 0x07; + $bytesleft = 3; + } + } + return $result; + } + + /** No bugs detected in iconv. */ + const ICONV_OK = 0; + + /** Iconv truncates output if converting from UTF-8 to another + * character set with //IGNORE, and a non-encodable character is found */ + const ICONV_TRUNCATES = 1; + + /** Iconv does not support //IGNORE, making it unusable for + * transcoding purposes */ + const ICONV_UNUSABLE = 2; + + /** + * glibc iconv has a known bug where it doesn't handle the magic + * //IGNORE stanza correctly. In particular, rather than ignore + * characters, it will return an EILSEQ after consuming some number + * of characters, and expect you to restart iconv as if it were + * an E2BIG. Old versions of PHP did not respect the errno, and + * returned the fragment, so as a result you would see iconv + * mysteriously truncating output. We can work around this by + * manually chopping our input into segments of about 8000 + * characters, as long as PHP ignores the error code. If PHP starts + * paying attention to the error code, iconv becomes unusable. + * + * @return int Error code indicating severity of bug. + */ + public static function testIconvTruncateBug() + { + static $code = null; + if ($code === null) { + // better not use iconv, otherwise infinite loop! + $r = self::unsafeIconv('utf-8', 'ascii//IGNORE', "\xCE\xB1" . str_repeat('a', 9000)); + if ($r === false) { + $code = self::ICONV_UNUSABLE; + } elseif (($c = strlen($r)) < 9000) { + $code = self::ICONV_TRUNCATES; + } elseif ($c > 9000) { + trigger_error( + 'Your copy of iconv is extremely buggy. Please notify HTML Purifier maintainers: ' . + 'include your iconv version as per phpversion()', + E_USER_ERROR + ); + } else { + $code = self::ICONV_OK; + } + } + return $code; + } + + /** + * This expensive function tests whether or not a given character + * encoding supports ASCII. 7/8-bit encodings like Shift_JIS will + * fail this test, and require special processing. Variable width + * encodings shouldn't ever fail. + * + * @param string $encoding Encoding name to test, as per iconv format + * @param bool $bypass Whether or not to bypass the precompiled arrays. + * @return Array of UTF-8 characters to their corresponding ASCII, + * which can be used to "undo" any overzealous iconv action. + */ + public static function testEncodingSupportsASCII($encoding, $bypass = false) + { + // All calls to iconv here are unsafe, proof by case analysis: + // If ICONV_OK, no difference. + // If ICONV_TRUNCATE, all calls involve one character inputs, + // so bug is not triggered. + // If ICONV_UNUSABLE, this call is irrelevant + static $encodings = array(); + if (!$bypass) { + if (isset($encodings[$encoding])) { + return $encodings[$encoding]; + } + $lenc = strtolower($encoding); + switch ($lenc) { + case 'shift_jis': + return array("\xC2\xA5" => '\\', "\xE2\x80\xBE" => '~'); + case 'johab': + return array("\xE2\x82\xA9" => '\\'); + } + if (strpos($lenc, 'iso-8859-') === 0) { + return array(); + } + } + $ret = array(); + if (self::unsafeIconv('UTF-8', $encoding, 'a') === false) { + return false; + } + for ($i = 0x20; $i <= 0x7E; $i++) { // all printable ASCII chars + $c = chr($i); // UTF-8 char + $r = self::unsafeIconv('UTF-8', "$encoding//IGNORE", $c); // initial conversion + if ($r === '' || + // This line is needed for iconv implementations that do not + // omit characters that do not exist in the target character set + ($r === $c && self::unsafeIconv($encoding, 'UTF-8//IGNORE', $r) !== $c) + ) { + // Reverse engineer: what's the UTF-8 equiv of this byte + // sequence? This assumes that there's no variable width + // encoding that doesn't support ASCII. + $ret[self::unsafeIconv($encoding, 'UTF-8//IGNORE', $c)] = $c; + } + } + $encodings[$encoding] = $ret; + return $ret; + } +} + + + + + +/** + * Object that provides entity lookup table from entity name to character + */ +class HTMLPurifier_EntityLookup +{ + /** + * Assoc array of entity name to character represented. + * @type array + */ + public $table; + + /** + * Sets up the entity lookup table from the serialized file contents. + * @param bool $file + * @note The serialized contents are versioned, but were generated + * using the maintenance script generate_entity_file.php + * @warning This is not in constructor to help enforce the Singleton + */ + public function setup($file = false) + { + if (!$file) { + $file = HTMLPURIFIER_PREFIX . '/HTMLPurifier/EntityLookup/entities.ser'; + } + $this->table = unserialize(file_get_contents($file)); + } + + /** + * Retrieves sole instance of the object. + * @param bool|HTMLPurifier_EntityLookup $prototype Optional prototype of custom lookup table to overload with. + * @return HTMLPurifier_EntityLookup + */ + public static function instance($prototype = false) + { + // no references, since PHP doesn't copy unless modified + static $instance = null; + if ($prototype) { + $instance = $prototype; + } elseif (!$instance) { + $instance = new HTMLPurifier_EntityLookup(); + $instance->setup(); + } + return $instance; + } +} + + + + + +// if want to implement error collecting here, we'll need to use some sort +// of global data (probably trigger_error) because it's impossible to pass +// $config or $context to the callback functions. + +/** + * Handles referencing and derefencing character entities + */ +class HTMLPurifier_EntityParser +{ + + /** + * Reference to entity lookup table. + * @type HTMLPurifier_EntityLookup + */ + protected $_entity_lookup; + + /** + * Callback regex string for entities in text. + * @type string + */ + protected $_textEntitiesRegex; + + /** + * Callback regex string for entities in attributes. + * @type string + */ + protected $_attrEntitiesRegex; + + /** + * Tests if the beginning of a string is a semi-optional regex + */ + protected $_semiOptionalPrefixRegex; + + public function __construct() { + // From + // http://stackoverflow.com/questions/15532252/why-is-reg-being-rendered-as-without-the-bounding-semicolon + $semi_optional = "quot|QUOT|lt|LT|gt|GT|amp|AMP|AElig|Aacute|Acirc|Agrave|Aring|Atilde|Auml|COPY|Ccedil|ETH|Eacute|Ecirc|Egrave|Euml|Iacute|Icirc|Igrave|Iuml|Ntilde|Oacute|Ocirc|Ograve|Oslash|Otilde|Ouml|REG|THORN|Uacute|Ucirc|Ugrave|Uuml|Yacute|aacute|acirc|acute|aelig|agrave|aring|atilde|auml|brvbar|ccedil|cedil|cent|copy|curren|deg|divide|eacute|ecirc|egrave|eth|euml|frac12|frac14|frac34|iacute|icirc|iexcl|igrave|iquest|iuml|laquo|macr|micro|middot|nbsp|not|ntilde|oacute|ocirc|ograve|ordf|ordm|oslash|otilde|ouml|para|plusmn|pound|raquo|reg|sect|shy|sup1|sup2|sup3|szlig|thorn|times|uacute|ucirc|ugrave|uml|uuml|yacute|yen|yuml"; + + // NB: three empty captures to put the fourth match in the right + // place + $this->_semiOptionalPrefixRegex = "/&()()()($semi_optional)/"; + + $this->_textEntitiesRegex = + '/&(?:'. + // hex + '[#]x([a-fA-F0-9]+);?|'. + // dec + '[#]0*(\d+);?|'. + // string (mandatory semicolon) + // NB: order matters: match semicolon preferentially + '([A-Za-z_:][A-Za-z0-9.\-_:]*);|'. + // string (optional semicolon) + "($semi_optional)". + ')/'; + + $this->_attrEntitiesRegex = + '/&(?:'. + // hex + '[#]x([a-fA-F0-9]+);?|'. + // dec + '[#]0*(\d+);?|'. + // string (mandatory semicolon) + // NB: order matters: match semicolon preferentially + '([A-Za-z_:][A-Za-z0-9.\-_:]*);|'. + // string (optional semicolon) + // don't match if trailing is equals or alphanumeric (URL + // like) + "($semi_optional)(?![=;A-Za-z0-9])". + ')/'; + + } + + /** + * Substitute entities with the parsed equivalents. Use this on + * textual data in an HTML document (as opposed to attributes.) + * + * @param string $string String to have entities parsed. + * @return string Parsed string. + */ + public function substituteTextEntities($string) + { + return preg_replace_callback( + $this->_textEntitiesRegex, + array($this, 'entityCallback'), + $string + ); + } + + /** + * Substitute entities with the parsed equivalents. Use this on + * attribute contents in documents. + * + * @param string $string String to have entities parsed. + * @return string Parsed string. + */ + public function substituteAttrEntities($string) + { + return preg_replace_callback( + $this->_attrEntitiesRegex, + array($this, 'entityCallback'), + $string + ); + } + + /** + * Callback function for substituteNonSpecialEntities() that does the work. + * + * @param array $matches PCRE matches array, with 0 the entire match, and + * either index 1, 2 or 3 set with a hex value, dec value, + * or string (respectively). + * @return string Replacement string. + */ + + protected function entityCallback($matches) + { + $entity = $matches[0]; + $hex_part = @$matches[1]; + $dec_part = @$matches[2]; + $named_part = empty($matches[3]) ? (empty($matches[4]) ? "" : $matches[4]) : $matches[3]; + if ($hex_part !== NULL && $hex_part !== "") { + return HTMLPurifier_Encoder::unichr(hexdec($hex_part)); + } elseif ($dec_part !== NULL && $dec_part !== "") { + return HTMLPurifier_Encoder::unichr((int) $dec_part); + } else { + if (!$this->_entity_lookup) { + $this->_entity_lookup = HTMLPurifier_EntityLookup::instance(); + } + if (isset($this->_entity_lookup->table[$named_part])) { + return $this->_entity_lookup->table[$named_part]; + } else { + // exact match didn't match anything, so test if + // any of the semicolon optional match the prefix. + // Test that this is an EXACT match is important to + // prevent infinite loop + if (!empty($matches[3])) { + return preg_replace_callback( + $this->_semiOptionalPrefixRegex, + array($this, 'entityCallback'), + $entity + ); + } + return $entity; + } + } + } + + // LEGACY CODE BELOW + + /** + * Callback regex string for parsing entities. + * @type string + */ + protected $_substituteEntitiesRegex = + '/&(?:[#]x([a-fA-F0-9]+)|[#]0*(\d+)|([A-Za-z_:][A-Za-z0-9.\-_:]*));?/'; + // 1. hex 2. dec 3. string (XML style) + + /** + * Decimal to parsed string conversion table for special entities. + * @type array + */ + protected $_special_dec2str = + array( + 34 => '"', + 38 => '&', + 39 => "'", + 60 => '<', + 62 => '>' + ); + + /** + * Stripped entity names to decimal conversion table for special entities. + * @type array + */ + protected $_special_ent2dec = + array( + 'quot' => 34, + 'amp' => 38, + 'lt' => 60, + 'gt' => 62 + ); + + /** + * Substitutes non-special entities with their parsed equivalents. Since + * running this whenever you have parsed character is t3h 5uck, we run + * it before everything else. + * + * @param string $string String to have non-special entities parsed. + * @return string Parsed string. + */ + public function substituteNonSpecialEntities($string) + { + // it will try to detect missing semicolons, but don't rely on it + return preg_replace_callback( + $this->_substituteEntitiesRegex, + array($this, 'nonSpecialEntityCallback'), + $string + ); + } + + /** + * Callback function for substituteNonSpecialEntities() that does the work. + * + * @param array $matches PCRE matches array, with 0 the entire match, and + * either index 1, 2 or 3 set with a hex value, dec value, + * or string (respectively). + * @return string Replacement string. + */ + + protected function nonSpecialEntityCallback($matches) + { + // replaces all but big five + $entity = $matches[0]; + $is_num = (@$matches[0][1] === '#'); + if ($is_num) { + $is_hex = (@$entity[2] === 'x'); + $code = $is_hex ? hexdec($matches[1]) : (int) $matches[2]; + // abort for special characters + if (isset($this->_special_dec2str[$code])) { + return $entity; + } + return HTMLPurifier_Encoder::unichr($code); + } else { + if (isset($this->_special_ent2dec[$matches[3]])) { + return $entity; + } + if (!$this->_entity_lookup) { + $this->_entity_lookup = HTMLPurifier_EntityLookup::instance(); + } + if (isset($this->_entity_lookup->table[$matches[3]])) { + return $this->_entity_lookup->table[$matches[3]]; + } else { + return $entity; + } + } + } + + /** + * Substitutes only special entities with their parsed equivalents. + * + * @notice We try to avoid calling this function because otherwise, it + * would have to be called a lot (for every parsed section). + * + * @param string $string String to have non-special entities parsed. + * @return string Parsed string. + */ + public function substituteSpecialEntities($string) + { + return preg_replace_callback( + $this->_substituteEntitiesRegex, + array($this, 'specialEntityCallback'), + $string + ); + } + + /** + * Callback function for substituteSpecialEntities() that does the work. + * + * This callback has same syntax as nonSpecialEntityCallback(). + * + * @param array $matches PCRE-style matches array, with 0 the entire match, and + * either index 1, 2 or 3 set with a hex value, dec value, + * or string (respectively). + * @return string Replacement string. + */ + protected function specialEntityCallback($matches) + { + $entity = $matches[0]; + $is_num = (@$matches[0][1] === '#'); + if ($is_num) { + $is_hex = (@$entity[2] === 'x'); + $int = $is_hex ? hexdec($matches[1]) : (int) $matches[2]; + return isset($this->_special_dec2str[$int]) ? + $this->_special_dec2str[$int] : + $entity; + } else { + return isset($this->_special_ent2dec[$matches[3]]) ? + $this->_special_dec2str[$this->_special_ent2dec[$matches[3]]] : + $entity; + } + } +} + + + + + +/** + * Error collection class that enables HTML Purifier to report HTML + * problems back to the user + */ +class HTMLPurifier_ErrorCollector +{ + + /** + * Identifiers for the returned error array. These are purposely numeric + * so list() can be used. + */ + const LINENO = 0; + const SEVERITY = 1; + const MESSAGE = 2; + const CHILDREN = 3; + + /** + * @type array + */ + protected $errors; + + /** + * @type array + */ + protected $_current; + + /** + * @type array + */ + protected $_stacks = array(array()); + + /** + * @type HTMLPurifier_Language + */ + protected $locale; + + /** + * @type HTMLPurifier_Generator + */ + protected $generator; + + /** + * @type HTMLPurifier_Context + */ + protected $context; + + /** + * @type array + */ + protected $lines = array(); + + /** + * @param HTMLPurifier_Context $context + */ + public function __construct($context) + { + $this->locale =& $context->get('Locale'); + $this->context = $context; + $this->_current =& $this->_stacks[0]; + $this->errors =& $this->_stacks[0]; + } + + /** + * Sends an error message to the collector for later use + * @param int $severity Error severity, PHP error style (don't use E_USER_) + * @param string $msg Error message text + */ + public function send($severity, $msg) + { + $args = array(); + if (func_num_args() > 2) { + $args = func_get_args(); + array_shift($args); + unset($args[0]); + } + + $token = $this->context->get('CurrentToken', true); + $line = $token ? $token->line : $this->context->get('CurrentLine', true); + $col = $token ? $token->col : $this->context->get('CurrentCol', true); + $attr = $this->context->get('CurrentAttr', true); + + // perform special substitutions, also add custom parameters + $subst = array(); + if (!is_null($token)) { + $args['CurrentToken'] = $token; + } + if (!is_null($attr)) { + $subst['$CurrentAttr.Name'] = $attr; + if (isset($token->attr[$attr])) { + $subst['$CurrentAttr.Value'] = $token->attr[$attr]; + } + } + + if (empty($args)) { + $msg = $this->locale->getMessage($msg); + } else { + $msg = $this->locale->formatMessage($msg, $args); + } + + if (!empty($subst)) { + $msg = strtr($msg, $subst); + } + + // (numerically indexed) + $error = array( + self::LINENO => $line, + self::SEVERITY => $severity, + self::MESSAGE => $msg, + self::CHILDREN => array() + ); + $this->_current[] = $error; + + // NEW CODE BELOW ... + // Top-level errors are either: + // TOKEN type, if $value is set appropriately, or + // "syntax" type, if $value is null + $new_struct = new HTMLPurifier_ErrorStruct(); + $new_struct->type = HTMLPurifier_ErrorStruct::TOKEN; + if ($token) { + $new_struct->value = clone $token; + } + if (is_int($line) && is_int($col)) { + if (isset($this->lines[$line][$col])) { + $struct = $this->lines[$line][$col]; + } else { + $struct = $this->lines[$line][$col] = $new_struct; + } + // These ksorts may present a performance problem + ksort($this->lines[$line], SORT_NUMERIC); + } else { + if (isset($this->lines[-1])) { + $struct = $this->lines[-1]; + } else { + $struct = $this->lines[-1] = $new_struct; + } + } + ksort($this->lines, SORT_NUMERIC); + + // Now, check if we need to operate on a lower structure + if (!empty($attr)) { + $struct = $struct->getChild(HTMLPurifier_ErrorStruct::ATTR, $attr); + if (!$struct->value) { + $struct->value = array($attr, 'PUT VALUE HERE'); + } + } + if (!empty($cssprop)) { + $struct = $struct->getChild(HTMLPurifier_ErrorStruct::CSSPROP, $cssprop); + if (!$struct->value) { + // if we tokenize CSS this might be a little more difficult to do + $struct->value = array($cssprop, 'PUT VALUE HERE'); + } + } + + // Ok, structs are all setup, now time to register the error + $struct->addError($severity, $msg); + } + + /** + * Retrieves raw error data for custom formatter to use + */ + public function getRaw() + { + return $this->errors; + } + + /** + * Default HTML formatting implementation for error messages + * @param HTMLPurifier_Config $config Configuration, vital for HTML output nature + * @param array $errors Errors array to display; used for recursion. + * @return string + */ + public function getHTMLFormatted($config, $errors = null) + { + $ret = array(); + + $this->generator = new HTMLPurifier_Generator($config, $this->context); + if ($errors === null) { + $errors = $this->errors; + } + + // 'At line' message needs to be removed + + // generation code for new structure goes here. It needs to be recursive. + foreach ($this->lines as $line => $col_array) { + if ($line == -1) { + continue; + } + foreach ($col_array as $col => $struct) { + $this->_renderStruct($ret, $struct, $line, $col); + } + } + if (isset($this->lines[-1])) { + $this->_renderStruct($ret, $this->lines[-1]); + } + + if (empty($errors)) { + return '

    ' . $this->locale->getMessage('ErrorCollector: No errors') . '

    '; + } else { + return '
    • ' . implode('
    • ', $ret) . '
    '; + } + + } + + private function _renderStruct(&$ret, $struct, $line = null, $col = null) + { + $stack = array($struct); + $context_stack = array(array()); + while ($current = array_pop($stack)) { + $context = array_pop($context_stack); + foreach ($current->errors as $error) { + list($severity, $msg) = $error; + $string = ''; + $string .= '
    '; + // W3C uses an icon to indicate the severity of the error. + $error = $this->locale->getErrorName($severity); + $string .= "$error "; + if (!is_null($line) && !is_null($col)) { + $string .= "Line $line, Column $col: "; + } else { + $string .= 'End of Document: '; + } + $string .= '' . $this->generator->escape($msg) . ' '; + $string .= '
    '; + // Here, have a marker for the character on the column appropriate. + // Be sure to clip extremely long lines. + //$string .= '
    ';
    +                //$string .= '';
    +                //$string .= '
    '; + $ret[] = $string; + } + foreach ($current->children as $array) { + $context[] = $current; + $stack = array_merge($stack, array_reverse($array, true)); + for ($i = count($array); $i > 0; $i--) { + $context_stack[] = $context; + } + } + } + } +} + + + + + +/** + * Records errors for particular segments of an HTML document such as tokens, + * attributes or CSS properties. They can contain error structs (which apply + * to components of what they represent), but their main purpose is to hold + * errors applying to whatever struct is being used. + */ +class HTMLPurifier_ErrorStruct +{ + + /** + * Possible values for $children first-key. Note that top-level structures + * are automatically token-level. + */ + const TOKEN = 0; + const ATTR = 1; + const CSSPROP = 2; + + /** + * Type of this struct. + * @type string + */ + public $type; + + /** + * Value of the struct we are recording errors for. There are various + * values for this: + * - TOKEN: Instance of HTMLPurifier_Token + * - ATTR: array('attr-name', 'value') + * - CSSPROP: array('prop-name', 'value') + * @type mixed + */ + public $value; + + /** + * Errors registered for this structure. + * @type array + */ + public $errors = array(); + + /** + * Child ErrorStructs that are from this structure. For example, a TOKEN + * ErrorStruct would contain ATTR ErrorStructs. This is a multi-dimensional + * array in structure: [TYPE]['identifier'] + * @type array + */ + public $children = array(); + + /** + * @param string $type + * @param string $id + * @return mixed + */ + public function getChild($type, $id) + { + if (!isset($this->children[$type][$id])) { + $this->children[$type][$id] = new HTMLPurifier_ErrorStruct(); + $this->children[$type][$id]->type = $type; + } + return $this->children[$type][$id]; + } + + /** + * @param int $severity + * @param string $message + */ + public function addError($severity, $message) + { + $this->errors[] = array($severity, $message); + } +} + + + + + +/** + * Global exception class for HTML Purifier; any exceptions we throw + * are from here. + */ +class HTMLPurifier_Exception extends Exception +{ + +} + + + + + +/** + * Represents a pre or post processing filter on HTML Purifier's output + * + * Sometimes, a little ad-hoc fixing of HTML has to be done before + * it gets sent through HTML Purifier: you can use filters to acheive + * this effect. For instance, YouTube videos can be preserved using + * this manner. You could have used a decorator for this task, but + * PHP's support for them is not terribly robust, so we're going + * to just loop through the filters. + * + * Filters should be exited first in, last out. If there are three filters, + * named 1, 2 and 3, the order of execution should go 1->preFilter, + * 2->preFilter, 3->preFilter, purify, 3->postFilter, 2->postFilter, + * 1->postFilter. + * + * @note Methods are not declared abstract as it is perfectly legitimate + * for an implementation not to want anything to happen on a step + */ + +class HTMLPurifier_Filter +{ + + /** + * Name of the filter for identification purposes. + * @type string + */ + public $name; + + /** + * Pre-processor function, handles HTML before HTML Purifier + * @param string $html + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + */ + public function preFilter($html, $config, $context) + { + return $html; + } + + /** + * Post-processor function, handles HTML after HTML Purifier + * @param string $html + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + */ + public function postFilter($html, $config, $context) + { + return $html; + } +} + + + + + +/** + * Generates HTML from tokens. + * @todo Refactor interface so that configuration/context is determined + * upon instantiation, no need for messy generateFromTokens() calls + * @todo Make some of the more internal functions protected, and have + * unit tests work around that + */ +class HTMLPurifier_Generator +{ + + /** + * Whether or not generator should produce XML output. + * @type bool + */ + private $_xhtml = true; + + /** + * :HACK: Whether or not generator should comment the insides of #i', '', $html); + } + + return $html; + } + + /** + * Takes a string of HTML (fragment or document) and returns the content + * @todo Consider making protected + */ + public function extractBody($html) + { + $matches = array(); + $result = preg_match('|(.*?)]*>(.*)|is', $html, $matches); + if ($result) { + // Make sure it's not in a comment + $comment_start = strrpos($matches[1], ''); + if ($comment_start === false || + ($comment_end !== false && $comment_end > $comment_start)) { + return $matches[2]; + } + } + return $html; + } +} + + + + + +/** + * Abstract base node class that all others inherit from. + * + * Why do we not use the DOM extension? (1) It is not always available, + * (2) it has funny constraints on the data it can represent, + * whereas we want a maximally flexible representation, and (3) its + * interface is a bit cumbersome. + */ +abstract class HTMLPurifier_Node +{ + /** + * Line number of the start token in the source document + * @type int + */ + public $line; + + /** + * Column number of the start token in the source document. Null if unknown. + * @type int + */ + public $col; + + /** + * Lookup array of processing that this token is exempt from. + * Currently, valid values are "ValidateAttributes". + * @type array + */ + public $armor = array(); + + /** + * When true, this node should be ignored as non-existent. + * + * Who is responsible for ignoring dead nodes? FixNesting is + * responsible for removing them before passing on to child + * validators. + */ + public $dead = false; + + /** + * Returns a pair of start and end tokens, where the end token + * is null if it is not necessary. Does not include children. + * @type array + */ + abstract public function toTokenPair(); +} + + + + + +/** + * Class that handles operations involving percent-encoding in URIs. + * + * @warning + * Be careful when reusing instances of PercentEncoder. The object + * you use for normalize() SHOULD NOT be used for encode(), or + * vice-versa. + */ +class HTMLPurifier_PercentEncoder +{ + + /** + * Reserved characters to preserve when using encode(). + * @type array + */ + protected $preserve = array(); + + /** + * String of characters that should be preserved while using encode(). + * @param bool $preserve + */ + public function __construct($preserve = false) + { + // unreserved letters, ought to const-ify + for ($i = 48; $i <= 57; $i++) { // digits + $this->preserve[$i] = true; + } + for ($i = 65; $i <= 90; $i++) { // upper-case + $this->preserve[$i] = true; + } + for ($i = 97; $i <= 122; $i++) { // lower-case + $this->preserve[$i] = true; + } + $this->preserve[45] = true; // Dash - + $this->preserve[46] = true; // Period . + $this->preserve[95] = true; // Underscore _ + $this->preserve[126]= true; // Tilde ~ + + // extra letters not to escape + if ($preserve !== false) { + for ($i = 0, $c = strlen($preserve); $i < $c; $i++) { + $this->preserve[ord($preserve[$i])] = true; + } + } + } + + /** + * Our replacement for urlencode, it encodes all non-reserved characters, + * as well as any extra characters that were instructed to be preserved. + * @note + * Assumes that the string has already been normalized, making any + * and all percent escape sequences valid. Percents will not be + * re-escaped, regardless of their status in $preserve + * @param string $string String to be encoded + * @return string Encoded string. + */ + public function encode($string) + { + $ret = ''; + for ($i = 0, $c = strlen($string); $i < $c; $i++) { + if ($string[$i] !== '%' && !isset($this->preserve[$int = ord($string[$i])])) { + $ret .= '%' . sprintf('%02X', $int); + } else { + $ret .= $string[$i]; + } + } + return $ret; + } + + /** + * Fix up percent-encoding by decoding unreserved characters and normalizing. + * @warning This function is affected by $preserve, even though the + * usual desired behavior is for this not to preserve those + * characters. Be careful when reusing instances of PercentEncoder! + * @param string $string String to normalize + * @return string + */ + public function normalize($string) + { + if ($string == '') { + return ''; + } + $parts = explode('%', $string); + $ret = array_shift($parts); + foreach ($parts as $part) { + $length = strlen($part); + if ($length < 2) { + $ret .= '%25' . $part; + continue; + } + $encoding = substr($part, 0, 2); + $text = substr($part, 2); + if (!ctype_xdigit($encoding)) { + $ret .= '%25' . $part; + continue; + } + $int = hexdec($encoding); + if (isset($this->preserve[$int])) { + $ret .= chr($int) . $text; + continue; + } + $encoding = strtoupper($encoding); + $ret .= '%' . $encoding . $text; + } + return $ret; + } +} + + + + + +/** + * Generic property list implementation + */ +class HTMLPurifier_PropertyList +{ + /** + * Internal data-structure for properties. + * @type array + */ + protected $data = array(); + + /** + * Parent plist. + * @type HTMLPurifier_PropertyList + */ + protected $parent; + + /** + * Cache. + * @type array + */ + protected $cache; + + /** + * @param HTMLPurifier_PropertyList $parent Parent plist + */ + public function __construct($parent = null) + { + $this->parent = $parent; + } + + /** + * Recursively retrieves the value for a key + * @param string $name + * @throws HTMLPurifier_Exception + */ + public function get($name) + { + if ($this->has($name)) { + return $this->data[$name]; + } + // possible performance bottleneck, convert to iterative if necessary + if ($this->parent) { + return $this->parent->get($name); + } + throw new HTMLPurifier_Exception("Key '$name' not found"); + } + + /** + * Sets the value of a key, for this plist + * @param string $name + * @param mixed $value + */ + public function set($name, $value) + { + $this->data[$name] = $value; + } + + /** + * Returns true if a given key exists + * @param string $name + * @return bool + */ + public function has($name) + { + return array_key_exists($name, $this->data); + } + + /** + * Resets a value to the value of it's parent, usually the default. If + * no value is specified, the entire plist is reset. + * @param string $name + */ + public function reset($name = null) + { + if ($name == null) { + $this->data = array(); + } else { + unset($this->data[$name]); + } + } + + /** + * Squashes this property list and all of its property lists into a single + * array, and returns the array. This value is cached by default. + * @param bool $force If true, ignores the cache and regenerates the array. + * @return array + */ + public function squash($force = false) + { + if ($this->cache !== null && !$force) { + return $this->cache; + } + if ($this->parent) { + return $this->cache = array_merge($this->parent->squash($force), $this->data); + } else { + return $this->cache = $this->data; + } + } + + /** + * Returns the parent plist. + * @return HTMLPurifier_PropertyList + */ + public function getParent() + { + return $this->parent; + } + + /** + * Sets the parent plist. + * @param HTMLPurifier_PropertyList $plist Parent plist + */ + public function setParent($plist) + { + $this->parent = $plist; + } +} + + + + + +/** + * Property list iterator. Do not instantiate this class directly. + */ +class HTMLPurifier_PropertyListIterator extends FilterIterator +{ + + /** + * @type int + */ + protected $l; + /** + * @type string + */ + protected $filter; + + /** + * @param Iterator $iterator Array of data to iterate over + * @param string $filter Optional prefix to only allow values of + */ + public function __construct(Iterator $iterator, $filter = null) + { + parent::__construct($iterator); + $this->l = strlen($filter); + $this->filter = $filter; + } + + /** + * @return bool + */ + public function accept() + { + $key = $this->getInnerIterator()->key(); + if (strncmp($key, $this->filter, $this->l) !== 0) { + return false; + } + return true; + } +} + + + + + +/** + * A simple array-backed queue, based off of the classic Okasaki + * persistent amortized queue. The basic idea is to maintain two + * stacks: an input stack and an output stack. When the output + * stack runs out, reverse the input stack and use it as the output + * stack. + * + * We don't use the SPL implementation because it's only supported + * on PHP 5.3 and later. + * + * Exercise: Prove that push/pop on this queue take amortized O(1) time. + * + * Exercise: Extend this queue to be a deque, while preserving amortized + * O(1) time. Some care must be taken on rebalancing to avoid quadratic + * behaviour caused by repeatedly shuffling data from the input stack + * to the output stack and back. + */ +class HTMLPurifier_Queue { + private $input; + private $output; + + public function __construct($input = array()) { + $this->input = $input; + $this->output = array(); + } + + /** + * Shifts an element off the front of the queue. + */ + public function shift() { + if (empty($this->output)) { + $this->output = array_reverse($this->input); + $this->input = array(); + } + if (empty($this->output)) { + return NULL; + } + return array_pop($this->output); + } + + /** + * Pushes an element onto the front of the queue. + */ + public function push($x) { + array_push($this->input, $x); + } + + /** + * Checks if it's empty. + */ + public function isEmpty() { + return empty($this->input) && empty($this->output); + } +} + + + +/** + * Supertype for classes that define a strategy for modifying/purifying tokens. + * + * While HTMLPurifier's core purpose is fixing HTML into something proper, + * strategies provide plug points for extra configuration or even extra + * features, such as custom tags, custom parsing of text, etc. + */ + + +abstract class HTMLPurifier_Strategy +{ + + /** + * Executes the strategy on the tokens. + * + * @param HTMLPurifier_Token[] $tokens Array of HTMLPurifier_Token objects to be operated on. + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return HTMLPurifier_Token[] Processed array of token objects. + */ + abstract public function execute($tokens, $config, $context); +} + + + + + +/** + * This is in almost every respect equivalent to an array except + * that it keeps track of which keys were accessed. + * + * @warning For the sake of backwards compatibility with early versions + * of PHP 5, you must not use the $hash[$key] syntax; if you do + * our version of offsetGet is never called. + */ +class HTMLPurifier_StringHash extends ArrayObject +{ + /** + * @type array + */ + protected $accessed = array(); + + /** + * Retrieves a value, and logs the access. + * @param mixed $index + * @return mixed + */ + public function offsetGet($index) + { + $this->accessed[$index] = true; + return parent::offsetGet($index); + } + + /** + * Returns a lookup array of all array indexes that have been accessed. + * @return array in form array($index => true). + */ + public function getAccessed() + { + return $this->accessed; + } + + /** + * Resets the access array. + */ + public function resetAccessed() + { + $this->accessed = array(); + } +} + + + + + +/** + * Parses string hash files. File format is as such: + * + * DefaultKeyValue + * KEY: Value + * KEY2: Value2 + * --MULTILINE-KEY-- + * Multiline + * value. + * + * Which would output something similar to: + * + * array( + * 'ID' => 'DefaultKeyValue', + * 'KEY' => 'Value', + * 'KEY2' => 'Value2', + * 'MULTILINE-KEY' => "Multiline\nvalue.\n", + * ) + * + * We use this as an easy to use file-format for configuration schema + * files, but the class itself is usage agnostic. + * + * You can use ---- to forcibly terminate parsing of a single string-hash; + * this marker is used in multi string-hashes to delimit boundaries. + */ +class HTMLPurifier_StringHashParser +{ + + /** + * @type string + */ + public $default = 'ID'; + + /** + * Parses a file that contains a single string-hash. + * @param string $file + * @return array + */ + public function parseFile($file) + { + if (!file_exists($file)) { + return false; + } + $fh = fopen($file, 'r'); + if (!$fh) { + return false; + } + $ret = $this->parseHandle($fh); + fclose($fh); + return $ret; + } + + /** + * Parses a file that contains multiple string-hashes delimited by '----' + * @param string $file + * @return array + */ + public function parseMultiFile($file) + { + if (!file_exists($file)) { + return false; + } + $ret = array(); + $fh = fopen($file, 'r'); + if (!$fh) { + return false; + } + while (!feof($fh)) { + $ret[] = $this->parseHandle($fh); + } + fclose($fh); + return $ret; + } + + /** + * Internal parser that acepts a file handle. + * @note While it's possible to simulate in-memory parsing by using + * custom stream wrappers, if such a use-case arises we should + * factor out the file handle into its own class. + * @param resource $fh File handle with pointer at start of valid string-hash + * block. + * @return array + */ + protected function parseHandle($fh) + { + $state = false; + $single = false; + $ret = array(); + do { + $line = fgets($fh); + if ($line === false) { + break; + } + $line = rtrim($line, "\n\r"); + if (!$state && $line === '') { + continue; + } + if ($line === '----') { + break; + } + if (strncmp('--#', $line, 3) === 0) { + // Comment + continue; + } elseif (strncmp('--', $line, 2) === 0) { + // Multiline declaration + $state = trim($line, '- '); + if (!isset($ret[$state])) { + $ret[$state] = ''; + } + continue; + } elseif (!$state) { + $single = true; + if (strpos($line, ':') !== false) { + // Single-line declaration + list($state, $line) = explode(':', $line, 2); + $line = trim($line); + } else { + // Use default declaration + $state = $this->default; + } + } + if ($single) { + $ret[$state] = $line; + $single = false; + $state = false; + } else { + $ret[$state] .= "$line\n"; + } + } while (!feof($fh)); + return $ret; + } +} + + + + + +/** + * Defines a mutation of an obsolete tag into a valid tag. + */ +abstract class HTMLPurifier_TagTransform +{ + + /** + * Tag name to transform the tag to. + * @type string + */ + public $transform_to; + + /** + * Transforms the obsolete tag into the valid tag. + * @param HTMLPurifier_Token_Tag $tag Tag to be transformed. + * @param HTMLPurifier_Config $config Mandatory HTMLPurifier_Config object + * @param HTMLPurifier_Context $context Mandatory HTMLPurifier_Context object + */ + abstract public function transform($tag, $config, $context); + + /** + * Prepends CSS properties to the style attribute, creating the + * attribute if it doesn't exist. + * @warning Copied over from AttrTransform, be sure to keep in sync + * @param array $attr Attribute array to process (passed by reference) + * @param string $css CSS to prepend + */ + protected function prependCSS(&$attr, $css) + { + $attr['style'] = isset($attr['style']) ? $attr['style'] : ''; + $attr['style'] = $css . $attr['style']; + } +} + + + + + +/** + * Abstract base token class that all others inherit from. + */ +abstract class HTMLPurifier_Token +{ + /** + * Line number node was on in source document. Null if unknown. + * @type int + */ + public $line; + + /** + * Column of line node was on in source document. Null if unknown. + * @type int + */ + public $col; + + /** + * Lookup array of processing that this token is exempt from. + * Currently, valid values are "ValidateAttributes" and + * "MakeWellFormed_TagClosedError" + * @type array + */ + public $armor = array(); + + /** + * Used during MakeWellFormed. See Note [Injector skips] + * @type + */ + public $skip; + + /** + * @type + */ + public $rewind; + + /** + * @type + */ + public $carryover; + + /** + * @param string $n + * @return null|string + */ + public function __get($n) + { + if ($n === 'type') { + trigger_error('Deprecated type property called; use instanceof', E_USER_NOTICE); + switch (get_class($this)) { + case 'HTMLPurifier_Token_Start': + return 'start'; + case 'HTMLPurifier_Token_Empty': + return 'empty'; + case 'HTMLPurifier_Token_End': + return 'end'; + case 'HTMLPurifier_Token_Text': + return 'text'; + case 'HTMLPurifier_Token_Comment': + return 'comment'; + default: + return null; + } + } + } + + /** + * Sets the position of the token in the source document. + * @param int $l + * @param int $c + */ + public function position($l = null, $c = null) + { + $this->line = $l; + $this->col = $c; + } + + /** + * Convenience function for DirectLex settings line/col position. + * @param int $l + * @param int $c + */ + public function rawPosition($l, $c) + { + if ($c === -1) { + $l++; + } + $this->line = $l; + $this->col = $c; + } + + /** + * Converts a token into its corresponding node. + */ + abstract public function toNode(); +} + + + + + +/** + * Factory for token generation. + * + * @note Doing some benchmarking indicates that the new operator is much + * slower than the clone operator (even discounting the cost of the + * constructor). This class is for that optimization. + * Other then that, there's not much point as we don't + * maintain parallel HTMLPurifier_Token hierarchies (the main reason why + * you'd want to use an abstract factory). + * @todo Port DirectLex to use this + */ +class HTMLPurifier_TokenFactory +{ + // p stands for prototype + + /** + * @type HTMLPurifier_Token_Start + */ + private $p_start; + + /** + * @type HTMLPurifier_Token_End + */ + private $p_end; + + /** + * @type HTMLPurifier_Token_Empty + */ + private $p_empty; + + /** + * @type HTMLPurifier_Token_Text + */ + private $p_text; + + /** + * @type HTMLPurifier_Token_Comment + */ + private $p_comment; + + /** + * Generates blank prototypes for cloning. + */ + public function __construct() + { + $this->p_start = new HTMLPurifier_Token_Start('', array()); + $this->p_end = new HTMLPurifier_Token_End(''); + $this->p_empty = new HTMLPurifier_Token_Empty('', array()); + $this->p_text = new HTMLPurifier_Token_Text(''); + $this->p_comment = new HTMLPurifier_Token_Comment(''); + } + + /** + * Creates a HTMLPurifier_Token_Start. + * @param string $name Tag name + * @param array $attr Associative array of attributes + * @return HTMLPurifier_Token_Start Generated HTMLPurifier_Token_Start + */ + public function createStart($name, $attr = array()) + { + $p = clone $this->p_start; + $p->__construct($name, $attr); + return $p; + } + + /** + * Creates a HTMLPurifier_Token_End. + * @param string $name Tag name + * @return HTMLPurifier_Token_End Generated HTMLPurifier_Token_End + */ + public function createEnd($name) + { + $p = clone $this->p_end; + $p->__construct($name); + return $p; + } + + /** + * Creates a HTMLPurifier_Token_Empty. + * @param string $name Tag name + * @param array $attr Associative array of attributes + * @return HTMLPurifier_Token_Empty Generated HTMLPurifier_Token_Empty + */ + public function createEmpty($name, $attr = array()) + { + $p = clone $this->p_empty; + $p->__construct($name, $attr); + return $p; + } + + /** + * Creates a HTMLPurifier_Token_Text. + * @param string $data Data of text token + * @return HTMLPurifier_Token_Text Generated HTMLPurifier_Token_Text + */ + public function createText($data) + { + $p = clone $this->p_text; + $p->__construct($data); + return $p; + } + + /** + * Creates a HTMLPurifier_Token_Comment. + * @param string $data Data of comment token + * @return HTMLPurifier_Token_Comment Generated HTMLPurifier_Token_Comment + */ + public function createComment($data) + { + $p = clone $this->p_comment; + $p->__construct($data); + return $p; + } +} + + + + + +/** + * HTML Purifier's internal representation of a URI. + * @note + * Internal data-structures are completely escaped. If the data needs + * to be used in a non-URI context (which is very unlikely), be sure + * to decode it first. The URI may not necessarily be well-formed until + * validate() is called. + */ +class HTMLPurifier_URI +{ + /** + * @type string + */ + public $scheme; + + /** + * @type string + */ + public $userinfo; + + /** + * @type string + */ + public $host; + + /** + * @type int + */ + public $port; + + /** + * @type string + */ + public $path; + + /** + * @type string + */ + public $query; + + /** + * @type string + */ + public $fragment; + + /** + * @param string $scheme + * @param string $userinfo + * @param string $host + * @param int $port + * @param string $path + * @param string $query + * @param string $fragment + * @note Automatically normalizes scheme and port + */ + public function __construct($scheme, $userinfo, $host, $port, $path, $query, $fragment) + { + $this->scheme = is_null($scheme) || ctype_lower($scheme) ? $scheme : strtolower($scheme); + $this->userinfo = $userinfo; + $this->host = $host; + $this->port = is_null($port) ? $port : (int)$port; + $this->path = $path; + $this->query = $query; + $this->fragment = $fragment; + } + + /** + * Retrieves a scheme object corresponding to the URI's scheme/default + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return HTMLPurifier_URIScheme Scheme object appropriate for validating this URI + */ + public function getSchemeObj($config, $context) + { + $registry = HTMLPurifier_URISchemeRegistry::instance(); + if ($this->scheme !== null) { + $scheme_obj = $registry->getScheme($this->scheme, $config, $context); + if (!$scheme_obj) { + return false; + } // invalid scheme, clean it out + } else { + // no scheme: retrieve the default one + $def = $config->getDefinition('URI'); + $scheme_obj = $def->getDefaultScheme($config, $context); + if (!$scheme_obj) { + if ($def->defaultScheme !== null) { + // something funky happened to the default scheme object + trigger_error( + 'Default scheme object "' . $def->defaultScheme . '" was not readable', + E_USER_WARNING + ); + } // suppress error if it's null + return false; + } + } + return $scheme_obj; + } + + /** + * Generic validation method applicable for all schemes. May modify + * this URI in order to get it into a compliant form. + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool True if validation/filtering succeeds, false if failure + */ + public function validate($config, $context) + { + // ABNF definitions from RFC 3986 + $chars_sub_delims = '!$&\'()*+,;='; + $chars_gen_delims = ':/?#[]@'; + $chars_pchar = $chars_sub_delims . ':@'; + + // validate host + if (!is_null($this->host)) { + $host_def = new HTMLPurifier_AttrDef_URI_Host(); + $this->host = $host_def->validate($this->host, $config, $context); + if ($this->host === false) { + $this->host = null; + } + } + + // validate scheme + // NOTE: It's not appropriate to check whether or not this + // scheme is in our registry, since a URIFilter may convert a + // URI that we don't allow into one we do. So instead, we just + // check if the scheme can be dropped because there is no host + // and it is our default scheme. + if (!is_null($this->scheme) && is_null($this->host) || $this->host === '') { + // support for relative paths is pretty abysmal when the + // scheme is present, so axe it when possible + $def = $config->getDefinition('URI'); + if ($def->defaultScheme === $this->scheme) { + $this->scheme = null; + } + } + + // validate username + if (!is_null($this->userinfo)) { + $encoder = new HTMLPurifier_PercentEncoder($chars_sub_delims . ':'); + $this->userinfo = $encoder->encode($this->userinfo); + } + + // validate port + if (!is_null($this->port)) { + if ($this->port < 1 || $this->port > 65535) { + $this->port = null; + } + } + + // validate path + $segments_encoder = new HTMLPurifier_PercentEncoder($chars_pchar . '/'); + if (!is_null($this->host)) { // this catches $this->host === '' + // path-abempty (hier and relative) + // http://www.example.com/my/path + // //www.example.com/my/path (looks odd, but works, and + // recognized by most browsers) + // (this set is valid or invalid on a scheme by scheme + // basis, so we'll deal with it later) + // file:///my/path + // ///my/path + $this->path = $segments_encoder->encode($this->path); + } elseif ($this->path !== '') { + if ($this->path[0] === '/') { + // path-absolute (hier and relative) + // http:/my/path + // /my/path + if (strlen($this->path) >= 2 && $this->path[1] === '/') { + // This could happen if both the host gets stripped + // out + // http://my/path + // //my/path + $this->path = ''; + } else { + $this->path = $segments_encoder->encode($this->path); + } + } elseif (!is_null($this->scheme)) { + // path-rootless (hier) + // http:my/path + // Short circuit evaluation means we don't need to check nz + $this->path = $segments_encoder->encode($this->path); + } else { + // path-noscheme (relative) + // my/path + // (once again, not checking nz) + $segment_nc_encoder = new HTMLPurifier_PercentEncoder($chars_sub_delims . '@'); + $c = strpos($this->path, '/'); + if ($c !== false) { + $this->path = + $segment_nc_encoder->encode(substr($this->path, 0, $c)) . + $segments_encoder->encode(substr($this->path, $c)); + } else { + $this->path = $segment_nc_encoder->encode($this->path); + } + } + } else { + // path-empty (hier and relative) + $this->path = ''; // just to be safe + } + + // qf = query and fragment + $qf_encoder = new HTMLPurifier_PercentEncoder($chars_pchar . '/?'); + + if (!is_null($this->query)) { + $this->query = $qf_encoder->encode($this->query); + } + + if (!is_null($this->fragment)) { + $this->fragment = $qf_encoder->encode($this->fragment); + } + return true; + } + + /** + * Convert URI back to string + * @return string URI appropriate for output + */ + public function toString() + { + // reconstruct authority + $authority = null; + // there is a rendering difference between a null authority + // (http:foo-bar) and an empty string authority + // (http:///foo-bar). + if (!is_null($this->host)) { + $authority = ''; + if (!is_null($this->userinfo)) { + $authority .= $this->userinfo . '@'; + } + $authority .= $this->host; + if (!is_null($this->port)) { + $authority .= ':' . $this->port; + } + } + + // Reconstruct the result + // One might wonder about parsing quirks from browsers after + // this reconstruction. Unfortunately, parsing behavior depends + // on what *scheme* was employed (file:///foo is handled *very* + // differently than http:///foo), so unfortunately we have to + // defer to the schemes to do the right thing. + $result = ''; + if (!is_null($this->scheme)) { + $result .= $this->scheme . ':'; + } + if (!is_null($authority)) { + $result .= '//' . $authority; + } + $result .= $this->path; + if (!is_null($this->query)) { + $result .= '?' . $this->query; + } + if (!is_null($this->fragment)) { + $result .= '#' . $this->fragment; + } + + return $result; + } + + /** + * Returns true if this URL might be considered a 'local' URL given + * the current context. This is true when the host is null, or + * when it matches the host supplied to the configuration. + * + * Note that this does not do any scheme checking, so it is mostly + * only appropriate for metadata that doesn't care about protocol + * security. isBenign is probably what you actually want. + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function isLocal($config, $context) + { + if ($this->host === null) { + return true; + } + $uri_def = $config->getDefinition('URI'); + if ($uri_def->host === $this->host) { + return true; + } + return false; + } + + /** + * Returns true if this URL should be considered a 'benign' URL, + * that is: + * + * - It is a local URL (isLocal), and + * - It has a equal or better level of security + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function isBenign($config, $context) + { + if (!$this->isLocal($config, $context)) { + return false; + } + + $scheme_obj = $this->getSchemeObj($config, $context); + if (!$scheme_obj) { + return false; + } // conservative approach + + $current_scheme_obj = $config->getDefinition('URI')->getDefaultScheme($config, $context); + if ($current_scheme_obj->secure) { + if (!$scheme_obj->secure) { + return false; + } + } + return true; + } +} + + + + + +class HTMLPurifier_URIDefinition extends HTMLPurifier_Definition +{ + + public $type = 'URI'; + protected $filters = array(); + protected $postFilters = array(); + protected $registeredFilters = array(); + + /** + * HTMLPurifier_URI object of the base specified at %URI.Base + */ + public $base; + + /** + * String host to consider "home" base, derived off of $base + */ + public $host; + + /** + * Name of default scheme based on %URI.DefaultScheme and %URI.Base + */ + public $defaultScheme; + + public function __construct() + { + $this->registerFilter(new HTMLPurifier_URIFilter_DisableExternal()); + $this->registerFilter(new HTMLPurifier_URIFilter_DisableExternalResources()); + $this->registerFilter(new HTMLPurifier_URIFilter_DisableResources()); + $this->registerFilter(new HTMLPurifier_URIFilter_HostBlacklist()); + $this->registerFilter(new HTMLPurifier_URIFilter_SafeIframe()); + $this->registerFilter(new HTMLPurifier_URIFilter_MakeAbsolute()); + $this->registerFilter(new HTMLPurifier_URIFilter_Munge()); + } + + public function registerFilter($filter) + { + $this->registeredFilters[$filter->name] = $filter; + } + + public function addFilter($filter, $config) + { + $r = $filter->prepare($config); + if ($r === false) return; // null is ok, for backwards compat + if ($filter->post) { + $this->postFilters[$filter->name] = $filter; + } else { + $this->filters[$filter->name] = $filter; + } + } + + protected function doSetup($config) + { + $this->setupMemberVariables($config); + $this->setupFilters($config); + } + + protected function setupFilters($config) + { + foreach ($this->registeredFilters as $name => $filter) { + if ($filter->always_load) { + $this->addFilter($filter, $config); + } else { + $conf = $config->get('URI.' . $name); + if ($conf !== false && $conf !== null) { + $this->addFilter($filter, $config); + } + } + } + unset($this->registeredFilters); + } + + protected function setupMemberVariables($config) + { + $this->host = $config->get('URI.Host'); + $base_uri = $config->get('URI.Base'); + if (!is_null($base_uri)) { + $parser = new HTMLPurifier_URIParser(); + $this->base = $parser->parse($base_uri); + $this->defaultScheme = $this->base->scheme; + if (is_null($this->host)) $this->host = $this->base->host; + } + if (is_null($this->defaultScheme)) $this->defaultScheme = $config->get('URI.DefaultScheme'); + } + + public function getDefaultScheme($config, $context) + { + return HTMLPurifier_URISchemeRegistry::instance()->getScheme($this->defaultScheme, $config, $context); + } + + public function filter(&$uri, $config, $context) + { + foreach ($this->filters as $name => $f) { + $result = $f->filter($uri, $config, $context); + if (!$result) return false; + } + return true; + } + + public function postFilter(&$uri, $config, $context) + { + foreach ($this->postFilters as $name => $f) { + $result = $f->filter($uri, $config, $context); + if (!$result) return false; + } + return true; + } + +} + + + + + +/** + * Chainable filters for custom URI processing. + * + * These filters can perform custom actions on a URI filter object, + * including transformation or blacklisting. A filter named Foo + * must have a corresponding configuration directive %URI.Foo, + * unless always_load is specified to be true. + * + * The following contexts may be available while URIFilters are being + * processed: + * + * - EmbeddedURI: true if URI is an embedded resource that will + * be loaded automatically on page load + * - CurrentToken: a reference to the token that is currently + * being processed + * - CurrentAttr: the name of the attribute that is currently being + * processed + * - CurrentCSSProperty: the name of the CSS property that is + * currently being processed (if applicable) + * + * @warning This filter is called before scheme object validation occurs. + * Make sure, if you require a specific scheme object, you + * you check that it exists. This allows filters to convert + * proprietary URI schemes into regular ones. + */ +abstract class HTMLPurifier_URIFilter +{ + + /** + * Unique identifier of filter. + * @type string + */ + public $name; + + /** + * True if this filter should be run after scheme validation. + * @type bool + */ + public $post = false; + + /** + * True if this filter should always be loaded. + * This permits a filter to be named Foo without the corresponding + * %URI.Foo directive existing. + * @type bool + */ + public $always_load = false; + + /** + * Performs initialization for the filter. If the filter returns + * false, this means that it shouldn't be considered active. + * @param HTMLPurifier_Config $config + * @return bool + */ + public function prepare($config) + { + return true; + } + + /** + * Filter a URI object + * @param HTMLPurifier_URI $uri Reference to URI object variable + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool Whether or not to continue processing: false indicates + * URL is no good, true indicates continue processing. Note that + * all changes are committed directly on the URI object + */ + abstract public function filter(&$uri, $config, $context); +} + + + + + +/** + * Parses a URI into the components and fragment identifier as specified + * by RFC 3986. + */ +class HTMLPurifier_URIParser +{ + + /** + * Instance of HTMLPurifier_PercentEncoder to do normalization with. + */ + protected $percentEncoder; + + public function __construct() + { + $this->percentEncoder = new HTMLPurifier_PercentEncoder(); + } + + /** + * Parses a URI. + * @param $uri string URI to parse + * @return HTMLPurifier_URI representation of URI. This representation has + * not been validated yet and may not conform to RFC. + */ + public function parse($uri) + { + $uri = $this->percentEncoder->normalize($uri); + + // Regexp is as per Appendix B. + // Note that ["<>] are an addition to the RFC's recommended + // characters, because they represent external delimeters. + $r_URI = '!'. + '(([a-zA-Z0-9\.\+\-]+):)?'. // 2. Scheme + '(//([^/?#"<>]*))?'. // 4. Authority + '([^?#"<>]*)'. // 5. Path + '(\?([^#"<>]*))?'. // 7. Query + '(#([^"<>]*))?'. // 8. Fragment + '!'; + + $matches = array(); + $result = preg_match($r_URI, $uri, $matches); + + if (!$result) return false; // *really* invalid URI + + // seperate out parts + $scheme = !empty($matches[1]) ? $matches[2] : null; + $authority = !empty($matches[3]) ? $matches[4] : null; + $path = $matches[5]; // always present, can be empty + $query = !empty($matches[6]) ? $matches[7] : null; + $fragment = !empty($matches[8]) ? $matches[9] : null; + + // further parse authority + if ($authority !== null) { + $r_authority = "/^((.+?)@)?(\[[^\]]+\]|[^:]*)(:(\d*))?/"; + $matches = array(); + preg_match($r_authority, $authority, $matches); + $userinfo = !empty($matches[1]) ? $matches[2] : null; + $host = !empty($matches[3]) ? $matches[3] : ''; + $port = !empty($matches[4]) ? (int) $matches[5] : null; + } else { + $port = $host = $userinfo = null; + } + + return new HTMLPurifier_URI( + $scheme, $userinfo, $host, $port, $path, $query, $fragment); + } + +} + + + + + +/** + * Validator for the components of a URI for a specific scheme + */ +abstract class HTMLPurifier_URIScheme +{ + + /** + * Scheme's default port (integer). If an explicit port number is + * specified that coincides with the default port, it will be + * elided. + * @type int + */ + public $default_port = null; + + /** + * Whether or not URIs of this scheme are locatable by a browser + * http and ftp are accessible, while mailto and news are not. + * @type bool + */ + public $browsable = false; + + /** + * Whether or not data transmitted over this scheme is encrypted. + * https is secure, http is not. + * @type bool + */ + public $secure = false; + + /** + * Whether or not the URI always uses , resolves edge cases + * with making relative URIs absolute + * @type bool + */ + public $hierarchical = false; + + /** + * Whether or not the URI may omit a hostname when the scheme is + * explicitly specified, ala file:///path/to/file. As of writing, + * 'file' is the only scheme that browsers support his properly. + * @type bool + */ + public $may_omit_host = false; + + /** + * Validates the components of a URI for a specific scheme. + * @param HTMLPurifier_URI $uri Reference to a HTMLPurifier_URI object + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool success or failure + */ + abstract public function doValidate(&$uri, $config, $context); + + /** + * Public interface for validating components of a URI. Performs a + * bunch of default actions. Don't overload this method. + * @param HTMLPurifier_URI $uri Reference to a HTMLPurifier_URI object + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool success or failure + */ + public function validate(&$uri, $config, $context) + { + if ($this->default_port == $uri->port) { + $uri->port = null; + } + // kludge: browsers do funny things when the scheme but not the + // authority is set + if (!$this->may_omit_host && + // if the scheme is present, a missing host is always in error + (!is_null($uri->scheme) && ($uri->host === '' || is_null($uri->host))) || + // if the scheme is not present, a *blank* host is in error, + // since this translates into '///path' which most browsers + // interpret as being 'http://path'. + (is_null($uri->scheme) && $uri->host === '') + ) { + do { + if (is_null($uri->scheme)) { + if (substr($uri->path, 0, 2) != '//') { + $uri->host = null; + break; + } + // URI is '////path', so we cannot nullify the + // host to preserve semantics. Try expanding the + // hostname instead (fall through) + } + // first see if we can manually insert a hostname + $host = $config->get('URI.Host'); + if (!is_null($host)) { + $uri->host = $host; + } else { + // we can't do anything sensible, reject the URL. + return false; + } + } while (false); + } + return $this->doValidate($uri, $config, $context); + } +} + + + + + +/** + * Registry for retrieving specific URI scheme validator objects. + */ +class HTMLPurifier_URISchemeRegistry +{ + + /** + * Retrieve sole instance of the registry. + * @param HTMLPurifier_URISchemeRegistry $prototype Optional prototype to overload sole instance with, + * or bool true to reset to default registry. + * @return HTMLPurifier_URISchemeRegistry + * @note Pass a registry object $prototype with a compatible interface and + * the function will copy it and return it all further times. + */ + public static function instance($prototype = null) + { + static $instance = null; + if ($prototype !== null) { + $instance = $prototype; + } elseif ($instance === null || $prototype == true) { + $instance = new HTMLPurifier_URISchemeRegistry(); + } + return $instance; + } + + /** + * Cache of retrieved schemes. + * @type HTMLPurifier_URIScheme[] + */ + protected $schemes = array(); + + /** + * Retrieves a scheme validator object + * @param string $scheme String scheme name like http or mailto + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return HTMLPurifier_URIScheme + */ + public function getScheme($scheme, $config, $context) + { + if (!$config) { + $config = HTMLPurifier_Config::createDefault(); + } + + // important, otherwise attacker could include arbitrary file + $allowed_schemes = $config->get('URI.AllowedSchemes'); + if (!$config->get('URI.OverrideAllowedSchemes') && + !isset($allowed_schemes[$scheme]) + ) { + return; + } + + if (isset($this->schemes[$scheme])) { + return $this->schemes[$scheme]; + } + if (!isset($allowed_schemes[$scheme])) { + return; + } + + $class = 'HTMLPurifier_URIScheme_' . $scheme; + if (!class_exists($class)) { + return; + } + $this->schemes[$scheme] = new $class(); + return $this->schemes[$scheme]; + } + + /** + * Registers a custom scheme to the cache, bypassing reflection. + * @param string $scheme Scheme name + * @param HTMLPurifier_URIScheme $scheme_obj + */ + public function register($scheme, $scheme_obj) + { + $this->schemes[$scheme] = $scheme_obj; + } +} + + + + + +/** + * Class for converting between different unit-lengths as specified by + * CSS. + */ +class HTMLPurifier_UnitConverter +{ + + const ENGLISH = 1; + const METRIC = 2; + const DIGITAL = 3; + + /** + * Units information array. Units are grouped into measuring systems + * (English, Metric), and are assigned an integer representing + * the conversion factor between that unit and the smallest unit in + * the system. Numeric indexes are actually magical constants that + * encode conversion data from one system to the next, with a O(n^2) + * constraint on memory (this is generally not a problem, since + * the number of measuring systems is small.) + */ + protected static $units = array( + self::ENGLISH => array( + 'px' => 3, // This is as per CSS 2.1 and Firefox. Your mileage may vary + 'pt' => 4, + 'pc' => 48, + 'in' => 288, + self::METRIC => array('pt', '0.352777778', 'mm'), + ), + self::METRIC => array( + 'mm' => 1, + 'cm' => 10, + self::ENGLISH => array('mm', '2.83464567', 'pt'), + ), + ); + + /** + * Minimum bcmath precision for output. + * @type int + */ + protected $outputPrecision; + + /** + * Bcmath precision for internal calculations. + * @type int + */ + protected $internalPrecision; + + /** + * Whether or not BCMath is available. + * @type bool + */ + private $bcmath; + + public function __construct($output_precision = 4, $internal_precision = 10, $force_no_bcmath = false) + { + $this->outputPrecision = $output_precision; + $this->internalPrecision = $internal_precision; + $this->bcmath = !$force_no_bcmath && function_exists('bcmul'); + } + + /** + * Converts a length object of one unit into another unit. + * @param HTMLPurifier_Length $length + * Instance of HTMLPurifier_Length to convert. You must validate() + * it before passing it here! + * @param string $to_unit + * Unit to convert to. + * @return HTMLPurifier_Length|bool + * @note + * About precision: This conversion function pays very special + * attention to the incoming precision of values and attempts + * to maintain a number of significant figure. Results are + * fairly accurate up to nine digits. Some caveats: + * - If a number is zero-padded as a result of this significant + * figure tracking, the zeroes will be eliminated. + * - If a number contains less than four sigfigs ($outputPrecision) + * and this causes some decimals to be excluded, those + * decimals will be added on. + */ + public function convert($length, $to_unit) + { + if (!$length->isValid()) { + return false; + } + + $n = $length->getN(); + $unit = $length->getUnit(); + + if ($n === '0' || $unit === false) { + return new HTMLPurifier_Length('0', false); + } + + $state = $dest_state = false; + foreach (self::$units as $k => $x) { + if (isset($x[$unit])) { + $state = $k; + } + if (isset($x[$to_unit])) { + $dest_state = $k; + } + } + if (!$state || !$dest_state) { + return false; + } + + // Some calculations about the initial precision of the number; + // this will be useful when we need to do final rounding. + $sigfigs = $this->getSigFigs($n); + if ($sigfigs < $this->outputPrecision) { + $sigfigs = $this->outputPrecision; + } + + // BCMath's internal precision deals only with decimals. Use + // our default if the initial number has no decimals, or increase + // it by how ever many decimals, thus, the number of guard digits + // will always be greater than or equal to internalPrecision. + $log = (int)floor(log(abs($n), 10)); + $cp = ($log < 0) ? $this->internalPrecision - $log : $this->internalPrecision; // internal precision + + for ($i = 0; $i < 2; $i++) { + + // Determine what unit IN THIS SYSTEM we need to convert to + if ($dest_state === $state) { + // Simple conversion + $dest_unit = $to_unit; + } else { + // Convert to the smallest unit, pending a system shift + $dest_unit = self::$units[$state][$dest_state][0]; + } + + // Do the conversion if necessary + if ($dest_unit !== $unit) { + $factor = $this->div(self::$units[$state][$unit], self::$units[$state][$dest_unit], $cp); + $n = $this->mul($n, $factor, $cp); + $unit = $dest_unit; + } + + // Output was zero, so bail out early. Shouldn't ever happen. + if ($n === '') { + $n = '0'; + $unit = $to_unit; + break; + } + + // It was a simple conversion, so bail out + if ($dest_state === $state) { + break; + } + + if ($i !== 0) { + // Conversion failed! Apparently, the system we forwarded + // to didn't have this unit. This should never happen! + return false; + } + + // Pre-condition: $i == 0 + + // Perform conversion to next system of units + $n = $this->mul($n, self::$units[$state][$dest_state][1], $cp); + $unit = self::$units[$state][$dest_state][2]; + $state = $dest_state; + + // One more loop around to convert the unit in the new system. + + } + + // Post-condition: $unit == $to_unit + if ($unit !== $to_unit) { + return false; + } + + // Useful for debugging: + //echo "
    n";
    +        //echo "$n\nsigfigs = $sigfigs\nnew_log = $new_log\nlog = $log\nrp = $rp\n
    \n"; + + $n = $this->round($n, $sigfigs); + if (strpos($n, '.') !== false) { + $n = rtrim($n, '0'); + } + $n = rtrim($n, '.'); + + return new HTMLPurifier_Length($n, $unit); + } + + /** + * Returns the number of significant figures in a string number. + * @param string $n Decimal number + * @return int number of sigfigs + */ + public function getSigFigs($n) + { + $n = ltrim($n, '0+-'); + $dp = strpos($n, '.'); // decimal position + if ($dp === false) { + $sigfigs = strlen(rtrim($n, '0')); + } else { + $sigfigs = strlen(ltrim($n, '0.')); // eliminate extra decimal character + if ($dp !== 0) { + $sigfigs--; + } + } + return $sigfigs; + } + + /** + * Adds two numbers, using arbitrary precision when available. + * @param string $s1 + * @param string $s2 + * @param int $scale + * @return string + */ + private function add($s1, $s2, $scale) + { + if ($this->bcmath) { + return bcadd($s1, $s2, $scale); + } else { + return $this->scale((float)$s1 + (float)$s2, $scale); + } + } + + /** + * Multiples two numbers, using arbitrary precision when available. + * @param string $s1 + * @param string $s2 + * @param int $scale + * @return string + */ + private function mul($s1, $s2, $scale) + { + if ($this->bcmath) { + return bcmul($s1, $s2, $scale); + } else { + return $this->scale((float)$s1 * (float)$s2, $scale); + } + } + + /** + * Divides two numbers, using arbitrary precision when available. + * @param string $s1 + * @param string $s2 + * @param int $scale + * @return string + */ + private function div($s1, $s2, $scale) + { + if ($this->bcmath) { + return bcdiv($s1, $s2, $scale); + } else { + return $this->scale((float)$s1 / (float)$s2, $scale); + } + } + + /** + * Rounds a number according to the number of sigfigs it should have, + * using arbitrary precision when available. + * @param float $n + * @param int $sigfigs + * @return string + */ + private function round($n, $sigfigs) + { + $new_log = (int)floor(log(abs($n), 10)); // Number of digits left of decimal - 1 + $rp = $sigfigs - $new_log - 1; // Number of decimal places needed + $neg = $n < 0 ? '-' : ''; // Negative sign + if ($this->bcmath) { + if ($rp >= 0) { + $n = bcadd($n, $neg . '0.' . str_repeat('0', $rp) . '5', $rp + 1); + $n = bcdiv($n, '1', $rp); + } else { + // This algorithm partially depends on the standardized + // form of numbers that comes out of bcmath. + $n = bcadd($n, $neg . '5' . str_repeat('0', $new_log - $sigfigs), 0); + $n = substr($n, 0, $sigfigs + strlen($neg)) . str_repeat('0', $new_log - $sigfigs + 1); + } + return $n; + } else { + return $this->scale(round($n, $sigfigs - $new_log - 1), $rp + 1); + } + } + + /** + * Scales a float to $scale digits right of decimal point, like BCMath. + * @param float $r + * @param int $scale + * @return string + */ + private function scale($r, $scale) + { + if ($scale < 0) { + // The f sprintf type doesn't support negative numbers, so we + // need to cludge things manually. First get the string. + $r = sprintf('%.0f', (float)$r); + // Due to floating point precision loss, $r will more than likely + // look something like 4652999999999.9234. We grab one more digit + // than we need to precise from $r and then use that to round + // appropriately. + $precise = (string)round(substr($r, 0, strlen($r) + $scale), -1); + // Now we return it, truncating the zero that was rounded off. + return substr($precise, 0, -1) . str_repeat('0', -$scale + 1); + } + return sprintf('%.' . $scale . 'f', (float)$r); + } +} + + + + + +/** + * Parses string representations into their corresponding native PHP + * variable type. The base implementation does a simple type-check. + */ +class HTMLPurifier_VarParser +{ + + const C_STRING = 1; + const ISTRING = 2; + const TEXT = 3; + const ITEXT = 4; + const C_INT = 5; + const C_FLOAT = 6; + const C_BOOL = 7; + const LOOKUP = 8; + const ALIST = 9; + const HASH = 10; + const C_MIXED = 11; + + /** + * Lookup table of allowed types. Mainly for backwards compatibility, but + * also convenient for transforming string type names to the integer constants. + */ + public static $types = array( + 'string' => self::C_STRING, + 'istring' => self::ISTRING, + 'text' => self::TEXT, + 'itext' => self::ITEXT, + 'int' => self::C_INT, + 'float' => self::C_FLOAT, + 'bool' => self::C_BOOL, + 'lookup' => self::LOOKUP, + 'list' => self::ALIST, + 'hash' => self::HASH, + 'mixed' => self::C_MIXED + ); + + /** + * Lookup table of types that are string, and can have aliases or + * allowed value lists. + */ + public static $stringTypes = array( + self::C_STRING => true, + self::ISTRING => true, + self::TEXT => true, + self::ITEXT => true, + ); + + /** + * Validate a variable according to type. + * It may return NULL as a valid type if $allow_null is true. + * + * @param mixed $var Variable to validate + * @param int $type Type of variable, see HTMLPurifier_VarParser->types + * @param bool $allow_null Whether or not to permit null as a value + * @return string Validated and type-coerced variable + * @throws HTMLPurifier_VarParserException + */ + final public function parse($var, $type, $allow_null = false) + { + if (is_string($type)) { + if (!isset(HTMLPurifier_VarParser::$types[$type])) { + throw new HTMLPurifier_VarParserException("Invalid type '$type'"); + } else { + $type = HTMLPurifier_VarParser::$types[$type]; + } + } + $var = $this->parseImplementation($var, $type, $allow_null); + if ($allow_null && $var === null) { + return null; + } + // These are basic checks, to make sure nothing horribly wrong + // happened in our implementations. + switch ($type) { + case (self::C_STRING): + case (self::ISTRING): + case (self::TEXT): + case (self::ITEXT): + if (!is_string($var)) { + break; + } + if ($type == self::ISTRING || $type == self::ITEXT) { + $var = strtolower($var); + } + return $var; + case (self::C_INT): + if (!is_int($var)) { + break; + } + return $var; + case (self::C_FLOAT): + if (!is_float($var)) { + break; + } + return $var; + case (self::C_BOOL): + if (!is_bool($var)) { + break; + } + return $var; + case (self::LOOKUP): + case (self::ALIST): + case (self::HASH): + if (!is_array($var)) { + break; + } + if ($type === self::LOOKUP) { + foreach ($var as $k) { + if ($k !== true) { + $this->error('Lookup table contains value other than true'); + } + } + } elseif ($type === self::ALIST) { + $keys = array_keys($var); + if (array_keys($keys) !== $keys) { + $this->error('Indices for list are not uniform'); + } + } + return $var; + case (self::C_MIXED): + return $var; + default: + $this->errorInconsistent(get_class($this), $type); + } + $this->errorGeneric($var, $type); + } + + /** + * Actually implements the parsing. Base implementation does not + * do anything to $var. Subclasses should overload this! + * @param mixed $var + * @param int $type + * @param bool $allow_null + * @return string + */ + protected function parseImplementation($var, $type, $allow_null) + { + return $var; + } + + /** + * Throws an exception. + * @throws HTMLPurifier_VarParserException + */ + protected function error($msg) + { + throw new HTMLPurifier_VarParserException($msg); + } + + /** + * Throws an inconsistency exception. + * @note This should not ever be called. It would be called if we + * extend the allowed values of HTMLPurifier_VarParser without + * updating subclasses. + * @param string $class + * @param int $type + * @throws HTMLPurifier_Exception + */ + protected function errorInconsistent($class, $type) + { + throw new HTMLPurifier_Exception( + "Inconsistency in $class: " . HTMLPurifier_VarParser::getTypeName($type) . + " not implemented" + ); + } + + /** + * Generic error for if a type didn't work. + * @param mixed $var + * @param int $type + */ + protected function errorGeneric($var, $type) + { + $vtype = gettype($var); + $this->error("Expected type " . HTMLPurifier_VarParser::getTypeName($type) . ", got $vtype"); + } + + /** + * @param int $type + * @return string + */ + public static function getTypeName($type) + { + static $lookup; + if (!$lookup) { + // Lazy load the alternative lookup table + $lookup = array_flip(HTMLPurifier_VarParser::$types); + } + if (!isset($lookup[$type])) { + return 'unknown'; + } + return $lookup[$type]; + } +} + + + + + +/** + * Exception type for HTMLPurifier_VarParser + */ +class HTMLPurifier_VarParserException extends HTMLPurifier_Exception +{ + +} + + + + + +/** + * A zipper is a purely-functional data structure which contains + * a focus that can be efficiently manipulated. It is known as + * a "one-hole context". This mutable variant implements a zipper + * for a list as a pair of two arrays, laid out as follows: + * + * Base list: 1 2 3 4 [ ] 6 7 8 9 + * Front list: 1 2 3 4 + * Back list: 9 8 7 6 + * + * User is expected to keep track of the "current element" and properly + * fill it back in as necessary. (ToDo: Maybe it's more user friendly + * to implicitly track the current element?) + * + * Nota bene: the current class gets confused if you try to store NULLs + * in the list. + */ + +class HTMLPurifier_Zipper +{ + public $front, $back; + + public function __construct($front, $back) { + $this->front = $front; + $this->back = $back; + } + + /** + * Creates a zipper from an array, with a hole in the + * 0-index position. + * @param Array to zipper-ify. + * @return Tuple of zipper and element of first position. + */ + static public function fromArray($array) { + $z = new self(array(), array_reverse($array)); + $t = $z->delete(); // delete the "dummy hole" + return array($z, $t); + } + + /** + * Convert zipper back into a normal array, optionally filling in + * the hole with a value. (Usually you should supply a $t, unless you + * are at the end of the array.) + */ + public function toArray($t = NULL) { + $a = $this->front; + if ($t !== NULL) $a[] = $t; + for ($i = count($this->back)-1; $i >= 0; $i--) { + $a[] = $this->back[$i]; + } + return $a; + } + + /** + * Move hole to the next element. + * @param $t Element to fill hole with + * @return Original contents of new hole. + */ + public function next($t) { + if ($t !== NULL) array_push($this->front, $t); + return empty($this->back) ? NULL : array_pop($this->back); + } + + /** + * Iterated hole advancement. + * @param $t Element to fill hole with + * @param $i How many forward to advance hole + * @return Original contents of new hole, i away + */ + public function advance($t, $n) { + for ($i = 0; $i < $n; $i++) { + $t = $this->next($t); + } + return $t; + } + + /** + * Move hole to the previous element + * @param $t Element to fill hole with + * @return Original contents of new hole. + */ + public function prev($t) { + if ($t !== NULL) array_push($this->back, $t); + return empty($this->front) ? NULL : array_pop($this->front); + } + + /** + * Delete contents of current hole, shifting hole to + * next element. + * @return Original contents of new hole. + */ + public function delete() { + return empty($this->back) ? NULL : array_pop($this->back); + } + + /** + * Returns true if we are at the end of the list. + * @return bool + */ + public function done() { + return empty($this->back); + } + + /** + * Insert element before hole. + * @param Element to insert + */ + public function insertBefore($t) { + if ($t !== NULL) array_push($this->front, $t); + } + + /** + * Insert element after hole. + * @param Element to insert + */ + public function insertAfter($t) { + if ($t !== NULL) array_push($this->back, $t); + } + + /** + * Splice in multiple elements at hole. Functional specification + * in terms of array_splice: + * + * $arr1 = $arr; + * $old1 = array_splice($arr1, $i, $delete, $replacement); + * + * list($z, $t) = HTMLPurifier_Zipper::fromArray($arr); + * $t = $z->advance($t, $i); + * list($old2, $t) = $z->splice($t, $delete, $replacement); + * $arr2 = $z->toArray($t); + * + * assert($old1 === $old2); + * assert($arr1 === $arr2); + * + * NB: the absolute index location after this operation is + * *unchanged!* + * + * @param Current contents of hole. + */ + public function splice($t, $delete, $replacement) { + // delete + $old = array(); + $r = $t; + for ($i = $delete; $i > 0; $i--) { + $old[] = $r; + $r = $this->delete(); + } + // insert + for ($i = count($replacement)-1; $i >= 0; $i--) { + $this->insertAfter($r); + $r = $replacement[$i]; + } + return array($old, $r); + } +} + + + +/** + * Validates the HTML attribute style, otherwise known as CSS. + * @note We don't implement the whole CSS specification, so it might be + * difficult to reuse this component in the context of validating + * actual stylesheet declarations. + * @note If we were really serious about validating the CSS, we would + * tokenize the styles and then parse the tokens. Obviously, we + * are not doing that. Doing that could seriously harm performance, + * but would make these components a lot more viable for a CSS + * filtering solution. + */ +class HTMLPurifier_AttrDef_CSS extends HTMLPurifier_AttrDef +{ + + /** + * @param string $css + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($css, $config, $context) + { + $css = $this->parseCDATA($css); + + $definition = $config->getCSSDefinition(); + $allow_duplicates = $config->get("CSS.AllowDuplicates"); + + + // According to the CSS2.1 spec, the places where a + // non-delimiting semicolon can appear are in strings + // escape sequences. So here is some dumb hack to + // handle quotes. + $len = strlen($css); + $accum = ""; + $declarations = array(); + $quoted = false; + for ($i = 0; $i < $len; $i++) { + $c = strcspn($css, ";'\"", $i); + $accum .= substr($css, $i, $c); + $i += $c; + if ($i == $len) break; + $d = $css[$i]; + if ($quoted) { + $accum .= $d; + if ($d == $quoted) { + $quoted = false; + } + } else { + if ($d == ";") { + $declarations[] = $accum; + $accum = ""; + } else { + $accum .= $d; + $quoted = $d; + } + } + } + if ($accum != "") $declarations[] = $accum; + + $propvalues = array(); + $new_declarations = ''; + + /** + * Name of the current CSS property being validated. + */ + $property = false; + $context->register('CurrentCSSProperty', $property); + + foreach ($declarations as $declaration) { + if (!$declaration) { + continue; + } + if (!strpos($declaration, ':')) { + continue; + } + list($property, $value) = explode(':', $declaration, 2); + $property = trim($property); + $value = trim($value); + $ok = false; + do { + if (isset($definition->info[$property])) { + $ok = true; + break; + } + if (ctype_lower($property)) { + break; + } + $property = strtolower($property); + if (isset($definition->info[$property])) { + $ok = true; + break; + } + } while (0); + if (!$ok) { + continue; + } + // inefficient call, since the validator will do this again + if (strtolower(trim($value)) !== 'inherit') { + // inherit works for everything (but only on the base property) + $result = $definition->info[$property]->validate( + $value, + $config, + $context + ); + } else { + $result = 'inherit'; + } + if ($result === false) { + continue; + } + if ($allow_duplicates) { + $new_declarations .= "$property:$result;"; + } else { + $propvalues[$property] = $result; + } + } + + $context->destroy('CurrentCSSProperty'); + + // procedure does not write the new CSS simultaneously, so it's + // slightly inefficient, but it's the only way of getting rid of + // duplicates. Perhaps config to optimize it, but not now. + + foreach ($propvalues as $prop => $value) { + $new_declarations .= "$prop:$value;"; + } + + return $new_declarations ? $new_declarations : false; + + } + +} + + + + + +/** + * Dummy AttrDef that mimics another AttrDef, BUT it generates clones + * with make. + */ +class HTMLPurifier_AttrDef_Clone extends HTMLPurifier_AttrDef +{ + /** + * What we're cloning. + * @type HTMLPurifier_AttrDef + */ + protected $clone; + + /** + * @param HTMLPurifier_AttrDef $clone + */ + public function __construct($clone) + { + $this->clone = $clone; + } + + /** + * @param string $v + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($v, $config, $context) + { + return $this->clone->validate($v, $config, $context); + } + + /** + * @param string $string + * @return HTMLPurifier_AttrDef + */ + public function make($string) + { + return clone $this->clone; + } +} + + + + + +// Enum = Enumerated +/** + * Validates a keyword against a list of valid values. + * @warning The case-insensitive compare of this function uses PHP's + * built-in strtolower and ctype_lower functions, which may + * cause problems with international comparisons + */ +class HTMLPurifier_AttrDef_Enum extends HTMLPurifier_AttrDef +{ + + /** + * Lookup table of valid values. + * @type array + * @todo Make protected + */ + public $valid_values = array(); + + /** + * Bool indicating whether or not enumeration is case sensitive. + * @note In general this is always case insensitive. + */ + protected $case_sensitive = false; // values according to W3C spec + + /** + * @param array $valid_values List of valid values + * @param bool $case_sensitive Whether or not case sensitive + */ + public function __construct($valid_values = array(), $case_sensitive = false) + { + $this->valid_values = array_flip($valid_values); + $this->case_sensitive = $case_sensitive; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = trim($string); + if (!$this->case_sensitive) { + // we may want to do full case-insensitive libraries + $string = ctype_lower($string) ? $string : strtolower($string); + } + $result = isset($this->valid_values[$string]); + + return $result ? $string : false; + } + + /** + * @param string $string In form of comma-delimited list of case-insensitive + * valid values. Example: "foo,bar,baz". Prepend "s:" to make + * case sensitive + * @return HTMLPurifier_AttrDef_Enum + */ + public function make($string) + { + if (strlen($string) > 2 && $string[0] == 's' && $string[1] == ':') { + $string = substr($string, 2); + $sensitive = true; + } else { + $sensitive = false; + } + $values = explode(',', $string); + return new HTMLPurifier_AttrDef_Enum($values, $sensitive); + } +} + + + + + +/** + * Validates an integer. + * @note While this class was modeled off the CSS definition, no currently + * allowed CSS uses this type. The properties that do are: widows, + * orphans, z-index, counter-increment, counter-reset. Some of the + * HTML attributes, however, find use for a non-negative version of this. + */ +class HTMLPurifier_AttrDef_Integer extends HTMLPurifier_AttrDef +{ + + /** + * Whether or not negative values are allowed. + * @type bool + */ + protected $negative = true; + + /** + * Whether or not zero is allowed. + * @type bool + */ + protected $zero = true; + + /** + * Whether or not positive values are allowed. + * @type bool + */ + protected $positive = true; + + /** + * @param $negative Bool indicating whether or not negative values are allowed + * @param $zero Bool indicating whether or not zero is allowed + * @param $positive Bool indicating whether or not positive values are allowed + */ + public function __construct($negative = true, $zero = true, $positive = true) + { + $this->negative = $negative; + $this->zero = $zero; + $this->positive = $positive; + } + + /** + * @param string $integer + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($integer, $config, $context) + { + $integer = $this->parseCDATA($integer); + if ($integer === '') { + return false; + } + + // we could possibly simply typecast it to integer, but there are + // certain fringe cases that must not return an integer. + + // clip leading sign + if ($this->negative && $integer[0] === '-') { + $digits = substr($integer, 1); + if ($digits === '0') { + $integer = '0'; + } // rm minus sign for zero + } elseif ($this->positive && $integer[0] === '+') { + $digits = $integer = substr($integer, 1); // rm unnecessary plus + } else { + $digits = $integer; + } + + // test if it's numeric + if (!ctype_digit($digits)) { + return false; + } + + // perform scope tests + if (!$this->zero && $integer == 0) { + return false; + } + if (!$this->positive && $integer > 0) { + return false; + } + if (!$this->negative && $integer < 0) { + return false; + } + + return $integer; + } +} + + + + + +/** + * Validates the HTML attribute lang, effectively a language code. + * @note Built according to RFC 3066, which obsoleted RFC 1766 + */ +class HTMLPurifier_AttrDef_Lang extends HTMLPurifier_AttrDef +{ + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = trim($string); + if (!$string) { + return false; + } + + $subtags = explode('-', $string); + $num_subtags = count($subtags); + + if ($num_subtags == 0) { // sanity check + return false; + } + + // process primary subtag : $subtags[0] + $length = strlen($subtags[0]); + switch ($length) { + case 0: + return false; + case 1: + if (!($subtags[0] == 'x' || $subtags[0] == 'i')) { + return false; + } + break; + case 2: + case 3: + if (!ctype_alpha($subtags[0])) { + return false; + } elseif (!ctype_lower($subtags[0])) { + $subtags[0] = strtolower($subtags[0]); + } + break; + default: + return false; + } + + $new_string = $subtags[0]; + if ($num_subtags == 1) { + return $new_string; + } + + // process second subtag : $subtags[1] + $length = strlen($subtags[1]); + if ($length == 0 || ($length == 1 && $subtags[1] != 'x') || $length > 8 || !ctype_alnum($subtags[1])) { + return $new_string; + } + if (!ctype_lower($subtags[1])) { + $subtags[1] = strtolower($subtags[1]); + } + + $new_string .= '-' . $subtags[1]; + if ($num_subtags == 2) { + return $new_string; + } + + // process all other subtags, index 2 and up + for ($i = 2; $i < $num_subtags; $i++) { + $length = strlen($subtags[$i]); + if ($length == 0 || $length > 8 || !ctype_alnum($subtags[$i])) { + return $new_string; + } + if (!ctype_lower($subtags[$i])) { + $subtags[$i] = strtolower($subtags[$i]); + } + $new_string .= '-' . $subtags[$i]; + } + return $new_string; + } +} + + + + + +/** + * Decorator that, depending on a token, switches between two definitions. + */ +class HTMLPurifier_AttrDef_Switch +{ + + /** + * @type string + */ + protected $tag; + + /** + * @type HTMLPurifier_AttrDef + */ + protected $withTag; + + /** + * @type HTMLPurifier_AttrDef + */ + protected $withoutTag; + + /** + * @param string $tag Tag name to switch upon + * @param HTMLPurifier_AttrDef $with_tag Call if token matches tag + * @param HTMLPurifier_AttrDef $without_tag Call if token doesn't match, or there is no token + */ + public function __construct($tag, $with_tag, $without_tag) + { + $this->tag = $tag; + $this->withTag = $with_tag; + $this->withoutTag = $without_tag; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $token = $context->get('CurrentToken', true); + if (!$token || $token->name !== $this->tag) { + return $this->withoutTag->validate($string, $config, $context); + } else { + return $this->withTag->validate($string, $config, $context); + } + } +} + + + + + +/** + * Validates arbitrary text according to the HTML spec. + */ +class HTMLPurifier_AttrDef_Text extends HTMLPurifier_AttrDef +{ + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + return $this->parseCDATA($string); + } +} + + + + + +/** + * Validates a URI as defined by RFC 3986. + * @note Scheme-specific mechanics deferred to HTMLPurifier_URIScheme + */ +class HTMLPurifier_AttrDef_URI extends HTMLPurifier_AttrDef +{ + + /** + * @type HTMLPurifier_URIParser + */ + protected $parser; + + /** + * @type bool + */ + protected $embedsResource; + + /** + * @param bool $embeds_resource Does the URI here result in an extra HTTP request? + */ + public function __construct($embeds_resource = false) + { + $this->parser = new HTMLPurifier_URIParser(); + $this->embedsResource = (bool)$embeds_resource; + } + + /** + * @param string $string + * @return HTMLPurifier_AttrDef_URI + */ + public function make($string) + { + $embeds = ($string === 'embedded'); + return new HTMLPurifier_AttrDef_URI($embeds); + } + + /** + * @param string $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($uri, $config, $context) + { + if ($config->get('URI.Disable')) { + return false; + } + + $uri = $this->parseCDATA($uri); + + // parse the URI + $uri = $this->parser->parse($uri); + if ($uri === false) { + return false; + } + + // add embedded flag to context for validators + $context->register('EmbeddedURI', $this->embedsResource); + + $ok = false; + do { + + // generic validation + $result = $uri->validate($config, $context); + if (!$result) { + break; + } + + // chained filtering + $uri_def = $config->getDefinition('URI'); + $result = $uri_def->filter($uri, $config, $context); + if (!$result) { + break; + } + + // scheme-specific validation + $scheme_obj = $uri->getSchemeObj($config, $context); + if (!$scheme_obj) { + break; + } + if ($this->embedsResource && !$scheme_obj->browsable) { + break; + } + $result = $scheme_obj->validate($uri, $config, $context); + if (!$result) { + break; + } + + // Post chained filtering + $result = $uri_def->postFilter($uri, $config, $context); + if (!$result) { + break; + } + + // survived gauntlet + $ok = true; + + } while (false); + + $context->destroy('EmbeddedURI'); + if (!$ok) { + return false; + } + // back to string + return $uri->toString(); + } +} + + + + + +/** + * Validates a number as defined by the CSS spec. + */ +class HTMLPurifier_AttrDef_CSS_Number extends HTMLPurifier_AttrDef +{ + + /** + * Indicates whether or not only positive values are allowed. + * @type bool + */ + protected $non_negative = false; + + /** + * @param bool $non_negative indicates whether negatives are forbidden + */ + public function __construct($non_negative = false) + { + $this->non_negative = $non_negative; + } + + /** + * @param string $number + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string|bool + * @warning Some contexts do not pass $config, $context. These + * variables should not be used without checking HTMLPurifier_Length + */ + public function validate($number, $config, $context) + { + $number = $this->parseCDATA($number); + + if ($number === '') { + return false; + } + if ($number === '0') { + return '0'; + } + + $sign = ''; + switch ($number[0]) { + case '-': + if ($this->non_negative) { + return false; + } + $sign = '-'; + case '+': + $number = substr($number, 1); + } + + if (ctype_digit($number)) { + $number = ltrim($number, '0'); + return $number ? $sign . $number : '0'; + } + + // Period is the only non-numeric character allowed + if (strpos($number, '.') === false) { + return false; + } + + list($left, $right) = explode('.', $number, 2); + + if ($left === '' && $right === '') { + return false; + } + if ($left !== '' && !ctype_digit($left)) { + return false; + } + + $left = ltrim($left, '0'); + $right = rtrim($right, '0'); + + if ($right === '') { + return $left ? $sign . $left : '0'; + } elseif (!ctype_digit($right)) { + return false; + } + return $sign . $left . '.' . $right; + } +} + + + + + +class HTMLPurifier_AttrDef_CSS_AlphaValue extends HTMLPurifier_AttrDef_CSS_Number +{ + + public function __construct() + { + parent::__construct(false); // opacity is non-negative, but we will clamp it + } + + /** + * @param string $number + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + */ + public function validate($number, $config, $context) + { + $result = parent::validate($number, $config, $context); + if ($result === false) { + return $result; + } + $float = (float)$result; + if ($float < 0.0) { + $result = '0'; + } + if ($float > 1.0) { + $result = '1'; + } + return $result; + } +} + + + + + +/** + * Validates shorthand CSS property background. + * @warning Does not support url tokens that have internal spaces. + */ +class HTMLPurifier_AttrDef_CSS_Background extends HTMLPurifier_AttrDef +{ + + /** + * Local copy of component validators. + * @type HTMLPurifier_AttrDef[] + * @note See HTMLPurifier_AttrDef_Font::$info for a similar impl. + */ + protected $info; + + /** + * @param HTMLPurifier_Config $config + */ + public function __construct($config) + { + $def = $config->getCSSDefinition(); + $this->info['background-color'] = $def->info['background-color']; + $this->info['background-image'] = $def->info['background-image']; + $this->info['background-repeat'] = $def->info['background-repeat']; + $this->info['background-attachment'] = $def->info['background-attachment']; + $this->info['background-position'] = $def->info['background-position']; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + // regular pre-processing + $string = $this->parseCDATA($string); + if ($string === '') { + return false; + } + + // munge rgb() decl if necessary + $string = $this->mungeRgb($string); + + // assumes URI doesn't have spaces in it + $bits = explode(' ', $string); // bits to process + + $caught = array(); + $caught['color'] = false; + $caught['image'] = false; + $caught['repeat'] = false; + $caught['attachment'] = false; + $caught['position'] = false; + + $i = 0; // number of catches + + foreach ($bits as $bit) { + if ($bit === '') { + continue; + } + foreach ($caught as $key => $status) { + if ($key != 'position') { + if ($status !== false) { + continue; + } + $r = $this->info['background-' . $key]->validate($bit, $config, $context); + } else { + $r = $bit; + } + if ($r === false) { + continue; + } + if ($key == 'position') { + if ($caught[$key] === false) { + $caught[$key] = ''; + } + $caught[$key] .= $r . ' '; + } else { + $caught[$key] = $r; + } + $i++; + break; + } + } + + if (!$i) { + return false; + } + if ($caught['position'] !== false) { + $caught['position'] = $this->info['background-position']-> + validate($caught['position'], $config, $context); + } + + $ret = array(); + foreach ($caught as $value) { + if ($value === false) { + continue; + } + $ret[] = $value; + } + + if (empty($ret)) { + return false; + } + return implode(' ', $ret); + } +} + + + + + +/* W3C says: + [ // adjective and number must be in correct order, even if + // you could switch them without introducing ambiguity. + // some browsers support that syntax + [ + | | left | center | right + ] + [ + | | top | center | bottom + ]? + ] | + [ // this signifies that the vertical and horizontal adjectives + // can be arbitrarily ordered, however, there can only be two, + // one of each, or none at all + [ + left | center | right + ] || + [ + top | center | bottom + ] + ] + top, left = 0% + center, (none) = 50% + bottom, right = 100% +*/ + +/* QuirksMode says: + keyword + length/percentage must be ordered correctly, as per W3C + + Internet Explorer and Opera, however, support arbitrary ordering. We + should fix it up. + + Minor issue though, not strictly necessary. +*/ + +// control freaks may appreciate the ability to convert these to +// percentages or something, but it's not necessary + +/** + * Validates the value of background-position. + */ +class HTMLPurifier_AttrDef_CSS_BackgroundPosition extends HTMLPurifier_AttrDef +{ + + /** + * @type HTMLPurifier_AttrDef_CSS_Length + */ + protected $length; + + /** + * @type HTMLPurifier_AttrDef_CSS_Percentage + */ + protected $percentage; + + public function __construct() + { + $this->length = new HTMLPurifier_AttrDef_CSS_Length(); + $this->percentage = new HTMLPurifier_AttrDef_CSS_Percentage(); + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = $this->parseCDATA($string); + $bits = explode(' ', $string); + + $keywords = array(); + $keywords['h'] = false; // left, right + $keywords['v'] = false; // top, bottom + $keywords['ch'] = false; // center (first word) + $keywords['cv'] = false; // center (second word) + $measures = array(); + + $i = 0; + + $lookup = array( + 'top' => 'v', + 'bottom' => 'v', + 'left' => 'h', + 'right' => 'h', + 'center' => 'c' + ); + + foreach ($bits as $bit) { + if ($bit === '') { + continue; + } + + // test for keyword + $lbit = ctype_lower($bit) ? $bit : strtolower($bit); + if (isset($lookup[$lbit])) { + $status = $lookup[$lbit]; + if ($status == 'c') { + if ($i == 0) { + $status = 'ch'; + } else { + $status = 'cv'; + } + } + $keywords[$status] = $lbit; + $i++; + } + + // test for length + $r = $this->length->validate($bit, $config, $context); + if ($r !== false) { + $measures[] = $r; + $i++; + } + + // test for percentage + $r = $this->percentage->validate($bit, $config, $context); + if ($r !== false) { + $measures[] = $r; + $i++; + } + } + + if (!$i) { + return false; + } // no valid values were caught + + $ret = array(); + + // first keyword + if ($keywords['h']) { + $ret[] = $keywords['h']; + } elseif ($keywords['ch']) { + $ret[] = $keywords['ch']; + $keywords['cv'] = false; // prevent re-use: center = center center + } elseif (count($measures)) { + $ret[] = array_shift($measures); + } + + if ($keywords['v']) { + $ret[] = $keywords['v']; + } elseif ($keywords['cv']) { + $ret[] = $keywords['cv']; + } elseif (count($measures)) { + $ret[] = array_shift($measures); + } + + if (empty($ret)) { + return false; + } + return implode(' ', $ret); + } +} + + + + + +/** + * Validates the border property as defined by CSS. + */ +class HTMLPurifier_AttrDef_CSS_Border extends HTMLPurifier_AttrDef +{ + + /** + * Local copy of properties this property is shorthand for. + * @type HTMLPurifier_AttrDef[] + */ + protected $info = array(); + + /** + * @param HTMLPurifier_Config $config + */ + public function __construct($config) + { + $def = $config->getCSSDefinition(); + $this->info['border-width'] = $def->info['border-width']; + $this->info['border-style'] = $def->info['border-style']; + $this->info['border-top-color'] = $def->info['border-top-color']; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = $this->parseCDATA($string); + $string = $this->mungeRgb($string); + $bits = explode(' ', $string); + $done = array(); // segments we've finished + $ret = ''; // return value + foreach ($bits as $bit) { + foreach ($this->info as $propname => $validator) { + if (isset($done[$propname])) { + continue; + } + $r = $validator->validate($bit, $config, $context); + if ($r !== false) { + $ret .= $r . ' '; + $done[$propname] = true; + break; + } + } + } + return rtrim($ret); + } +} + + + + + +/** + * Validates Color as defined by CSS. + */ +class HTMLPurifier_AttrDef_CSS_Color extends HTMLPurifier_AttrDef +{ + + /** + * @type HTMLPurifier_AttrDef_CSS_AlphaValue + */ + protected $alpha; + + public function __construct() + { + $this->alpha = new HTMLPurifier_AttrDef_CSS_AlphaValue(); + } + + /** + * @param string $color + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($color, $config, $context) + { + static $colors = null; + if ($colors === null) { + $colors = $config->get('Core.ColorKeywords'); + } + + $color = trim($color); + if ($color === '') { + return false; + } + + $lower = strtolower($color); + if (isset($colors[$lower])) { + return $colors[$lower]; + } + + if (preg_match('#(rgb|rgba|hsl|hsla)\(#', $color, $matches) === 1) { + $length = strlen($color); + if (strpos($color, ')') !== $length - 1) { + return false; + } + + // get used function : rgb, rgba, hsl or hsla + $function = $matches[1]; + + $parameters_size = 3; + $alpha_channel = false; + if (substr($function, -1) === 'a') { + $parameters_size = 4; + $alpha_channel = true; + } + + /* + * Allowed types for values : + * parameter_position => [type => max_value] + */ + $allowed_types = array( + 1 => array('percentage' => 100, 'integer' => 255), + 2 => array('percentage' => 100, 'integer' => 255), + 3 => array('percentage' => 100, 'integer' => 255), + ); + $allow_different_types = false; + + if (strpos($function, 'hsl') !== false) { + $allowed_types = array( + 1 => array('integer' => 360), + 2 => array('percentage' => 100), + 3 => array('percentage' => 100), + ); + $allow_different_types = true; + } + + $values = trim(str_replace($function, '', $color), ' ()'); + + $parts = explode(',', $values); + if (count($parts) !== $parameters_size) { + return false; + } + + $type = false; + $new_parts = array(); + $i = 0; + + foreach ($parts as $part) { + $i++; + $part = trim($part); + + if ($part === '') { + return false; + } + + // different check for alpha channel + if ($alpha_channel === true && $i === count($parts)) { + $result = $this->alpha->validate($part, $config, $context); + + if ($result === false) { + return false; + } + + $new_parts[] = (string)$result; + continue; + } + + if (substr($part, -1) === '%') { + $current_type = 'percentage'; + } else { + $current_type = 'integer'; + } + + if (!array_key_exists($current_type, $allowed_types[$i])) { + return false; + } + + if (!$type) { + $type = $current_type; + } + + if ($allow_different_types === false && $type != $current_type) { + return false; + } + + $max_value = $allowed_types[$i][$current_type]; + + if ($current_type == 'integer') { + // Return value between range 0 -> $max_value + $new_parts[] = (int)max(min($part, $max_value), 0); + } elseif ($current_type == 'percentage') { + $new_parts[] = (float)max(min(rtrim($part, '%'), $max_value), 0) . '%'; + } + } + + $new_values = implode(',', $new_parts); + + $color = $function . '(' . $new_values . ')'; + } else { + // hexadecimal handling + if ($color[0] === '#') { + $hex = substr($color, 1); + } else { + $hex = $color; + $color = '#' . $color; + } + $length = strlen($hex); + if ($length !== 3 && $length !== 6) { + return false; + } + if (!ctype_xdigit($hex)) { + return false; + } + } + return $color; + } + +} + + + + + +/** + * Allows multiple validators to attempt to validate attribute. + * + * Composite is just what it sounds like: a composite of many validators. + * This means that multiple HTMLPurifier_AttrDef objects will have a whack + * at the string. If one of them passes, that's what is returned. This is + * especially useful for CSS values, which often are a choice between + * an enumerated set of predefined values or a flexible data type. + */ +class HTMLPurifier_AttrDef_CSS_Composite extends HTMLPurifier_AttrDef +{ + + /** + * List of objects that may process strings. + * @type HTMLPurifier_AttrDef[] + * @todo Make protected + */ + public $defs; + + /** + * @param HTMLPurifier_AttrDef[] $defs List of HTMLPurifier_AttrDef objects + */ + public function __construct($defs) + { + $this->defs = $defs; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + foreach ($this->defs as $i => $def) { + $result = $this->defs[$i]->validate($string, $config, $context); + if ($result !== false) { + return $result; + } + } + return false; + } +} + + + + + +/** + * Decorator which enables CSS properties to be disabled for specific elements. + */ +class HTMLPurifier_AttrDef_CSS_DenyElementDecorator extends HTMLPurifier_AttrDef +{ + /** + * @type HTMLPurifier_AttrDef + */ + public $def; + /** + * @type string + */ + public $element; + + /** + * @param HTMLPurifier_AttrDef $def Definition to wrap + * @param string $element Element to deny + */ + public function __construct($def, $element) + { + $this->def = $def; + $this->element = $element; + } + + /** + * Checks if CurrentToken is set and equal to $this->element + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $token = $context->get('CurrentToken', true); + if ($token && $token->name == $this->element) { + return false; + } + return $this->def->validate($string, $config, $context); + } +} + + + + + +/** + * Microsoft's proprietary filter: CSS property + * @note Currently supports the alpha filter. In the future, this will + * probably need an extensible framework + */ +class HTMLPurifier_AttrDef_CSS_Filter extends HTMLPurifier_AttrDef +{ + /** + * @type HTMLPurifier_AttrDef_Integer + */ + protected $intValidator; + + public function __construct() + { + $this->intValidator = new HTMLPurifier_AttrDef_Integer(); + } + + /** + * @param string $value + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($value, $config, $context) + { + $value = $this->parseCDATA($value); + if ($value === 'none') { + return $value; + } + // if we looped this we could support multiple filters + $function_length = strcspn($value, '('); + $function = trim(substr($value, 0, $function_length)); + if ($function !== 'alpha' && + $function !== 'Alpha' && + $function !== 'progid:DXImageTransform.Microsoft.Alpha' + ) { + return false; + } + $cursor = $function_length + 1; + $parameters_length = strcspn($value, ')', $cursor); + $parameters = substr($value, $cursor, $parameters_length); + $params = explode(',', $parameters); + $ret_params = array(); + $lookup = array(); + foreach ($params as $param) { + list($key, $value) = explode('=', $param); + $key = trim($key); + $value = trim($value); + if (isset($lookup[$key])) { + continue; + } + if ($key !== 'opacity') { + continue; + } + $value = $this->intValidator->validate($value, $config, $context); + if ($value === false) { + continue; + } + $int = (int)$value; + if ($int > 100) { + $value = '100'; + } + if ($int < 0) { + $value = '0'; + } + $ret_params[] = "$key=$value"; + $lookup[$key] = true; + } + $ret_parameters = implode(',', $ret_params); + $ret_function = "$function($ret_parameters)"; + return $ret_function; + } +} + + + + + +/** + * Validates shorthand CSS property font. + */ +class HTMLPurifier_AttrDef_CSS_Font extends HTMLPurifier_AttrDef +{ + + /** + * Local copy of validators + * @type HTMLPurifier_AttrDef[] + * @note If we moved specific CSS property definitions to their own + * classes instead of having them be assembled at run time by + * CSSDefinition, this wouldn't be necessary. We'd instantiate + * our own copies. + */ + protected $info = array(); + + /** + * @param HTMLPurifier_Config $config + */ + public function __construct($config) + { + $def = $config->getCSSDefinition(); + $this->info['font-style'] = $def->info['font-style']; + $this->info['font-variant'] = $def->info['font-variant']; + $this->info['font-weight'] = $def->info['font-weight']; + $this->info['font-size'] = $def->info['font-size']; + $this->info['line-height'] = $def->info['line-height']; + $this->info['font-family'] = $def->info['font-family']; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + static $system_fonts = array( + 'caption' => true, + 'icon' => true, + 'menu' => true, + 'message-box' => true, + 'small-caption' => true, + 'status-bar' => true + ); + + // regular pre-processing + $string = $this->parseCDATA($string); + if ($string === '') { + return false; + } + + // check if it's one of the keywords + $lowercase_string = strtolower($string); + if (isset($system_fonts[$lowercase_string])) { + return $lowercase_string; + } + + $bits = explode(' ', $string); // bits to process + $stage = 0; // this indicates what we're looking for + $caught = array(); // which stage 0 properties have we caught? + $stage_1 = array('font-style', 'font-variant', 'font-weight'); + $final = ''; // output + + for ($i = 0, $size = count($bits); $i < $size; $i++) { + if ($bits[$i] === '') { + continue; + } + switch ($stage) { + case 0: // attempting to catch font-style, font-variant or font-weight + foreach ($stage_1 as $validator_name) { + if (isset($caught[$validator_name])) { + continue; + } + $r = $this->info[$validator_name]->validate( + $bits[$i], + $config, + $context + ); + if ($r !== false) { + $final .= $r . ' '; + $caught[$validator_name] = true; + break; + } + } + // all three caught, continue on + if (count($caught) >= 3) { + $stage = 1; + } + if ($r !== false) { + break; + } + case 1: // attempting to catch font-size and perhaps line-height + $found_slash = false; + if (strpos($bits[$i], '/') !== false) { + list($font_size, $line_height) = + explode('/', $bits[$i]); + if ($line_height === '') { + // ooh, there's a space after the slash! + $line_height = false; + $found_slash = true; + } + } else { + $font_size = $bits[$i]; + $line_height = false; + } + $r = $this->info['font-size']->validate( + $font_size, + $config, + $context + ); + if ($r !== false) { + $final .= $r; + // attempt to catch line-height + if ($line_height === false) { + // we need to scroll forward + for ($j = $i + 1; $j < $size; $j++) { + if ($bits[$j] === '') { + continue; + } + if ($bits[$j] === '/') { + if ($found_slash) { + return false; + } else { + $found_slash = true; + continue; + } + } + $line_height = $bits[$j]; + break; + } + } else { + // slash already found + $found_slash = true; + $j = $i; + } + if ($found_slash) { + $i = $j; + $r = $this->info['line-height']->validate( + $line_height, + $config, + $context + ); + if ($r !== false) { + $final .= '/' . $r; + } + } + $final .= ' '; + $stage = 2; + break; + } + return false; + case 2: // attempting to catch font-family + $font_family = + implode(' ', array_slice($bits, $i, $size - $i)); + $r = $this->info['font-family']->validate( + $font_family, + $config, + $context + ); + if ($r !== false) { + $final .= $r . ' '; + // processing completed successfully + return rtrim($final); + } + return false; + } + } + return false; + } +} + + + + + +/** + * Validates a font family list according to CSS spec + */ +class HTMLPurifier_AttrDef_CSS_FontFamily extends HTMLPurifier_AttrDef +{ + + protected $mask = null; + + public function __construct() + { + $this->mask = '_- '; + for ($c = 'a'; $c <= 'z'; $c++) { + $this->mask .= $c; + } + for ($c = 'A'; $c <= 'Z'; $c++) { + $this->mask .= $c; + } + for ($c = '0'; $c <= '9'; $c++) { + $this->mask .= $c; + } // cast-y, but should be fine + // special bytes used by UTF-8 + for ($i = 0x80; $i <= 0xFF; $i++) { + // We don't bother excluding invalid bytes in this range, + // because the our restriction of well-formed UTF-8 will + // prevent these from ever occurring. + $this->mask .= chr($i); + } + + /* + PHP's internal strcspn implementation is + O(length of string * length of mask), making it inefficient + for large masks. However, it's still faster than + preg_match 8) + for (p = s1;;) { + spanp = s2; + do { + if (*spanp == c || p == s1_end) { + return p - s1; + } + } while (spanp++ < (s2_end - 1)); + c = *++p; + } + */ + // possible optimization: invert the mask. + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + static $generic_names = array( + 'serif' => true, + 'sans-serif' => true, + 'monospace' => true, + 'fantasy' => true, + 'cursive' => true + ); + $allowed_fonts = $config->get('CSS.AllowedFonts'); + + // assume that no font names contain commas in them + $fonts = explode(',', $string); + $final = ''; + foreach ($fonts as $font) { + $font = trim($font); + if ($font === '') { + continue; + } + // match a generic name + if (isset($generic_names[$font])) { + if ($allowed_fonts === null || isset($allowed_fonts[$font])) { + $final .= $font . ', '; + } + continue; + } + // match a quoted name + if ($font[0] === '"' || $font[0] === "'") { + $length = strlen($font); + if ($length <= 2) { + continue; + } + $quote = $font[0]; + if ($font[$length - 1] !== $quote) { + continue; + } + $font = substr($font, 1, $length - 2); + } + + $font = $this->expandCSSEscape($font); + + // $font is a pure representation of the font name + + if ($allowed_fonts !== null && !isset($allowed_fonts[$font])) { + continue; + } + + if (ctype_alnum($font) && $font !== '') { + // very simple font, allow it in unharmed + $final .= $font . ', '; + continue; + } + + // bugger out on whitespace. form feed (0C) really + // shouldn't show up regardless + $font = str_replace(array("\n", "\t", "\r", "\x0C"), ' ', $font); + + // Here, there are various classes of characters which need + // to be treated differently: + // - Alphanumeric characters are essentially safe. We + // handled these above. + // - Spaces require quoting, though most parsers will do + // the right thing if there aren't any characters that + // can be misinterpreted + // - Dashes rarely occur, but they fairly unproblematic + // for parsing/rendering purposes. + // The above characters cover the majority of Western font + // names. + // - Arbitrary Unicode characters not in ASCII. Because + // most parsers give little thought to Unicode, treatment + // of these codepoints is basically uniform, even for + // punctuation-like codepoints. These characters can + // show up in non-Western pages and are supported by most + // major browsers, for example: "ï¼­ï¼³ 明æœ" is a + // legitimate font-name + // . See + // the CSS3 spec for more examples: + // + // You can see live samples of these on the Internet: + // + // However, most of these fonts have ASCII equivalents: + // for example, 'MS Mincho', and it's considered + // professional to use ASCII font names instead of + // Unicode font names. Thanks Takeshi Terada for + // providing this information. + // The following characters, to my knowledge, have not been + // used to name font names. + // - Single quote. While theoretically you might find a + // font name that has a single quote in its name (serving + // as an apostrophe, e.g. Dave's Scribble), I haven't + // been able to find any actual examples of this. + // Internet Explorer's cssText translation (which I + // believe is invoked by innerHTML) normalizes any + // quoting to single quotes, and fails to escape single + // quotes. (Note that this is not IE's behavior for all + // CSS properties, just some sort of special casing for + // font-family). So a single quote *cannot* be used + // safely in the font-family context if there will be an + // innerHTML/cssText translation. Note that Firefox 3.x + // does this too. + // - Double quote. In IE, these get normalized to + // single-quotes, no matter what the encoding. (Fun + // fact, in IE8, the 'content' CSS property gained + // support, where they special cased to preserve encoded + // double quotes, but still translate unadorned double + // quotes into single quotes.) So, because their + // fixpoint behavior is identical to single quotes, they + // cannot be allowed either. Firefox 3.x displays + // single-quote style behavior. + // - Backslashes are reduced by one (so \\ -> \) every + // iteration, so they cannot be used safely. This shows + // up in IE7, IE8 and FF3 + // - Semicolons, commas and backticks are handled properly. + // - The rest of the ASCII punctuation is handled properly. + // We haven't checked what browsers do to unadorned + // versions, but this is not important as long as the + // browser doesn't /remove/ surrounding quotes (as IE does + // for HTML). + // + // With these results in hand, we conclude that there are + // various levels of safety: + // - Paranoid: alphanumeric, spaces and dashes(?) + // - International: Paranoid + non-ASCII Unicode + // - Edgy: Everything except quotes, backslashes + // - NoJS: Standards compliance, e.g. sod IE. Note that + // with some judicious character escaping (since certain + // types of escaping doesn't work) this is theoretically + // OK as long as innerHTML/cssText is not called. + // We believe that international is a reasonable default + // (that we will implement now), and once we do more + // extensive research, we may feel comfortable with dropping + // it down to edgy. + + // Edgy: alphanumeric, spaces, dashes, underscores and Unicode. Use of + // str(c)spn assumes that the string was already well formed + // Unicode (which of course it is). + if (strspn($font, $this->mask) !== strlen($font)) { + continue; + } + + // Historical: + // In the absence of innerHTML/cssText, these ugly + // transforms don't pose a security risk (as \\ and \" + // might--these escapes are not supported by most browsers). + // We could try to be clever and use single-quote wrapping + // when there is a double quote present, but I have choosen + // not to implement that. (NOTE: you can reduce the amount + // of escapes by one depending on what quoting style you use) + // $font = str_replace('\\', '\\5C ', $font); + // $font = str_replace('"', '\\22 ', $font); + // $font = str_replace("'", '\\27 ', $font); + + // font possibly with spaces, requires quoting + $final .= "'$font', "; + } + $final = rtrim($final, ', '); + if ($final === '') { + return false; + } + return $final; + } + +} + + + + + +/** + * Validates based on {ident} CSS grammar production + */ +class HTMLPurifier_AttrDef_CSS_Ident extends HTMLPurifier_AttrDef +{ + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = trim($string); + + // early abort: '' and '0' (strings that convert to false) are invalid + if (!$string) { + return false; + } + + $pattern = '/^(-?[A-Za-z_][A-Za-z_\-0-9]*)$/'; + if (!preg_match($pattern, $string)) { + return false; + } + return $string; + } +} + + + + + +/** + * Decorator which enables !important to be used in CSS values. + */ +class HTMLPurifier_AttrDef_CSS_ImportantDecorator extends HTMLPurifier_AttrDef +{ + /** + * @type HTMLPurifier_AttrDef + */ + public $def; + /** + * @type bool + */ + public $allow; + + /** + * @param HTMLPurifier_AttrDef $def Definition to wrap + * @param bool $allow Whether or not to allow !important + */ + public function __construct($def, $allow = false) + { + $this->def = $def; + $this->allow = $allow; + } + + /** + * Intercepts and removes !important if necessary + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + // test for ! and important tokens + $string = trim($string); + $is_important = false; + // :TODO: optimization: test directly for !important and ! important + if (strlen($string) >= 9 && substr($string, -9) === 'important') { + $temp = rtrim(substr($string, 0, -9)); + // use a temp, because we might want to restore important + if (strlen($temp) >= 1 && substr($temp, -1) === '!') { + $string = rtrim(substr($temp, 0, -1)); + $is_important = true; + } + } + $string = $this->def->validate($string, $config, $context); + if ($this->allow && $is_important) { + $string .= ' !important'; + } + return $string; + } +} + + + + + +/** + * Represents a Length as defined by CSS. + */ +class HTMLPurifier_AttrDef_CSS_Length extends HTMLPurifier_AttrDef +{ + + /** + * @type HTMLPurifier_Length|string + */ + protected $min; + + /** + * @type HTMLPurifier_Length|string + */ + protected $max; + + /** + * @param HTMLPurifier_Length|string $min Minimum length, or null for no bound. String is also acceptable. + * @param HTMLPurifier_Length|string $max Maximum length, or null for no bound. String is also acceptable. + */ + public function __construct($min = null, $max = null) + { + $this->min = $min !== null ? HTMLPurifier_Length::make($min) : null; + $this->max = $max !== null ? HTMLPurifier_Length::make($max) : null; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = $this->parseCDATA($string); + + // Optimizations + if ($string === '') { + return false; + } + if ($string === '0') { + return '0'; + } + if (strlen($string) === 1) { + return false; + } + + $length = HTMLPurifier_Length::make($string); + if (!$length->isValid()) { + return false; + } + + if ($this->min) { + $c = $length->compareTo($this->min); + if ($c === false) { + return false; + } + if ($c < 0) { + return false; + } + } + if ($this->max) { + $c = $length->compareTo($this->max); + if ($c === false) { + return false; + } + if ($c > 0) { + return false; + } + } + return $length->toString(); + } +} + + + + + +/** + * Validates shorthand CSS property list-style. + * @warning Does not support url tokens that have internal spaces. + */ +class HTMLPurifier_AttrDef_CSS_ListStyle extends HTMLPurifier_AttrDef +{ + + /** + * Local copy of validators. + * @type HTMLPurifier_AttrDef[] + * @note See HTMLPurifier_AttrDef_CSS_Font::$info for a similar impl. + */ + protected $info; + + /** + * @param HTMLPurifier_Config $config + */ + public function __construct($config) + { + $def = $config->getCSSDefinition(); + $this->info['list-style-type'] = $def->info['list-style-type']; + $this->info['list-style-position'] = $def->info['list-style-position']; + $this->info['list-style-image'] = $def->info['list-style-image']; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + // regular pre-processing + $string = $this->parseCDATA($string); + if ($string === '') { + return false; + } + + // assumes URI doesn't have spaces in it + $bits = explode(' ', strtolower($string)); // bits to process + + $caught = array(); + $caught['type'] = false; + $caught['position'] = false; + $caught['image'] = false; + + $i = 0; // number of catches + $none = false; + + foreach ($bits as $bit) { + if ($i >= 3) { + return; + } // optimization bit + if ($bit === '') { + continue; + } + foreach ($caught as $key => $status) { + if ($status !== false) { + continue; + } + $r = $this->info['list-style-' . $key]->validate($bit, $config, $context); + if ($r === false) { + continue; + } + if ($r === 'none') { + if ($none) { + continue; + } else { + $none = true; + } + if ($key == 'image') { + continue; + } + } + $caught[$key] = $r; + $i++; + break; + } + } + + if (!$i) { + return false; + } + + $ret = array(); + + // construct type + if ($caught['type']) { + $ret[] = $caught['type']; + } + + // construct image + if ($caught['image']) { + $ret[] = $caught['image']; + } + + // construct position + if ($caught['position']) { + $ret[] = $caught['position']; + } + + if (empty($ret)) { + return false; + } + return implode(' ', $ret); + } +} + + + + + +/** + * Framework class for strings that involve multiple values. + * + * Certain CSS properties such as border-width and margin allow multiple + * lengths to be specified. This class can take a vanilla border-width + * definition and multiply it, usually into a max of four. + * + * @note Even though the CSS specification isn't clear about it, inherit + * can only be used alone: it will never manifest as part of a multi + * shorthand declaration. Thus, this class does not allow inherit. + */ +class HTMLPurifier_AttrDef_CSS_Multiple extends HTMLPurifier_AttrDef +{ + /** + * Instance of component definition to defer validation to. + * @type HTMLPurifier_AttrDef + * @todo Make protected + */ + public $single; + + /** + * Max number of values allowed. + * @todo Make protected + */ + public $max; + + /** + * @param HTMLPurifier_AttrDef $single HTMLPurifier_AttrDef to multiply + * @param int $max Max number of values allowed (usually four) + */ + public function __construct($single, $max = 4) + { + $this->single = $single; + $this->max = $max; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = $this->mungeRgb($this->parseCDATA($string)); + if ($string === '') { + return false; + } + $parts = explode(' ', $string); // parseCDATA replaced \r, \t and \n + $length = count($parts); + $final = ''; + for ($i = 0, $num = 0; $i < $length && $num < $this->max; $i++) { + if (ctype_space($parts[$i])) { + continue; + } + $result = $this->single->validate($parts[$i], $config, $context); + if ($result !== false) { + $final .= $result . ' '; + $num++; + } + } + if ($final === '') { + return false; + } + return rtrim($final); + } +} + + + + + +/** + * Validates a Percentage as defined by the CSS spec. + */ +class HTMLPurifier_AttrDef_CSS_Percentage extends HTMLPurifier_AttrDef +{ + + /** + * Instance to defer number validation to. + * @type HTMLPurifier_AttrDef_CSS_Number + */ + protected $number_def; + + /** + * @param bool $non_negative Whether to forbid negative values + */ + public function __construct($non_negative = false) + { + $this->number_def = new HTMLPurifier_AttrDef_CSS_Number($non_negative); + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = $this->parseCDATA($string); + + if ($string === '') { + return false; + } + $length = strlen($string); + if ($length === 1) { + return false; + } + if ($string[$length - 1] !== '%') { + return false; + } + + $number = substr($string, 0, $length - 1); + $number = $this->number_def->validate($number, $config, $context); + + if ($number === false) { + return false; + } + return "$number%"; + } +} + + + + + +/** + * Validates the value for the CSS property text-decoration + * @note This class could be generalized into a version that acts sort of + * like Enum except you can compound the allowed values. + */ +class HTMLPurifier_AttrDef_CSS_TextDecoration extends HTMLPurifier_AttrDef +{ + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + static $allowed_values = array( + 'line-through' => true, + 'overline' => true, + 'underline' => true, + ); + + $string = strtolower($this->parseCDATA($string)); + + if ($string === 'none') { + return $string; + } + + $parts = explode(' ', $string); + $final = ''; + foreach ($parts as $part) { + if (isset($allowed_values[$part])) { + $final .= $part . ' '; + } + } + $final = rtrim($final); + if ($final === '') { + return false; + } + return $final; + } +} + + + + + +/** + * Validates a URI in CSS syntax, which uses url('http://example.com') + * @note While theoretically speaking a URI in a CSS document could + * be non-embedded, as of CSS2 there is no such usage so we're + * generalizing it. This may need to be changed in the future. + * @warning Since HTMLPurifier_AttrDef_CSS blindly uses semicolons as + * the separator, you cannot put a literal semicolon in + * in the URI. Try percent encoding it, in that case. + */ +class HTMLPurifier_AttrDef_CSS_URI extends HTMLPurifier_AttrDef_URI +{ + + public function __construct() + { + parent::__construct(true); // always embedded + } + + /** + * @param string $uri_string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($uri_string, $config, $context) + { + // parse the URI out of the string and then pass it onto + // the parent object + + $uri_string = $this->parseCDATA($uri_string); + if (strpos($uri_string, 'url(') !== 0) { + return false; + } + $uri_string = substr($uri_string, 4); + if (strlen($uri_string) == 0) { + return false; + } + $new_length = strlen($uri_string) - 1; + if ($uri_string[$new_length] != ')') { + return false; + } + $uri = trim(substr($uri_string, 0, $new_length)); + + if (!empty($uri) && ($uri[0] == "'" || $uri[0] == '"')) { + $quote = $uri[0]; + $new_length = strlen($uri) - 1; + if ($uri[$new_length] !== $quote) { + return false; + } + $uri = substr($uri, 1, $new_length - 1); + } + + $uri = $this->expandCSSEscape($uri); + + $result = parent::validate($uri, $config, $context); + + if ($result === false) { + return false; + } + + // extra sanity check; should have been done by URI + $result = str_replace(array('"', "\\", "\n", "\x0c", "\r"), "", $result); + + // suspicious characters are ()'; we're going to percent encode + // them for safety. + $result = str_replace(array('(', ')', "'"), array('%28', '%29', '%27'), $result); + + // there's an extra bug where ampersands lose their escaping on + // an innerHTML cycle, so a very unlucky query parameter could + // then change the meaning of the URL. Unfortunately, there's + // not much we can do about that... + return "url(\"$result\")"; + } +} + + + + + +/** + * Validates a boolean attribute + */ +class HTMLPurifier_AttrDef_HTML_Bool extends HTMLPurifier_AttrDef +{ + + /** + * @type string + */ + protected $name; + + /** + * @type bool + */ + public $minimized = true; + + /** + * @param bool|string $name + */ + public function __construct($name = false) + { + $this->name = $name; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + return $this->name; + } + + /** + * @param string $string Name of attribute + * @return HTMLPurifier_AttrDef_HTML_Bool + */ + public function make($string) + { + return new HTMLPurifier_AttrDef_HTML_Bool($string); + } +} + + + + + +/** + * Validates contents based on NMTOKENS attribute type. + */ +class HTMLPurifier_AttrDef_HTML_Nmtokens extends HTMLPurifier_AttrDef +{ + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = trim($string); + + // early abort: '' and '0' (strings that convert to false) are invalid + if (!$string) { + return false; + } + + $tokens = $this->split($string, $config, $context); + $tokens = $this->filter($tokens, $config, $context); + if (empty($tokens)) { + return false; + } + return implode(' ', $tokens); + } + + /** + * Splits a space separated list of tokens into its constituent parts. + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + protected function split($string, $config, $context) + { + // OPTIMIZABLE! + // do the preg_match, capture all subpatterns for reformulation + + // we don't support U+00A1 and up codepoints or + // escaping because I don't know how to do that with regexps + // and plus it would complicate optimization efforts (you never + // see that anyway). + $pattern = '/(?:(?<=\s)|\A)' . // look behind for space or string start + '((?:--|-?[A-Za-z_])[A-Za-z_\-0-9]*)' . + '(?:(?=\s)|\z)/'; // look ahead for space or string end + preg_match_all($pattern, $string, $matches); + return $matches[1]; + } + + /** + * Template method for removing certain tokens based on arbitrary criteria. + * @note If we wanted to be really functional, we'd do an array_filter + * with a callback. But... we're not. + * @param array $tokens + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + protected function filter($tokens, $config, $context) + { + return $tokens; + } +} + + + + + +/** + * Implements special behavior for class attribute (normally NMTOKENS) + */ +class HTMLPurifier_AttrDef_HTML_Class extends HTMLPurifier_AttrDef_HTML_Nmtokens +{ + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + protected function split($string, $config, $context) + { + // really, this twiddle should be lazy loaded + $name = $config->getDefinition('HTML')->doctype->name; + if ($name == "XHTML 1.1" || $name == "XHTML 2.0") { + return parent::split($string, $config, $context); + } else { + return preg_split('/\s+/', $string); + } + } + + /** + * @param array $tokens + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + protected function filter($tokens, $config, $context) + { + $allowed = $config->get('Attr.AllowedClasses'); + $forbidden = $config->get('Attr.ForbiddenClasses'); + $ret = array(); + foreach ($tokens as $token) { + if (($allowed === null || isset($allowed[$token])) && + !isset($forbidden[$token]) && + // We need this O(n) check because of PHP's array + // implementation that casts -0 to 0. + !in_array($token, $ret, true) + ) { + $ret[] = $token; + } + } + return $ret; + } +} + + + +/** + * Validates a color according to the HTML spec. + */ +class HTMLPurifier_AttrDef_HTML_Color extends HTMLPurifier_AttrDef +{ + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + static $colors = null; + if ($colors === null) { + $colors = $config->get('Core.ColorKeywords'); + } + + $string = trim($string); + + if (empty($string)) { + return false; + } + $lower = strtolower($string); + if (isset($colors[$lower])) { + return $colors[$lower]; + } + if ($string[0] === '#') { + $hex = substr($string, 1); + } else { + $hex = $string; + } + + $length = strlen($hex); + if ($length !== 3 && $length !== 6) { + return false; + } + if (!ctype_xdigit($hex)) { + return false; + } + if ($length === 3) { + $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2]; + } + return "#$hex"; + } +} + + + + + +/** + * Special-case enum attribute definition that lazy loads allowed frame targets + */ +class HTMLPurifier_AttrDef_HTML_FrameTarget extends HTMLPurifier_AttrDef_Enum +{ + + /** + * @type array + */ + public $valid_values = false; // uninitialized value + + /** + * @type bool + */ + protected $case_sensitive = false; + + public function __construct() + { + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + if ($this->valid_values === false) { + $this->valid_values = $config->get('Attr.AllowedFrameTargets'); + } + return parent::validate($string, $config, $context); + } +} + + + + + +/** + * Validates the HTML attribute ID. + * @warning Even though this is the id processor, it + * will ignore the directive Attr:IDBlacklist, since it will only + * go according to the ID accumulator. Since the accumulator is + * automatically generated, it will have already absorbed the + * blacklist. If you're hacking around, make sure you use load()! + */ + +class HTMLPurifier_AttrDef_HTML_ID extends HTMLPurifier_AttrDef +{ + + // selector is NOT a valid thing to use for IDREFs, because IDREFs + // *must* target IDs that exist, whereas selector #ids do not. + + /** + * Determines whether or not we're validating an ID in a CSS + * selector context. + * @type bool + */ + protected $selector; + + /** + * @param bool $selector + */ + public function __construct($selector = false) + { + $this->selector = $selector; + } + + /** + * @param string $id + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($id, $config, $context) + { + if (!$this->selector && !$config->get('Attr.EnableID')) { + return false; + } + + $id = trim($id); // trim it first + + if ($id === '') { + return false; + } + + $prefix = $config->get('Attr.IDPrefix'); + if ($prefix !== '') { + $prefix .= $config->get('Attr.IDPrefixLocal'); + // prevent re-appending the prefix + if (strpos($id, $prefix) !== 0) { + $id = $prefix . $id; + } + } elseif ($config->get('Attr.IDPrefixLocal') !== '') { + trigger_error( + '%Attr.IDPrefixLocal cannot be used unless ' . + '%Attr.IDPrefix is set', + E_USER_WARNING + ); + } + + if (!$this->selector) { + $id_accumulator =& $context->get('IDAccumulator'); + if (isset($id_accumulator->ids[$id])) { + return false; + } + } + + // we purposely avoid using regex, hopefully this is faster + + if ($config->get('Attr.ID.HTML5') === true) { + if (preg_match('/[\t\n\x0b\x0c ]/', $id)) { + return false; + } + } else { + if (ctype_alpha($id)) { + // OK + } else { + if (!ctype_alpha(@$id[0])) { + return false; + } + // primitive style of regexps, I suppose + $trim = trim( + $id, + 'A..Za..z0..9:-._' + ); + if ($trim !== '') { + return false; + } + } + } + + $regexp = $config->get('Attr.IDBlacklistRegexp'); + if ($regexp && preg_match($regexp, $id)) { + return false; + } + + if (!$this->selector) { + $id_accumulator->add($id); + } + + // if no change was made to the ID, return the result + // else, return the new id if stripping whitespace made it + // valid, or return false. + return $id; + } +} + + + + + +/** + * Validates an integer representation of pixels according to the HTML spec. + */ +class HTMLPurifier_AttrDef_HTML_Pixels extends HTMLPurifier_AttrDef +{ + + /** + * @type int + */ + protected $max; + + /** + * @param int $max + */ + public function __construct($max = null) + { + $this->max = $max; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = trim($string); + if ($string === '0') { + return $string; + } + if ($string === '') { + return false; + } + $length = strlen($string); + if (substr($string, $length - 2) == 'px') { + $string = substr($string, 0, $length - 2); + } + if (!is_numeric($string)) { + return false; + } + $int = (int)$string; + + if ($int < 0) { + return '0'; + } + + // upper-bound value, extremely high values can + // crash operating systems, see + // WARNING, above link WILL crash you if you're using Windows + + if ($this->max !== null && $int > $this->max) { + return (string)$this->max; + } + return (string)$int; + } + + /** + * @param string $string + * @return HTMLPurifier_AttrDef + */ + public function make($string) + { + if ($string === '') { + $max = null; + } else { + $max = (int)$string; + } + $class = get_class($this); + return new $class($max); + } +} + + + + + +/** + * Validates the HTML type length (not to be confused with CSS's length). + * + * This accepts integer pixels or percentages as lengths for certain + * HTML attributes. + */ + +class HTMLPurifier_AttrDef_HTML_Length extends HTMLPurifier_AttrDef_HTML_Pixels +{ + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = trim($string); + if ($string === '') { + return false; + } + + $parent_result = parent::validate($string, $config, $context); + if ($parent_result !== false) { + return $parent_result; + } + + $length = strlen($string); + $last_char = $string[$length - 1]; + + if ($last_char !== '%') { + return false; + } + + $points = substr($string, 0, $length - 1); + + if (!is_numeric($points)) { + return false; + } + + $points = (int)$points; + + if ($points < 0) { + return '0%'; + } + if ($points > 100) { + return '100%'; + } + return ((string)$points) . '%'; + } +} + + + + + +/** + * Validates a rel/rev link attribute against a directive of allowed values + * @note We cannot use Enum because link types allow multiple + * values. + * @note Assumes link types are ASCII text + */ +class HTMLPurifier_AttrDef_HTML_LinkTypes extends HTMLPurifier_AttrDef +{ + + /** + * Name config attribute to pull. + * @type string + */ + protected $name; + + /** + * @param string $name + */ + public function __construct($name) + { + $configLookup = array( + 'rel' => 'AllowedRel', + 'rev' => 'AllowedRev' + ); + if (!isset($configLookup[$name])) { + trigger_error( + 'Unrecognized attribute name for link ' . + 'relationship.', + E_USER_ERROR + ); + return; + } + $this->name = $configLookup[$name]; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $allowed = $config->get('Attr.' . $this->name); + if (empty($allowed)) { + return false; + } + + $string = $this->parseCDATA($string); + $parts = explode(' ', $string); + + // lookup to prevent duplicates + $ret_lookup = array(); + foreach ($parts as $part) { + $part = strtolower(trim($part)); + if (!isset($allowed[$part])) { + continue; + } + $ret_lookup[$part] = true; + } + + if (empty($ret_lookup)) { + return false; + } + $string = implode(' ', array_keys($ret_lookup)); + return $string; + } +} + + + + + +/** + * Validates a MultiLength as defined by the HTML spec. + * + * A multilength is either a integer (pixel count), a percentage, or + * a relative number. + */ +class HTMLPurifier_AttrDef_HTML_MultiLength extends HTMLPurifier_AttrDef_HTML_Length +{ + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = trim($string); + if ($string === '') { + return false; + } + + $parent_result = parent::validate($string, $config, $context); + if ($parent_result !== false) { + return $parent_result; + } + + $length = strlen($string); + $last_char = $string[$length - 1]; + + if ($last_char !== '*') { + return false; + } + + $int = substr($string, 0, $length - 1); + + if ($int == '') { + return '*'; + } + if (!is_numeric($int)) { + return false; + } + + $int = (int)$int; + if ($int < 0) { + return false; + } + if ($int == 0) { + return '0'; + } + if ($int == 1) { + return '*'; + } + return ((string)$int) . '*'; + } +} + + + + + +abstract class HTMLPurifier_AttrDef_URI_Email extends HTMLPurifier_AttrDef +{ + + /** + * Unpacks a mailbox into its display-name and address + * @param string $string + * @return mixed + */ + public function unpack($string) + { + // needs to be implemented + } + +} + +// sub-implementations + + + + + +/** + * Validates a host according to the IPv4, IPv6 and DNS (future) specifications. + */ +class HTMLPurifier_AttrDef_URI_Host extends HTMLPurifier_AttrDef +{ + + /** + * IPv4 sub-validator. + * @type HTMLPurifier_AttrDef_URI_IPv4 + */ + protected $ipv4; + + /** + * IPv6 sub-validator. + * @type HTMLPurifier_AttrDef_URI_IPv6 + */ + protected $ipv6; + + public function __construct() + { + $this->ipv4 = new HTMLPurifier_AttrDef_URI_IPv4(); + $this->ipv6 = new HTMLPurifier_AttrDef_URI_IPv6(); + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $length = strlen($string); + // empty hostname is OK; it's usually semantically equivalent: + // the default host as defined by a URI scheme is used: + // + // If the URI scheme defines a default for host, then that + // default applies when the host subcomponent is undefined + // or when the registered name is empty (zero length). + if ($string === '') { + return ''; + } + if ($length > 1 && $string[0] === '[' && $string[$length - 1] === ']') { + //IPv6 + $ip = substr($string, 1, $length - 2); + $valid = $this->ipv6->validate($ip, $config, $context); + if ($valid === false) { + return false; + } + return '[' . $valid . ']'; + } + + // need to do checks on unusual encodings too + $ipv4 = $this->ipv4->validate($string, $config, $context); + if ($ipv4 !== false) { + return $ipv4; + } + + // A regular domain name. + + // This doesn't match I18N domain names, but we don't have proper IRI support, + // so force users to insert Punycode. + + // There is not a good sense in which underscores should be + // allowed, since it's technically not! (And if you go as + // far to allow everything as specified by the DNS spec... + // well, that's literally everything, modulo some space limits + // for the components and the overall name (which, by the way, + // we are NOT checking!). So we (arbitrarily) decide this: + // let's allow underscores wherever we would have allowed + // hyphens, if they are enabled. This is a pretty good match + // for browser behavior, for example, a large number of browsers + // cannot handle foo_.example.com, but foo_bar.example.com is + // fairly well supported. + $underscore = $config->get('Core.AllowHostnameUnderscore') ? '_' : ''; + + // Based off of RFC 1738, but amended so that + // as per RFC 3696, the top label need only not be all numeric. + // The productions describing this are: + $a = '[a-z]'; // alpha + $an = '[a-z0-9]'; // alphanum + $and = "[a-z0-9-$underscore]"; // alphanum | "-" + // domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum + $domainlabel = "$an(?:$and*$an)?"; + // AMENDED as per RFC 3696 + // toplabel = alphanum | alphanum *( alphanum | "-" ) alphanum + // side condition: not all numeric + $toplabel = "$an(?:$and*$an)?"; + // hostname = *( domainlabel "." ) toplabel [ "." ] + if (preg_match("/^(?:$domainlabel\.)*($toplabel)\.?$/i", $string, $matches)) { + if (!ctype_digit($matches[1])) { + return $string; + } + } + + // PHP 5.3 and later support this functionality natively + if (function_exists('idn_to_ascii')) { + if (defined('IDNA_NONTRANSITIONAL_TO_ASCII') && defined('INTL_IDNA_VARIANT_UTS46')) { + $string = idn_to_ascii($string, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46); + } else { + $string = idn_to_ascii($string); + } + + // If we have Net_IDNA2 support, we can support IRIs by + // punycoding them. (This is the most portable thing to do, + // since otherwise we have to assume browsers support + } elseif ($config->get('Core.EnableIDNA')) { + $idna = new Net_IDNA2(array('encoding' => 'utf8', 'overlong' => false, 'strict' => true)); + // we need to encode each period separately + $parts = explode('.', $string); + try { + $new_parts = array(); + foreach ($parts as $part) { + $encodable = false; + for ($i = 0, $c = strlen($part); $i < $c; $i++) { + if (ord($part[$i]) > 0x7a) { + $encodable = true; + break; + } + } + if (!$encodable) { + $new_parts[] = $part; + } else { + $new_parts[] = $idna->encode($part); + } + } + $string = implode('.', $new_parts); + } catch (Exception $e) { + // XXX error reporting + } + } + // Try again + if (preg_match("/^($domainlabel\.)*$toplabel\.?$/i", $string)) { + return $string; + } + return false; + } +} + + + + + +/** + * Validates an IPv4 address + * @author Feyd @ forums.devnetwork.net (public domain) + */ +class HTMLPurifier_AttrDef_URI_IPv4 extends HTMLPurifier_AttrDef +{ + + /** + * IPv4 regex, protected so that IPv6 can reuse it. + * @type string + */ + protected $ip4; + + /** + * @param string $aIP + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($aIP, $config, $context) + { + if (!$this->ip4) { + $this->_loadRegex(); + } + + if (preg_match('#^' . $this->ip4 . '$#s', $aIP)) { + return $aIP; + } + return false; + } + + /** + * Lazy load function to prevent regex from being stuffed in + * cache. + */ + protected function _loadRegex() + { + $oct = '(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])'; // 0-255 + $this->ip4 = "(?:{$oct}\\.{$oct}\\.{$oct}\\.{$oct})"; + } +} + + + + + +/** + * Validates an IPv6 address. + * @author Feyd @ forums.devnetwork.net (public domain) + * @note This function requires brackets to have been removed from address + * in URI. + */ +class HTMLPurifier_AttrDef_URI_IPv6 extends HTMLPurifier_AttrDef_URI_IPv4 +{ + + /** + * @param string $aIP + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($aIP, $config, $context) + { + if (!$this->ip4) { + $this->_loadRegex(); + } + + $original = $aIP; + + $hex = '[0-9a-fA-F]'; + $blk = '(?:' . $hex . '{1,4})'; + $pre = '(?:/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))'; // /0 - /128 + + // prefix check + if (strpos($aIP, '/') !== false) { + if (preg_match('#' . $pre . '$#s', $aIP, $find)) { + $aIP = substr($aIP, 0, 0 - strlen($find[0])); + unset($find); + } else { + return false; + } + } + + // IPv4-compatiblity check + if (preg_match('#(?<=:' . ')' . $this->ip4 . '$#s', $aIP, $find)) { + $aIP = substr($aIP, 0, 0 - strlen($find[0])); + $ip = explode('.', $find[0]); + $ip = array_map('dechex', $ip); + $aIP .= $ip[0] . $ip[1] . ':' . $ip[2] . $ip[3]; + unset($find, $ip); + } + + // compression check + $aIP = explode('::', $aIP); + $c = count($aIP); + if ($c > 2) { + return false; + } elseif ($c == 2) { + list($first, $second) = $aIP; + $first = explode(':', $first); + $second = explode(':', $second); + + if (count($first) + count($second) > 8) { + return false; + } + + while (count($first) < 8) { + array_push($first, '0'); + } + + array_splice($first, 8 - count($second), 8, $second); + $aIP = $first; + unset($first, $second); + } else { + $aIP = explode(':', $aIP[0]); + } + $c = count($aIP); + + if ($c != 8) { + return false; + } + + // All the pieces should be 16-bit hex strings. Are they? + foreach ($aIP as $piece) { + if (!preg_match('#^[0-9a-fA-F]{4}$#s', sprintf('%04s', $piece))) { + return false; + } + } + return $original; + } +} + + + + + +/** + * Primitive email validation class based on the regexp found at + * http://www.regular-expressions.info/email.html + */ +class HTMLPurifier_AttrDef_URI_Email_SimpleCheck extends HTMLPurifier_AttrDef_URI_Email +{ + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + // no support for named mailboxes i.e. "Bob " + // that needs more percent encoding to be done + if ($string == '') { + return false; + } + $string = trim($string); + $result = preg_match('/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $string); + return $result ? $string : false; + } +} + + + + + +/** + * Pre-transform that changes proprietary background attribute to CSS. + */ +class HTMLPurifier_AttrTransform_Background extends HTMLPurifier_AttrTransform +{ + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr['background'])) { + return $attr; + } + + $background = $this->confiscateAttr($attr, 'background'); + // some validation should happen here + + $this->prependCSS($attr, "background-image:url($background);"); + return $attr; + } +} + + + + + +// this MUST be placed in post, as it assumes that any value in dir is valid + +/** + * Post-trasnform that ensures that bdo tags have the dir attribute set. + */ +class HTMLPurifier_AttrTransform_BdoDir extends HTMLPurifier_AttrTransform +{ + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (isset($attr['dir'])) { + return $attr; + } + $attr['dir'] = $config->get('Attr.DefaultTextDir'); + return $attr; + } +} + + + + + +/** + * Pre-transform that changes deprecated bgcolor attribute to CSS. + */ +class HTMLPurifier_AttrTransform_BgColor extends HTMLPurifier_AttrTransform +{ + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr['bgcolor'])) { + return $attr; + } + + $bgcolor = $this->confiscateAttr($attr, 'bgcolor'); + // some validation should happen here + + $this->prependCSS($attr, "background-color:$bgcolor;"); + return $attr; + } +} + + + + + +/** + * Pre-transform that changes converts a boolean attribute to fixed CSS + */ +class HTMLPurifier_AttrTransform_BoolToCSS extends HTMLPurifier_AttrTransform +{ + /** + * Name of boolean attribute that is trigger. + * @type string + */ + protected $attr; + + /** + * CSS declarations to add to style, needs trailing semicolon. + * @type string + */ + protected $css; + + /** + * @param string $attr attribute name to convert from + * @param string $css CSS declarations to add to style (needs semicolon) + */ + public function __construct($attr, $css) + { + $this->attr = $attr; + $this->css = $css; + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr[$this->attr])) { + return $attr; + } + unset($attr[$this->attr]); + $this->prependCSS($attr, $this->css); + return $attr; + } +} + + + + + +/** + * Pre-transform that changes deprecated border attribute to CSS. + */ +class HTMLPurifier_AttrTransform_Border extends HTMLPurifier_AttrTransform +{ + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr['border'])) { + return $attr; + } + $border_width = $this->confiscateAttr($attr, 'border'); + // some validation should happen here + $this->prependCSS($attr, "border:{$border_width}px solid;"); + return $attr; + } +} + + + + + +/** + * Generic pre-transform that converts an attribute with a fixed number of + * values (enumerated) to CSS. + */ +class HTMLPurifier_AttrTransform_EnumToCSS extends HTMLPurifier_AttrTransform +{ + /** + * Name of attribute to transform from. + * @type string + */ + protected $attr; + + /** + * Lookup array of attribute values to CSS. + * @type array + */ + protected $enumToCSS = array(); + + /** + * Case sensitivity of the matching. + * @type bool + * @warning Currently can only be guaranteed to work with ASCII + * values. + */ + protected $caseSensitive = false; + + /** + * @param string $attr Attribute name to transform from + * @param array $enum_to_css Lookup array of attribute values to CSS + * @param bool $case_sensitive Case sensitivity indicator, default false + */ + public function __construct($attr, $enum_to_css, $case_sensitive = false) + { + $this->attr = $attr; + $this->enumToCSS = $enum_to_css; + $this->caseSensitive = (bool)$case_sensitive; + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr[$this->attr])) { + return $attr; + } + + $value = trim($attr[$this->attr]); + unset($attr[$this->attr]); + + if (!$this->caseSensitive) { + $value = strtolower($value); + } + + if (!isset($this->enumToCSS[$value])) { + return $attr; + } + $this->prependCSS($attr, $this->enumToCSS[$value]); + return $attr; + } +} + + + + + +// must be called POST validation + +/** + * Transform that supplies default values for the src and alt attributes + * in img tags, as well as prevents the img tag from being removed + * because of a missing alt tag. This needs to be registered as both + * a pre and post attribute transform. + */ +class HTMLPurifier_AttrTransform_ImgRequired extends HTMLPurifier_AttrTransform +{ + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + $src = true; + if (!isset($attr['src'])) { + if ($config->get('Core.RemoveInvalidImg')) { + return $attr; + } + $attr['src'] = $config->get('Attr.DefaultInvalidImage'); + $src = false; + } + + if (!isset($attr['alt'])) { + if ($src) { + $alt = $config->get('Attr.DefaultImageAlt'); + if ($alt === null) { + $attr['alt'] = basename($attr['src']); + } else { + $attr['alt'] = $alt; + } + } else { + $attr['alt'] = $config->get('Attr.DefaultInvalidImageAlt'); + } + } + return $attr; + } +} + + + + + +/** + * Pre-transform that changes deprecated hspace and vspace attributes to CSS + */ +class HTMLPurifier_AttrTransform_ImgSpace extends HTMLPurifier_AttrTransform +{ + /** + * @type string + */ + protected $attr; + + /** + * @type array + */ + protected $css = array( + 'hspace' => array('left', 'right'), + 'vspace' => array('top', 'bottom') + ); + + /** + * @param string $attr + */ + public function __construct($attr) + { + $this->attr = $attr; + if (!isset($this->css[$attr])) { + trigger_error(htmlspecialchars($attr) . ' is not valid space attribute'); + } + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr[$this->attr])) { + return $attr; + } + + $width = $this->confiscateAttr($attr, $this->attr); + // some validation could happen here + + if (!isset($this->css[$this->attr])) { + return $attr; + } + + $style = ''; + foreach ($this->css[$this->attr] as $suffix) { + $property = "margin-$suffix"; + $style .= "$property:{$width}px;"; + } + $this->prependCSS($attr, $style); + return $attr; + } +} + + + + + +/** + * Performs miscellaneous cross attribute validation and filtering for + * input elements. This is meant to be a post-transform. + */ +class HTMLPurifier_AttrTransform_Input extends HTMLPurifier_AttrTransform +{ + /** + * @type HTMLPurifier_AttrDef_HTML_Pixels + */ + protected $pixels; + + public function __construct() + { + $this->pixels = new HTMLPurifier_AttrDef_HTML_Pixels(); + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr['type'])) { + $t = 'text'; + } else { + $t = strtolower($attr['type']); + } + if (isset($attr['checked']) && $t !== 'radio' && $t !== 'checkbox') { + unset($attr['checked']); + } + if (isset($attr['maxlength']) && $t !== 'text' && $t !== 'password') { + unset($attr['maxlength']); + } + if (isset($attr['size']) && $t !== 'text' && $t !== 'password') { + $result = $this->pixels->validate($attr['size'], $config, $context); + if ($result === false) { + unset($attr['size']); + } else { + $attr['size'] = $result; + } + } + if (isset($attr['src']) && $t !== 'image') { + unset($attr['src']); + } + if (!isset($attr['value']) && ($t === 'radio' || $t === 'checkbox')) { + $attr['value'] = ''; + } + return $attr; + } +} + + + + + +/** + * Post-transform that copies lang's value to xml:lang (and vice-versa) + * @note Theoretically speaking, this could be a pre-transform, but putting + * post is more efficient. + */ +class HTMLPurifier_AttrTransform_Lang extends HTMLPurifier_AttrTransform +{ + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + $lang = isset($attr['lang']) ? $attr['lang'] : false; + $xml_lang = isset($attr['xml:lang']) ? $attr['xml:lang'] : false; + + if ($lang !== false && $xml_lang === false) { + $attr['xml:lang'] = $lang; + } elseif ($xml_lang !== false) { + $attr['lang'] = $xml_lang; + } + return $attr; + } +} + + + + + +/** + * Class for handling width/height length attribute transformations to CSS + */ +class HTMLPurifier_AttrTransform_Length extends HTMLPurifier_AttrTransform +{ + + /** + * @type string + */ + protected $name; + + /** + * @type string + */ + protected $cssName; + + public function __construct($name, $css_name = null) + { + $this->name = $name; + $this->cssName = $css_name ? $css_name : $name; + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr[$this->name])) { + return $attr; + } + $length = $this->confiscateAttr($attr, $this->name); + if (ctype_digit($length)) { + $length .= 'px'; + } + $this->prependCSS($attr, $this->cssName . ":$length;"); + return $attr; + } +} + + + + + +/** + * Pre-transform that changes deprecated name attribute to ID if necessary + */ +class HTMLPurifier_AttrTransform_Name extends HTMLPurifier_AttrTransform +{ + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + // Abort early if we're using relaxed definition of name + if ($config->get('HTML.Attr.Name.UseCDATA')) { + return $attr; + } + if (!isset($attr['name'])) { + return $attr; + } + $id = $this->confiscateAttr($attr, 'name'); + if (isset($attr['id'])) { + return $attr; + } + $attr['id'] = $id; + return $attr; + } +} + + + + + +/** + * Post-transform that performs validation to the name attribute; if + * it is present with an equivalent id attribute, it is passed through; + * otherwise validation is performed. + */ +class HTMLPurifier_AttrTransform_NameSync extends HTMLPurifier_AttrTransform +{ + + public function __construct() + { + $this->idDef = new HTMLPurifier_AttrDef_HTML_ID(); + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr['name'])) { + return $attr; + } + $name = $attr['name']; + if (isset($attr['id']) && $attr['id'] === $name) { + return $attr; + } + $result = $this->idDef->validate($name, $config, $context); + if ($result === false) { + unset($attr['name']); + } else { + $attr['name'] = $result; + } + return $attr; + } +} + + + + + +// must be called POST validation + +/** + * Adds rel="nofollow" to all outbound links. This transform is + * only attached if Attr.Nofollow is TRUE. + */ +class HTMLPurifier_AttrTransform_Nofollow extends HTMLPurifier_AttrTransform +{ + /** + * @type HTMLPurifier_URIParser + */ + private $parser; + + public function __construct() + { + $this->parser = new HTMLPurifier_URIParser(); + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr['href'])) { + return $attr; + } + + // XXX Kind of inefficient + $url = $this->parser->parse($attr['href']); + $scheme = $url->getSchemeObj($config, $context); + + if ($scheme->browsable && !$url->isLocal($config, $context)) { + if (isset($attr['rel'])) { + $rels = explode(' ', $attr['rel']); + if (!in_array('nofollow', $rels)) { + $rels[] = 'nofollow'; + } + $attr['rel'] = implode(' ', $rels); + } else { + $attr['rel'] = 'nofollow'; + } + } + return $attr; + } +} + + + + + +class HTMLPurifier_AttrTransform_SafeEmbed extends HTMLPurifier_AttrTransform +{ + /** + * @type string + */ + public $name = "SafeEmbed"; + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + $attr['allowscriptaccess'] = 'never'; + $attr['allownetworking'] = 'internal'; + $attr['type'] = 'application/x-shockwave-flash'; + return $attr; + } +} + + + + + +/** + * Writes default type for all objects. Currently only supports flash. + */ +class HTMLPurifier_AttrTransform_SafeObject extends HTMLPurifier_AttrTransform +{ + /** + * @type string + */ + public $name = "SafeObject"; + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr['type'])) { + $attr['type'] = 'application/x-shockwave-flash'; + } + return $attr; + } +} + + + + + +/** + * Validates name/value pairs in param tags to be used in safe objects. This + * will only allow name values it recognizes, and pre-fill certain attributes + * with required values. + * + * @note + * This class only supports Flash. In the future, Quicktime support + * may be added. + * + * @warning + * This class expects an injector to add the necessary parameters tags. + */ +class HTMLPurifier_AttrTransform_SafeParam extends HTMLPurifier_AttrTransform +{ + /** + * @type string + */ + public $name = "SafeParam"; + + /** + * @type HTMLPurifier_AttrDef_URI + */ + private $uri; + + public function __construct() + { + $this->uri = new HTMLPurifier_AttrDef_URI(true); // embedded + $this->wmode = new HTMLPurifier_AttrDef_Enum(array('window', 'opaque', 'transparent')); + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + // If we add support for other objects, we'll need to alter the + // transforms. + switch ($attr['name']) { + // application/x-shockwave-flash + // Keep this synchronized with Injector/SafeObject.php + case 'allowScriptAccess': + $attr['value'] = 'never'; + break; + case 'allowNetworking': + $attr['value'] = 'internal'; + break; + case 'allowFullScreen': + if ($config->get('HTML.FlashAllowFullScreen')) { + $attr['value'] = ($attr['value'] == 'true') ? 'true' : 'false'; + } else { + $attr['value'] = 'false'; + } + break; + case 'wmode': + $attr['value'] = $this->wmode->validate($attr['value'], $config, $context); + break; + case 'movie': + case 'src': + $attr['name'] = "movie"; + $attr['value'] = $this->uri->validate($attr['value'], $config, $context); + break; + case 'flashvars': + // we're going to allow arbitrary inputs to the SWF, on + // the reasoning that it could only hack the SWF, not us. + break; + // add other cases to support other param name/value pairs + default: + $attr['name'] = $attr['value'] = null; + } + return $attr; + } +} + + + + + +/** + * Implements required attribute stipulation for )#si', + array($this, 'scriptCallback'), + $html + ); + } + + $html = $this->normalize($html, $config, $context); + + $cursor = 0; // our location in the text + $inside_tag = false; // whether or not we're parsing the inside of a tag + $array = array(); // result array + + // This is also treated to mean maintain *column* numbers too + $maintain_line_numbers = $config->get('Core.MaintainLineNumbers'); + + if ($maintain_line_numbers === null) { + // automatically determine line numbering by checking + // if error collection is on + $maintain_line_numbers = $config->get('Core.CollectErrors'); + } + + if ($maintain_line_numbers) { + $current_line = 1; + $current_col = 0; + $length = strlen($html); + } else { + $current_line = false; + $current_col = false; + $length = false; + } + $context->register('CurrentLine', $current_line); + $context->register('CurrentCol', $current_col); + $nl = "\n"; + // how often to manually recalculate. This will ALWAYS be right, + // but it's pretty wasteful. Set to 0 to turn off + $synchronize_interval = $config->get('Core.DirectLexLineNumberSyncInterval'); + + $e = false; + if ($config->get('Core.CollectErrors')) { + $e =& $context->get('ErrorCollector'); + } + + // for testing synchronization + $loops = 0; + + while (++$loops) { + // $cursor is either at the start of a token, or inside of + // a tag (i.e. there was a < immediately before it), as indicated + // by $inside_tag + + if ($maintain_line_numbers) { + // $rcursor, however, is always at the start of a token. + $rcursor = $cursor - (int)$inside_tag; + + // Column number is cheap, so we calculate it every round. + // We're interested at the *end* of the newline string, so + // we need to add strlen($nl) == 1 to $nl_pos before subtracting it + // from our "rcursor" position. + $nl_pos = strrpos($html, $nl, $rcursor - $length); + $current_col = $rcursor - (is_bool($nl_pos) ? 0 : $nl_pos + 1); + + // recalculate lines + if ($synchronize_interval && // synchronization is on + $cursor > 0 && // cursor is further than zero + $loops % $synchronize_interval === 0) { // time to synchronize! + $current_line = 1 + $this->substrCount($html, $nl, 0, $cursor); + } + } + + $position_next_lt = strpos($html, '<', $cursor); + $position_next_gt = strpos($html, '>', $cursor); + + // triggers on "asdf" but not "asdf " + // special case to set up context + if ($position_next_lt === $cursor) { + $inside_tag = true; + $cursor++; + } + + if (!$inside_tag && $position_next_lt !== false) { + // We are not inside tag and there still is another tag to parse + $token = new + HTMLPurifier_Token_Text( + $this->parseText( + substr( + $html, + $cursor, + $position_next_lt - $cursor + ), $config + ) + ); + if ($maintain_line_numbers) { + $token->rawPosition($current_line, $current_col); + $current_line += $this->substrCount($html, $nl, $cursor, $position_next_lt - $cursor); + } + $array[] = $token; + $cursor = $position_next_lt + 1; + $inside_tag = true; + continue; + } elseif (!$inside_tag) { + // We are not inside tag but there are no more tags + // If we're already at the end, break + if ($cursor === strlen($html)) { + break; + } + // Create Text of rest of string + $token = new + HTMLPurifier_Token_Text( + $this->parseText( + substr( + $html, + $cursor + ), $config + ) + ); + if ($maintain_line_numbers) { + $token->rawPosition($current_line, $current_col); + } + $array[] = $token; + break; + } elseif ($inside_tag && $position_next_gt !== false) { + // We are in tag and it is well formed + // Grab the internals of the tag + $strlen_segment = $position_next_gt - $cursor; + + if ($strlen_segment < 1) { + // there's nothing to process! + $token = new HTMLPurifier_Token_Text('<'); + $cursor++; + continue; + } + + $segment = substr($html, $cursor, $strlen_segment); + + if ($segment === false) { + // somehow, we attempted to access beyond the end of + // the string, defense-in-depth, reported by Nate Abele + break; + } + + // Check if it's a comment + if (substr($segment, 0, 3) === '!--') { + // re-determine segment length, looking for --> + $position_comment_end = strpos($html, '-->', $cursor); + if ($position_comment_end === false) { + // uh oh, we have a comment that extends to + // infinity. Can't be helped: set comment + // end position to end of string + if ($e) { + $e->send(E_WARNING, 'Lexer: Unclosed comment'); + } + $position_comment_end = strlen($html); + $end = true; + } else { + $end = false; + } + $strlen_segment = $position_comment_end - $cursor; + $segment = substr($html, $cursor, $strlen_segment); + $token = new + HTMLPurifier_Token_Comment( + substr( + $segment, + 3, + $strlen_segment - 3 + ) + ); + if ($maintain_line_numbers) { + $token->rawPosition($current_line, $current_col); + $current_line += $this->substrCount($html, $nl, $cursor, $strlen_segment); + } + $array[] = $token; + $cursor = $end ? $position_comment_end : $position_comment_end + 3; + $inside_tag = false; + continue; + } + + // Check if it's an end tag + $is_end_tag = (strpos($segment, '/') === 0); + if ($is_end_tag) { + $type = substr($segment, 1); + $token = new HTMLPurifier_Token_End($type); + if ($maintain_line_numbers) { + $token->rawPosition($current_line, $current_col); + $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor); + } + $array[] = $token; + $inside_tag = false; + $cursor = $position_next_gt + 1; + continue; + } + + // Check leading character is alnum, if not, we may + // have accidently grabbed an emoticon. Translate into + // text and go our merry way + if (!ctype_alpha($segment[0])) { + // XML: $segment[0] !== '_' && $segment[0] !== ':' + if ($e) { + $e->send(E_NOTICE, 'Lexer: Unescaped lt'); + } + $token = new HTMLPurifier_Token_Text('<'); + if ($maintain_line_numbers) { + $token->rawPosition($current_line, $current_col); + $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor); + } + $array[] = $token; + $inside_tag = false; + continue; + } + + // Check if it is explicitly self closing, if so, remove + // trailing slash. Remember, we could have a tag like
    , so + // any later token processing scripts must convert improperly + // classified EmptyTags from StartTags. + $is_self_closing = (strrpos($segment, '/') === $strlen_segment - 1); + if ($is_self_closing) { + $strlen_segment--; + $segment = substr($segment, 0, $strlen_segment); + } + + // Check if there are any attributes + $position_first_space = strcspn($segment, $this->_whitespace); + + if ($position_first_space >= $strlen_segment) { + if ($is_self_closing) { + $token = new HTMLPurifier_Token_Empty($segment); + } else { + $token = new HTMLPurifier_Token_Start($segment); + } + if ($maintain_line_numbers) { + $token->rawPosition($current_line, $current_col); + $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor); + } + $array[] = $token; + $inside_tag = false; + $cursor = $position_next_gt + 1; + continue; + } + + // Grab out all the data + $type = substr($segment, 0, $position_first_space); + $attribute_string = + trim( + substr( + $segment, + $position_first_space + ) + ); + if ($attribute_string) { + $attr = $this->parseAttributeString( + $attribute_string, + $config, + $context + ); + } else { + $attr = array(); + } + + if ($is_self_closing) { + $token = new HTMLPurifier_Token_Empty($type, $attr); + } else { + $token = new HTMLPurifier_Token_Start($type, $attr); + } + if ($maintain_line_numbers) { + $token->rawPosition($current_line, $current_col); + $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor); + } + $array[] = $token; + $cursor = $position_next_gt + 1; + $inside_tag = false; + continue; + } else { + // inside tag, but there's no ending > sign + if ($e) { + $e->send(E_WARNING, 'Lexer: Missing gt'); + } + $token = new + HTMLPurifier_Token_Text( + '<' . + $this->parseText( + substr($html, $cursor), $config + ) + ); + if ($maintain_line_numbers) { + $token->rawPosition($current_line, $current_col); + } + // no cursor scroll? Hmm... + $array[] = $token; + break; + } + break; + } + + $context->destroy('CurrentLine'); + $context->destroy('CurrentCol'); + return $array; + } + + /** + * PHP 5.0.x compatible substr_count that implements offset and length + * @param string $haystack + * @param string $needle + * @param int $offset + * @param int $length + * @return int + */ + protected function substrCount($haystack, $needle, $offset, $length) + { + static $oldVersion; + if ($oldVersion === null) { + $oldVersion = version_compare(PHP_VERSION, '5.1', '<'); + } + if ($oldVersion) { + $haystack = substr($haystack, $offset, $length); + return substr_count($haystack, $needle); + } else { + return substr_count($haystack, $needle, $offset, $length); + } + } + + /** + * Takes the inside of an HTML tag and makes an assoc array of attributes. + * + * @param string $string Inside of tag excluding name. + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array Assoc array of attributes. + */ + public function parseAttributeString($string, $config, $context) + { + $string = (string)$string; // quick typecast + + if ($string == '') { + return array(); + } // no attributes + + $e = false; + if ($config->get('Core.CollectErrors')) { + $e =& $context->get('ErrorCollector'); + } + + // let's see if we can abort as quickly as possible + // one equal sign, no spaces => one attribute + $num_equal = substr_count($string, '='); + $has_space = strpos($string, ' '); + if ($num_equal === 0 && !$has_space) { + // bool attribute + return array($string => $string); + } elseif ($num_equal === 1 && !$has_space) { + // only one attribute + list($key, $quoted_value) = explode('=', $string); + $quoted_value = trim($quoted_value); + if (!$key) { + if ($e) { + $e->send(E_ERROR, 'Lexer: Missing attribute key'); + } + return array(); + } + if (!$quoted_value) { + return array($key => ''); + } + $first_char = @$quoted_value[0]; + $last_char = @$quoted_value[strlen($quoted_value) - 1]; + + $same_quote = ($first_char == $last_char); + $open_quote = ($first_char == '"' || $first_char == "'"); + + if ($same_quote && $open_quote) { + // well behaved + $value = substr($quoted_value, 1, strlen($quoted_value) - 2); + } else { + // not well behaved + if ($open_quote) { + if ($e) { + $e->send(E_ERROR, 'Lexer: Missing end quote'); + } + $value = substr($quoted_value, 1); + } else { + $value = $quoted_value; + } + } + if ($value === false) { + $value = ''; + } + return array($key => $this->parseAttr($value, $config)); + } + + // setup loop environment + $array = array(); // return assoc array of attributes + $cursor = 0; // current position in string (moves forward) + $size = strlen($string); // size of the string (stays the same) + + // if we have unquoted attributes, the parser expects a terminating + // space, so let's guarantee that there's always a terminating space. + $string .= ' '; + + $old_cursor = -1; + while ($cursor < $size) { + if ($old_cursor >= $cursor) { + throw new Exception("Infinite loop detected"); + } + $old_cursor = $cursor; + + $cursor += ($value = strspn($string, $this->_whitespace, $cursor)); + // grab the key + + $key_begin = $cursor; //we're currently at the start of the key + + // scroll past all characters that are the key (not whitespace or =) + $cursor += strcspn($string, $this->_whitespace . '=', $cursor); + + $key_end = $cursor; // now at the end of the key + + $key = substr($string, $key_begin, $key_end - $key_begin); + + if (!$key) { + if ($e) { + $e->send(E_ERROR, 'Lexer: Missing attribute key'); + } + $cursor += 1 + strcspn($string, $this->_whitespace, $cursor + 1); // prevent infinite loop + continue; // empty key + } + + // scroll past all whitespace + $cursor += strspn($string, $this->_whitespace, $cursor); + + if ($cursor >= $size) { + $array[$key] = $key; + break; + } + + // if the next character is an equal sign, we've got a regular + // pair, otherwise, it's a bool attribute + $first_char = @$string[$cursor]; + + if ($first_char == '=') { + // key="value" + + $cursor++; + $cursor += strspn($string, $this->_whitespace, $cursor); + + if ($cursor === false) { + $array[$key] = ''; + break; + } + + // we might be in front of a quote right now + + $char = @$string[$cursor]; + + if ($char == '"' || $char == "'") { + // it's quoted, end bound is $char + $cursor++; + $value_begin = $cursor; + $cursor = strpos($string, $char, $cursor); + $value_end = $cursor; + } else { + // it's not quoted, end bound is whitespace + $value_begin = $cursor; + $cursor += strcspn($string, $this->_whitespace, $cursor); + $value_end = $cursor; + } + + // we reached a premature end + if ($cursor === false) { + $cursor = $size; + $value_end = $cursor; + } + + $value = substr($string, $value_begin, $value_end - $value_begin); + if ($value === false) { + $value = ''; + } + $array[$key] = $this->parseAttr($value, $config); + $cursor++; + } else { + // boolattr + if ($key !== '') { + $array[$key] = $key; + } else { + // purely theoretical + if ($e) { + $e->send(E_ERROR, 'Lexer: Missing attribute key'); + } + } + } + } + return $array; + } +} + + + + + +/** + * Concrete comment node class. + */ +class HTMLPurifier_Node_Comment extends HTMLPurifier_Node +{ + /** + * Character data within comment. + * @type string + */ + public $data; + + /** + * @type bool + */ + public $is_whitespace = true; + + /** + * Transparent constructor. + * + * @param string $data String comment data. + * @param int $line + * @param int $col + */ + public function __construct($data, $line = null, $col = null) + { + $this->data = $data; + $this->line = $line; + $this->col = $col; + } + + public function toTokenPair() { + return array(new HTMLPurifier_Token_Comment($this->data, $this->line, $this->col), null); + } +} + + + +/** + * Concrete element node class. + */ +class HTMLPurifier_Node_Element extends HTMLPurifier_Node +{ + /** + * The lower-case name of the tag, like 'a', 'b' or 'blockquote'. + * + * @note Strictly speaking, XML tags are case sensitive, so we shouldn't + * be lower-casing them, but these tokens cater to HTML tags, which are + * insensitive. + * @type string + */ + public $name; + + /** + * Associative array of the node's attributes. + * @type array + */ + public $attr = array(); + + /** + * List of child elements. + * @type array + */ + public $children = array(); + + /** + * Does this use the form or the form, i.e. + * is it a pair of start/end tokens or an empty token. + * @bool + */ + public $empty = false; + + public $endCol = null, $endLine = null, $endArmor = array(); + + public function __construct($name, $attr = array(), $line = null, $col = null, $armor = array()) { + $this->name = $name; + $this->attr = $attr; + $this->line = $line; + $this->col = $col; + $this->armor = $armor; + } + + public function toTokenPair() { + // XXX inefficiency here, normalization is not necessary + if ($this->empty) { + return array(new HTMLPurifier_Token_Empty($this->name, $this->attr, $this->line, $this->col, $this->armor), null); + } else { + $start = new HTMLPurifier_Token_Start($this->name, $this->attr, $this->line, $this->col, $this->armor); + $end = new HTMLPurifier_Token_End($this->name, array(), $this->endLine, $this->endCol, $this->endArmor); + //$end->start = $start; + return array($start, $end); + } + } +} + + + + +/** + * Concrete text token class. + * + * Text tokens comprise of regular parsed character data (PCDATA) and raw + * character data (from the CDATA sections). Internally, their + * data is parsed with all entities expanded. Surprisingly, the text token + * does have a "tag name" called #PCDATA, which is how the DTD represents it + * in permissible child nodes. + */ +class HTMLPurifier_Node_Text extends HTMLPurifier_Node +{ + + /** + * PCDATA tag name compatible with DTD, see + * HTMLPurifier_ChildDef_Custom for details. + * @type string + */ + public $name = '#PCDATA'; + + /** + * @type string + */ + public $data; + /**< Parsed character data of text. */ + + /** + * @type bool + */ + public $is_whitespace; + + /**< Bool indicating if node is whitespace. */ + + /** + * Constructor, accepts data and determines if it is whitespace. + * @param string $data String parsed character data. + * @param int $line + * @param int $col + */ + public function __construct($data, $is_whitespace, $line = null, $col = null) + { + $this->data = $data; + $this->is_whitespace = $is_whitespace; + $this->line = $line; + $this->col = $col; + } + + public function toTokenPair() { + return array(new HTMLPurifier_Token_Text($this->data, $this->line, $this->col), null); + } +} + + + + + +/** + * Composite strategy that runs multiple strategies on tokens. + */ +abstract class HTMLPurifier_Strategy_Composite extends HTMLPurifier_Strategy +{ + + /** + * List of strategies to run tokens through. + * @type HTMLPurifier_Strategy[] + */ + protected $strategies = array(); + + /** + * @param HTMLPurifier_Token[] $tokens + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return HTMLPurifier_Token[] + */ + public function execute($tokens, $config, $context) + { + foreach ($this->strategies as $strategy) { + $tokens = $strategy->execute($tokens, $config, $context); + } + return $tokens; + } +} + + + + + +/** + * Core strategy composed of the big four strategies. + */ +class HTMLPurifier_Strategy_Core extends HTMLPurifier_Strategy_Composite +{ + public function __construct() + { + $this->strategies[] = new HTMLPurifier_Strategy_RemoveForeignElements(); + $this->strategies[] = new HTMLPurifier_Strategy_MakeWellFormed(); + $this->strategies[] = new HTMLPurifier_Strategy_FixNesting(); + $this->strategies[] = new HTMLPurifier_Strategy_ValidateAttributes(); + } +} + + + + + +/** + * Takes a well formed list of tokens and fixes their nesting. + * + * HTML elements dictate which elements are allowed to be their children, + * for example, you can't have a p tag in a span tag. Other elements have + * much more rigorous definitions: tables, for instance, require a specific + * order for their elements. There are also constraints not expressible by + * document type definitions, such as the chameleon nature of ins/del + * tags and global child exclusions. + * + * The first major objective of this strategy is to iterate through all + * the nodes and determine whether or not their children conform to the + * element's definition. If they do not, the child definition may + * optionally supply an amended list of elements that is valid or + * require that the entire node be deleted (and the previous node + * rescanned). + * + * The second objective is to ensure that explicitly excluded elements of + * an element do not appear in its children. Code that accomplishes this + * task is pervasive through the strategy, though the two are distinct tasks + * and could, theoretically, be seperated (although it's not recommended). + * + * @note Whether or not unrecognized children are silently dropped or + * translated into text depends on the child definitions. + * + * @todo Enable nodes to be bubbled out of the structure. This is + * easier with our new algorithm. + */ + +class HTMLPurifier_Strategy_FixNesting extends HTMLPurifier_Strategy +{ + + /** + * @param HTMLPurifier_Token[] $tokens + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array|HTMLPurifier_Token[] + */ + public function execute($tokens, $config, $context) + { + + //####################################################################// + // Pre-processing + + // O(n) pass to convert to a tree, so that we can efficiently + // refer to substrings + $top_node = HTMLPurifier_Arborize::arborize($tokens, $config, $context); + + // get a copy of the HTML definition + $definition = $config->getHTMLDefinition(); + + $excludes_enabled = !$config->get('Core.DisableExcludes'); + + // setup the context variable 'IsInline', for chameleon processing + // is 'false' when we are not inline, 'true' when it must always + // be inline, and an integer when it is inline for a certain + // branch of the document tree + $is_inline = $definition->info_parent_def->descendants_are_inline; + $context->register('IsInline', $is_inline); + + // setup error collector + $e =& $context->get('ErrorCollector', true); + + //####################################################################// + // Loop initialization + + // stack that contains all elements that are excluded + // it is organized by parent elements, similar to $stack, + // but it is only populated when an element with exclusions is + // processed, i.e. there won't be empty exclusions. + $exclude_stack = array($definition->info_parent_def->excludes); + + // variable that contains the start token while we are processing + // nodes. This enables error reporting to do its job + $node = $top_node; + // dummy token + list($token, $d) = $node->toTokenPair(); + $context->register('CurrentNode', $node); + $context->register('CurrentToken', $token); + + //####################################################################// + // Loop + + // We need to implement a post-order traversal iteratively, to + // avoid running into stack space limits. This is pretty tricky + // to reason about, so we just manually stack-ify the recursive + // variant: + // + // function f($node) { + // foreach ($node->children as $child) { + // f($child); + // } + // validate($node); + // } + // + // Thus, we will represent a stack frame as array($node, + // $is_inline, stack of children) + // e.g. array_reverse($node->children) - already processed + // children. + + $parent_def = $definition->info_parent_def; + $stack = array( + array($top_node, + $parent_def->descendants_are_inline, + $parent_def->excludes, // exclusions + 0) + ); + + while (!empty($stack)) { + list($node, $is_inline, $excludes, $ix) = array_pop($stack); + // recursive call + $go = false; + $def = empty($stack) ? $definition->info_parent_def : $definition->info[$node->name]; + while (isset($node->children[$ix])) { + $child = $node->children[$ix++]; + if ($child instanceof HTMLPurifier_Node_Element) { + $go = true; + $stack[] = array($node, $is_inline, $excludes, $ix); + $stack[] = array($child, + // ToDo: I don't think it matters if it's def or + // child_def, but double check this... + $is_inline || $def->descendants_are_inline, + empty($def->excludes) ? $excludes + : array_merge($excludes, $def->excludes), + 0); + break; + } + }; + if ($go) continue; + list($token, $d) = $node->toTokenPair(); + // base case + if ($excludes_enabled && isset($excludes[$node->name])) { + $node->dead = true; + if ($e) $e->send(E_ERROR, 'Strategy_FixNesting: Node excluded'); + } else { + // XXX I suppose it would be slightly more efficient to + // avoid the allocation here and have children + // strategies handle it + $children = array(); + foreach ($node->children as $child) { + if (!$child->dead) $children[] = $child; + } + $result = $def->child->validateChildren($children, $config, $context); + if ($result === true) { + // nop + $node->children = $children; + } elseif ($result === false) { + $node->dead = true; + if ($e) $e->send(E_ERROR, 'Strategy_FixNesting: Node removed'); + } else { + $node->children = $result; + if ($e) { + // XXX This will miss mutations of internal nodes. Perhaps defer to the child validators + if (empty($result) && !empty($children)) { + $e->send(E_ERROR, 'Strategy_FixNesting: Node contents removed'); + } else if ($result != $children) { + $e->send(E_WARNING, 'Strategy_FixNesting: Node reorganized'); + } + } + } + } + } + + //####################################################################// + // Post-processing + + // remove context variables + $context->destroy('IsInline'); + $context->destroy('CurrentNode'); + $context->destroy('CurrentToken'); + + //####################################################################// + // Return + + return HTMLPurifier_Arborize::flatten($node, $config, $context); + } +} + + + + + +/** + * Takes tokens makes them well-formed (balance end tags, etc.) + * + * Specification of the armor attributes this strategy uses: + * + * - MakeWellFormed_TagClosedError: This armor field is used to + * suppress tag closed errors for certain tokens [TagClosedSuppress], + * in particular, if a tag was generated automatically by HTML + * Purifier, we may rely on our infrastructure to close it for us + * and shouldn't report an error to the user [TagClosedAuto]. + */ +class HTMLPurifier_Strategy_MakeWellFormed extends HTMLPurifier_Strategy +{ + + /** + * Array stream of tokens being processed. + * @type HTMLPurifier_Token[] + */ + protected $tokens; + + /** + * Current token. + * @type HTMLPurifier_Token + */ + protected $token; + + /** + * Zipper managing the true state. + * @type HTMLPurifier_Zipper + */ + protected $zipper; + + /** + * Current nesting of elements. + * @type array + */ + protected $stack; + + /** + * Injectors active in this stream processing. + * @type HTMLPurifier_Injector[] + */ + protected $injectors; + + /** + * Current instance of HTMLPurifier_Config. + * @type HTMLPurifier_Config + */ + protected $config; + + /** + * Current instance of HTMLPurifier_Context. + * @type HTMLPurifier_Context + */ + protected $context; + + /** + * @param HTMLPurifier_Token[] $tokens + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return HTMLPurifier_Token[] + * @throws HTMLPurifier_Exception + */ + public function execute($tokens, $config, $context) + { + $definition = $config->getHTMLDefinition(); + + // local variables + $generator = new HTMLPurifier_Generator($config, $context); + $escape_invalid_tags = $config->get('Core.EscapeInvalidTags'); + // used for autoclose early abortion + $global_parent_allowed_elements = $definition->info_parent_def->child->getAllowedElements($config); + $e = $context->get('ErrorCollector', true); + $i = false; // injector index + list($zipper, $token) = HTMLPurifier_Zipper::fromArray($tokens); + if ($token === NULL) { + return array(); + } + $reprocess = false; // whether or not to reprocess the same token + $stack = array(); + + // member variables + $this->stack =& $stack; + $this->tokens =& $tokens; + $this->token =& $token; + $this->zipper =& $zipper; + $this->config = $config; + $this->context = $context; + + // context variables + $context->register('CurrentNesting', $stack); + $context->register('InputZipper', $zipper); + $context->register('CurrentToken', $token); + + // -- begin INJECTOR -- + + $this->injectors = array(); + + $injectors = $config->getBatch('AutoFormat'); + $def_injectors = $definition->info_injector; + $custom_injectors = $injectors['Custom']; + unset($injectors['Custom']); // special case + foreach ($injectors as $injector => $b) { + // XXX: Fix with a legitimate lookup table of enabled filters + if (strpos($injector, '.') !== false) { + continue; + } + $injector = "HTMLPurifier_Injector_$injector"; + if (!$b) { + continue; + } + $this->injectors[] = new $injector; + } + foreach ($def_injectors as $injector) { + // assumed to be objects + $this->injectors[] = $injector; + } + foreach ($custom_injectors as $injector) { + if (!$injector) { + continue; + } + if (is_string($injector)) { + $injector = "HTMLPurifier_Injector_$injector"; + $injector = new $injector; + } + $this->injectors[] = $injector; + } + + // give the injectors references to the definition and context + // variables for performance reasons + foreach ($this->injectors as $ix => $injector) { + $error = $injector->prepare($config, $context); + if (!$error) { + continue; + } + array_splice($this->injectors, $ix, 1); // rm the injector + trigger_error("Cannot enable {$injector->name} injector because $error is not allowed", E_USER_WARNING); + } + + // -- end INJECTOR -- + + // a note on reprocessing: + // In order to reduce code duplication, whenever some code needs + // to make HTML changes in order to make things "correct", the + // new HTML gets sent through the purifier, regardless of its + // status. This means that if we add a start token, because it + // was totally necessary, we don't have to update nesting; we just + // punt ($reprocess = true; continue;) and it does that for us. + + // isset is in loop because $tokens size changes during loop exec + for (;; + // only increment if we don't need to reprocess + $reprocess ? $reprocess = false : $token = $zipper->next($token)) { + + // check for a rewind + if (is_int($i)) { + // possibility: disable rewinding if the current token has a + // rewind set on it already. This would offer protection from + // infinite loop, but might hinder some advanced rewinding. + $rewind_offset = $this->injectors[$i]->getRewindOffset(); + if (is_int($rewind_offset)) { + for ($j = 0; $j < $rewind_offset; $j++) { + if (empty($zipper->front)) break; + $token = $zipper->prev($token); + // indicate that other injectors should not process this token, + // but we need to reprocess it. See Note [Injector skips] + unset($token->skip[$i]); + $token->rewind = $i; + if ($token instanceof HTMLPurifier_Token_Start) { + array_pop($this->stack); + } elseif ($token instanceof HTMLPurifier_Token_End) { + $this->stack[] = $token->start; + } + } + } + $i = false; + } + + // handle case of document end + if ($token === NULL) { + // kill processing if stack is empty + if (empty($this->stack)) { + break; + } + + // peek + $top_nesting = array_pop($this->stack); + $this->stack[] = $top_nesting; + + // send error [TagClosedSuppress] + if ($e && !isset($top_nesting->armor['MakeWellFormed_TagClosedError'])) { + $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by document end', $top_nesting); + } + + // append, don't splice, since this is the end + $token = new HTMLPurifier_Token_End($top_nesting->name); + + // punt! + $reprocess = true; + continue; + } + + //echo '
    '; printZipper($zipper, $token);//printTokens($this->stack); + //flush(); + + // quick-check: if it's not a tag, no need to process + if (empty($token->is_tag)) { + if ($token instanceof HTMLPurifier_Token_Text) { + foreach ($this->injectors as $i => $injector) { + if (isset($token->skip[$i])) { + // See Note [Injector skips] + continue; + } + if ($token->rewind !== null && $token->rewind !== $i) { + continue; + } + // XXX fuckup + $r = $token; + $injector->handleText($r); + $token = $this->processToken($r, $i); + $reprocess = true; + break; + } + } + // another possibility is a comment + continue; + } + + if (isset($definition->info[$token->name])) { + $type = $definition->info[$token->name]->child->type; + } else { + $type = false; // Type is unknown, treat accordingly + } + + // quick tag checks: anything that's *not* an end tag + $ok = false; + if ($type === 'empty' && $token instanceof HTMLPurifier_Token_Start) { + // claims to be a start tag but is empty + $token = new HTMLPurifier_Token_Empty( + $token->name, + $token->attr, + $token->line, + $token->col, + $token->armor + ); + $ok = true; + } elseif ($type && $type !== 'empty' && $token instanceof HTMLPurifier_Token_Empty) { + // claims to be empty but really is a start tag + // NB: this assignment is required + $old_token = $token; + $token = new HTMLPurifier_Token_End($token->name); + $token = $this->insertBefore( + new HTMLPurifier_Token_Start($old_token->name, $old_token->attr, $old_token->line, $old_token->col, $old_token->armor) + ); + // punt (since we had to modify the input stream in a non-trivial way) + $reprocess = true; + continue; + } elseif ($token instanceof HTMLPurifier_Token_Empty) { + // real empty token + $ok = true; + } elseif ($token instanceof HTMLPurifier_Token_Start) { + // start tag + + // ...unless they also have to close their parent + if (!empty($this->stack)) { + + // Performance note: you might think that it's rather + // inefficient, recalculating the autoclose information + // for every tag that a token closes (since when we + // do an autoclose, we push a new token into the + // stream and then /process/ that, before + // re-processing this token.) But this is + // necessary, because an injector can make an + // arbitrary transformations to the autoclosing + // tokens we introduce, so things may have changed + // in the meantime. Also, doing the inefficient thing is + // "easy" to reason about (for certain perverse definitions + // of "easy") + + $parent = array_pop($this->stack); + $this->stack[] = $parent; + + $parent_def = null; + $parent_elements = null; + $autoclose = false; + if (isset($definition->info[$parent->name])) { + $parent_def = $definition->info[$parent->name]; + $parent_elements = $parent_def->child->getAllowedElements($config); + $autoclose = !isset($parent_elements[$token->name]); + } + + if ($autoclose && $definition->info[$token->name]->wrap) { + // Check if an element can be wrapped by another + // element to make it valid in a context (for + // example,
        needs a
      • in between) + $wrapname = $definition->info[$token->name]->wrap; + $wrapdef = $definition->info[$wrapname]; + $elements = $wrapdef->child->getAllowedElements($config); + if (isset($elements[$token->name]) && isset($parent_elements[$wrapname])) { + $newtoken = new HTMLPurifier_Token_Start($wrapname); + $token = $this->insertBefore($newtoken); + $reprocess = true; + continue; + } + } + + $carryover = false; + if ($autoclose && $parent_def->formatting) { + $carryover = true; + } + + if ($autoclose) { + // check if this autoclose is doomed to fail + // (this rechecks $parent, which his harmless) + $autoclose_ok = isset($global_parent_allowed_elements[$token->name]); + if (!$autoclose_ok) { + foreach ($this->stack as $ancestor) { + $elements = $definition->info[$ancestor->name]->child->getAllowedElements($config); + if (isset($elements[$token->name])) { + $autoclose_ok = true; + break; + } + if ($definition->info[$token->name]->wrap) { + $wrapname = $definition->info[$token->name]->wrap; + $wrapdef = $definition->info[$wrapname]; + $wrap_elements = $wrapdef->child->getAllowedElements($config); + if (isset($wrap_elements[$token->name]) && isset($elements[$wrapname])) { + $autoclose_ok = true; + break; + } + } + } + } + if ($autoclose_ok) { + // errors need to be updated + $new_token = new HTMLPurifier_Token_End($parent->name); + $new_token->start = $parent; + // [TagClosedSuppress] + if ($e && !isset($parent->armor['MakeWellFormed_TagClosedError'])) { + if (!$carryover) { + $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag auto closed', $parent); + } else { + $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag carryover', $parent); + } + } + if ($carryover) { + $element = clone $parent; + // [TagClosedAuto] + $element->armor['MakeWellFormed_TagClosedError'] = true; + $element->carryover = true; + $token = $this->processToken(array($new_token, $token, $element)); + } else { + $token = $this->insertBefore($new_token); + } + } else { + $token = $this->remove(); + } + $reprocess = true; + continue; + } + + } + $ok = true; + } + + if ($ok) { + foreach ($this->injectors as $i => $injector) { + if (isset($token->skip[$i])) { + // See Note [Injector skips] + continue; + } + if ($token->rewind !== null && $token->rewind !== $i) { + continue; + } + $r = $token; + $injector->handleElement($r); + $token = $this->processToken($r, $i); + $reprocess = true; + break; + } + if (!$reprocess) { + // ah, nothing interesting happened; do normal processing + if ($token instanceof HTMLPurifier_Token_Start) { + $this->stack[] = $token; + } elseif ($token instanceof HTMLPurifier_Token_End) { + throw new HTMLPurifier_Exception( + 'Improper handling of end tag in start code; possible error in MakeWellFormed' + ); + } + } + continue; + } + + // sanity check: we should be dealing with a closing tag + if (!$token instanceof HTMLPurifier_Token_End) { + throw new HTMLPurifier_Exception('Unaccounted for tag token in input stream, bug in HTML Purifier'); + } + + // make sure that we have something open + if (empty($this->stack)) { + if ($escape_invalid_tags) { + if ($e) { + $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag to text'); + } + $token = new HTMLPurifier_Token_Text($generator->generateFromToken($token)); + } else { + if ($e) { + $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag removed'); + } + $token = $this->remove(); + } + $reprocess = true; + continue; + } + + // first, check for the simplest case: everything closes neatly. + // Eventually, everything passes through here; if there are problems + // we modify the input stream accordingly and then punt, so that + // the tokens get processed again. + $current_parent = array_pop($this->stack); + if ($current_parent->name == $token->name) { + $token->start = $current_parent; + foreach ($this->injectors as $i => $injector) { + if (isset($token->skip[$i])) { + // See Note [Injector skips] + continue; + } + if ($token->rewind !== null && $token->rewind !== $i) { + continue; + } + $r = $token; + $injector->handleEnd($r); + $token = $this->processToken($r, $i); + $this->stack[] = $current_parent; + $reprocess = true; + break; + } + continue; + } + + // okay, so we're trying to close the wrong tag + + // undo the pop previous pop + $this->stack[] = $current_parent; + + // scroll back the entire nest, trying to find our tag. + // (feature could be to specify how far you'd like to go) + $size = count($this->stack); + // -2 because -1 is the last element, but we already checked that + $skipped_tags = false; + for ($j = $size - 2; $j >= 0; $j--) { + if ($this->stack[$j]->name == $token->name) { + $skipped_tags = array_slice($this->stack, $j); + break; + } + } + + // we didn't find the tag, so remove + if ($skipped_tags === false) { + if ($escape_invalid_tags) { + if ($e) { + $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag to text'); + } + $token = new HTMLPurifier_Token_Text($generator->generateFromToken($token)); + } else { + if ($e) { + $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag removed'); + } + $token = $this->remove(); + } + $reprocess = true; + continue; + } + + // do errors, in REVERSE $j order: a,b,c with + $c = count($skipped_tags); + if ($e) { + for ($j = $c - 1; $j > 0; $j--) { + // notice we exclude $j == 0, i.e. the current ending tag, from + // the errors... [TagClosedSuppress] + if (!isset($skipped_tags[$j]->armor['MakeWellFormed_TagClosedError'])) { + $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by element end', $skipped_tags[$j]); + } + } + } + + // insert tags, in FORWARD $j order: c,b,a with + $replace = array($token); + for ($j = 1; $j < $c; $j++) { + // ...as well as from the insertions + $new_token = new HTMLPurifier_Token_End($skipped_tags[$j]->name); + $new_token->start = $skipped_tags[$j]; + array_unshift($replace, $new_token); + if (isset($definition->info[$new_token->name]) && $definition->info[$new_token->name]->formatting) { + // [TagClosedAuto] + $element = clone $skipped_tags[$j]; + $element->carryover = true; + $element->armor['MakeWellFormed_TagClosedError'] = true; + $replace[] = $element; + } + } + $token = $this->processToken($replace); + $reprocess = true; + continue; + } + + $context->destroy('CurrentToken'); + $context->destroy('CurrentNesting'); + $context->destroy('InputZipper'); + + unset($this->injectors, $this->stack, $this->tokens); + return $zipper->toArray($token); + } + + /** + * Processes arbitrary token values for complicated substitution patterns. + * In general: + * + * If $token is an array, it is a list of tokens to substitute for the + * current token. These tokens then get individually processed. If there + * is a leading integer in the list, that integer determines how many + * tokens from the stream should be removed. + * + * If $token is a regular token, it is swapped with the current token. + * + * If $token is false, the current token is deleted. + * + * If $token is an integer, that number of tokens (with the first token + * being the current one) will be deleted. + * + * @param HTMLPurifier_Token|array|int|bool $token Token substitution value + * @param HTMLPurifier_Injector|int $injector Injector that performed the substitution; default is if + * this is not an injector related operation. + * @throws HTMLPurifier_Exception + */ + protected function processToken($token, $injector = -1) + { + // Zend OpCache miscompiles $token = array($token), so + // avoid this pattern. See: https://github.com/ezyang/htmlpurifier/issues/108 + + // normalize forms of token + if (is_object($token)) { + $tmp = $token; + $token = array(1, $tmp); + } + if (is_int($token)) { + $tmp = $token; + $token = array($tmp); + } + if ($token === false) { + $token = array(1); + } + if (!is_array($token)) { + throw new HTMLPurifier_Exception('Invalid token type from injector'); + } + if (!is_int($token[0])) { + array_unshift($token, 1); + } + if ($token[0] === 0) { + throw new HTMLPurifier_Exception('Deleting zero tokens is not valid'); + } + + // $token is now an array with the following form: + // array(number nodes to delete, new node 1, new node 2, ...) + + $delete = array_shift($token); + list($old, $r) = $this->zipper->splice($this->token, $delete, $token); + + if ($injector > -1) { + // See Note [Injector skips] + // Determine appropriate skips. Here's what the code does: + // *If* we deleted one or more tokens, copy the skips + // of those tokens into the skips of the new tokens (in $token). + // Also, mark the newly inserted tokens as having come from + // $injector. + $oldskip = isset($old[0]) ? $old[0]->skip : array(); + foreach ($token as $object) { + $object->skip = $oldskip; + $object->skip[$injector] = true; + } + } + + return $r; + + } + + /** + * Inserts a token before the current token. Cursor now points to + * this token. You must reprocess after this. + * @param HTMLPurifier_Token $token + */ + private function insertBefore($token) + { + // NB not $this->zipper->insertBefore(), due to positioning + // differences + $splice = $this->zipper->splice($this->token, 0, array($token)); + + return $splice[1]; + } + + /** + * Removes current token. Cursor now points to new token occupying previously + * occupied space. You must reprocess after this. + */ + private function remove() + { + return $this->zipper->delete(); + } +} + +// Note [Injector skips] +// ~~~~~~~~~~~~~~~~~~~~~ +// When I originally designed this class, the idea behind the 'skip' +// property of HTMLPurifier_Token was to help avoid infinite loops +// in injector processing. For example, suppose you wrote an injector +// that bolded swear words. Naively, you might write it so that +// whenever you saw ****, you replaced it with ****. +// +// When this happens, we will reprocess all of the tokens with the +// other injectors. Now there is an opportunity for infinite loop: +// if we rerun the swear-word injector on these tokens, we might +// see **** and then reprocess again to get +// **** ad infinitum. +// +// Thus, the idea of a skip is that once we process a token with +// an injector, we mark all of those tokens as having "come from" +// the injector, and we never run the injector again on these +// tokens. +// +// There were two more complications, however: +// +// - With HTMLPurifier_Injector_RemoveEmpty, we noticed that if +// you had , after you removed the , you +// really would like this injector to go back and reprocess +// the tag, discovering that it is now empty and can be +// removed. So we reintroduced the possibility of infinite looping +// by adding a "rewind" function, which let you go back to an +// earlier point in the token stream and reprocess it with injectors. +// Needless to say, we need to UN-skip the token so it gets +// reprocessed. +// +// - Suppose that you successfuly process a token, replace it with +// one with your skip mark, but now another injector wants to +// process the skipped token with another token. Should you continue +// to skip that new token, or reprocess it? If you reprocess, +// you can end up with an infinite loop where one injector converts +// to , and then another injector converts it back. So +// we inherit the skips, but for some reason, I thought that we +// should inherit the skip from the first token of the token +// that we deleted. Why? Well, it seems to work OK. +// +// If I were to redesign this functionality, I would absolutely not +// go about doing it this way: the semantics are just not very well +// defined, and in any case you probably wanted to operate on trees, +// not token streams. + + + + + +/** + * Removes all unrecognized tags from the list of tokens. + * + * This strategy iterates through all the tokens and removes unrecognized + * tokens. If a token is not recognized but a TagTransform is defined for + * that element, the element will be transformed accordingly. + */ + +class HTMLPurifier_Strategy_RemoveForeignElements extends HTMLPurifier_Strategy +{ + + /** + * @param HTMLPurifier_Token[] $tokens + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array|HTMLPurifier_Token[] + */ + public function execute($tokens, $config, $context) + { + $definition = $config->getHTMLDefinition(); + $generator = new HTMLPurifier_Generator($config, $context); + $result = array(); + + $escape_invalid_tags = $config->get('Core.EscapeInvalidTags'); + $remove_invalid_img = $config->get('Core.RemoveInvalidImg'); + + // currently only used to determine if comments should be kept + $trusted = $config->get('HTML.Trusted'); + $comment_lookup = $config->get('HTML.AllowedComments'); + $comment_regexp = $config->get('HTML.AllowedCommentsRegexp'); + $check_comments = $comment_lookup !== array() || $comment_regexp !== null; + + $remove_script_contents = $config->get('Core.RemoveScriptContents'); + $hidden_elements = $config->get('Core.HiddenElements'); + + // remove script contents compatibility + if ($remove_script_contents === true) { + $hidden_elements['script'] = true; + } elseif ($remove_script_contents === false && isset($hidden_elements['script'])) { + unset($hidden_elements['script']); + } + + $attr_validator = new HTMLPurifier_AttrValidator(); + + // removes tokens until it reaches a closing tag with its value + $remove_until = false; + + // converts comments into text tokens when this is equal to a tag name + $textify_comments = false; + + $token = false; + $context->register('CurrentToken', $token); + + $e = false; + if ($config->get('Core.CollectErrors')) { + $e =& $context->get('ErrorCollector'); + } + + foreach ($tokens as $token) { + if ($remove_until) { + if (empty($token->is_tag) || $token->name !== $remove_until) { + continue; + } + } + if (!empty($token->is_tag)) { + // DEFINITION CALL + + // before any processing, try to transform the element + if (isset($definition->info_tag_transform[$token->name])) { + $original_name = $token->name; + // there is a transformation for this tag + // DEFINITION CALL + $token = $definition-> + info_tag_transform[$token->name]->transform($token, $config, $context); + if ($e) { + $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Tag transform', $original_name); + } + } + + if (isset($definition->info[$token->name])) { + // mostly everything's good, but + // we need to make sure required attributes are in order + if (($token instanceof HTMLPurifier_Token_Start || $token instanceof HTMLPurifier_Token_Empty) && + $definition->info[$token->name]->required_attr && + ($token->name != 'img' || $remove_invalid_img) // ensure config option still works + ) { + $attr_validator->validateToken($token, $config, $context); + $ok = true; + foreach ($definition->info[$token->name]->required_attr as $name) { + if (!isset($token->attr[$name])) { + $ok = false; + break; + } + } + if (!$ok) { + if ($e) { + $e->send( + E_ERROR, + 'Strategy_RemoveForeignElements: Missing required attribute', + $name + ); + } + continue; + } + $token->armor['ValidateAttributes'] = true; + } + + if (isset($hidden_elements[$token->name]) && $token instanceof HTMLPurifier_Token_Start) { + $textify_comments = $token->name; + } elseif ($token->name === $textify_comments && $token instanceof HTMLPurifier_Token_End) { + $textify_comments = false; + } + + } elseif ($escape_invalid_tags) { + // invalid tag, generate HTML representation and insert in + if ($e) { + $e->send(E_WARNING, 'Strategy_RemoveForeignElements: Foreign element to text'); + } + $token = new HTMLPurifier_Token_Text( + $generator->generateFromToken($token) + ); + } else { + // check if we need to destroy all of the tag's children + // CAN BE GENERICIZED + if (isset($hidden_elements[$token->name])) { + if ($token instanceof HTMLPurifier_Token_Start) { + $remove_until = $token->name; + } elseif ($token instanceof HTMLPurifier_Token_Empty) { + // do nothing: we're still looking + } else { + $remove_until = false; + } + if ($e) { + $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign meta element removed'); + } + } else { + if ($e) { + $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign element removed'); + } + } + continue; + } + } elseif ($token instanceof HTMLPurifier_Token_Comment) { + // textify comments in script tags when they are allowed + if ($textify_comments !== false) { + $data = $token->data; + $token = new HTMLPurifier_Token_Text($data); + } elseif ($trusted || $check_comments) { + // always cleanup comments + $trailing_hyphen = false; + if ($e) { + // perform check whether or not there's a trailing hyphen + if (substr($token->data, -1) == '-') { + $trailing_hyphen = true; + } + } + $token->data = rtrim($token->data, '-'); + $found_double_hyphen = false; + while (strpos($token->data, '--') !== false) { + $found_double_hyphen = true; + $token->data = str_replace('--', '-', $token->data); + } + if ($trusted || !empty($comment_lookup[trim($token->data)]) || + ($comment_regexp !== null && preg_match($comment_regexp, trim($token->data)))) { + // OK good + if ($e) { + if ($trailing_hyphen) { + $e->send( + E_NOTICE, + 'Strategy_RemoveForeignElements: Trailing hyphen in comment removed' + ); + } + if ($found_double_hyphen) { + $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Hyphens in comment collapsed'); + } + } + } else { + if ($e) { + $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Comment removed'); + } + continue; + } + } else { + // strip comments + if ($e) { + $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Comment removed'); + } + continue; + } + } elseif ($token instanceof HTMLPurifier_Token_Text) { + } else { + continue; + } + $result[] = $token; + } + if ($remove_until && $e) { + // we removed tokens until the end, throw error + $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Token removed to end', $remove_until); + } + $context->destroy('CurrentToken'); + return $result; + } +} + + + + + +/** + * Validate all attributes in the tokens. + */ + +class HTMLPurifier_Strategy_ValidateAttributes extends HTMLPurifier_Strategy +{ + + /** + * @param HTMLPurifier_Token[] $tokens + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return HTMLPurifier_Token[] + */ + public function execute($tokens, $config, $context) + { + // setup validator + $validator = new HTMLPurifier_AttrValidator(); + + $token = false; + $context->register('CurrentToken', $token); + + foreach ($tokens as $key => $token) { + + // only process tokens that have attributes, + // namely start and empty tags + if (!$token instanceof HTMLPurifier_Token_Start && !$token instanceof HTMLPurifier_Token_Empty) { + continue; + } + + // skip tokens that are armored + if (!empty($token->armor['ValidateAttributes'])) { + continue; + } + + // note that we have no facilities here for removing tokens + $validator->validateToken($token, $config, $context); + } + $context->destroy('CurrentToken'); + return $tokens; + } +} + + + + + +/** + * Transforms FONT tags to the proper form (SPAN with CSS styling) + * + * This transformation takes the three proprietary attributes of FONT and + * transforms them into their corresponding CSS attributes. These are color, + * face, and size. + * + * @note Size is an interesting case because it doesn't map cleanly to CSS. + * Thanks to + * http://style.cleverchimp.com/font_size_intervals/altintervals.html + * for reasonable mappings. + * @warning This doesn't work completely correctly; specifically, this + * TagTransform operates before well-formedness is enforced, so + * the "active formatting elements" algorithm doesn't get applied. + */ +class HTMLPurifier_TagTransform_Font extends HTMLPurifier_TagTransform +{ + /** + * @type string + */ + public $transform_to = 'span'; + + /** + * @type array + */ + protected $_size_lookup = array( + '0' => 'xx-small', + '1' => 'xx-small', + '2' => 'small', + '3' => 'medium', + '4' => 'large', + '5' => 'x-large', + '6' => 'xx-large', + '7' => '300%', + '-1' => 'smaller', + '-2' => '60%', + '+1' => 'larger', + '+2' => '150%', + '+3' => '200%', + '+4' => '300%' + ); + + /** + * @param HTMLPurifier_Token_Tag $tag + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return HTMLPurifier_Token_End|string + */ + public function transform($tag, $config, $context) + { + if ($tag instanceof HTMLPurifier_Token_End) { + $new_tag = clone $tag; + $new_tag->name = $this->transform_to; + return $new_tag; + } + + $attr = $tag->attr; + $prepend_style = ''; + + // handle color transform + if (isset($attr['color'])) { + $prepend_style .= 'color:' . $attr['color'] . ';'; + unset($attr['color']); + } + + // handle face transform + if (isset($attr['face'])) { + $prepend_style .= 'font-family:' . $attr['face'] . ';'; + unset($attr['face']); + } + + // handle size transform + if (isset($attr['size'])) { + // normalize large numbers + if ($attr['size'] !== '') { + if ($attr['size'][0] == '+' || $attr['size'][0] == '-') { + $size = (int)$attr['size']; + if ($size < -2) { + $attr['size'] = '-2'; + } + if ($size > 4) { + $attr['size'] = '+4'; + } + } else { + $size = (int)$attr['size']; + if ($size > 7) { + $attr['size'] = '7'; + } + } + } + if (isset($this->_size_lookup[$attr['size']])) { + $prepend_style .= 'font-size:' . + $this->_size_lookup[$attr['size']] . ';'; + } + unset($attr['size']); + } + + if ($prepend_style) { + $attr['style'] = isset($attr['style']) ? + $prepend_style . $attr['style'] : + $prepend_style; + } + + $new_tag = clone $tag; + $new_tag->name = $this->transform_to; + $new_tag->attr = $attr; + + return $new_tag; + } +} + + + + + +/** + * Simple transformation, just change tag name to something else, + * and possibly add some styling. This will cover most of the deprecated + * tag cases. + */ +class HTMLPurifier_TagTransform_Simple extends HTMLPurifier_TagTransform +{ + /** + * @type string + */ + protected $style; + + /** + * @param string $transform_to Tag name to transform to. + * @param string $style CSS style to add to the tag + */ + public function __construct($transform_to, $style = null) + { + $this->transform_to = $transform_to; + $this->style = $style; + } + + /** + * @param HTMLPurifier_Token_Tag $tag + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + */ + public function transform($tag, $config, $context) + { + $new_tag = clone $tag; + $new_tag->name = $this->transform_to; + if (!is_null($this->style) && + ($new_tag instanceof HTMLPurifier_Token_Start || $new_tag instanceof HTMLPurifier_Token_Empty) + ) { + $this->prependCSS($new_tag->attr, $this->style); + } + return $new_tag; + } +} + + + + + +/** + * Concrete comment token class. Generally will be ignored. + */ +class HTMLPurifier_Token_Comment extends HTMLPurifier_Token +{ + /** + * Character data within comment. + * @type string + */ + public $data; + + /** + * @type bool + */ + public $is_whitespace = true; + + /** + * Transparent constructor. + * + * @param string $data String comment data. + * @param int $line + * @param int $col + */ + public function __construct($data, $line = null, $col = null) + { + $this->data = $data; + $this->line = $line; + $this->col = $col; + } + + public function toNode() { + return new HTMLPurifier_Node_Comment($this->data, $this->line, $this->col); + } +} + + + + + +/** + * Abstract class of a tag token (start, end or empty), and its behavior. + */ +abstract class HTMLPurifier_Token_Tag extends HTMLPurifier_Token +{ + /** + * Static bool marker that indicates the class is a tag. + * + * This allows us to check objects with !empty($obj->is_tag) + * without having to use a function call is_a(). + * @type bool + */ + public $is_tag = true; + + /** + * The lower-case name of the tag, like 'a', 'b' or 'blockquote'. + * + * @note Strictly speaking, XML tags are case sensitive, so we shouldn't + * be lower-casing them, but these tokens cater to HTML tags, which are + * insensitive. + * @type string + */ + public $name; + + /** + * Associative array of the tag's attributes. + * @type array + */ + public $attr = array(); + + /** + * Non-overloaded constructor, which lower-cases passed tag name. + * + * @param string $name String name. + * @param array $attr Associative array of attributes. + * @param int $line + * @param int $col + * @param array $armor + */ + public function __construct($name, $attr = array(), $line = null, $col = null, $armor = array()) + { + $this->name = ctype_lower($name) ? $name : strtolower($name); + foreach ($attr as $key => $value) { + // normalization only necessary when key is not lowercase + if (!ctype_lower($key)) { + $new_key = strtolower($key); + if (!isset($attr[$new_key])) { + $attr[$new_key] = $attr[$key]; + } + if ($new_key !== $key) { + unset($attr[$key]); + } + } + } + $this->attr = $attr; + $this->line = $line; + $this->col = $col; + $this->armor = $armor; + } + + public function toNode() { + return new HTMLPurifier_Node_Element($this->name, $this->attr, $this->line, $this->col, $this->armor); + } +} + + + + + +/** + * Concrete empty token class. + */ +class HTMLPurifier_Token_Empty extends HTMLPurifier_Token_Tag +{ + public function toNode() { + $n = parent::toNode(); + $n->empty = true; + return $n; + } +} + + + + + +/** + * Concrete end token class. + * + * @warning This class accepts attributes even though end tags cannot. This + * is for optimization reasons, as under normal circumstances, the Lexers + * do not pass attributes. + */ +class HTMLPurifier_Token_End extends HTMLPurifier_Token_Tag +{ + /** + * Token that started this node. + * Added by MakeWellFormed. Please do not edit this! + * @type HTMLPurifier_Token + */ + public $start; + + public function toNode() { + throw new Exception("HTMLPurifier_Token_End->toNode not supported!"); + } +} + + + + + +/** + * Concrete start token class. + */ +class HTMLPurifier_Token_Start extends HTMLPurifier_Token_Tag +{ +} + + + + + +/** + * Concrete text token class. + * + * Text tokens comprise of regular parsed character data (PCDATA) and raw + * character data (from the CDATA sections). Internally, their + * data is parsed with all entities expanded. Surprisingly, the text token + * does have a "tag name" called #PCDATA, which is how the DTD represents it + * in permissible child nodes. + */ +class HTMLPurifier_Token_Text extends HTMLPurifier_Token +{ + + /** + * @type string + */ + public $name = '#PCDATA'; + /**< PCDATA tag name compatible with DTD. */ + + /** + * @type string + */ + public $data; + /**< Parsed character data of text. */ + + /** + * @type bool + */ + public $is_whitespace; + + /**< Bool indicating if node is whitespace. */ + + /** + * Constructor, accepts data and determines if it is whitespace. + * @param string $data String parsed character data. + * @param int $line + * @param int $col + */ + public function __construct($data, $line = null, $col = null) + { + $this->data = $data; + $this->is_whitespace = ctype_space($data); + $this->line = $line; + $this->col = $col; + } + + public function toNode() { + return new HTMLPurifier_Node_Text($this->data, $this->is_whitespace, $this->line, $this->col); + } +} + + + + + +class HTMLPurifier_URIFilter_DisableExternal extends HTMLPurifier_URIFilter +{ + /** + * @type string + */ + public $name = 'DisableExternal'; + + /** + * @type array + */ + protected $ourHostParts = false; + + /** + * @param HTMLPurifier_Config $config + * @return void + */ + public function prepare($config) + { + $our_host = $config->getDefinition('URI')->host; + if ($our_host !== null) { + $this->ourHostParts = array_reverse(explode('.', $our_host)); + } + } + + /** + * @param HTMLPurifier_URI $uri Reference + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function filter(&$uri, $config, $context) + { + if (is_null($uri->host)) { + return true; + } + if ($this->ourHostParts === false) { + return false; + } + $host_parts = array_reverse(explode('.', $uri->host)); + foreach ($this->ourHostParts as $i => $x) { + if (!isset($host_parts[$i])) { + return false; + } + if ($host_parts[$i] != $this->ourHostParts[$i]) { + return false; + } + } + return true; + } +} + + + + + +class HTMLPurifier_URIFilter_DisableExternalResources extends HTMLPurifier_URIFilter_DisableExternal +{ + /** + * @type string + */ + public $name = 'DisableExternalResources'; + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function filter(&$uri, $config, $context) + { + if (!$context->get('EmbeddedURI', true)) { + return true; + } + return parent::filter($uri, $config, $context); + } +} + + + + + +class HTMLPurifier_URIFilter_DisableResources extends HTMLPurifier_URIFilter +{ + /** + * @type string + */ + public $name = 'DisableResources'; + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function filter(&$uri, $config, $context) + { + return !$context->get('EmbeddedURI', true); + } +} + + + + + +// It's not clear to me whether or not Punycode means that hostnames +// do not have canonical forms anymore. As far as I can tell, it's +// not a problem (punycoding should be identity when no Unicode +// points are involved), but I'm not 100% sure +class HTMLPurifier_URIFilter_HostBlacklist extends HTMLPurifier_URIFilter +{ + /** + * @type string + */ + public $name = 'HostBlacklist'; + + /** + * @type array + */ + protected $blacklist = array(); + + /** + * @param HTMLPurifier_Config $config + * @return bool + */ + public function prepare($config) + { + $this->blacklist = $config->get('URI.HostBlacklist'); + return true; + } + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function filter(&$uri, $config, $context) + { + foreach ($this->blacklist as $blacklisted_host_fragment) { + if (strpos($uri->host, $blacklisted_host_fragment) !== false) { + return false; + } + } + return true; + } +} + + + + + +// does not support network paths + +class HTMLPurifier_URIFilter_MakeAbsolute extends HTMLPurifier_URIFilter +{ + /** + * @type string + */ + public $name = 'MakeAbsolute'; + + /** + * @type + */ + protected $base; + + /** + * @type array + */ + protected $basePathStack = array(); + + /** + * @param HTMLPurifier_Config $config + * @return bool + */ + public function prepare($config) + { + $def = $config->getDefinition('URI'); + $this->base = $def->base; + if (is_null($this->base)) { + trigger_error( + 'URI.MakeAbsolute is being ignored due to lack of ' . + 'value for URI.Base configuration', + E_USER_WARNING + ); + return false; + } + $this->base->fragment = null; // fragment is invalid for base URI + $stack = explode('/', $this->base->path); + array_pop($stack); // discard last segment + $stack = $this->_collapseStack($stack); // do pre-parsing + $this->basePathStack = $stack; + return true; + } + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function filter(&$uri, $config, $context) + { + if (is_null($this->base)) { + return true; + } // abort early + if ($uri->path === '' && is_null($uri->scheme) && + is_null($uri->host) && is_null($uri->query) && is_null($uri->fragment)) { + // reference to current document + $uri = clone $this->base; + return true; + } + if (!is_null($uri->scheme)) { + // absolute URI already: don't change + if (!is_null($uri->host)) { + return true; + } + $scheme_obj = $uri->getSchemeObj($config, $context); + if (!$scheme_obj) { + // scheme not recognized + return false; + } + if (!$scheme_obj->hierarchical) { + // non-hierarchal URI with explicit scheme, don't change + return true; + } + // special case: had a scheme but always is hierarchical and had no authority + } + if (!is_null($uri->host)) { + // network path, don't bother + return true; + } + if ($uri->path === '') { + $uri->path = $this->base->path; + } elseif ($uri->path[0] !== '/') { + // relative path, needs more complicated processing + $stack = explode('/', $uri->path); + $new_stack = array_merge($this->basePathStack, $stack); + if ($new_stack[0] !== '' && !is_null($this->base->host)) { + array_unshift($new_stack, ''); + } + $new_stack = $this->_collapseStack($new_stack); + $uri->path = implode('/', $new_stack); + } else { + // absolute path, but still we should collapse + $uri->path = implode('/', $this->_collapseStack(explode('/', $uri->path))); + } + // re-combine + $uri->scheme = $this->base->scheme; + if (is_null($uri->userinfo)) { + $uri->userinfo = $this->base->userinfo; + } + if (is_null($uri->host)) { + $uri->host = $this->base->host; + } + if (is_null($uri->port)) { + $uri->port = $this->base->port; + } + return true; + } + + /** + * Resolve dots and double-dots in a path stack + * @param array $stack + * @return array + */ + private function _collapseStack($stack) + { + $result = array(); + $is_folder = false; + for ($i = 0; isset($stack[$i]); $i++) { + $is_folder = false; + // absorb an internally duplicated slash + if ($stack[$i] == '' && $i && isset($stack[$i + 1])) { + continue; + } + if ($stack[$i] == '..') { + if (!empty($result)) { + $segment = array_pop($result); + if ($segment === '' && empty($result)) { + // error case: attempted to back out too far: + // restore the leading slash + $result[] = ''; + } elseif ($segment === '..') { + $result[] = '..'; // cannot remove .. with .. + } + } else { + // relative path, preserve the double-dots + $result[] = '..'; + } + $is_folder = true; + continue; + } + if ($stack[$i] == '.') { + // silently absorb + $is_folder = true; + continue; + } + $result[] = $stack[$i]; + } + if ($is_folder) { + $result[] = ''; + } + return $result; + } +} + + + + + +class HTMLPurifier_URIFilter_Munge extends HTMLPurifier_URIFilter +{ + /** + * @type string + */ + public $name = 'Munge'; + + /** + * @type bool + */ + public $post = true; + + /** + * @type string + */ + private $target; + + /** + * @type HTMLPurifier_URIParser + */ + private $parser; + + /** + * @type bool + */ + private $doEmbed; + + /** + * @type string + */ + private $secretKey; + + /** + * @type array + */ + protected $replace = array(); + + /** + * @param HTMLPurifier_Config $config + * @return bool + */ + public function prepare($config) + { + $this->target = $config->get('URI.' . $this->name); + $this->parser = new HTMLPurifier_URIParser(); + $this->doEmbed = $config->get('URI.MungeResources'); + $this->secretKey = $config->get('URI.MungeSecretKey'); + if ($this->secretKey && !function_exists('hash_hmac')) { + throw new Exception("Cannot use %URI.MungeSecretKey without hash_hmac support."); + } + return true; + } + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function filter(&$uri, $config, $context) + { + if ($context->get('EmbeddedURI', true) && !$this->doEmbed) { + return true; + } + + $scheme_obj = $uri->getSchemeObj($config, $context); + if (!$scheme_obj) { + return true; + } // ignore unknown schemes, maybe another postfilter did it + if (!$scheme_obj->browsable) { + return true; + } // ignore non-browseable schemes, since we can't munge those in a reasonable way + if ($uri->isBenign($config, $context)) { + return true; + } // don't redirect if a benign URL + + $this->makeReplace($uri, $config, $context); + $this->replace = array_map('rawurlencode', $this->replace); + + $new_uri = strtr($this->target, $this->replace); + $new_uri = $this->parser->parse($new_uri); + // don't redirect if the target host is the same as the + // starting host + if ($uri->host === $new_uri->host) { + return true; + } + $uri = $new_uri; // overwrite + return true; + } + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + */ + protected function makeReplace($uri, $config, $context) + { + $string = $uri->toString(); + // always available + $this->replace['%s'] = $string; + $this->replace['%r'] = $context->get('EmbeddedURI', true); + $token = $context->get('CurrentToken', true); + $this->replace['%n'] = $token ? $token->name : null; + $this->replace['%m'] = $context->get('CurrentAttr', true); + $this->replace['%p'] = $context->get('CurrentCSSProperty', true); + // not always available + if ($this->secretKey) { + $this->replace['%t'] = hash_hmac("sha256", $string, $this->secretKey); + } + } +} + + + + + +/** + * Implements safety checks for safe iframes. + * + * @warning This filter is *critical* for ensuring that %HTML.SafeIframe + * works safely. + */ +class HTMLPurifier_URIFilter_SafeIframe extends HTMLPurifier_URIFilter +{ + /** + * @type string + */ + public $name = 'SafeIframe'; + + /** + * @type bool + */ + public $always_load = true; + + /** + * @type string + */ + protected $regexp = null; + + // XXX: The not so good bit about how this is all set up now is we + // can't check HTML.SafeIframe in the 'prepare' step: we have to + // defer till the actual filtering. + /** + * @param HTMLPurifier_Config $config + * @return bool + */ + public function prepare($config) + { + $this->regexp = $config->get('URI.SafeIframeRegexp'); + return true; + } + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function filter(&$uri, $config, $context) + { + // check if filter not applicable + if (!$config->get('HTML.SafeIframe')) { + return true; + } + // check if the filter should actually trigger + if (!$context->get('EmbeddedURI', true)) { + return true; + } + $token = $context->get('CurrentToken', true); + if (!($token && $token->name == 'iframe')) { + return true; + } + // check if we actually have some whitelists enabled + if ($this->regexp === null) { + return false; + } + // actually check the whitelists + return preg_match($this->regexp, $uri->toString()); + } +} + + + + + +/** + * Implements data: URI for base64 encoded images supported by GD. + */ +class HTMLPurifier_URIScheme_data extends HTMLPurifier_URIScheme +{ + /** + * @type bool + */ + public $browsable = true; + + /** + * @type array + */ + public $allowed_types = array( + // you better write validation code for other types if you + // decide to allow them + 'image/jpeg' => true, + 'image/gif' => true, + 'image/png' => true, + ); + // this is actually irrelevant since we only write out the path + // component + /** + * @type bool + */ + public $may_omit_host = true; + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function doValidate(&$uri, $config, $context) + { + $result = explode(',', $uri->path, 2); + $is_base64 = false; + $charset = null; + $content_type = null; + if (count($result) == 2) { + list($metadata, $data) = $result; + // do some legwork on the metadata + $metas = explode(';', $metadata); + while (!empty($metas)) { + $cur = array_shift($metas); + if ($cur == 'base64') { + $is_base64 = true; + break; + } + if (substr($cur, 0, 8) == 'charset=') { + // doesn't match if there are arbitrary spaces, but + // whatever dude + if ($charset !== null) { + continue; + } // garbage + $charset = substr($cur, 8); // not used + } else { + if ($content_type !== null) { + continue; + } // garbage + $content_type = $cur; + } + } + } else { + $data = $result[0]; + } + if ($content_type !== null && empty($this->allowed_types[$content_type])) { + return false; + } + if ($charset !== null) { + // error; we don't allow plaintext stuff + $charset = null; + } + $data = rawurldecode($data); + if ($is_base64) { + $raw_data = base64_decode($data); + } else { + $raw_data = $data; + } + if ( strlen($raw_data) < 12 ) { + // error; exif_imagetype throws exception with small files, + // and this likely indicates a corrupt URI/failed parse anyway + return false; + } + // XXX probably want to refactor this into a general mechanism + // for filtering arbitrary content types + if (function_exists('sys_get_temp_dir')) { + $file = tempnam(sys_get_temp_dir(), ""); + } else { + $file = tempnam("/tmp", ""); + } + file_put_contents($file, $raw_data); + if (function_exists('exif_imagetype')) { + $image_code = exif_imagetype($file); + unlink($file); + } elseif (function_exists('getimagesize')) { + set_error_handler(array($this, 'muteErrorHandler')); + $info = getimagesize($file); + restore_error_handler(); + unlink($file); + if ($info == false) { + return false; + } + $image_code = $info[2]; + } else { + trigger_error("could not find exif_imagetype or getimagesize functions", E_USER_ERROR); + } + $real_content_type = image_type_to_mime_type($image_code); + if ($real_content_type != $content_type) { + // we're nice guys; if the content type is something else we + // support, change it over + if (empty($this->allowed_types[$real_content_type])) { + return false; + } + $content_type = $real_content_type; + } + // ok, it's kosher, rewrite what we need + $uri->userinfo = null; + $uri->host = null; + $uri->port = null; + $uri->fragment = null; + $uri->query = null; + $uri->path = "$content_type;base64," . base64_encode($raw_data); + return true; + } + + /** + * @param int $errno + * @param string $errstr + */ + public function muteErrorHandler($errno, $errstr) + { + } +} + + + +/** + * Validates file as defined by RFC 1630 and RFC 1738. + */ +class HTMLPurifier_URIScheme_file extends HTMLPurifier_URIScheme +{ + /** + * Generally file:// URLs are not accessible from most + * machines, so placing them as an img src is incorrect. + * @type bool + */ + public $browsable = false; + + /** + * Basically the *only* URI scheme for which this is true, since + * accessing files on the local machine is very common. In fact, + * browsers on some operating systems don't understand the + * authority, though I hear it is used on Windows to refer to + * network shares. + * @type bool + */ + public $may_omit_host = true; + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function doValidate(&$uri, $config, $context) + { + // Authentication method is not supported + $uri->userinfo = null; + // file:// makes no provisions for accessing the resource + $uri->port = null; + // While it seems to work on Firefox, the querystring has + // no possible effect and is thus stripped. + $uri->query = null; + return true; + } +} + + + + + +/** + * Validates ftp (File Transfer Protocol) URIs as defined by generic RFC 1738. + */ +class HTMLPurifier_URIScheme_ftp extends HTMLPurifier_URIScheme +{ + /** + * @type int + */ + public $default_port = 21; + + /** + * @type bool + */ + public $browsable = true; // usually + + /** + * @type bool + */ + public $hierarchical = true; + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function doValidate(&$uri, $config, $context) + { + $uri->query = null; + + // typecode check + $semicolon_pos = strrpos($uri->path, ';'); // reverse + if ($semicolon_pos !== false) { + $type = substr($uri->path, $semicolon_pos + 1); // no semicolon + $uri->path = substr($uri->path, 0, $semicolon_pos); + $type_ret = ''; + if (strpos($type, '=') !== false) { + // figure out whether or not the declaration is correct + list($key, $typecode) = explode('=', $type, 2); + if ($key !== 'type') { + // invalid key, tack it back on encoded + $uri->path .= '%3B' . $type; + } elseif ($typecode === 'a' || $typecode === 'i' || $typecode === 'd') { + $type_ret = ";type=$typecode"; + } + } else { + $uri->path .= '%3B' . $type; + } + $uri->path = str_replace(';', '%3B', $uri->path); + $uri->path .= $type_ret; + } + return true; + } +} + + + + + +/** + * Validates http (HyperText Transfer Protocol) as defined by RFC 2616 + */ +class HTMLPurifier_URIScheme_http extends HTMLPurifier_URIScheme +{ + /** + * @type int + */ + public $default_port = 80; + + /** + * @type bool + */ + public $browsable = true; + + /** + * @type bool + */ + public $hierarchical = true; + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function doValidate(&$uri, $config, $context) + { + $uri->userinfo = null; + return true; + } +} + + + + + +/** + * Validates https (Secure HTTP) according to http scheme. + */ +class HTMLPurifier_URIScheme_https extends HTMLPurifier_URIScheme_http +{ + /** + * @type int + */ + public $default_port = 443; + /** + * @type bool + */ + public $secure = true; +} + + + + + +// VERY RELAXED! Shouldn't cause problems, not even Firefox checks if the +// email is valid, but be careful! + +/** + * Validates mailto (for E-mail) according to RFC 2368 + * @todo Validate the email address + * @todo Filter allowed query parameters + */ + +class HTMLPurifier_URIScheme_mailto extends HTMLPurifier_URIScheme +{ + /** + * @type bool + */ + public $browsable = false; + + /** + * @type bool + */ + public $may_omit_host = true; + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function doValidate(&$uri, $config, $context) + { + $uri->userinfo = null; + $uri->host = null; + $uri->port = null; + // we need to validate path against RFC 2368's addr-spec + return true; + } +} + + + + + +/** + * Validates news (Usenet) as defined by generic RFC 1738 + */ +class HTMLPurifier_URIScheme_news extends HTMLPurifier_URIScheme +{ + /** + * @type bool + */ + public $browsable = false; + + /** + * @type bool + */ + public $may_omit_host = true; + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function doValidate(&$uri, $config, $context) + { + $uri->userinfo = null; + $uri->host = null; + $uri->port = null; + $uri->query = null; + // typecode check needed on path + return true; + } +} + + + + + +/** + * Validates nntp (Network News Transfer Protocol) as defined by generic RFC 1738 + */ +class HTMLPurifier_URIScheme_nntp extends HTMLPurifier_URIScheme +{ + /** + * @type int + */ + public $default_port = 119; + + /** + * @type bool + */ + public $browsable = false; + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function doValidate(&$uri, $config, $context) + { + $uri->userinfo = null; + $uri->query = null; + return true; + } +} + + + + + +/** + * Validates tel (for phone numbers). + * + * The relevant specifications for this protocol are RFC 3966 and RFC 5341, + * but this class takes a much simpler approach: we normalize phone + * numbers so that they only include (possibly) a leading plus, + * and then any number of digits and x'es. + */ + +class HTMLPurifier_URIScheme_tel extends HTMLPurifier_URIScheme +{ + /** + * @type bool + */ + public $browsable = false; + + /** + * @type bool + */ + public $may_omit_host = true; + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function doValidate(&$uri, $config, $context) + { + $uri->userinfo = null; + $uri->host = null; + $uri->port = null; + + // Delete all non-numeric characters, non-x characters + // from phone number, EXCEPT for a leading plus sign. + $uri->path = preg_replace('/(?!^\+)[^\dx]/', '', + // Normalize e(x)tension to lower-case + str_replace('X', 'x', $uri->path)); + + return true; + } +} + + + + + +/** + * Performs safe variable parsing based on types which can be used by + * users. This may not be able to represent all possible data inputs, + * however. + */ +class HTMLPurifier_VarParser_Flexible extends HTMLPurifier_VarParser +{ + /** + * @param mixed $var + * @param int $type + * @param bool $allow_null + * @return array|bool|float|int|mixed|null|string + * @throws HTMLPurifier_VarParserException + */ + protected function parseImplementation($var, $type, $allow_null) + { + if ($allow_null && $var === null) { + return null; + } + switch ($type) { + // Note: if code "breaks" from the switch, it triggers a generic + // exception to be thrown. Specific errors can be specifically + // done here. + case self::C_MIXED: + case self::ISTRING: + case self::C_STRING: + case self::TEXT: + case self::ITEXT: + return $var; + case self::C_INT: + if (is_string($var) && ctype_digit($var)) { + $var = (int)$var; + } + return $var; + case self::C_FLOAT: + if ((is_string($var) && is_numeric($var)) || is_int($var)) { + $var = (float)$var; + } + return $var; + case self::C_BOOL: + if (is_int($var) && ($var === 0 || $var === 1)) { + $var = (bool)$var; + } elseif (is_string($var)) { + if ($var == 'on' || $var == 'true' || $var == '1') { + $var = true; + } elseif ($var == 'off' || $var == 'false' || $var == '0') { + $var = false; + } else { + throw new HTMLPurifier_VarParserException("Unrecognized value '$var' for $type"); + } + } + return $var; + case self::ALIST: + case self::HASH: + case self::LOOKUP: + if (is_string($var)) { + // special case: technically, this is an array with + // a single empty string item, but having an empty + // array is more intuitive + if ($var == '') { + return array(); + } + if (strpos($var, "\n") === false && strpos($var, "\r") === false) { + // simplistic string to array method that only works + // for simple lists of tag names or alphanumeric characters + $var = explode(',', $var); + } else { + $var = preg_split('/(,|[\n\r]+)/', $var); + } + // remove spaces + foreach ($var as $i => $j) { + $var[$i] = trim($j); + } + if ($type === self::HASH) { + // key:value,key2:value2 + $nvar = array(); + foreach ($var as $keypair) { + $c = explode(':', $keypair, 2); + if (!isset($c[1])) { + continue; + } + $nvar[trim($c[0])] = trim($c[1]); + } + $var = $nvar; + } + } + if (!is_array($var)) { + break; + } + $keys = array_keys($var); + if ($keys === array_keys($keys)) { + if ($type == self::ALIST) { + return $var; + } elseif ($type == self::LOOKUP) { + $new = array(); + foreach ($var as $key) { + $new[$key] = true; + } + return $new; + } else { + break; + } + } + if ($type === self::ALIST) { + trigger_error("Array list did not have consecutive integer indexes", E_USER_WARNING); + return array_values($var); + } + if ($type === self::LOOKUP) { + foreach ($var as $key => $value) { + if ($value !== true) { + trigger_error( + "Lookup array has non-true value at key '$key'; " . + "maybe your input array was not indexed numerically", + E_USER_WARNING + ); + } + $var[$key] = true; + } + } + return $var; + default: + $this->errorInconsistent(__CLASS__, $type); + } + $this->errorGeneric($var, $type); + } +} + + + + + +/** + * This variable parser uses PHP's internal code engine. Because it does + * this, it can represent all inputs; however, it is dangerous and cannot + * be used by users. + */ +class HTMLPurifier_VarParser_Native extends HTMLPurifier_VarParser +{ + + /** + * @param mixed $var + * @param int $type + * @param bool $allow_null + * @return null|string + */ + protected function parseImplementation($var, $type, $allow_null) + { + return $this->evalExpression($var); + } + + /** + * @param string $expr + * @return mixed + * @throws HTMLPurifier_VarParserException + */ + protected function evalExpression($expr) + { + $var = null; + $result = eval("\$var = $expr;"); + if ($result === false) { + throw new HTMLPurifier_VarParserException("Fatal error in evaluated code"); + } + return $var; + } +} + + + diff --git a/hesk/inc/htmlpurifier/HeskHTMLPurifier.php b/hesk/inc/htmlpurifier/HeskHTMLPurifier.php new file mode 100644 index 0000000..018cc1e --- /dev/null +++ b/hesk/inc/htmlpurifier/HeskHTMLPurifier.php @@ -0,0 +1,66 @@ +allowIframes = $allowIframes; + $this->cacheDir = $this->setupCacheDir($cacheDir); + } + + public function heskPurify($content) + { + $config = HTMLPurifier_Config::createDefault(); + $config->set('Attr.AllowedRel', array('follow', 'referrer', 'nofollow', 'noreferrer') ); + $config->set('Attr.AllowedFrameTargets', array('_blank', '_self', '_parent', '_top') ); + $config->set('Cache.SerializerPath', $this->cacheDir); + $config->set('URI.AllowedSchemes', array( + 'http' => true, + 'https' => true, + 'mailto' => true, + 'ftp' => true, + 'nntp' => true, + 'news' => true, + 'tel' => true, + 'data' => true, + ) + ); + + if ($this->allowIframes) + { + require(HESK_PATH . 'inc/htmlpurifier/custom/heskIframe.php'); + $config->set('Filter.Custom', array(new HTMLPurifier_Filter_HeskIframe())); + } + + $purifier = new HTMLPurifier($config); + return $purifier->purify($content); + } + + private function setupCacheDir($cache_dir) + { + $cache_dir = dirname(dirname(dirname(__FILE__))).'/'.$cache_dir.'/hp'; + + if (is_dir($cache_dir) || ( @mkdir($cache_dir, 0777) && is_writable($cache_dir) ) ) + { + return $cache_dir; + } + + return null; + } +} diff --git a/hesk/inc/htmlpurifier/custom/heskIframe.php b/hesk/inc/htmlpurifier/custom/heskIframe.php new file mode 100644 index 0000000..2ea9b5e --- /dev/null +++ b/hesk/inc/htmlpurifier/custom/heskIframe.php @@ -0,0 +1,71 @@ +#i', '', $html); + return $html; + } + + /** + * + * @param string $html + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + */ + public function postFilter($html, $config, $context) + { + $post_regex = '#]+?)/?>#'; + return preg_replace_callback($post_regex, array($this, 'postFilterCallback'), $html); + } + + /** + * + * @param array $matches + * @return string + */ + protected function postFilterCallback($matches) + { + // Domain Whitelist + $youTubeMatch = preg_match('#src="https?://www.youtube(-nocookie)?.com/#i', $matches[1]); + $vimeoMatch = preg_match('#src="https?://player.vimeo.com/#i', $matches[1]); + if ($youTubeMatch || $vimeoMatch) { + $extra = ' frameborder="0"'; + if ($youTubeMatch) { + $extra .= ' allowfullscreen'; + } elseif ($vimeoMatch) { + $extra .= ' webkitAllowFullScreen mozallowfullscreen allowFullScreen'; + } + return ''; + } else { + return ''; + } + } +} diff --git a/hesk/inc/htmlpurifier/custom/index.htm b/hesk/inc/htmlpurifier/custom/index.htm new file mode 100644 index 0000000..d79f2c9 --- /dev/null +++ b/hesk/inc/htmlpurifier/custom/index.htm @@ -0,0 +1,8 @@ + + +403 Forbidden + +

        Forbidden

        +You don't have permission to access this folder.

        +


        + \ No newline at end of file diff --git a/hesk/inc/htmlpurifier/index.htm b/hesk/inc/htmlpurifier/index.htm new file mode 100644 index 0000000..d79f2c9 --- /dev/null +++ b/hesk/inc/htmlpurifier/index.htm @@ -0,0 +1,8 @@ + + +403 Forbidden + +

        Forbidden

        +You don't have permission to access this folder.

        +


        + \ No newline at end of file diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php new file mode 100644 index 0000000..1174575 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php @@ -0,0 +1,48 @@ +directives as $d) { + $schema->add( + $d->id->key, + $d->default, + $d->type, + $d->typeAllowsNull + ); + if ($d->allowed !== null) { + $schema->addAllowedValues( + $d->id->key, + $d->allowed + ); + } + foreach ($d->aliases as $alias) { + $schema->addAlias( + $alias->key, + $d->id->key + ); + } + if ($d->valueAliases !== null) { + $schema->addValueAliases( + $d->id->key, + $d->valueAliases + ); + } + } + $schema->postProcess(); + return $schema; + } +} + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Builder/Xml.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Builder/Xml.php new file mode 100644 index 0000000..0d00bf1 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Builder/Xml.php @@ -0,0 +1,144 @@ +startElement('div'); + + $purifier = HTMLPurifier::getInstance(); + $html = $purifier->purify($html); + $this->writeAttribute('xmlns', 'http://www.w3.org/1999/xhtml'); + $this->writeRaw($html); + + $this->endElement(); // div + } + + /** + * @param mixed $var + * @return string + */ + protected function export($var) + { + if ($var === array()) { + return 'array()'; + } + return var_export($var, true); + } + + /** + * @param HTMLPurifier_ConfigSchema_Interchange $interchange + */ + public function build($interchange) + { + // global access, only use as last resort + $this->interchange = $interchange; + + $this->setIndent(true); + $this->startDocument('1.0', 'UTF-8'); + $this->startElement('configdoc'); + $this->writeElement('title', $interchange->name); + + foreach ($interchange->directives as $directive) { + $this->buildDirective($directive); + } + + if ($this->namespace) { + $this->endElement(); + } // namespace + + $this->endElement(); // configdoc + $this->flush(); + } + + /** + * @param HTMLPurifier_ConfigSchema_Interchange_Directive $directive + */ + public function buildDirective($directive) + { + // Kludge, although I suppose having a notion of a "root namespace" + // certainly makes things look nicer when documentation is built. + // Depends on things being sorted. + if (!$this->namespace || $this->namespace !== $directive->id->getRootNamespace()) { + if ($this->namespace) { + $this->endElement(); + } // namespace + $this->namespace = $directive->id->getRootNamespace(); + $this->startElement('namespace'); + $this->writeAttribute('id', $this->namespace); + $this->writeElement('name', $this->namespace); + } + + $this->startElement('directive'); + $this->writeAttribute('id', $directive->id->toString()); + + $this->writeElement('name', $directive->id->getDirective()); + + $this->startElement('aliases'); + foreach ($directive->aliases as $alias) { + $this->writeElement('alias', $alias->toString()); + } + $this->endElement(); // aliases + + $this->startElement('constraints'); + if ($directive->version) { + $this->writeElement('version', $directive->version); + } + $this->startElement('type'); + if ($directive->typeAllowsNull) { + $this->writeAttribute('allow-null', 'yes'); + } + $this->text($directive->type); + $this->endElement(); // type + if ($directive->allowed) { + $this->startElement('allowed'); + foreach ($directive->allowed as $value => $x) { + $this->writeElement('value', $value); + } + $this->endElement(); // allowed + } + $this->writeElement('default', $this->export($directive->default)); + $this->writeAttribute('xml:space', 'preserve'); + if ($directive->external) { + $this->startElement('external'); + foreach ($directive->external as $project) { + $this->writeElement('project', $project); + } + $this->endElement(); + } + $this->endElement(); // constraints + + if ($directive->deprecatedVersion) { + $this->startElement('deprecated'); + $this->writeElement('version', $directive->deprecatedVersion); + $this->writeElement('use', $directive->deprecatedUse->toString()); + $this->endElement(); // deprecated + } + + $this->startElement('description'); + $this->writeHTMLDiv($directive->description); + $this->endElement(); // description + + $this->endElement(); // directive + } +} + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Exception.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Exception.php new file mode 100644 index 0000000..1abdcfc --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Exception.php @@ -0,0 +1,11 @@ + array(directive info) + * @type HTMLPurifier_ConfigSchema_Interchange_Directive[] + */ + public $directives = array(); + + /** + * Adds a directive array to $directives + * @param HTMLPurifier_ConfigSchema_Interchange_Directive $directive + * @throws HTMLPurifier_ConfigSchema_Exception + */ + public function addDirective($directive) + { + if (isset($this->directives[$i = $directive->id->toString()])) { + throw new HTMLPurifier_ConfigSchema_Exception("Cannot redefine directive '$i'"); + } + $this->directives[$i] = $directive; + } + + /** + * Convenience function to perform standard validation. Throws exception + * on failed validation. + */ + public function validate() + { + $validator = new HTMLPurifier_ConfigSchema_Validator(); + return $validator->validate($this); + } +} + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Interchange/Directive.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Interchange/Directive.php new file mode 100644 index 0000000..4c39c5c --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Interchange/Directive.php @@ -0,0 +1,89 @@ + true). + * Null if all values are allowed. + * @type array + */ + public $allowed; + + /** + * List of aliases for the directive. + * e.g. array(new HTMLPurifier_ConfigSchema_Interchange_Id('Ns', 'Dir'))). + * @type HTMLPurifier_ConfigSchema_Interchange_Id[] + */ + public $aliases = array(); + + /** + * Hash of value aliases, e.g. array('alt' => 'real'). Null if value + * aliasing is disabled (necessary for non-scalar types). + * @type array + */ + public $valueAliases; + + /** + * Version of HTML Purifier the directive was introduced, e.g. '1.3.1'. + * Null if the directive has always existed. + * @type string + */ + public $version; + + /** + * ID of directive that supercedes this old directive. + * Null if not deprecated. + * @type HTMLPurifier_ConfigSchema_Interchange_Id + */ + public $deprecatedUse; + + /** + * Version of HTML Purifier this directive was deprecated. Null if not + * deprecated. + * @type string + */ + public $deprecatedVersion; + + /** + * List of external projects this directive depends on, e.g. array('CSSTidy'). + * @type array + */ + public $external = array(); +} + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Interchange/Id.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Interchange/Id.php new file mode 100644 index 0000000..3ee8171 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Interchange/Id.php @@ -0,0 +1,58 @@ +key = $key; + } + + /** + * @return string + * @warning This is NOT magic, to ensure that people don't abuse SPL and + * cause problems for PHP 5.0 support. + */ + public function toString() + { + return $this->key; + } + + /** + * @return string + */ + public function getRootNamespace() + { + return substr($this->key, 0, strpos($this->key, ".")); + } + + /** + * @return string + */ + public function getDirective() + { + return substr($this->key, strpos($this->key, ".") + 1); + } + + /** + * @param string $id + * @return HTMLPurifier_ConfigSchema_Interchange_Id + */ + public static function make($id) + { + return new HTMLPurifier_ConfigSchema_Interchange_Id($id); + } +} + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/InterchangeBuilder.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/InterchangeBuilder.php new file mode 100644 index 0000000..fe9b326 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/InterchangeBuilder.php @@ -0,0 +1,226 @@ +varParser = $varParser ? $varParser : new HTMLPurifier_VarParser_Native(); + } + + /** + * @param string $dir + * @return HTMLPurifier_ConfigSchema_Interchange + */ + public static function buildFromDirectory($dir = null) + { + $builder = new HTMLPurifier_ConfigSchema_InterchangeBuilder(); + $interchange = new HTMLPurifier_ConfigSchema_Interchange(); + return $builder->buildDir($interchange, $dir); + } + + /** + * @param HTMLPurifier_ConfigSchema_Interchange $interchange + * @param string $dir + * @return HTMLPurifier_ConfigSchema_Interchange + */ + public function buildDir($interchange, $dir = null) + { + if (!$dir) { + $dir = HTMLPURIFIER_PREFIX . '/HTMLPurifier/ConfigSchema/schema'; + } + if (file_exists($dir . '/info.ini')) { + $info = parse_ini_file($dir . '/info.ini'); + $interchange->name = $info['name']; + } + + $files = array(); + $dh = opendir($dir); + while (false !== ($file = readdir($dh))) { + if (!$file || $file[0] == '.' || strrchr($file, '.') !== '.txt') { + continue; + } + $files[] = $file; + } + closedir($dh); + + sort($files); + foreach ($files as $file) { + $this->buildFile($interchange, $dir . '/' . $file); + } + return $interchange; + } + + /** + * @param HTMLPurifier_ConfigSchema_Interchange $interchange + * @param string $file + */ + public function buildFile($interchange, $file) + { + $parser = new HTMLPurifier_StringHashParser(); + $this->build( + $interchange, + new HTMLPurifier_StringHash($parser->parseFile($file)) + ); + } + + /** + * Builds an interchange object based on a hash. + * @param HTMLPurifier_ConfigSchema_Interchange $interchange HTMLPurifier_ConfigSchema_Interchange object to build + * @param HTMLPurifier_StringHash $hash source data + * @throws HTMLPurifier_ConfigSchema_Exception + */ + public function build($interchange, $hash) + { + if (!$hash instanceof HTMLPurifier_StringHash) { + $hash = new HTMLPurifier_StringHash($hash); + } + if (!isset($hash['ID'])) { + throw new HTMLPurifier_ConfigSchema_Exception('Hash does not have any ID'); + } + if (strpos($hash['ID'], '.') === false) { + if (count($hash) == 2 && isset($hash['DESCRIPTION'])) { + $hash->offsetGet('DESCRIPTION'); // prevent complaining + } else { + throw new HTMLPurifier_ConfigSchema_Exception('All directives must have a namespace'); + } + } else { + $this->buildDirective($interchange, $hash); + } + $this->_findUnused($hash); + } + + /** + * @param HTMLPurifier_ConfigSchema_Interchange $interchange + * @param HTMLPurifier_StringHash $hash + * @throws HTMLPurifier_ConfigSchema_Exception + */ + public function buildDirective($interchange, $hash) + { + $directive = new HTMLPurifier_ConfigSchema_Interchange_Directive(); + + // These are required elements: + $directive->id = $this->id($hash->offsetGet('ID')); + $id = $directive->id->toString(); // convenience + + if (isset($hash['TYPE'])) { + $type = explode('/', $hash->offsetGet('TYPE')); + if (isset($type[1])) { + $directive->typeAllowsNull = true; + } + $directive->type = $type[0]; + } else { + throw new HTMLPurifier_ConfigSchema_Exception("TYPE in directive hash '$id' not defined"); + } + + if (isset($hash['DEFAULT'])) { + try { + $directive->default = $this->varParser->parse( + $hash->offsetGet('DEFAULT'), + $directive->type, + $directive->typeAllowsNull + ); + } catch (HTMLPurifier_VarParserException $e) { + throw new HTMLPurifier_ConfigSchema_Exception($e->getMessage() . " in DEFAULT in directive hash '$id'"); + } + } + + if (isset($hash['DESCRIPTION'])) { + $directive->description = $hash->offsetGet('DESCRIPTION'); + } + + if (isset($hash['ALLOWED'])) { + $directive->allowed = $this->lookup($this->evalArray($hash->offsetGet('ALLOWED'))); + } + + if (isset($hash['VALUE-ALIASES'])) { + $directive->valueAliases = $this->evalArray($hash->offsetGet('VALUE-ALIASES')); + } + + if (isset($hash['ALIASES'])) { + $raw_aliases = trim($hash->offsetGet('ALIASES')); + $aliases = preg_split('/\s*,\s*/', $raw_aliases); + foreach ($aliases as $alias) { + $directive->aliases[] = $this->id($alias); + } + } + + if (isset($hash['VERSION'])) { + $directive->version = $hash->offsetGet('VERSION'); + } + + if (isset($hash['DEPRECATED-USE'])) { + $directive->deprecatedUse = $this->id($hash->offsetGet('DEPRECATED-USE')); + } + + if (isset($hash['DEPRECATED-VERSION'])) { + $directive->deprecatedVersion = $hash->offsetGet('DEPRECATED-VERSION'); + } + + if (isset($hash['EXTERNAL'])) { + $directive->external = preg_split('/\s*,\s*/', trim($hash->offsetGet('EXTERNAL'))); + } + + $interchange->addDirective($directive); + } + + /** + * Evaluates an array PHP code string without array() wrapper + * @param string $contents + */ + protected function evalArray($contents) + { + return eval('return array(' . $contents . ');'); + } + + /** + * Converts an array list into a lookup array. + * @param array $array + * @return array + */ + protected function lookup($array) + { + $ret = array(); + foreach ($array as $val) { + $ret[$val] = true; + } + return $ret; + } + + /** + * Convenience function that creates an HTMLPurifier_ConfigSchema_Interchange_Id + * object based on a string Id. + * @param string $id + * @return HTMLPurifier_ConfigSchema_Interchange_Id + */ + protected function id($id) + { + return HTMLPurifier_ConfigSchema_Interchange_Id::make($id); + } + + /** + * Triggers errors for any unused keys passed in the hash; such keys + * may indicate typos, missing values, etc. + * @param HTMLPurifier_StringHash $hash Hash to check. + */ + protected function _findUnused($hash) + { + $accessed = $hash->getAccessed(); + foreach ($hash as $k => $v) { + if (!isset($accessed[$k])) { + trigger_error("String hash key '$k' not used by builder", E_USER_NOTICE); + } + } + } +} + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Validator.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Validator.php new file mode 100644 index 0000000..9f14444 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Validator.php @@ -0,0 +1,248 @@ +parser = new HTMLPurifier_VarParser(); + } + + /** + * Validates a fully-formed interchange object. + * @param HTMLPurifier_ConfigSchema_Interchange $interchange + * @return bool + */ + public function validate($interchange) + { + $this->interchange = $interchange; + $this->aliases = array(); + // PHP is a bit lax with integer <=> string conversions in + // arrays, so we don't use the identical !== comparison + foreach ($interchange->directives as $i => $directive) { + $id = $directive->id->toString(); + if ($i != $id) { + $this->error(false, "Integrity violation: key '$i' does not match internal id '$id'"); + } + $this->validateDirective($directive); + } + return true; + } + + /** + * Validates a HTMLPurifier_ConfigSchema_Interchange_Id object. + * @param HTMLPurifier_ConfigSchema_Interchange_Id $id + */ + public function validateId($id) + { + $id_string = $id->toString(); + $this->context[] = "id '$id_string'"; + if (!$id instanceof HTMLPurifier_ConfigSchema_Interchange_Id) { + // handled by InterchangeBuilder + $this->error(false, 'is not an instance of HTMLPurifier_ConfigSchema_Interchange_Id'); + } + // keys are now unconstrained (we might want to narrow down to A-Za-z0-9.) + // we probably should check that it has at least one namespace + $this->with($id, 'key') + ->assertNotEmpty() + ->assertIsString(); // implicit assertIsString handled by InterchangeBuilder + array_pop($this->context); + } + + /** + * Validates a HTMLPurifier_ConfigSchema_Interchange_Directive object. + * @param HTMLPurifier_ConfigSchema_Interchange_Directive $d + */ + public function validateDirective($d) + { + $id = $d->id->toString(); + $this->context[] = "directive '$id'"; + $this->validateId($d->id); + + $this->with($d, 'description') + ->assertNotEmpty(); + + // BEGIN - handled by InterchangeBuilder + $this->with($d, 'type') + ->assertNotEmpty(); + $this->with($d, 'typeAllowsNull') + ->assertIsBool(); + try { + // This also tests validity of $d->type + $this->parser->parse($d->default, $d->type, $d->typeAllowsNull); + } catch (HTMLPurifier_VarParserException $e) { + $this->error('default', 'had error: ' . $e->getMessage()); + } + // END - handled by InterchangeBuilder + + if (!is_null($d->allowed) || !empty($d->valueAliases)) { + // allowed and valueAliases require that we be dealing with + // strings, so check for that early. + $d_int = HTMLPurifier_VarParser::$types[$d->type]; + if (!isset(HTMLPurifier_VarParser::$stringTypes[$d_int])) { + $this->error('type', 'must be a string type when used with allowed or value aliases'); + } + } + + $this->validateDirectiveAllowed($d); + $this->validateDirectiveValueAliases($d); + $this->validateDirectiveAliases($d); + + array_pop($this->context); + } + + /** + * Extra validation if $allowed member variable of + * HTMLPurifier_ConfigSchema_Interchange_Directive is defined. + * @param HTMLPurifier_ConfigSchema_Interchange_Directive $d + */ + public function validateDirectiveAllowed($d) + { + if (is_null($d->allowed)) { + return; + } + $this->with($d, 'allowed') + ->assertNotEmpty() + ->assertIsLookup(); // handled by InterchangeBuilder + if (is_string($d->default) && !isset($d->allowed[$d->default])) { + $this->error('default', 'must be an allowed value'); + } + $this->context[] = 'allowed'; + foreach ($d->allowed as $val => $x) { + if (!is_string($val)) { + $this->error("value $val", 'must be a string'); + } + } + array_pop($this->context); + } + + /** + * Extra validation if $valueAliases member variable of + * HTMLPurifier_ConfigSchema_Interchange_Directive is defined. + * @param HTMLPurifier_ConfigSchema_Interchange_Directive $d + */ + public function validateDirectiveValueAliases($d) + { + if (is_null($d->valueAliases)) { + return; + } + $this->with($d, 'valueAliases') + ->assertIsArray(); // handled by InterchangeBuilder + $this->context[] = 'valueAliases'; + foreach ($d->valueAliases as $alias => $real) { + if (!is_string($alias)) { + $this->error("alias $alias", 'must be a string'); + } + if (!is_string($real)) { + $this->error("alias target $real from alias '$alias'", 'must be a string'); + } + if ($alias === $real) { + $this->error("alias '$alias'", "must not be an alias to itself"); + } + } + if (!is_null($d->allowed)) { + foreach ($d->valueAliases as $alias => $real) { + if (isset($d->allowed[$alias])) { + $this->error("alias '$alias'", 'must not be an allowed value'); + } elseif (!isset($d->allowed[$real])) { + $this->error("alias '$alias'", 'must be an alias to an allowed value'); + } + } + } + array_pop($this->context); + } + + /** + * Extra validation if $aliases member variable of + * HTMLPurifier_ConfigSchema_Interchange_Directive is defined. + * @param HTMLPurifier_ConfigSchema_Interchange_Directive $d + */ + public function validateDirectiveAliases($d) + { + $this->with($d, 'aliases') + ->assertIsArray(); // handled by InterchangeBuilder + $this->context[] = 'aliases'; + foreach ($d->aliases as $alias) { + $this->validateId($alias); + $s = $alias->toString(); + if (isset($this->interchange->directives[$s])) { + $this->error("alias '$s'", 'collides with another directive'); + } + if (isset($this->aliases[$s])) { + $other_directive = $this->aliases[$s]; + $this->error("alias '$s'", "collides with alias for directive '$other_directive'"); + } + $this->aliases[$s] = $d->id->toString(); + } + array_pop($this->context); + } + + // protected helper functions + + /** + * Convenience function for generating HTMLPurifier_ConfigSchema_ValidatorAtom + * for validating simple member variables of objects. + * @param $obj + * @param $member + * @return HTMLPurifier_ConfigSchema_ValidatorAtom + */ + protected function with($obj, $member) + { + return new HTMLPurifier_ConfigSchema_ValidatorAtom($this->getFormattedContext(), $obj, $member); + } + + /** + * Emits an error, providing helpful context. + * @throws HTMLPurifier_ConfigSchema_Exception + */ + protected function error($target, $msg) + { + if ($target !== false) { + $prefix = ucfirst($target) . ' in ' . $this->getFormattedContext(); + } else { + $prefix = ucfirst($this->getFormattedContext()); + } + throw new HTMLPurifier_ConfigSchema_Exception(trim($prefix . ' ' . $msg)); + } + + /** + * Returns a formatted context string. + * @return string + */ + protected function getFormattedContext() + { + return implode(' in ', array_reverse($this->context)); + } +} + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/ValidatorAtom.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/ValidatorAtom.php new file mode 100644 index 0000000..a2e0b4a --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/ValidatorAtom.php @@ -0,0 +1,130 @@ +context = $context; + $this->obj = $obj; + $this->member = $member; + $this->contents =& $obj->$member; + } + + /** + * @return HTMLPurifier_ConfigSchema_ValidatorAtom + */ + public function assertIsString() + { + if (!is_string($this->contents)) { + $this->error('must be a string'); + } + return $this; + } + + /** + * @return HTMLPurifier_ConfigSchema_ValidatorAtom + */ + public function assertIsBool() + { + if (!is_bool($this->contents)) { + $this->error('must be a boolean'); + } + return $this; + } + + /** + * @return HTMLPurifier_ConfigSchema_ValidatorAtom + */ + public function assertIsArray() + { + if (!is_array($this->contents)) { + $this->error('must be an array'); + } + return $this; + } + + /** + * @return HTMLPurifier_ConfigSchema_ValidatorAtom + */ + public function assertNotNull() + { + if ($this->contents === null) { + $this->error('must not be null'); + } + return $this; + } + + /** + * @return HTMLPurifier_ConfigSchema_ValidatorAtom + */ + public function assertAlnum() + { + $this->assertIsString(); + if (!ctype_alnum($this->contents)) { + $this->error('must be alphanumeric'); + } + return $this; + } + + /** + * @return HTMLPurifier_ConfigSchema_ValidatorAtom + */ + public function assertNotEmpty() + { + if (empty($this->contents)) { + $this->error('must not be empty'); + } + return $this; + } + + /** + * @return HTMLPurifier_ConfigSchema_ValidatorAtom + */ + public function assertIsLookup() + { + $this->assertIsArray(); + foreach ($this->contents as $v) { + if ($v !== true) { + $this->error('must be a lookup array'); + } + } + return $this; + } + + /** + * @param string $msg + * @throws HTMLPurifier_ConfigSchema_Exception + */ + protected function error($msg) + { + throw new HTMLPurifier_ConfigSchema_Exception(ucfirst($this->member) . ' in ' . $this->context . ' ' . $msg); + } +} + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema.ser b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema.ser new file mode 100644 index 0000000..47bd259 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema.ser @@ -0,0 +1 @@ +O:25:"HTMLPurifier_ConfigSchema":3:{s:8:"defaults";a:126:{s:19:"Attr.AllowedClasses";N;s:24:"Attr.AllowedFrameTargets";a:0:{}s:15:"Attr.AllowedRel";a:0:{}s:15:"Attr.AllowedRev";a:0:{}s:18:"Attr.ClassUseCDATA";N;s:20:"Attr.DefaultImageAlt";N;s:24:"Attr.DefaultInvalidImage";s:0:"";s:27:"Attr.DefaultInvalidImageAlt";s:13:"Invalid image";s:19:"Attr.DefaultTextDir";s:3:"ltr";s:13:"Attr.EnableID";b:0;s:21:"Attr.ForbiddenClasses";a:0:{}s:13:"Attr.ID.HTML5";N;s:16:"Attr.IDBlacklist";a:0:{}s:22:"Attr.IDBlacklistRegexp";N;s:13:"Attr.IDPrefix";s:0:"";s:18:"Attr.IDPrefixLocal";s:0:"";s:24:"AutoFormat.AutoParagraph";b:0;s:17:"AutoFormat.Custom";a:0:{}s:25:"AutoFormat.DisplayLinkURI";b:0;s:18:"AutoFormat.Linkify";b:0;s:33:"AutoFormat.PurifierLinkify.DocURL";s:3:"#%s";s:26:"AutoFormat.PurifierLinkify";b:0;s:32:"AutoFormat.RemoveEmpty.Predicate";a:4:{s:8:"colgroup";a:0:{}s:2:"th";a:0:{}s:2:"td";a:0:{}s:6:"iframe";a:1:{i:0;s:3:"src";}}s:44:"AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions";a:2:{s:2:"td";b:1;s:2:"th";b:1;}s:33:"AutoFormat.RemoveEmpty.RemoveNbsp";b:0;s:22:"AutoFormat.RemoveEmpty";b:0;s:39:"AutoFormat.RemoveSpansWithoutAttributes";b:0;s:19:"CSS.AllowDuplicates";b:0;s:18:"CSS.AllowImportant";b:0;s:15:"CSS.AllowTricky";b:0;s:16:"CSS.AllowedFonts";N;s:21:"CSS.AllowedProperties";N;s:17:"CSS.DefinitionRev";i:1;s:23:"CSS.ForbiddenProperties";a:0:{}s:16:"CSS.MaxImgLength";s:6:"1200px";s:15:"CSS.Proprietary";b:0;s:11:"CSS.Trusted";b:0;s:20:"Cache.DefinitionImpl";s:10:"Serializer";s:20:"Cache.SerializerPath";N;s:27:"Cache.SerializerPermissions";i:493;s:22:"Core.AggressivelyFixLt";b:1;s:29:"Core.AggressivelyRemoveScript";b:1;s:28:"Core.AllowHostnameUnderscore";b:0;s:23:"Core.AllowParseManyTags";b:0;s:18:"Core.CollectErrors";b:0;s:18:"Core.ColorKeywords";a:148:{s:9:"aliceblue";s:7:"#F0F8FF";s:12:"antiquewhite";s:7:"#FAEBD7";s:4:"aqua";s:7:"#00FFFF";s:10:"aquamarine";s:7:"#7FFFD4";s:5:"azure";s:7:"#F0FFFF";s:5:"beige";s:7:"#F5F5DC";s:6:"bisque";s:7:"#FFE4C4";s:5:"black";s:7:"#000000";s:14:"blanchedalmond";s:7:"#FFEBCD";s:4:"blue";s:7:"#0000FF";s:10:"blueviolet";s:7:"#8A2BE2";s:5:"brown";s:7:"#A52A2A";s:9:"burlywood";s:7:"#DEB887";s:9:"cadetblue";s:7:"#5F9EA0";s:10:"chartreuse";s:7:"#7FFF00";s:9:"chocolate";s:7:"#D2691E";s:5:"coral";s:7:"#FF7F50";s:14:"cornflowerblue";s:7:"#6495ED";s:8:"cornsilk";s:7:"#FFF8DC";s:7:"crimson";s:7:"#DC143C";s:4:"cyan";s:7:"#00FFFF";s:8:"darkblue";s:7:"#00008B";s:8:"darkcyan";s:7:"#008B8B";s:13:"darkgoldenrod";s:7:"#B8860B";s:8:"darkgray";s:7:"#A9A9A9";s:8:"darkgrey";s:7:"#A9A9A9";s:9:"darkgreen";s:7:"#006400";s:9:"darkkhaki";s:7:"#BDB76B";s:11:"darkmagenta";s:7:"#8B008B";s:14:"darkolivegreen";s:7:"#556B2F";s:10:"darkorange";s:7:"#FF8C00";s:10:"darkorchid";s:7:"#9932CC";s:7:"darkred";s:7:"#8B0000";s:10:"darksalmon";s:7:"#E9967A";s:12:"darkseagreen";s:7:"#8FBC8F";s:13:"darkslateblue";s:7:"#483D8B";s:13:"darkslategray";s:7:"#2F4F4F";s:13:"darkslategrey";s:7:"#2F4F4F";s:13:"darkturquoise";s:7:"#00CED1";s:10:"darkviolet";s:7:"#9400D3";s:8:"deeppink";s:7:"#FF1493";s:11:"deepskyblue";s:7:"#00BFFF";s:7:"dimgray";s:7:"#696969";s:7:"dimgrey";s:7:"#696969";s:10:"dodgerblue";s:7:"#1E90FF";s:9:"firebrick";s:7:"#B22222";s:11:"floralwhite";s:7:"#FFFAF0";s:11:"forestgreen";s:7:"#228B22";s:7:"fuchsia";s:7:"#FF00FF";s:9:"gainsboro";s:7:"#DCDCDC";s:10:"ghostwhite";s:7:"#F8F8FF";s:4:"gold";s:7:"#FFD700";s:9:"goldenrod";s:7:"#DAA520";s:4:"gray";s:7:"#808080";s:4:"grey";s:7:"#808080";s:5:"green";s:7:"#008000";s:11:"greenyellow";s:7:"#ADFF2F";s:8:"honeydew";s:7:"#F0FFF0";s:7:"hotpink";s:7:"#FF69B4";s:9:"indianred";s:7:"#CD5C5C";s:6:"indigo";s:7:"#4B0082";s:5:"ivory";s:7:"#FFFFF0";s:5:"khaki";s:7:"#F0E68C";s:8:"lavender";s:7:"#E6E6FA";s:13:"lavenderblush";s:7:"#FFF0F5";s:9:"lawngreen";s:7:"#7CFC00";s:12:"lemonchiffon";s:7:"#FFFACD";s:9:"lightblue";s:7:"#ADD8E6";s:10:"lightcoral";s:7:"#F08080";s:9:"lightcyan";s:7:"#E0FFFF";s:20:"lightgoldenrodyellow";s:7:"#FAFAD2";s:9:"lightgray";s:7:"#D3D3D3";s:9:"lightgrey";s:7:"#D3D3D3";s:10:"lightgreen";s:7:"#90EE90";s:9:"lightpink";s:7:"#FFB6C1";s:11:"lightsalmon";s:7:"#FFA07A";s:13:"lightseagreen";s:7:"#20B2AA";s:12:"lightskyblue";s:7:"#87CEFA";s:14:"lightslategray";s:7:"#778899";s:14:"lightslategrey";s:7:"#778899";s:14:"lightsteelblue";s:7:"#B0C4DE";s:11:"lightyellow";s:7:"#FFFFE0";s:4:"lime";s:7:"#00FF00";s:9:"limegreen";s:7:"#32CD32";s:5:"linen";s:7:"#FAF0E6";s:7:"magenta";s:7:"#FF00FF";s:6:"maroon";s:7:"#800000";s:16:"mediumaquamarine";s:7:"#66CDAA";s:10:"mediumblue";s:7:"#0000CD";s:12:"mediumorchid";s:7:"#BA55D3";s:12:"mediumpurple";s:7:"#9370DB";s:14:"mediumseagreen";s:7:"#3CB371";s:15:"mediumslateblue";s:7:"#7B68EE";s:17:"mediumspringgreen";s:7:"#00FA9A";s:15:"mediumturquoise";s:7:"#48D1CC";s:15:"mediumvioletred";s:7:"#C71585";s:12:"midnightblue";s:7:"#191970";s:9:"mintcream";s:7:"#F5FFFA";s:9:"mistyrose";s:7:"#FFE4E1";s:8:"moccasin";s:7:"#FFE4B5";s:11:"navajowhite";s:7:"#FFDEAD";s:4:"navy";s:7:"#000080";s:7:"oldlace";s:7:"#FDF5E6";s:5:"olive";s:7:"#808000";s:9:"olivedrab";s:7:"#6B8E23";s:6:"orange";s:7:"#FFA500";s:9:"orangered";s:7:"#FF4500";s:6:"orchid";s:7:"#DA70D6";s:13:"palegoldenrod";s:7:"#EEE8AA";s:9:"palegreen";s:7:"#98FB98";s:13:"paleturquoise";s:7:"#AFEEEE";s:13:"palevioletred";s:7:"#DB7093";s:10:"papayawhip";s:7:"#FFEFD5";s:9:"peachpuff";s:7:"#FFDAB9";s:4:"peru";s:7:"#CD853F";s:4:"pink";s:7:"#FFC0CB";s:4:"plum";s:7:"#DDA0DD";s:10:"powderblue";s:7:"#B0E0E6";s:6:"purple";s:7:"#800080";s:13:"rebeccapurple";s:7:"#663399";s:3:"red";s:7:"#FF0000";s:9:"rosybrown";s:7:"#BC8F8F";s:9:"royalblue";s:7:"#4169E1";s:11:"saddlebrown";s:7:"#8B4513";s:6:"salmon";s:7:"#FA8072";s:10:"sandybrown";s:7:"#F4A460";s:8:"seagreen";s:7:"#2E8B57";s:8:"seashell";s:7:"#FFF5EE";s:6:"sienna";s:7:"#A0522D";s:6:"silver";s:7:"#C0C0C0";s:7:"skyblue";s:7:"#87CEEB";s:9:"slateblue";s:7:"#6A5ACD";s:9:"slategray";s:7:"#708090";s:9:"slategrey";s:7:"#708090";s:4:"snow";s:7:"#FFFAFA";s:11:"springgreen";s:7:"#00FF7F";s:9:"steelblue";s:7:"#4682B4";s:3:"tan";s:7:"#D2B48C";s:4:"teal";s:7:"#008080";s:7:"thistle";s:7:"#D8BFD8";s:6:"tomato";s:7:"#FF6347";s:9:"turquoise";s:7:"#40E0D0";s:6:"violet";s:7:"#EE82EE";s:5:"wheat";s:7:"#F5DEB3";s:5:"white";s:7:"#FFFFFF";s:10:"whitesmoke";s:7:"#F5F5F5";s:6:"yellow";s:7:"#FFFF00";s:11:"yellowgreen";s:7:"#9ACD32";}s:30:"Core.ConvertDocumentToFragment";b:1;s:36:"Core.DirectLexLineNumberSyncInterval";i:0;s:20:"Core.DisableExcludes";b:0;s:15:"Core.EnableIDNA";b:0;s:13:"Core.Encoding";s:5:"utf-8";s:26:"Core.EscapeInvalidChildren";b:0;s:22:"Core.EscapeInvalidTags";b:0;s:29:"Core.EscapeNonASCIICharacters";b:0;s:19:"Core.HiddenElements";a:2:{s:6:"script";b:1;s:5:"style";b:1;}s:13:"Core.Language";s:2:"en";s:24:"Core.LegacyEntityDecoder";b:0;s:14:"Core.LexerImpl";N;s:24:"Core.MaintainLineNumbers";N;s:22:"Core.NormalizeNewlines";b:1;s:21:"Core.RemoveInvalidImg";b:1;s:33:"Core.RemoveProcessingInstructions";b:0;s:25:"Core.RemoveScriptContents";N;s:13:"Filter.Custom";a:0:{}s:34:"Filter.ExtractStyleBlocks.Escaping";b:1;s:31:"Filter.ExtractStyleBlocks.Scope";N;s:34:"Filter.ExtractStyleBlocks.TidyImpl";N;s:25:"Filter.ExtractStyleBlocks";b:0;s:14:"Filter.YouTube";b:0;s:12:"HTML.Allowed";N;s:22:"HTML.AllowedAttributes";N;s:20:"HTML.AllowedComments";a:0:{}s:26:"HTML.AllowedCommentsRegexp";N;s:20:"HTML.AllowedElements";N;s:19:"HTML.AllowedModules";N;s:23:"HTML.Attr.Name.UseCDATA";b:0;s:17:"HTML.BlockWrapper";s:1:"p";s:16:"HTML.CoreModules";a:7:{s:9:"Structure";b:1;s:4:"Text";b:1;s:9:"Hypertext";b:1;s:4:"List";b:1;s:22:"NonXMLCommonAttributes";b:1;s:19:"XMLCommonAttributes";b:1;s:16:"CommonAttributes";b:1;}s:18:"HTML.CustomDoctype";N;s:17:"HTML.DefinitionID";N;s:18:"HTML.DefinitionRev";i:1;s:12:"HTML.Doctype";N;s:25:"HTML.FlashAllowFullScreen";b:0;s:24:"HTML.ForbiddenAttributes";a:0:{}s:22:"HTML.ForbiddenElements";a:0:{}s:17:"HTML.MaxImgLength";i:1200;s:13:"HTML.Nofollow";b:0;s:11:"HTML.Parent";s:3:"div";s:16:"HTML.Proprietary";b:0;s:14:"HTML.SafeEmbed";b:0;s:15:"HTML.SafeIframe";b:0;s:15:"HTML.SafeObject";b:0;s:18:"HTML.SafeScripting";a:0:{}s:11:"HTML.Strict";b:0;s:16:"HTML.TargetBlank";b:0;s:19:"HTML.TargetNoopener";b:1;s:21:"HTML.TargetNoreferrer";b:1;s:12:"HTML.TidyAdd";a:0:{}s:14:"HTML.TidyLevel";s:6:"medium";s:15:"HTML.TidyRemove";a:0:{}s:12:"HTML.Trusted";b:0;s:10:"HTML.XHTML";b:1;s:28:"Output.CommentScriptContents";b:1;s:19:"Output.FixInnerHTML";b:1;s:18:"Output.FlashCompat";b:0;s:14:"Output.Newline";N;s:15:"Output.SortAttr";b:0;s:17:"Output.TidyFormat";b:0;s:17:"Test.ForceNoIconv";b:0;s:18:"URI.AllowedSchemes";a:7:{s:4:"http";b:1;s:5:"https";b:1;s:6:"mailto";b:1;s:3:"ftp";b:1;s:4:"nntp";b:1;s:4:"news";b:1;s:3:"tel";b:1;}s:8:"URI.Base";N;s:17:"URI.DefaultScheme";s:4:"http";s:16:"URI.DefinitionID";N;s:17:"URI.DefinitionRev";i:1;s:11:"URI.Disable";b:0;s:19:"URI.DisableExternal";b:0;s:28:"URI.DisableExternalResources";b:0;s:20:"URI.DisableResources";b:0;s:8:"URI.Host";N;s:17:"URI.HostBlacklist";a:0:{}s:16:"URI.MakeAbsolute";b:0;s:9:"URI.Munge";N;s:18:"URI.MungeResources";b:0;s:18:"URI.MungeSecretKey";N;s:26:"URI.OverrideAllowedSchemes";b:1;s:20:"URI.SafeIframeRegexp";N;}s:12:"defaultPlist";O:25:"HTMLPurifier_PropertyList":3:{s:7:"*data";a:126:{s:19:"Attr.AllowedClasses";N;s:24:"Attr.AllowedFrameTargets";a:0:{}s:15:"Attr.AllowedRel";a:0:{}s:15:"Attr.AllowedRev";a:0:{}s:18:"Attr.ClassUseCDATA";N;s:20:"Attr.DefaultImageAlt";N;s:24:"Attr.DefaultInvalidImage";s:0:"";s:27:"Attr.DefaultInvalidImageAlt";s:13:"Invalid image";s:19:"Attr.DefaultTextDir";s:3:"ltr";s:13:"Attr.EnableID";b:0;s:21:"Attr.ForbiddenClasses";a:0:{}s:13:"Attr.ID.HTML5";N;s:16:"Attr.IDBlacklist";a:0:{}s:22:"Attr.IDBlacklistRegexp";N;s:13:"Attr.IDPrefix";s:0:"";s:18:"Attr.IDPrefixLocal";s:0:"";s:24:"AutoFormat.AutoParagraph";b:0;s:17:"AutoFormat.Custom";a:0:{}s:25:"AutoFormat.DisplayLinkURI";b:0;s:18:"AutoFormat.Linkify";b:0;s:33:"AutoFormat.PurifierLinkify.DocURL";s:3:"#%s";s:26:"AutoFormat.PurifierLinkify";b:0;s:32:"AutoFormat.RemoveEmpty.Predicate";a:4:{s:8:"colgroup";a:0:{}s:2:"th";a:0:{}s:2:"td";a:0:{}s:6:"iframe";a:1:{i:0;s:3:"src";}}s:44:"AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions";a:2:{s:2:"td";b:1;s:2:"th";b:1;}s:33:"AutoFormat.RemoveEmpty.RemoveNbsp";b:0;s:22:"AutoFormat.RemoveEmpty";b:0;s:39:"AutoFormat.RemoveSpansWithoutAttributes";b:0;s:19:"CSS.AllowDuplicates";b:0;s:18:"CSS.AllowImportant";b:0;s:15:"CSS.AllowTricky";b:0;s:16:"CSS.AllowedFonts";N;s:21:"CSS.AllowedProperties";N;s:17:"CSS.DefinitionRev";i:1;s:23:"CSS.ForbiddenProperties";a:0:{}s:16:"CSS.MaxImgLength";s:6:"1200px";s:15:"CSS.Proprietary";b:0;s:11:"CSS.Trusted";b:0;s:20:"Cache.DefinitionImpl";s:10:"Serializer";s:20:"Cache.SerializerPath";N;s:27:"Cache.SerializerPermissions";i:493;s:22:"Core.AggressivelyFixLt";b:1;s:29:"Core.AggressivelyRemoveScript";b:1;s:28:"Core.AllowHostnameUnderscore";b:0;s:23:"Core.AllowParseManyTags";b:0;s:18:"Core.CollectErrors";b:0;s:18:"Core.ColorKeywords";a:148:{s:9:"aliceblue";s:7:"#F0F8FF";s:12:"antiquewhite";s:7:"#FAEBD7";s:4:"aqua";s:7:"#00FFFF";s:10:"aquamarine";s:7:"#7FFFD4";s:5:"azure";s:7:"#F0FFFF";s:5:"beige";s:7:"#F5F5DC";s:6:"bisque";s:7:"#FFE4C4";s:5:"black";s:7:"#000000";s:14:"blanchedalmond";s:7:"#FFEBCD";s:4:"blue";s:7:"#0000FF";s:10:"blueviolet";s:7:"#8A2BE2";s:5:"brown";s:7:"#A52A2A";s:9:"burlywood";s:7:"#DEB887";s:9:"cadetblue";s:7:"#5F9EA0";s:10:"chartreuse";s:7:"#7FFF00";s:9:"chocolate";s:7:"#D2691E";s:5:"coral";s:7:"#FF7F50";s:14:"cornflowerblue";s:7:"#6495ED";s:8:"cornsilk";s:7:"#FFF8DC";s:7:"crimson";s:7:"#DC143C";s:4:"cyan";s:7:"#00FFFF";s:8:"darkblue";s:7:"#00008B";s:8:"darkcyan";s:7:"#008B8B";s:13:"darkgoldenrod";s:7:"#B8860B";s:8:"darkgray";s:7:"#A9A9A9";s:8:"darkgrey";s:7:"#A9A9A9";s:9:"darkgreen";s:7:"#006400";s:9:"darkkhaki";s:7:"#BDB76B";s:11:"darkmagenta";s:7:"#8B008B";s:14:"darkolivegreen";s:7:"#556B2F";s:10:"darkorange";s:7:"#FF8C00";s:10:"darkorchid";s:7:"#9932CC";s:7:"darkred";s:7:"#8B0000";s:10:"darksalmon";s:7:"#E9967A";s:12:"darkseagreen";s:7:"#8FBC8F";s:13:"darkslateblue";s:7:"#483D8B";s:13:"darkslategray";s:7:"#2F4F4F";s:13:"darkslategrey";s:7:"#2F4F4F";s:13:"darkturquoise";s:7:"#00CED1";s:10:"darkviolet";s:7:"#9400D3";s:8:"deeppink";s:7:"#FF1493";s:11:"deepskyblue";s:7:"#00BFFF";s:7:"dimgray";s:7:"#696969";s:7:"dimgrey";s:7:"#696969";s:10:"dodgerblue";s:7:"#1E90FF";s:9:"firebrick";s:7:"#B22222";s:11:"floralwhite";s:7:"#FFFAF0";s:11:"forestgreen";s:7:"#228B22";s:7:"fuchsia";s:7:"#FF00FF";s:9:"gainsboro";s:7:"#DCDCDC";s:10:"ghostwhite";s:7:"#F8F8FF";s:4:"gold";s:7:"#FFD700";s:9:"goldenrod";s:7:"#DAA520";s:4:"gray";s:7:"#808080";s:4:"grey";s:7:"#808080";s:5:"green";s:7:"#008000";s:11:"greenyellow";s:7:"#ADFF2F";s:8:"honeydew";s:7:"#F0FFF0";s:7:"hotpink";s:7:"#FF69B4";s:9:"indianred";s:7:"#CD5C5C";s:6:"indigo";s:7:"#4B0082";s:5:"ivory";s:7:"#FFFFF0";s:5:"khaki";s:7:"#F0E68C";s:8:"lavender";s:7:"#E6E6FA";s:13:"lavenderblush";s:7:"#FFF0F5";s:9:"lawngreen";s:7:"#7CFC00";s:12:"lemonchiffon";s:7:"#FFFACD";s:9:"lightblue";s:7:"#ADD8E6";s:10:"lightcoral";s:7:"#F08080";s:9:"lightcyan";s:7:"#E0FFFF";s:20:"lightgoldenrodyellow";s:7:"#FAFAD2";s:9:"lightgray";s:7:"#D3D3D3";s:9:"lightgrey";s:7:"#D3D3D3";s:10:"lightgreen";s:7:"#90EE90";s:9:"lightpink";s:7:"#FFB6C1";s:11:"lightsalmon";s:7:"#FFA07A";s:13:"lightseagreen";s:7:"#20B2AA";s:12:"lightskyblue";s:7:"#87CEFA";s:14:"lightslategray";s:7:"#778899";s:14:"lightslategrey";s:7:"#778899";s:14:"lightsteelblue";s:7:"#B0C4DE";s:11:"lightyellow";s:7:"#FFFFE0";s:4:"lime";s:7:"#00FF00";s:9:"limegreen";s:7:"#32CD32";s:5:"linen";s:7:"#FAF0E6";s:7:"magenta";s:7:"#FF00FF";s:6:"maroon";s:7:"#800000";s:16:"mediumaquamarine";s:7:"#66CDAA";s:10:"mediumblue";s:7:"#0000CD";s:12:"mediumorchid";s:7:"#BA55D3";s:12:"mediumpurple";s:7:"#9370DB";s:14:"mediumseagreen";s:7:"#3CB371";s:15:"mediumslateblue";s:7:"#7B68EE";s:17:"mediumspringgreen";s:7:"#00FA9A";s:15:"mediumturquoise";s:7:"#48D1CC";s:15:"mediumvioletred";s:7:"#C71585";s:12:"midnightblue";s:7:"#191970";s:9:"mintcream";s:7:"#F5FFFA";s:9:"mistyrose";s:7:"#FFE4E1";s:8:"moccasin";s:7:"#FFE4B5";s:11:"navajowhite";s:7:"#FFDEAD";s:4:"navy";s:7:"#000080";s:7:"oldlace";s:7:"#FDF5E6";s:5:"olive";s:7:"#808000";s:9:"olivedrab";s:7:"#6B8E23";s:6:"orange";s:7:"#FFA500";s:9:"orangered";s:7:"#FF4500";s:6:"orchid";s:7:"#DA70D6";s:13:"palegoldenrod";s:7:"#EEE8AA";s:9:"palegreen";s:7:"#98FB98";s:13:"paleturquoise";s:7:"#AFEEEE";s:13:"palevioletred";s:7:"#DB7093";s:10:"papayawhip";s:7:"#FFEFD5";s:9:"peachpuff";s:7:"#FFDAB9";s:4:"peru";s:7:"#CD853F";s:4:"pink";s:7:"#FFC0CB";s:4:"plum";s:7:"#DDA0DD";s:10:"powderblue";s:7:"#B0E0E6";s:6:"purple";s:7:"#800080";s:13:"rebeccapurple";s:7:"#663399";s:3:"red";s:7:"#FF0000";s:9:"rosybrown";s:7:"#BC8F8F";s:9:"royalblue";s:7:"#4169E1";s:11:"saddlebrown";s:7:"#8B4513";s:6:"salmon";s:7:"#FA8072";s:10:"sandybrown";s:7:"#F4A460";s:8:"seagreen";s:7:"#2E8B57";s:8:"seashell";s:7:"#FFF5EE";s:6:"sienna";s:7:"#A0522D";s:6:"silver";s:7:"#C0C0C0";s:7:"skyblue";s:7:"#87CEEB";s:9:"slateblue";s:7:"#6A5ACD";s:9:"slategray";s:7:"#708090";s:9:"slategrey";s:7:"#708090";s:4:"snow";s:7:"#FFFAFA";s:11:"springgreen";s:7:"#00FF7F";s:9:"steelblue";s:7:"#4682B4";s:3:"tan";s:7:"#D2B48C";s:4:"teal";s:7:"#008080";s:7:"thistle";s:7:"#D8BFD8";s:6:"tomato";s:7:"#FF6347";s:9:"turquoise";s:7:"#40E0D0";s:6:"violet";s:7:"#EE82EE";s:5:"wheat";s:7:"#F5DEB3";s:5:"white";s:7:"#FFFFFF";s:10:"whitesmoke";s:7:"#F5F5F5";s:6:"yellow";s:7:"#FFFF00";s:11:"yellowgreen";s:7:"#9ACD32";}s:30:"Core.ConvertDocumentToFragment";b:1;s:36:"Core.DirectLexLineNumberSyncInterval";i:0;s:20:"Core.DisableExcludes";b:0;s:15:"Core.EnableIDNA";b:0;s:13:"Core.Encoding";s:5:"utf-8";s:26:"Core.EscapeInvalidChildren";b:0;s:22:"Core.EscapeInvalidTags";b:0;s:29:"Core.EscapeNonASCIICharacters";b:0;s:19:"Core.HiddenElements";a:2:{s:6:"script";b:1;s:5:"style";b:1;}s:13:"Core.Language";s:2:"en";s:24:"Core.LegacyEntityDecoder";b:0;s:14:"Core.LexerImpl";N;s:24:"Core.MaintainLineNumbers";N;s:22:"Core.NormalizeNewlines";b:1;s:21:"Core.RemoveInvalidImg";b:1;s:33:"Core.RemoveProcessingInstructions";b:0;s:25:"Core.RemoveScriptContents";N;s:13:"Filter.Custom";a:0:{}s:34:"Filter.ExtractStyleBlocks.Escaping";b:1;s:31:"Filter.ExtractStyleBlocks.Scope";N;s:34:"Filter.ExtractStyleBlocks.TidyImpl";N;s:25:"Filter.ExtractStyleBlocks";b:0;s:14:"Filter.YouTube";b:0;s:12:"HTML.Allowed";N;s:22:"HTML.AllowedAttributes";N;s:20:"HTML.AllowedComments";a:0:{}s:26:"HTML.AllowedCommentsRegexp";N;s:20:"HTML.AllowedElements";N;s:19:"HTML.AllowedModules";N;s:23:"HTML.Attr.Name.UseCDATA";b:0;s:17:"HTML.BlockWrapper";s:1:"p";s:16:"HTML.CoreModules";a:7:{s:9:"Structure";b:1;s:4:"Text";b:1;s:9:"Hypertext";b:1;s:4:"List";b:1;s:22:"NonXMLCommonAttributes";b:1;s:19:"XMLCommonAttributes";b:1;s:16:"CommonAttributes";b:1;}s:18:"HTML.CustomDoctype";N;s:17:"HTML.DefinitionID";N;s:18:"HTML.DefinitionRev";i:1;s:12:"HTML.Doctype";N;s:25:"HTML.FlashAllowFullScreen";b:0;s:24:"HTML.ForbiddenAttributes";a:0:{}s:22:"HTML.ForbiddenElements";a:0:{}s:17:"HTML.MaxImgLength";i:1200;s:13:"HTML.Nofollow";b:0;s:11:"HTML.Parent";s:3:"div";s:16:"HTML.Proprietary";b:0;s:14:"HTML.SafeEmbed";b:0;s:15:"HTML.SafeIframe";b:0;s:15:"HTML.SafeObject";b:0;s:18:"HTML.SafeScripting";a:0:{}s:11:"HTML.Strict";b:0;s:16:"HTML.TargetBlank";b:0;s:19:"HTML.TargetNoopener";b:1;s:21:"HTML.TargetNoreferrer";b:1;s:12:"HTML.TidyAdd";a:0:{}s:14:"HTML.TidyLevel";s:6:"medium";s:15:"HTML.TidyRemove";a:0:{}s:12:"HTML.Trusted";b:0;s:10:"HTML.XHTML";b:1;s:28:"Output.CommentScriptContents";b:1;s:19:"Output.FixInnerHTML";b:1;s:18:"Output.FlashCompat";b:0;s:14:"Output.Newline";N;s:15:"Output.SortAttr";b:0;s:17:"Output.TidyFormat";b:0;s:17:"Test.ForceNoIconv";b:0;s:18:"URI.AllowedSchemes";a:7:{s:4:"http";b:1;s:5:"https";b:1;s:6:"mailto";b:1;s:3:"ftp";b:1;s:4:"nntp";b:1;s:4:"news";b:1;s:3:"tel";b:1;}s:8:"URI.Base";N;s:17:"URI.DefaultScheme";s:4:"http";s:16:"URI.DefinitionID";N;s:17:"URI.DefinitionRev";i:1;s:11:"URI.Disable";b:0;s:19:"URI.DisableExternal";b:0;s:28:"URI.DisableExternalResources";b:0;s:20:"URI.DisableResources";b:0;s:8:"URI.Host";N;s:17:"URI.HostBlacklist";a:0:{}s:16:"URI.MakeAbsolute";b:0;s:9:"URI.Munge";N;s:18:"URI.MungeResources";b:0;s:18:"URI.MungeSecretKey";N;s:26:"URI.OverrideAllowedSchemes";b:1;s:20:"URI.SafeIframeRegexp";N;}s:9:"*parent";N;s:8:"*cache";N;}s:4:"info";a:139:{s:19:"Attr.AllowedClasses";i:-8;s:24:"Attr.AllowedFrameTargets";i:8;s:15:"Attr.AllowedRel";i:8;s:15:"Attr.AllowedRev";i:8;s:18:"Attr.ClassUseCDATA";i:-7;s:20:"Attr.DefaultImageAlt";i:-1;s:24:"Attr.DefaultInvalidImage";i:1;s:27:"Attr.DefaultInvalidImageAlt";i:1;s:19:"Attr.DefaultTextDir";O:8:"stdClass":2:{s:4:"type";i:1;s:7:"allowed";a:2:{s:3:"ltr";b:1;s:3:"rtl";b:1;}}s:13:"Attr.EnableID";i:7;s:17:"HTML.EnableAttrID";O:8:"stdClass":2:{s:3:"key";s:13:"Attr.EnableID";s:7:"isAlias";b:1;}s:21:"Attr.ForbiddenClasses";i:8;s:13:"Attr.ID.HTML5";i:-7;s:16:"Attr.IDBlacklist";i:9;s:22:"Attr.IDBlacklistRegexp";i:-1;s:13:"Attr.IDPrefix";i:1;s:18:"Attr.IDPrefixLocal";i:1;s:24:"AutoFormat.AutoParagraph";i:7;s:17:"AutoFormat.Custom";i:9;s:25:"AutoFormat.DisplayLinkURI";i:7;s:18:"AutoFormat.Linkify";i:7;s:33:"AutoFormat.PurifierLinkify.DocURL";i:1;s:37:"AutoFormatParam.PurifierLinkifyDocURL";O:8:"stdClass":2:{s:3:"key";s:33:"AutoFormat.PurifierLinkify.DocURL";s:7:"isAlias";b:1;}s:26:"AutoFormat.PurifierLinkify";i:7;s:32:"AutoFormat.RemoveEmpty.Predicate";i:10;s:44:"AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions";i:8;s:33:"AutoFormat.RemoveEmpty.RemoveNbsp";i:7;s:22:"AutoFormat.RemoveEmpty";i:7;s:39:"AutoFormat.RemoveSpansWithoutAttributes";i:7;s:19:"CSS.AllowDuplicates";i:7;s:18:"CSS.AllowImportant";i:7;s:15:"CSS.AllowTricky";i:7;s:16:"CSS.AllowedFonts";i:-8;s:21:"CSS.AllowedProperties";i:-8;s:17:"CSS.DefinitionRev";i:5;s:23:"CSS.ForbiddenProperties";i:8;s:16:"CSS.MaxImgLength";i:-1;s:15:"CSS.Proprietary";i:7;s:11:"CSS.Trusted";i:7;s:20:"Cache.DefinitionImpl";i:-1;s:20:"Core.DefinitionCache";O:8:"stdClass":2:{s:3:"key";s:20:"Cache.DefinitionImpl";s:7:"isAlias";b:1;}s:20:"Cache.SerializerPath";i:-1;s:27:"Cache.SerializerPermissions";i:-5;s:22:"Core.AggressivelyFixLt";i:7;s:29:"Core.AggressivelyRemoveScript";i:7;s:28:"Core.AllowHostnameUnderscore";i:7;s:23:"Core.AllowParseManyTags";i:7;s:18:"Core.CollectErrors";i:7;s:18:"Core.ColorKeywords";i:10;s:30:"Core.ConvertDocumentToFragment";i:7;s:24:"Core.AcceptFullDocuments";O:8:"stdClass":2:{s:3:"key";s:30:"Core.ConvertDocumentToFragment";s:7:"isAlias";b:1;}s:36:"Core.DirectLexLineNumberSyncInterval";i:5;s:20:"Core.DisableExcludes";i:7;s:15:"Core.EnableIDNA";i:7;s:13:"Core.Encoding";i:2;s:26:"Core.EscapeInvalidChildren";i:7;s:22:"Core.EscapeInvalidTags";i:7;s:29:"Core.EscapeNonASCIICharacters";i:7;s:19:"Core.HiddenElements";i:8;s:13:"Core.Language";i:1;s:24:"Core.LegacyEntityDecoder";i:7;s:14:"Core.LexerImpl";i:-11;s:24:"Core.MaintainLineNumbers";i:-7;s:22:"Core.NormalizeNewlines";i:7;s:21:"Core.RemoveInvalidImg";i:7;s:33:"Core.RemoveProcessingInstructions";i:7;s:25:"Core.RemoveScriptContents";i:-7;s:13:"Filter.Custom";i:9;s:34:"Filter.ExtractStyleBlocks.Escaping";i:7;s:33:"Filter.ExtractStyleBlocksEscaping";O:8:"stdClass":2:{s:3:"key";s:34:"Filter.ExtractStyleBlocks.Escaping";s:7:"isAlias";b:1;}s:38:"FilterParam.ExtractStyleBlocksEscaping";O:8:"stdClass":2:{s:3:"key";s:34:"Filter.ExtractStyleBlocks.Escaping";s:7:"isAlias";b:1;}s:31:"Filter.ExtractStyleBlocks.Scope";i:-1;s:30:"Filter.ExtractStyleBlocksScope";O:8:"stdClass":2:{s:3:"key";s:31:"Filter.ExtractStyleBlocks.Scope";s:7:"isAlias";b:1;}s:35:"FilterParam.ExtractStyleBlocksScope";O:8:"stdClass":2:{s:3:"key";s:31:"Filter.ExtractStyleBlocks.Scope";s:7:"isAlias";b:1;}s:34:"Filter.ExtractStyleBlocks.TidyImpl";i:-11;s:38:"FilterParam.ExtractStyleBlocksTidyImpl";O:8:"stdClass":2:{s:3:"key";s:34:"Filter.ExtractStyleBlocks.TidyImpl";s:7:"isAlias";b:1;}s:25:"Filter.ExtractStyleBlocks";i:7;s:14:"Filter.YouTube";i:7;s:12:"HTML.Allowed";i:-4;s:22:"HTML.AllowedAttributes";i:-8;s:20:"HTML.AllowedComments";i:8;s:26:"HTML.AllowedCommentsRegexp";i:-1;s:20:"HTML.AllowedElements";i:-8;s:19:"HTML.AllowedModules";i:-8;s:23:"HTML.Attr.Name.UseCDATA";i:7;s:17:"HTML.BlockWrapper";i:1;s:16:"HTML.CoreModules";i:8;s:18:"HTML.CustomDoctype";i:-1;s:17:"HTML.DefinitionID";i:-1;s:18:"HTML.DefinitionRev";i:5;s:12:"HTML.Doctype";O:8:"stdClass":3:{s:4:"type";i:1;s:10:"allow_null";b:1;s:7:"allowed";a:5:{s:22:"HTML 4.01 Transitional";b:1;s:16:"HTML 4.01 Strict";b:1;s:22:"XHTML 1.0 Transitional";b:1;s:16:"XHTML 1.0 Strict";b:1;s:9:"XHTML 1.1";b:1;}}s:25:"HTML.FlashAllowFullScreen";i:7;s:24:"HTML.ForbiddenAttributes";i:8;s:22:"HTML.ForbiddenElements";i:8;s:17:"HTML.MaxImgLength";i:-5;s:13:"HTML.Nofollow";i:7;s:11:"HTML.Parent";i:1;s:16:"HTML.Proprietary";i:7;s:14:"HTML.SafeEmbed";i:7;s:15:"HTML.SafeIframe";i:7;s:15:"HTML.SafeObject";i:7;s:18:"HTML.SafeScripting";i:8;s:11:"HTML.Strict";i:7;s:16:"HTML.TargetBlank";i:7;s:19:"HTML.TargetNoopener";i:7;s:21:"HTML.TargetNoreferrer";i:7;s:12:"HTML.TidyAdd";i:8;s:14:"HTML.TidyLevel";O:8:"stdClass":2:{s:4:"type";i:1;s:7:"allowed";a:4:{s:4:"none";b:1;s:5:"light";b:1;s:6:"medium";b:1;s:5:"heavy";b:1;}}s:15:"HTML.TidyRemove";i:8;s:12:"HTML.Trusted";i:7;s:10:"HTML.XHTML";i:7;s:10:"Core.XHTML";O:8:"stdClass":2:{s:3:"key";s:10:"HTML.XHTML";s:7:"isAlias";b:1;}s:28:"Output.CommentScriptContents";i:7;s:26:"Core.CommentScriptContents";O:8:"stdClass":2:{s:3:"key";s:28:"Output.CommentScriptContents";s:7:"isAlias";b:1;}s:19:"Output.FixInnerHTML";i:7;s:18:"Output.FlashCompat";i:7;s:14:"Output.Newline";i:-1;s:15:"Output.SortAttr";i:7;s:17:"Output.TidyFormat";i:7;s:15:"Core.TidyFormat";O:8:"stdClass":2:{s:3:"key";s:17:"Output.TidyFormat";s:7:"isAlias";b:1;}s:17:"Test.ForceNoIconv";i:7;s:18:"URI.AllowedSchemes";i:8;s:8:"URI.Base";i:-1;s:17:"URI.DefaultScheme";i:-1;s:16:"URI.DefinitionID";i:-1;s:17:"URI.DefinitionRev";i:5;s:11:"URI.Disable";i:7;s:15:"Attr.DisableURI";O:8:"stdClass":2:{s:3:"key";s:11:"URI.Disable";s:7:"isAlias";b:1;}s:19:"URI.DisableExternal";i:7;s:28:"URI.DisableExternalResources";i:7;s:20:"URI.DisableResources";i:7;s:8:"URI.Host";i:-1;s:17:"URI.HostBlacklist";i:9;s:16:"URI.MakeAbsolute";i:7;s:9:"URI.Munge";i:-1;s:18:"URI.MungeResources";i:7;s:18:"URI.MungeSecretKey";i:-1;s:26:"URI.OverrideAllowedSchemes";i:7;s:20:"URI.SafeIframeRegexp";i:-1;}} \ No newline at end of file diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt new file mode 100644 index 0000000..4a42382 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt @@ -0,0 +1,8 @@ +Attr.AllowedClasses +TYPE: lookup/null +VERSION: 4.0.0 +DEFAULT: null +--DESCRIPTION-- +List of allowed class values in the class attribute. By default, this is null, +which means all classes are allowed. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt new file mode 100644 index 0000000..b033eb5 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt @@ -0,0 +1,12 @@ +Attr.AllowedFrameTargets +TYPE: lookup +DEFAULT: array() +--DESCRIPTION-- +Lookup table of all allowed link frame targets. Some commonly used link +targets include _blank, _self, _parent and _top. Values should be +lowercase, as validation will be done in a case-sensitive manner despite +W3C's recommendation. XHTML 1.0 Strict does not permit the target attribute +so this directive will have no effect in that doctype. XHTML 1.1 does not +enable the Target module by default, you will have to manually enable it +(see the module documentation for more details.) +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt new file mode 100644 index 0000000..ed72a9d --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt @@ -0,0 +1,9 @@ +Attr.AllowedRel +TYPE: lookup +VERSION: 1.6.0 +DEFAULT: array() +--DESCRIPTION-- +List of allowed forward document relationships in the rel attribute. Common +values may be nofollow or print. By default, this is empty, meaning that no +document relationships are allowed. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt new file mode 100644 index 0000000..1ae672d --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt @@ -0,0 +1,9 @@ +Attr.AllowedRev +TYPE: lookup +VERSION: 1.6.0 +DEFAULT: array() +--DESCRIPTION-- +List of allowed reverse document relationships in the rev attribute. This +attribute is a bit of an edge-case; if you don't know what it is for, stay +away. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt new file mode 100644 index 0000000..119a9d2 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt @@ -0,0 +1,19 @@ +Attr.ClassUseCDATA +TYPE: bool/null +DEFAULT: null +VERSION: 4.0.0 +--DESCRIPTION-- +If null, class will auto-detect the doctype and, if matching XHTML 1.1 or +XHTML 2.0, will use the restrictive NMTOKENS specification of class. Otherwise, +it will use a relaxed CDATA definition. If true, the relaxed CDATA definition +is forced; if false, the NMTOKENS definition is forced. To get behavior +of HTML Purifier prior to 4.0.0, set this directive to false. + +Some rational behind the auto-detection: +in previous versions of HTML Purifier, it was assumed that the form of +class was NMTOKENS, as specified by the XHTML Modularization (representing +XHTML 1.1 and XHTML 2.0). The DTDs for HTML 4.01 and XHTML 1.0, however +specify class as CDATA. HTML 5 effectively defines it as CDATA, but +with the additional constraint that each name should be unique (this is not +explicitly outlined in previous specifications). +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt new file mode 100644 index 0000000..80b1431 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt @@ -0,0 +1,11 @@ +Attr.DefaultImageAlt +TYPE: string/null +DEFAULT: null +VERSION: 3.2.0 +--DESCRIPTION-- +This is the content of the alt tag of an image if the user had not +previously specified an alt attribute. This applies to all images without +a valid alt attribute, as opposed to %Attr.DefaultInvalidImageAlt, which +only applies to invalid images, and overrides in the case of an invalid image. +Default behavior with null is to use the basename of the src tag for the alt. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt new file mode 100644 index 0000000..c51000d --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt @@ -0,0 +1,9 @@ +Attr.DefaultInvalidImage +TYPE: string +DEFAULT: '' +--DESCRIPTION-- +This is the default image an img tag will be pointed to if it does not have +a valid src attribute. In future versions, we may allow the image tag to +be removed completely, but due to design issues, this is not possible right +now. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt new file mode 100644 index 0000000..c1ec4b0 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt @@ -0,0 +1,8 @@ +Attr.DefaultInvalidImageAlt +TYPE: string +DEFAULT: 'Invalid image' +--DESCRIPTION-- +This is the content of the alt tag of an invalid image if the user had not +previously specified an alt attribute. It has no effect when the image is +valid but there was no alt attribute present. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt new file mode 100644 index 0000000..f57dcc4 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt @@ -0,0 +1,10 @@ +Attr.DefaultTextDir +TYPE: string +DEFAULT: 'ltr' +--DESCRIPTION-- +Defines the default text direction (ltr or rtl) of the document being +parsed. This generally is the same as the value of the dir attribute in +HTML, or ltr if that is not specified. +--ALLOWED-- +'ltr', 'rtl' +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt new file mode 100644 index 0000000..9b93a55 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt @@ -0,0 +1,16 @@ +Attr.EnableID +TYPE: bool +DEFAULT: false +VERSION: 1.2.0 +--DESCRIPTION-- +Allows the ID attribute in HTML. This is disabled by default due to the +fact that without proper configuration user input can easily break the +validation of a webpage by specifying an ID that is already on the +surrounding HTML. If you don't mind throwing caution to the wind, enable +this directive, but I strongly recommend you also consider blacklisting IDs +you use (%Attr.IDBlacklist) or prefixing all user supplied IDs +(%Attr.IDPrefix). When set to true HTML Purifier reverts to the behavior of +pre-1.2.0 versions. +--ALIASES-- +HTML.EnableAttrID +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt new file mode 100644 index 0000000..fed8954 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt @@ -0,0 +1,8 @@ +Attr.ForbiddenClasses +TYPE: lookup +VERSION: 4.0.0 +DEFAULT: array() +--DESCRIPTION-- +List of forbidden class values in the class attribute. By default, this is +empty, which means that no classes are forbidden. See also %Attr.AllowedClasses. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ID.HTML5.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ID.HTML5.txt new file mode 100644 index 0000000..c48e62f --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ID.HTML5.txt @@ -0,0 +1,10 @@ +Attr.ID.HTML5 +TYPE: bool/null +DEFAULT: null +VERSION: 4.8.0 +--DESCRIPTION-- +In HTML5, restrictions on the format of the id attribute have been significantly +relaxed, such that any string is valid so long as it contains no spaces and +is at least one character. In lieu of a general HTML5 compatibility flag, +set this configuration directive to true to use the relaxed rules. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt new file mode 100644 index 0000000..52168bb --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt @@ -0,0 +1,5 @@ +Attr.IDBlacklist +TYPE: list +DEFAULT: array() +DESCRIPTION: Array of IDs not allowed in the document. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt new file mode 100644 index 0000000..7b85043 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt @@ -0,0 +1,9 @@ +Attr.IDBlacklistRegexp +TYPE: string/null +VERSION: 1.6.0 +DEFAULT: NULL +--DESCRIPTION-- +PCRE regular expression to be matched against all IDs. If the expression is +matches, the ID is rejected. Use this with care: may cause significant +degradation. ID matching is done after all other validation. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt new file mode 100644 index 0000000..5781382 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt @@ -0,0 +1,12 @@ +Attr.IDPrefix +TYPE: string +VERSION: 1.2.0 +DEFAULT: '' +--DESCRIPTION-- +String to prefix to IDs. If you have no idea what IDs your pages may use, +you may opt to simply add a prefix to all user-submitted ID attributes so +that they are still usable, but will not conflict with core page IDs. +Example: setting the directive to 'user_' will result in a user submitted +'foo' to become 'user_foo' Be sure to set %HTML.EnableAttrID to true +before using this. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt new file mode 100644 index 0000000..f91fcd6 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt @@ -0,0 +1,14 @@ +Attr.IDPrefixLocal +TYPE: string +VERSION: 1.2.0 +DEFAULT: '' +--DESCRIPTION-- +Temporary prefix for IDs used in conjunction with %Attr.IDPrefix. If you +need to allow multiple sets of user content on web page, you may need to +have a seperate prefix that changes with each iteration. This way, +seperately submitted user content displayed on the same page doesn't +clobber each other. Ideal values are unique identifiers for the content it +represents (i.e. the id of the row in the database). Be sure to add a +seperator (like an underscore) at the end. Warning: this directive will +not work unless %Attr.IDPrefix is set to a non-empty value! +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt new file mode 100644 index 0000000..2d7f94e --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt @@ -0,0 +1,31 @@ +AutoFormat.AutoParagraph +TYPE: bool +VERSION: 2.0.1 +DEFAULT: false +--DESCRIPTION-- + +

        + This directive turns on auto-paragraphing, where double newlines are + converted in to paragraphs whenever possible. Auto-paragraphing: +

        +
          +
        • Always applies to inline elements or text in the root node,
        • +
        • Applies to inline elements or text with double newlines in nodes + that allow paragraph tags,
        • +
        • Applies to double newlines in paragraph tags
        • +
        +

        + p tags must be allowed for this directive to take effect. + We do not use br tags for paragraphing, as that is + semantically incorrect. +

        +

        + To prevent auto-paragraphing as a content-producer, refrain from using + double-newlines except to specify a new paragraph or in contexts where + it has special meaning (whitespace usually has no meaning except in + tags like pre, so this should not be difficult.) To prevent + the paragraphing of inline text adjacent to block elements, wrap them + in div tags (the behavior is slightly different outside of + the root node.) +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt new file mode 100644 index 0000000..2eb1974 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt @@ -0,0 +1,12 @@ +AutoFormat.Custom +TYPE: list +VERSION: 2.0.1 +DEFAULT: array() +--DESCRIPTION-- + +

        + This directive can be used to add custom auto-format injectors. + Specify an array of injector names (class name minus the prefix) + or concrete implementations. Injector class must exist. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt new file mode 100644 index 0000000..c955de7 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt @@ -0,0 +1,11 @@ +AutoFormat.DisplayLinkURI +TYPE: bool +VERSION: 3.2.0 +DEFAULT: false +--DESCRIPTION-- +

        + This directive turns on the in-text display of URIs in <a> tags, and disables + those links. For example, example becomes + example (http://example.com). +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt new file mode 100644 index 0000000..328b2b2 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt @@ -0,0 +1,12 @@ +AutoFormat.Linkify +TYPE: bool +VERSION: 2.0.1 +DEFAULT: false +--DESCRIPTION-- + +

        + This directive turns on linkification, auto-linking http, ftp and + https URLs. a tags with the href attribute + must be allowed. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt new file mode 100644 index 0000000..d0532b6 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt @@ -0,0 +1,12 @@ +AutoFormat.PurifierLinkify.DocURL +TYPE: string +VERSION: 2.0.1 +DEFAULT: '#%s' +ALIASES: AutoFormatParam.PurifierLinkifyDocURL +--DESCRIPTION-- +

        + Location of configuration documentation to link to, let %s substitute + into the configuration's namespace and directive names sans the percent + sign. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt new file mode 100644 index 0000000..f3ab259 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt @@ -0,0 +1,12 @@ +AutoFormat.PurifierLinkify +TYPE: bool +VERSION: 2.0.1 +DEFAULT: false +--DESCRIPTION-- + +

        + Internal auto-formatter that converts configuration directives in + syntax %Namespace.Directive to links. a tags + with the href attribute must be allowed. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.Predicate.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.Predicate.txt new file mode 100644 index 0000000..376f771 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.Predicate.txt @@ -0,0 +1,14 @@ +AutoFormat.RemoveEmpty.Predicate +TYPE: hash +VERSION: 4.7.0 +DEFAULT: array('colgroup' => array(), 'th' => array(), 'td' => array(), 'iframe' => array('src')) +--DESCRIPTION-- +

        + Given that an element has no contents, it will be removed by default, unless + this predicate dictates otherwise. The predicate can either be an associative + map from tag name to list of attributes that must be present for the element + to be considered preserved: thus, the default always preserves colgroup, + th and td, and also iframe if it + has a src. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt new file mode 100644 index 0000000..219d04a --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt @@ -0,0 +1,11 @@ +AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions +TYPE: lookup +VERSION: 4.0.0 +DEFAULT: array('td' => true, 'th' => true) +--DESCRIPTION-- +

        + When %AutoFormat.RemoveEmpty and %AutoFormat.RemoveEmpty.RemoveNbsp + are enabled, this directive defines what HTML elements should not be + removede if they have only a non-breaking space in them. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt new file mode 100644 index 0000000..e557ad2 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt @@ -0,0 +1,15 @@ +AutoFormat.RemoveEmpty.RemoveNbsp +TYPE: bool +VERSION: 4.0.0 +DEFAULT: false +--DESCRIPTION-- +

        + When enabled, HTML Purifier will treat any elements that contain only + non-breaking spaces as well as regular whitespace as empty, and remove + them when %AutoFormat.RemoveEmpty is enabled. +

        +

        + See %AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions for a list of elements + that don't have this behavior applied to them. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt new file mode 100644 index 0000000..6b5a7a5 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt @@ -0,0 +1,46 @@ +AutoFormat.RemoveEmpty +TYPE: bool +VERSION: 3.2.0 +DEFAULT: false +--DESCRIPTION-- +

        + When enabled, HTML Purifier will attempt to remove empty elements that + contribute no semantic information to the document. The following types + of nodes will be removed: +

        +
        • + Tags with no attributes and no content, and that are not empty + elements (remove <a></a> but not + <br />), and +
        • +
        • + Tags with no content, except for:
            +
          • The colgroup element, or
          • +
          • + Elements with the id or name attribute, + when those attributes are permitted on those elements. +
          • +
        • +
        +

        + Please be very careful when using this functionality; while it may not + seem that empty elements contain useful information, they can alter the + layout of a document given appropriate styling. This directive is most + useful when you are processing machine-generated HTML, please avoid using + it on regular user HTML. +

        +

        + Elements that contain only whitespace will be treated as empty. Non-breaking + spaces, however, do not count as whitespace. See + %AutoFormat.RemoveEmpty.RemoveNbsp for alternate behavior. +

        +

        + This algorithm is not perfect; you may still notice some empty tags, + particularly if a node had elements, but those elements were later removed + because they were not permitted in that context, or tags that, after + being auto-closed by another tag, where empty. This is for safety reasons + to prevent clever code from breaking validation. The general rule of thumb: + if a tag looked empty on the way in, it will get removed; if HTML Purifier + made it empty, it will stay. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveSpansWithoutAttributes.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveSpansWithoutAttributes.txt new file mode 100644 index 0000000..a448770 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveSpansWithoutAttributes.txt @@ -0,0 +1,11 @@ +AutoFormat.RemoveSpansWithoutAttributes +TYPE: bool +VERSION: 4.0.1 +DEFAULT: false +--DESCRIPTION-- +

        + This directive causes span tags without any attributes + to be removed. It will also remove spans that had all attributes + removed during processing. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowDuplicates.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowDuplicates.txt new file mode 100644 index 0000000..acfeab3 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowDuplicates.txt @@ -0,0 +1,11 @@ +CSS.AllowDuplicates +TYPE: bool +DEFAULT: false +VERSION: 4.8.0 +--DESCRIPTION-- +

        + By default, HTML Purifier removes duplicate CSS properties, + like color:red; color:blue. If this is set to + true, duplicate properties are allowed. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt new file mode 100644 index 0000000..8096eb0 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt @@ -0,0 +1,8 @@ +CSS.AllowImportant +TYPE: bool +DEFAULT: false +VERSION: 3.1.0 +--DESCRIPTION-- +This parameter determines whether or not !important cascade modifiers should +be allowed in user CSS. If false, !important will stripped. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt new file mode 100644 index 0000000..9d34deb --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt @@ -0,0 +1,11 @@ +CSS.AllowTricky +TYPE: bool +DEFAULT: false +VERSION: 3.1.0 +--DESCRIPTION-- +This parameter determines whether or not to allow "tricky" CSS properties and +values. Tricky CSS properties/values can drastically modify page layout or +be used for deceptive practices but do not directly constitute a security risk. +For example, display:none; is considered a tricky property that +will only be allowed if this directive is set to true. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowedFonts.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowedFonts.txt new file mode 100644 index 0000000..7c2b547 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowedFonts.txt @@ -0,0 +1,12 @@ +CSS.AllowedFonts +TYPE: lookup/null +VERSION: 4.3.0 +DEFAULT: NULL +--DESCRIPTION-- +

        + Allows you to manually specify a set of allowed fonts. If + NULL, all fonts are allowed. This directive + affects generic names (serif, sans-serif, monospace, cursive, + fantasy) as well as specific font families. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt new file mode 100644 index 0000000..f1ba513 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt @@ -0,0 +1,18 @@ +CSS.AllowedProperties +TYPE: lookup/null +VERSION: 3.1.0 +DEFAULT: NULL +--DESCRIPTION-- + +

        + If HTML Purifier's style attributes set is unsatisfactory for your needs, + you can overload it with your own list of tags to allow. Note that this + method is subtractive: it does its job by taking away from HTML Purifier + usual feature set, so you cannot add an attribute that HTML Purifier never + supported in the first place. +

        +

        + Warning: If another directive conflicts with the + elements here, that directive will win and override. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt new file mode 100644 index 0000000..96b4108 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt @@ -0,0 +1,11 @@ +CSS.DefinitionRev +TYPE: int +VERSION: 2.0.0 +DEFAULT: 1 +--DESCRIPTION-- + +

        + Revision identifier for your custom definition. See + %HTML.DefinitionRev for details. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.ForbiddenProperties.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.ForbiddenProperties.txt new file mode 100644 index 0000000..923e8e9 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.ForbiddenProperties.txt @@ -0,0 +1,13 @@ +CSS.ForbiddenProperties +TYPE: lookup +VERSION: 4.2.0 +DEFAULT: array() +--DESCRIPTION-- +

        + This is the logical inverse of %CSS.AllowedProperties, and it will + override that directive or any other directive. If possible, + %CSS.AllowedProperties is recommended over this directive, + because it can sometimes be difficult to tell whether or not you've + forbidden all of the CSS properties you truly would like to disallow. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt new file mode 100644 index 0000000..3808581 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt @@ -0,0 +1,16 @@ +CSS.MaxImgLength +TYPE: string/null +DEFAULT: '1200px' +VERSION: 3.1.1 +--DESCRIPTION-- +

        + This parameter sets the maximum allowed length on img tags, + effectively the width and height properties. + Only absolute units of measurement (in, pt, pc, mm, cm) and pixels (px) are allowed. This is + in place to prevent imagecrash attacks, disable with null at your own risk. + This directive is similar to %HTML.MaxImgLength, and both should be + concurrently edited, although there are + subtle differences in the input format (the CSS max is a number with + a unit). +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt new file mode 100644 index 0000000..8a26f22 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt @@ -0,0 +1,10 @@ +CSS.Proprietary +TYPE: bool +VERSION: 3.0.0 +DEFAULT: false +--DESCRIPTION-- + +

        + Whether or not to allow safe, proprietary CSS values. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.Trusted.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.Trusted.txt new file mode 100644 index 0000000..917ec42 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.Trusted.txt @@ -0,0 +1,9 @@ +CSS.Trusted +TYPE: bool +VERSION: 4.2.1 +DEFAULT: false +--DESCRIPTION-- +Indicates whether or not the user's CSS input is trusted or not. If the +input is trusted, a more expansive set of allowed properties. See +also %HTML.Trusted. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt new file mode 100644 index 0000000..afc6a87 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt @@ -0,0 +1,14 @@ +Cache.DefinitionImpl +TYPE: string/null +VERSION: 2.0.0 +DEFAULT: 'Serializer' +--DESCRIPTION-- + +This directive defines which method to use when caching definitions, +the complex data-type that makes HTML Purifier tick. Set to null +to disable caching (not recommended, as you will see a definite +performance degradation). + +--ALIASES-- +Core.DefinitionCache +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt new file mode 100644 index 0000000..668f248 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt @@ -0,0 +1,13 @@ +Cache.SerializerPath +TYPE: string/null +VERSION: 2.0.0 +DEFAULT: NULL +--DESCRIPTION-- + +

        + Absolute path with no trailing slash to store serialized definitions in. + Default is within the + HTML Purifier library inside DefinitionCache/Serializer. This + path must be writable by the webserver. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt new file mode 100644 index 0000000..f6059e6 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt @@ -0,0 +1,16 @@ +Cache.SerializerPermissions +TYPE: int/null +VERSION: 4.3.0 +DEFAULT: 0755 +--DESCRIPTION-- + +

        + Directory permissions of the files and directories created inside + the DefinitionCache/Serializer or other custom serializer path. +

        +

        + In HTML Purifier 4.8.0, this also supports NULL, + which means that no chmod'ing or directory creation shall + occur. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt new file mode 100644 index 0000000..e0fa378 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt @@ -0,0 +1,18 @@ +Core.AggressivelyFixLt +TYPE: bool +VERSION: 2.1.0 +DEFAULT: true +--DESCRIPTION-- +

        + This directive enables aggressive pre-filter fixes HTML Purifier can + perform in order to ensure that open angled-brackets do not get killed + during parsing stage. Enabling this will result in two preg_replace_callback + calls and at least two preg_replace calls for every HTML document parsed; + if your users make very well-formed HTML, you can set this directive false. + This has no effect when DirectLex is used. +

        +

        + Notice: This directive's default turned from false to true + in HTML Purifier 3.2.0. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyRemoveScript.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyRemoveScript.txt new file mode 100644 index 0000000..fb140b6 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyRemoveScript.txt @@ -0,0 +1,16 @@ +Core.AggressivelyRemoveScript +TYPE: bool +VERSION: 4.9.0 +DEFAULT: true +--DESCRIPTION-- +

        + This directive enables aggressive pre-filter removal of + script tags. This is not necessary for security, + but it can help work around a bug in libxml where embedded + HTML elements inside script sections cause the parser to + choke. To revert to pre-4.9.0 behavior, set this to false. + This directive has no effect if %Core.Trusted is true, + %Core.RemoveScriptContents is false, or %Core.HiddenElements + does not contain script. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.AllowHostnameUnderscore.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.AllowHostnameUnderscore.txt new file mode 100644 index 0000000..405d36f --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.AllowHostnameUnderscore.txt @@ -0,0 +1,16 @@ +Core.AllowHostnameUnderscore +TYPE: bool +VERSION: 4.6.0 +DEFAULT: false +--DESCRIPTION-- +

        + By RFC 1123, underscores are not permitted in host names. + (This is in contrast to the specification for DNS, RFC + 2181, which allows underscores.) + However, most browsers do the right thing when faced with + an underscore in the host name, and so some poorly written + websites are written with the expectation this should work. + Setting this parameter to true relaxes our allowed character + check so that underscores are permitted. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.AllowParseManyTags.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.AllowParseManyTags.txt new file mode 100644 index 0000000..b4b9b10 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.AllowParseManyTags.txt @@ -0,0 +1,12 @@ +Core.AllowParseManyTags +TYPE: bool +DEFAULT: false +VERSION: 4.10.1 +--DESCRIPTION-- +

        + This directive allows parsing of many nested tags. + If you set true, relaxes any hardcoded limit from the parser. + However, in that case it may cause a Dos attack. + Be careful when enabling it. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt new file mode 100644 index 0000000..c6ea069 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt @@ -0,0 +1,12 @@ +Core.CollectErrors +TYPE: bool +VERSION: 2.0.0 +DEFAULT: false +--DESCRIPTION-- + +Whether or not to collect errors found while filtering the document. This +is a useful way to give feedback to your users. Warning: +Currently this feature is very patchy and experimental, with lots of +possible error messages not yet implemented. It will not cause any +problems, but it may not help your users either. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt new file mode 100644 index 0000000..fc10086 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt @@ -0,0 +1,160 @@ +Core.ColorKeywords +TYPE: hash +VERSION: 2.0.0 +--DEFAULT-- +array ( + 'aliceblue' => '#F0F8FF', + 'antiquewhite' => '#FAEBD7', + 'aqua' => '#00FFFF', + 'aquamarine' => '#7FFFD4', + 'azure' => '#F0FFFF', + 'beige' => '#F5F5DC', + 'bisque' => '#FFE4C4', + 'black' => '#000000', + 'blanchedalmond' => '#FFEBCD', + 'blue' => '#0000FF', + 'blueviolet' => '#8A2BE2', + 'brown' => '#A52A2A', + 'burlywood' => '#DEB887', + 'cadetblue' => '#5F9EA0', + 'chartreuse' => '#7FFF00', + 'chocolate' => '#D2691E', + 'coral' => '#FF7F50', + 'cornflowerblue' => '#6495ED', + 'cornsilk' => '#FFF8DC', + 'crimson' => '#DC143C', + 'cyan' => '#00FFFF', + 'darkblue' => '#00008B', + 'darkcyan' => '#008B8B', + 'darkgoldenrod' => '#B8860B', + 'darkgray' => '#A9A9A9', + 'darkgrey' => '#A9A9A9', + 'darkgreen' => '#006400', + 'darkkhaki' => '#BDB76B', + 'darkmagenta' => '#8B008B', + 'darkolivegreen' => '#556B2F', + 'darkorange' => '#FF8C00', + 'darkorchid' => '#9932CC', + 'darkred' => '#8B0000', + 'darksalmon' => '#E9967A', + 'darkseagreen' => '#8FBC8F', + 'darkslateblue' => '#483D8B', + 'darkslategray' => '#2F4F4F', + 'darkslategrey' => '#2F4F4F', + 'darkturquoise' => '#00CED1', + 'darkviolet' => '#9400D3', + 'deeppink' => '#FF1493', + 'deepskyblue' => '#00BFFF', + 'dimgray' => '#696969', + 'dimgrey' => '#696969', + 'dodgerblue' => '#1E90FF', + 'firebrick' => '#B22222', + 'floralwhite' => '#FFFAF0', + 'forestgreen' => '#228B22', + 'fuchsia' => '#FF00FF', + 'gainsboro' => '#DCDCDC', + 'ghostwhite' => '#F8F8FF', + 'gold' => '#FFD700', + 'goldenrod' => '#DAA520', + 'gray' => '#808080', + 'grey' => '#808080', + 'green' => '#008000', + 'greenyellow' => '#ADFF2F', + 'honeydew' => '#F0FFF0', + 'hotpink' => '#FF69B4', + 'indianred' => '#CD5C5C', + 'indigo' => '#4B0082', + 'ivory' => '#FFFFF0', + 'khaki' => '#F0E68C', + 'lavender' => '#E6E6FA', + 'lavenderblush' => '#FFF0F5', + 'lawngreen' => '#7CFC00', + 'lemonchiffon' => '#FFFACD', + 'lightblue' => '#ADD8E6', + 'lightcoral' => '#F08080', + 'lightcyan' => '#E0FFFF', + 'lightgoldenrodyellow' => '#FAFAD2', + 'lightgray' => '#D3D3D3', + 'lightgrey' => '#D3D3D3', + 'lightgreen' => '#90EE90', + 'lightpink' => '#FFB6C1', + 'lightsalmon' => '#FFA07A', + 'lightseagreen' => '#20B2AA', + 'lightskyblue' => '#87CEFA', + 'lightslategray' => '#778899', + 'lightslategrey' => '#778899', + 'lightsteelblue' => '#B0C4DE', + 'lightyellow' => '#FFFFE0', + 'lime' => '#00FF00', + 'limegreen' => '#32CD32', + 'linen' => '#FAF0E6', + 'magenta' => '#FF00FF', + 'maroon' => '#800000', + 'mediumaquamarine' => '#66CDAA', + 'mediumblue' => '#0000CD', + 'mediumorchid' => '#BA55D3', + 'mediumpurple' => '#9370DB', + 'mediumseagreen' => '#3CB371', + 'mediumslateblue' => '#7B68EE', + 'mediumspringgreen' => '#00FA9A', + 'mediumturquoise' => '#48D1CC', + 'mediumvioletred' => '#C71585', + 'midnightblue' => '#191970', + 'mintcream' => '#F5FFFA', + 'mistyrose' => '#FFE4E1', + 'moccasin' => '#FFE4B5', + 'navajowhite' => '#FFDEAD', + 'navy' => '#000080', + 'oldlace' => '#FDF5E6', + 'olive' => '#808000', + 'olivedrab' => '#6B8E23', + 'orange' => '#FFA500', + 'orangered' => '#FF4500', + 'orchid' => '#DA70D6', + 'palegoldenrod' => '#EEE8AA', + 'palegreen' => '#98FB98', + 'paleturquoise' => '#AFEEEE', + 'palevioletred' => '#DB7093', + 'papayawhip' => '#FFEFD5', + 'peachpuff' => '#FFDAB9', + 'peru' => '#CD853F', + 'pink' => '#FFC0CB', + 'plum' => '#DDA0DD', + 'powderblue' => '#B0E0E6', + 'purple' => '#800080', + 'rebeccapurple' => '#663399', + 'red' => '#FF0000', + 'rosybrown' => '#BC8F8F', + 'royalblue' => '#4169E1', + 'saddlebrown' => '#8B4513', + 'salmon' => '#FA8072', + 'sandybrown' => '#F4A460', + 'seagreen' => '#2E8B57', + 'seashell' => '#FFF5EE', + 'sienna' => '#A0522D', + 'silver' => '#C0C0C0', + 'skyblue' => '#87CEEB', + 'slateblue' => '#6A5ACD', + 'slategray' => '#708090', + 'slategrey' => '#708090', + 'snow' => '#FFFAFA', + 'springgreen' => '#00FF7F', + 'steelblue' => '#4682B4', + 'tan' => '#D2B48C', + 'teal' => '#008080', + 'thistle' => '#D8BFD8', + 'tomato' => '#FF6347', + 'turquoise' => '#40E0D0', + 'violet' => '#EE82EE', + 'wheat' => '#F5DEB3', + 'white' => '#FFFFFF', + 'whitesmoke' => '#F5F5F5', + 'yellow' => '#FFFF00', + 'yellowgreen' => '#9ACD32' +) +--DESCRIPTION-- + +Lookup array of color names to six digit hexadecimal number corresponding +to color, with preceding hash mark. Used when parsing colors. The lookup +is done in a case-insensitive manner. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt new file mode 100644 index 0000000..656d378 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt @@ -0,0 +1,14 @@ +Core.ConvertDocumentToFragment +TYPE: bool +DEFAULT: true +--DESCRIPTION-- + +This parameter determines whether or not the filter should convert +input that is a full document with html and body tags to a fragment +of just the contents of a body tag. This parameter is simply something +HTML Purifier can do during an edge-case: for most inputs, this +processing is not necessary. + +--ALIASES-- +Core.AcceptFullDocuments +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt new file mode 100644 index 0000000..2f54e46 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt @@ -0,0 +1,17 @@ +Core.DirectLexLineNumberSyncInterval +TYPE: int +VERSION: 2.0.0 +DEFAULT: 0 +--DESCRIPTION-- + +

        + Specifies the number of tokens the DirectLex line number tracking + implementations should process before attempting to resyncronize the + current line count by manually counting all previous new-lines. When + at 0, this functionality is disabled. Lower values will decrease + performance, and this is only strictly necessary if the counting + algorithm is buggy (in which case you should report it as a bug). + This has no effect when %Core.MaintainLineNumbers is disabled or DirectLex is + not being used. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.DisableExcludes.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.DisableExcludes.txt new file mode 100644 index 0000000..3c63c92 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.DisableExcludes.txt @@ -0,0 +1,14 @@ +Core.DisableExcludes +TYPE: bool +DEFAULT: false +VERSION: 4.5.0 +--DESCRIPTION-- +

        + This directive disables SGML-style exclusions, e.g. the exclusion of + <object> in any descendant of a + <pre> tag. Disabling excludes will allow some + invalid documents to pass through HTML Purifier, but HTML Purifier + will also be less likely to accidentally remove large documents during + processing. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EnableIDNA.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EnableIDNA.txt new file mode 100644 index 0000000..7f498e7 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EnableIDNA.txt @@ -0,0 +1,9 @@ +Core.EnableIDNA +TYPE: bool +DEFAULT: false +VERSION: 4.4.0 +--DESCRIPTION-- +Allows international domain names in URLs. This configuration option +requires the PEAR Net_IDNA2 module to be installed. It operates by +punycoding any internationalized host names for maximum portability. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt new file mode 100644 index 0000000..89e2ae3 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt @@ -0,0 +1,15 @@ +Core.Encoding +TYPE: istring +DEFAULT: 'utf-8' +--DESCRIPTION-- +If for some reason you are unable to convert all webpages to UTF-8, you can +use this directive as a stop-gap compatibility change to let HTML Purifier +deal with non UTF-8 input. This technique has notable deficiencies: +absolutely no characters outside of the selected character encoding will be +preserved, not even the ones that have been ampersand escaped (this is due +to a UTF-8 specific feature that automatically resolves all +entities), making it pretty useless for anything except the most I18N-blind +applications, although %Core.EscapeNonASCIICharacters offers fixes this +trouble with another tradeoff. This directive only accepts ISO-8859-1 if +iconv is not enabled. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt new file mode 100644 index 0000000..1cc3fcd --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt @@ -0,0 +1,12 @@ +Core.EscapeInvalidChildren +TYPE: bool +DEFAULT: false +--DESCRIPTION-- +

        Warning: this configuration option is no longer does anything as of 4.6.0.

        + +

        When true, a child is found that is not allowed in the context of the +parent element will be transformed into text as if it were ASCII. When +false, that element and all internal tags will be dropped, though text will +be preserved. There is no option for dropping the element but preserving +child nodes.

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt new file mode 100644 index 0000000..299775f --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt @@ -0,0 +1,7 @@ +Core.EscapeInvalidTags +TYPE: bool +DEFAULT: false +--DESCRIPTION-- +When true, invalid tags will be written back to the document as plain text. +Otherwise, they are silently dropped. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt new file mode 100644 index 0000000..f50db2f --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt @@ -0,0 +1,13 @@ +Core.EscapeNonASCIICharacters +TYPE: bool +VERSION: 1.4.0 +DEFAULT: false +--DESCRIPTION-- +This directive overcomes a deficiency in %Core.Encoding by blindly +converting all non-ASCII characters into decimal numeric entities before +converting it to its native encoding. This means that even characters that +can be expressed in the non-UTF-8 encoding will be entity-ized, which can +be a real downer for encodings like Big5. It also assumes that the ASCII +repetoire is available, although this is the case for almost all encodings. +Anyway, use UTF-8! +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt new file mode 100644 index 0000000..c337e47 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt @@ -0,0 +1,19 @@ +Core.HiddenElements +TYPE: lookup +--DEFAULT-- +array ( + 'script' => true, + 'style' => true, +) +--DESCRIPTION-- + +

        + This directive is a lookup array of elements which should have their + contents removed when they are not allowed by the HTML definition. + For example, the contents of a script tag are not + normally shown in a document, so if script tags are to be removed, + their contents should be removed to. This is opposed to a b + tag, which defines some presentational changes but does not hide its + contents. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.Language.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.Language.txt new file mode 100644 index 0000000..ed1f39b --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.Language.txt @@ -0,0 +1,10 @@ +Core.Language +TYPE: string +VERSION: 2.0.0 +DEFAULT: 'en' +--DESCRIPTION-- + +ISO 639 language code for localizable things in HTML Purifier to use, +which is mainly error reporting. There is currently only an English (en) +translation, so this directive is currently useless. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.LegacyEntityDecoder.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.LegacyEntityDecoder.txt new file mode 100644 index 0000000..81d9ae4 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.LegacyEntityDecoder.txt @@ -0,0 +1,36 @@ +Core.LegacyEntityDecoder +TYPE: bool +VERSION: 4.9.0 +DEFAULT: false +--DESCRIPTION-- +

        + Prior to HTML Purifier 4.9.0, entities were decoded by performing + a global search replace for all entities whose decoded versions + did not have special meanings under HTML, and replaced them with + their decoded versions. We would match all entities, even if they did + not have a trailing semicolon, but only if there weren't any trailing + alphanumeric characters. +

        + + + + + + +
        OriginalTextAttribute
        &yen;¥¥
        &yen¥¥
        &yena&yena&yena
        &yen=¥=¥=
        +

        + In HTML Purifier 4.9.0, we changed the behavior of entity parsing + to match entities that had missing trailing semicolons in less + cases, to more closely match HTML5 parsing behavior: +

        + + + + + + +
        OriginalTextAttribute
        &yen;¥¥
        &yen¥¥
        &yena¥a&yena
        &yen=¥=&yen=
        +

        + This flag reverts back to pre-HTML Purifier 4.9.0 behavior. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt new file mode 100644 index 0000000..e11c015 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt @@ -0,0 +1,34 @@ +Core.LexerImpl +TYPE: mixed/null +VERSION: 2.0.0 +DEFAULT: NULL +--DESCRIPTION-- + +

        + This parameter determines what lexer implementation can be used. The + valid values are: +

        +
        +
        null
        +
        + Recommended, the lexer implementation will be auto-detected based on + your PHP-version and configuration. +
        +
        string lexer identifier
        +
        + This is a slim way of manually overridding the implementation. + Currently recognized values are: DOMLex (the default PHP5 +implementation) + and DirectLex (the default PHP4 implementation). Only use this if + you know what you are doing: usually, the auto-detection will + manage things for cases you aren't even aware of. +
        +
        object lexer instance
        +
        + Super-advanced: you can specify your own, custom, implementation that + implements the interface defined by HTMLPurifier_Lexer. + I may remove this option simply because I don't expect anyone + to use it. +
        +
        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt new file mode 100644 index 0000000..838f10f --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt @@ -0,0 +1,16 @@ +Core.MaintainLineNumbers +TYPE: bool/null +VERSION: 2.0.0 +DEFAULT: NULL +--DESCRIPTION-- + +

        + If true, HTML Purifier will add line number information to all tokens. + This is useful when error reporting is turned on, but can result in + significant performance degradation and should not be used when + unnecessary. This directive must be used with the DirectLex lexer, + as the DOMLex lexer does not (yet) support this functionality. + If the value is null, an appropriate value will be selected based + on other configuration. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.NormalizeNewlines.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.NormalizeNewlines.txt new file mode 100644 index 0000000..94a8860 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.NormalizeNewlines.txt @@ -0,0 +1,11 @@ +Core.NormalizeNewlines +TYPE: bool +VERSION: 4.2.0 +DEFAULT: true +--DESCRIPTION-- +

        + Whether or not to normalize newlines to the operating + system default. When false, HTML Purifier + will attempt to preserve mixed newline files. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt new file mode 100644 index 0000000..704ac56 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt @@ -0,0 +1,12 @@ +Core.RemoveInvalidImg +TYPE: bool +DEFAULT: true +VERSION: 1.3.0 +--DESCRIPTION-- + +

        + This directive enables pre-emptive URI checking in img + tags, as the attribute validation strategy is not authorized to + remove elements from the document. Revert to pre-1.3.0 behavior by setting to false. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveProcessingInstructions.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveProcessingInstructions.txt new file mode 100644 index 0000000..ed6f134 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveProcessingInstructions.txt @@ -0,0 +1,11 @@ +Core.RemoveProcessingInstructions +TYPE: bool +VERSION: 4.2.0 +DEFAULT: false +--DESCRIPTION-- +Instead of escaping processing instructions in the form <? ... +?>, remove it out-right. This may be useful if the HTML +you are validating contains XML processing instruction gunk, however, +it can also be user-unfriendly for people attempting to post PHP +snippets. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt new file mode 100644 index 0000000..efbe994 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt @@ -0,0 +1,12 @@ +Core.RemoveScriptContents +TYPE: bool/null +DEFAULT: NULL +VERSION: 2.0.0 +DEPRECATED-VERSION: 2.1.0 +DEPRECATED-USE: Core.HiddenElements +--DESCRIPTION-- +

        + This directive enables HTML Purifier to remove not only script tags + but all of their contents. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt new file mode 100644 index 0000000..861ae66 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt @@ -0,0 +1,11 @@ +Filter.Custom +TYPE: list +VERSION: 3.1.0 +DEFAULT: array() +--DESCRIPTION-- +

        + This directive can be used to add custom filters; it is nearly the + equivalent of the now deprecated HTMLPurifier->addFilter() + method. Specify an array of concrete implementations. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt new file mode 100644 index 0000000..6960263 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt @@ -0,0 +1,14 @@ +Filter.ExtractStyleBlocks.Escaping +TYPE: bool +VERSION: 3.0.0 +DEFAULT: true +ALIASES: Filter.ExtractStyleBlocksEscaping, FilterParam.ExtractStyleBlocksEscaping +--DESCRIPTION-- + +

        + Whether or not to escape the dangerous characters <, > and & + as \3C, \3E and \26, respectively. This is can be safely set to false + if the contents of StyleBlocks will be placed in an external stylesheet, + where there is no risk of it being interpreted as HTML. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt new file mode 100644 index 0000000..baa81ae --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt @@ -0,0 +1,29 @@ +Filter.ExtractStyleBlocks.Scope +TYPE: string/null +VERSION: 3.0.0 +DEFAULT: NULL +ALIASES: Filter.ExtractStyleBlocksScope, FilterParam.ExtractStyleBlocksScope +--DESCRIPTION-- + +

        + If you would like users to be able to define external stylesheets, but + only allow them to specify CSS declarations for a specific node and + prevent them from fiddling with other elements, use this directive. + It accepts any valid CSS selector, and will prepend this to any + CSS declaration extracted from the document. For example, if this + directive is set to #user-content and a user uses the + selector a:hover, the final selector will be + #user-content a:hover. +

        +

        + The comma shorthand may be used; consider the above example, with + #user-content, #user-content2, the final selector will + be #user-content a:hover, #user-content2 a:hover. +

        +

        + Warning: It is possible for users to bypass this measure + using a naughty + selector. This is a bug in CSS Tidy 1.3, not HTML + Purifier, and I am working to get it fixed. Until then, HTML Purifier + performs a basic check to prevent this. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt new file mode 100644 index 0000000..3b70189 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt @@ -0,0 +1,16 @@ +Filter.ExtractStyleBlocks.TidyImpl +TYPE: mixed/null +VERSION: 3.1.0 +DEFAULT: NULL +ALIASES: FilterParam.ExtractStyleBlocksTidyImpl +--DESCRIPTION-- +

        + If left NULL, HTML Purifier will attempt to instantiate a csstidy + class to use for internal cleaning. This will usually be good enough. +

        +

        + However, for trusted user input, you can set this to false to + disable cleaning. In addition, you can supply your own concrete implementation + of Tidy's interface to use, although I don't know why you'd want to do that. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt new file mode 100644 index 0000000..be0177d --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt @@ -0,0 +1,74 @@ +Filter.ExtractStyleBlocks +TYPE: bool +VERSION: 3.1.0 +DEFAULT: false +EXTERNAL: CSSTidy +--DESCRIPTION-- +

        + This directive turns on the style block extraction filter, which removes + style blocks from input HTML, cleans them up with CSSTidy, + and places them in the StyleBlocks context variable, for further + use by you, usually to be placed in an external stylesheet, or a + style block in the head of your document. +

        +

        + Sample usage: +

        +
        ';
        +?>
        +
        +
        +
        +  Filter.ExtractStyleBlocks
        +body {color:#F00;} Some text';
        +
        +    $config = HTMLPurifier_Config::createDefault();
        +    $config->set('Filter', 'ExtractStyleBlocks', true);
        +    $purifier = new HTMLPurifier($config);
        +
        +    $html = $purifier->purify($dirty);
        +
        +    // This implementation writes the stylesheets to the styles/ directory.
        +    // You can also echo the styles inside the document, but it's a bit
        +    // more difficult to make sure they get interpreted properly by
        +    // browsers; try the usual CSS armoring techniques.
        +    $styles = $purifier->context->get('StyleBlocks');
        +    $dir = 'styles/';
        +    if (!is_dir($dir)) mkdir($dir);
        +    $hash = sha1($_GET['html']);
        +    foreach ($styles as $i => $style) {
        +        file_put_contents($name = $dir . $hash . "_$i");
        +        echo '';
        +    }
        +?>
        +
        +
        +  
        + +
        + + +]]>
        +

        + Warning: It is possible for a user to mount an + imagecrash attack using this CSS. Counter-measures are difficult; + it is not simply enough to limit the range of CSS lengths (using + relative lengths with many nesting levels allows for large values + to be attained without actually specifying them in the stylesheet), + and the flexible nature of selectors makes it difficult to selectively + disable lengths on image tags (HTML Purifier, however, does disable + CSS width and height in inline styling). There are probably two effective + counter measures: an explicit width and height set to auto in all + images in your document (unlikely) or the disabling of width and + height (somewhat reasonable). Whether or not these measures should be + used is left to the reader. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt new file mode 100644 index 0000000..8822186 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt @@ -0,0 +1,16 @@ +Filter.YouTube +TYPE: bool +VERSION: 3.1.0 +DEFAULT: false +--DESCRIPTION-- +

        + Warning: Deprecated in favor of %HTML.SafeObject and + %Output.FlashCompat (turn both on to allow YouTube videos and other + Flash content). +

        +

        + This directive enables YouTube video embedding in HTML Purifier. Check + this document + on embedding videos for more information on what this filter does. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt new file mode 100644 index 0000000..afd48a0 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt @@ -0,0 +1,25 @@ +HTML.Allowed +TYPE: itext/null +VERSION: 2.0.0 +DEFAULT: NULL +--DESCRIPTION-- + +

        + This is a preferred convenience directive that combines + %HTML.AllowedElements and %HTML.AllowedAttributes. + Specify elements and attributes that are allowed using: + element1[attr1|attr2],element2.... For example, + if you would like to only allow paragraphs and links, specify + a[href],p. You can specify attributes that apply + to all elements using an asterisk, e.g. *[lang]. + You can also use newlines instead of commas to separate elements. +

        +

        + Warning: + All of the constraints on the component directives are still enforced. + The syntax is a subset of TinyMCE's valid_elements + whitelist: directly copy-pasting it here will probably result in + broken whitelists. If %HTML.AllowedElements or %HTML.AllowedAttributes + are set, this directive has no effect. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt new file mode 100644 index 0000000..0e6ec54 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt @@ -0,0 +1,19 @@ +HTML.AllowedAttributes +TYPE: lookup/null +VERSION: 1.3.0 +DEFAULT: NULL +--DESCRIPTION-- + +

        + If HTML Purifier's attribute set is unsatisfactory, overload it! + The syntax is "tag.attr" or "*.attr" for the global attributes + (style, id, class, dir, lang, xml:lang). +

        +

        + Warning: If another directive conflicts with the + elements here, that directive will win and override. For + example, %HTML.EnableAttrID will take precedence over *.id in this + directive. You must set that directive to true before you can use + IDs at all. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedComments.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedComments.txt new file mode 100644 index 0000000..8440bc3 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedComments.txt @@ -0,0 +1,10 @@ +HTML.AllowedComments +TYPE: lookup +VERSION: 4.4.0 +DEFAULT: array() +--DESCRIPTION-- +A whitelist which indicates what explicit comment bodies should be +allowed, modulo leading and trailing whitespace. See also %HTML.AllowedCommentsRegexp +(these directives are union'ed together, so a comment is considered +valid if any directive deems it valid.) +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedCommentsRegexp.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedCommentsRegexp.txt new file mode 100644 index 0000000..b1e65be --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedCommentsRegexp.txt @@ -0,0 +1,15 @@ +HTML.AllowedCommentsRegexp +TYPE: string/null +VERSION: 4.4.0 +DEFAULT: NULL +--DESCRIPTION-- +A regexp, which if it matches the body of a comment, indicates that +it should be allowed. Trailing and leading spaces are removed prior +to running this regular expression. +Warning: Make sure you specify +correct anchor metacharacters ^regex$, otherwise you may accept +comments that you did not mean to! In particular, the regex /foo|bar/ +is probably not sufficiently strict, since it also allows foobar. +See also %HTML.AllowedComments (these directives are union'ed together, +so a comment is considered valid if any directive deems it valid.) +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt new file mode 100644 index 0000000..ca3c13d --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt @@ -0,0 +1,23 @@ +HTML.AllowedElements +TYPE: lookup/null +VERSION: 1.3.0 +DEFAULT: NULL +--DESCRIPTION-- +

        + If HTML Purifier's tag set is unsatisfactory for your needs, you can + overload it with your own list of tags to allow. If you change + this, you probably also want to change %HTML.AllowedAttributes; see + also %HTML.Allowed which lets you set allowed elements and + attributes at the same time. +

        +

        + If you attempt to allow an element that HTML Purifier does not know + about, HTML Purifier will raise an error. You will need to manually + tell HTML Purifier about this element by using the + advanced customization features. +

        +

        + Warning: If another directive conflicts with the + elements here, that directive will win and override. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt new file mode 100644 index 0000000..e373791 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt @@ -0,0 +1,20 @@ +HTML.AllowedModules +TYPE: lookup/null +VERSION: 2.0.0 +DEFAULT: NULL +--DESCRIPTION-- + +

        + A doctype comes with a set of usual modules to use. Without having + to mucking about with the doctypes, you can quickly activate or + disable these modules by specifying which modules you wish to allow + with this directive. This is most useful for unit testing specific + modules, although end users may find it useful for their own ends. +

        +

        + If you specify a module that does not exist, the manager will silently + fail to use it, so be careful! User-defined modules are not affected + by this directive. Modules defined in %HTML.CoreModules are not + affected by this directive. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt new file mode 100644 index 0000000..75d680e --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt @@ -0,0 +1,11 @@ +HTML.Attr.Name.UseCDATA +TYPE: bool +DEFAULT: false +VERSION: 4.0.0 +--DESCRIPTION-- +The W3C specification DTD defines the name attribute to be CDATA, not ID, due +to limitations of DTD. In certain documents, this relaxed behavior is desired, +whether it is to specify duplicate names, or to specify names that would be +illegal IDs (for example, names that begin with a digit.) Set this configuration +directive to true to use the relaxed parsing rules. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt new file mode 100644 index 0000000..f32b802 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt @@ -0,0 +1,18 @@ +HTML.BlockWrapper +TYPE: string +VERSION: 1.3.0 +DEFAULT: 'p' +--DESCRIPTION-- + +

        + String name of element to wrap inline elements that are inside a block + context. This only occurs in the children of blockquote in strict mode. +

        +

        + Example: by default value, + <blockquote>Foo</blockquote> would become + <blockquote><p>Foo</p></blockquote>. + The <p> tags can be replaced with whatever you desire, + as long as it is a block level element. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt new file mode 100644 index 0000000..fc8e402 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt @@ -0,0 +1,23 @@ +HTML.CoreModules +TYPE: lookup +VERSION: 2.0.0 +--DEFAULT-- +array ( + 'Structure' => true, + 'Text' => true, + 'Hypertext' => true, + 'List' => true, + 'NonXMLCommonAttributes' => true, + 'XMLCommonAttributes' => true, + 'CommonAttributes' => true, +) +--DESCRIPTION-- + +

        + Certain modularized doctypes (XHTML, namely), have certain modules + that must be included for the doctype to be an conforming document + type: put those modules here. By default, XHTML's core modules + are used. You can set this to a blank array to disable core module + protection, but this is not recommended. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt new file mode 100644 index 0000000..187c0a0 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt @@ -0,0 +1,9 @@ +HTML.CustomDoctype +TYPE: string/null +VERSION: 2.0.1 +DEFAULT: NULL +--DESCRIPTION-- + +A custom doctype for power-users who defined their own document +type. This directive only applies when %HTML.Doctype is blank. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt new file mode 100644 index 0000000..f5433e3 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt @@ -0,0 +1,33 @@ +HTML.DefinitionID +TYPE: string/null +DEFAULT: NULL +VERSION: 2.0.0 +--DESCRIPTION-- + +

        + Unique identifier for a custom-built HTML definition. If you edit + the raw version of the HTMLDefinition, introducing changes that the + configuration object does not reflect, you must specify this variable. + If you change your custom edits, you should change this directive, or + clear your cache. Example: +

        +
        +$config = HTMLPurifier_Config::createDefault();
        +$config->set('HTML', 'DefinitionID', '1');
        +$def = $config->getHTMLDefinition();
        +$def->addAttribute('a', 'tabindex', 'Number');
        +
        +

        + In the above example, the configuration is still at the defaults, but + using the advanced API, an extra attribute has been added. The + configuration object normally has no way of knowing that this change + has taken place, so it needs an extra directive: %HTML.DefinitionID. + If someone else attempts to use the default configuration, these two + pieces of code will not clobber each other in the cache, since one has + an extra directive attached to it. +

        +

        + You must specify a value to this directive to use the + advanced API features. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt new file mode 100644 index 0000000..0bb5a71 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt @@ -0,0 +1,16 @@ +HTML.DefinitionRev +TYPE: int +VERSION: 2.0.0 +DEFAULT: 1 +--DESCRIPTION-- + +

        + Revision identifier for your custom definition specified in + %HTML.DefinitionID. This serves the same purpose: uniquely identifying + your custom definition, but this one does so in a chronological + context: revision 3 is more up-to-date then revision 2. Thus, when + this gets incremented, the cache handling is smart enough to clean + up any older revisions of your definition as well as flush the + cache. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt new file mode 100644 index 0000000..a6969b9 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt @@ -0,0 +1,11 @@ +HTML.Doctype +TYPE: string/null +DEFAULT: NULL +--DESCRIPTION-- +Doctype to use during filtering. Technically speaking this is not actually +a doctype (as it does not identify a corresponding DTD), but we are using +this name for sake of simplicity. When non-blank, this will override any +older directives like %HTML.XHTML or %HTML.Strict. +--ALLOWED-- +'HTML 4.01 Transitional', 'HTML 4.01 Strict', 'XHTML 1.0 Transitional', 'XHTML 1.0 Strict', 'XHTML 1.1' +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.FlashAllowFullScreen.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.FlashAllowFullScreen.txt new file mode 100644 index 0000000..08d641f --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.FlashAllowFullScreen.txt @@ -0,0 +1,11 @@ +HTML.FlashAllowFullScreen +TYPE: bool +VERSION: 4.2.0 +DEFAULT: false +--DESCRIPTION-- +

        + Whether or not to permit embedded Flash content from + %HTML.SafeObject to expand to the full screen. Corresponds to + the allowFullScreen parameter. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt new file mode 100644 index 0000000..2b8df97 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt @@ -0,0 +1,21 @@ +HTML.ForbiddenAttributes +TYPE: lookup +VERSION: 3.1.0 +DEFAULT: array() +--DESCRIPTION-- +

        + While this directive is similar to %HTML.AllowedAttributes, for + forwards-compatibility with XML, this attribute has a different syntax. Instead of + tag.attr, use tag@attr. To disallow href + attributes in a tags, set this directive to + a@href. You can also disallow an attribute globally with + attr or *@attr (either syntax is fine; the latter + is provided for consistency with %HTML.AllowedAttributes). +

        +

        + Warning: This directive complements %HTML.ForbiddenElements, + accordingly, check + out that directive for a discussion of why you + should think twice before using this directive. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt new file mode 100644 index 0000000..40466c4 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt @@ -0,0 +1,20 @@ +HTML.ForbiddenElements +TYPE: lookup +VERSION: 3.1.0 +DEFAULT: array() +--DESCRIPTION-- +

        + This was, perhaps, the most requested feature ever in HTML + Purifier. Please don't abuse it! This is the logical inverse of + %HTML.AllowedElements, and it will override that directive, or any + other directive. +

        +

        + If possible, %HTML.Allowed is recommended over this directive, because it + can sometimes be difficult to tell whether or not you've forbidden all of + the behavior you would like to disallow. If you forbid img + with the expectation of preventing images on your site, you'll be in for + a nasty surprise when people start using the background-image + CSS property. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt new file mode 100644 index 0000000..3197479 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt @@ -0,0 +1,14 @@ +HTML.MaxImgLength +TYPE: int/null +DEFAULT: 1200 +VERSION: 3.1.1 +--DESCRIPTION-- +

        + This directive controls the maximum number of pixels in the width and + height attributes in img tags. This is + in place to prevent imagecrash attacks, disable with null at your own risk. + This directive is similar to %CSS.MaxImgLength, and both should be + concurrently edited, although there are + subtle differences in the input format (the HTML max is an integer). +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Nofollow.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Nofollow.txt new file mode 100644 index 0000000..7aa3563 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Nofollow.txt @@ -0,0 +1,7 @@ +HTML.Nofollow +TYPE: bool +VERSION: 4.3.0 +DEFAULT: FALSE +--DESCRIPTION-- +If enabled, nofollow rel attributes are added to all outgoing links. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt new file mode 100644 index 0000000..2d2fbd1 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt @@ -0,0 +1,12 @@ +HTML.Parent +TYPE: string +VERSION: 1.3.0 +DEFAULT: 'div' +--DESCRIPTION-- + +

        + String name of element that HTML fragment passed to library will be + inserted in. An interesting variation would be using span as the + parent element, meaning that only inline tags would be allowed. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt new file mode 100644 index 0000000..b3c45e1 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt @@ -0,0 +1,12 @@ +HTML.Proprietary +TYPE: bool +VERSION: 3.1.0 +DEFAULT: false +--DESCRIPTION-- +

        + Whether or not to allow proprietary elements and attributes in your + documents, as per HTMLPurifier_HTMLModule_Proprietary. + Warning: This can cause your documents to stop + validating! +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt new file mode 100644 index 0000000..556fa67 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt @@ -0,0 +1,13 @@ +HTML.SafeEmbed +TYPE: bool +VERSION: 3.1.1 +DEFAULT: false +--DESCRIPTION-- +

        + Whether or not to permit embed tags in documents, with a number of extra + security features added to prevent script execution. This is similar to + what websites like MySpace do to embed tags. Embed is a proprietary + element and will cause your website to stop validating; you should + see if you can use %Output.FlashCompat with %HTML.SafeObject instead + first.

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeIframe.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeIframe.txt new file mode 100644 index 0000000..295a8cf --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeIframe.txt @@ -0,0 +1,13 @@ +HTML.SafeIframe +TYPE: bool +VERSION: 4.4.0 +DEFAULT: false +--DESCRIPTION-- +

        + Whether or not to permit iframe tags in untrusted documents. This + directive must be accompanied by a whitelist of permitted iframes, + such as %URI.SafeIframeRegexp, otherwise it will fatally error. + This directive has no effect on strict doctypes, as iframes are not + valid. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt new file mode 100644 index 0000000..07f6e53 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt @@ -0,0 +1,13 @@ +HTML.SafeObject +TYPE: bool +VERSION: 3.1.1 +DEFAULT: false +--DESCRIPTION-- +

        + Whether or not to permit object tags in documents, with a number of extra + security features added to prevent script execution. This is similar to + what websites like MySpace do to object tags. You should also enable + %Output.FlashCompat in order to generate Internet Explorer + compatibility code for your object tags. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeScripting.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeScripting.txt new file mode 100644 index 0000000..641b4a8 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeScripting.txt @@ -0,0 +1,10 @@ +HTML.SafeScripting +TYPE: lookup +VERSION: 4.5.0 +DEFAULT: array() +--DESCRIPTION-- +

        + Whether or not to permit script tags to external scripts in documents. + Inline scripting is not allowed, and the script must match an explicit whitelist. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt new file mode 100644 index 0000000..d99663a --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt @@ -0,0 +1,9 @@ +HTML.Strict +TYPE: bool +VERSION: 1.3.0 +DEFAULT: false +DEPRECATED-VERSION: 1.7.0 +DEPRECATED-USE: HTML.Doctype +--DESCRIPTION-- +Determines whether or not to use Transitional (loose) or Strict rulesets. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetBlank.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetBlank.txt new file mode 100644 index 0000000..d65f0d0 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetBlank.txt @@ -0,0 +1,8 @@ +HTML.TargetBlank +TYPE: bool +VERSION: 4.4.0 +DEFAULT: FALSE +--DESCRIPTION-- +If enabled, target=blank attributes are added to all outgoing links. +(This includes links from an HTTPS version of a page to an HTTP version.) +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoopener.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoopener.txt new file mode 100644 index 0000000..05cb342 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoopener.txt @@ -0,0 +1,10 @@ +--# vim: et sw=4 sts=4 +HTML.TargetNoopener +TYPE: bool +VERSION: 4.8.0 +DEFAULT: TRUE +--DESCRIPTION-- +If enabled, noopener rel attributes are added to links which have +a target attribute associated with them. This prevents malicious +destinations from overwriting the original window. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoreferrer.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoreferrer.txt new file mode 100644 index 0000000..993a817 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoreferrer.txt @@ -0,0 +1,9 @@ +HTML.TargetNoreferrer +TYPE: bool +VERSION: 4.8.0 +DEFAULT: TRUE +--DESCRIPTION-- +If enabled, noreferrer rel attributes are added to links which have +a target attribute associated with them. This prevents malicious +destinations from overwriting the original window. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt new file mode 100644 index 0000000..602453f --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt @@ -0,0 +1,8 @@ +HTML.TidyAdd +TYPE: lookup +VERSION: 2.0.0 +DEFAULT: array() +--DESCRIPTION-- + +Fixes to add to the default set of Tidy fixes as per your level. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt new file mode 100644 index 0000000..bf943e8 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt @@ -0,0 +1,24 @@ +HTML.TidyLevel +TYPE: string +VERSION: 2.0.0 +DEFAULT: 'medium' +--DESCRIPTION-- + +

        General level of cleanliness the Tidy module should enforce. +There are four allowed values:

        +
        +
        none
        +
        No extra tidying should be done
        +
        light
        +
        Only fix elements that would be discarded otherwise due to + lack of support in doctype
        +
        medium
        +
        Enforce best practices
        +
        heavy
        +
        Transform all deprecated elements and attributes to standards + compliant equivalents
        +
        + +--ALLOWED-- +'none', 'light', 'medium', 'heavy' +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt new file mode 100644 index 0000000..92cca2a --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt @@ -0,0 +1,8 @@ +HTML.TidyRemove +TYPE: lookup +VERSION: 2.0.0 +DEFAULT: array() +--DESCRIPTION-- + +Fixes to remove from the default set of Tidy fixes as per your level. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt new file mode 100644 index 0000000..bc8e654 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt @@ -0,0 +1,9 @@ +HTML.Trusted +TYPE: bool +VERSION: 2.0.0 +DEFAULT: false +--DESCRIPTION-- +Indicates whether or not the user input is trusted or not. If the input is +trusted, a more expansive set of allowed tags and attributes will be used. +See also %CSS.Trusted. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt new file mode 100644 index 0000000..a3c2f42 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt @@ -0,0 +1,11 @@ +HTML.XHTML +TYPE: bool +DEFAULT: true +VERSION: 1.1.0 +DEPRECATED-VERSION: 1.7.0 +DEPRECATED-USE: HTML.Doctype +--DESCRIPTION-- +Determines whether or not output is XHTML 1.0 or HTML 4.01 flavor. +--ALIASES-- +Core.XHTML +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt new file mode 100644 index 0000000..2a13704 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt @@ -0,0 +1,10 @@ +Output.CommentScriptContents +TYPE: bool +VERSION: 2.0.0 +DEFAULT: true +--DESCRIPTION-- +Determines whether or not HTML Purifier should attempt to fix up the +contents of script tags for legacy browsers with comments. +--ALIASES-- +Core.CommentScriptContents +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.FixInnerHTML.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.FixInnerHTML.txt new file mode 100644 index 0000000..d215ba2 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.FixInnerHTML.txt @@ -0,0 +1,15 @@ +Output.FixInnerHTML +TYPE: bool +VERSION: 4.3.0 +DEFAULT: true +--DESCRIPTION-- +

        + If true, HTML Purifier will protect against Internet Explorer's + mishandling of the innerHTML attribute by appending + a space to any attribute that does not contain angled brackets, spaces + or quotes, but contains a backtick. This slightly changes the + semantics of any given attribute, so if this is unacceptable and + you do not use innerHTML on any of your pages, you can + turn this directive off. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.FlashCompat.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.FlashCompat.txt new file mode 100644 index 0000000..e58f91a --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.FlashCompat.txt @@ -0,0 +1,11 @@ +Output.FlashCompat +TYPE: bool +VERSION: 4.1.0 +DEFAULT: false +--DESCRIPTION-- +

        + If true, HTML Purifier will generate Internet Explorer compatibility + code for all object code. This is highly recommended if you enable + %HTML.SafeObject. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt new file mode 100644 index 0000000..4bb9025 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt @@ -0,0 +1,13 @@ +Output.Newline +TYPE: string/null +VERSION: 2.0.1 +DEFAULT: NULL +--DESCRIPTION-- + +

        + Newline string to format final output with. If left null, HTML Purifier + will auto-detect the default newline type of the system and use that; + you can manually override it here. Remember, \r\n is Windows, \r + is Mac, and \n is Unix. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt new file mode 100644 index 0000000..3223106 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt @@ -0,0 +1,14 @@ +Output.SortAttr +TYPE: bool +VERSION: 3.2.0 +DEFAULT: false +--DESCRIPTION-- +

        + If true, HTML Purifier will sort attributes by name before writing them back + to the document, converting a tag like: <el b="" a="" c="" /> + to <el a="" b="" c="" />. This is a workaround for + a bug in FCKeditor which causes it to swap attributes order, adding noise + to text diffs. If you're not seeing this bug, chances are, you don't need + this directive. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt new file mode 100644 index 0000000..23dd4d3 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt @@ -0,0 +1,25 @@ +Output.TidyFormat +TYPE: bool +VERSION: 1.1.1 +DEFAULT: false +--DESCRIPTION-- +

        + Determines whether or not to run Tidy on the final output for pretty + formatting reasons, such as indentation and wrap. +

        +

        + This can greatly improve readability for editors who are hand-editing + the HTML, but is by no means necessary as HTML Purifier has already + fixed all major errors the HTML may have had. Tidy is a non-default + extension, and this directive will silently fail if Tidy is not + available. +

        +

        + If you are looking to make the overall look of your page's source + better, I recommend running Tidy on the entire page rather than just + user-content (after all, the indentation relative to the containing + blocks will be incorrect). +

        +--ALIASES-- +Core.TidyFormat +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt new file mode 100644 index 0000000..d1820cd --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt @@ -0,0 +1,7 @@ +Test.ForceNoIconv +TYPE: bool +DEFAULT: false +--DESCRIPTION-- +When set to true, HTMLPurifier_Encoder will act as if iconv does not exist +and use only pure PHP implementations. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt new file mode 100644 index 0000000..0b0533a --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt @@ -0,0 +1,18 @@ +URI.AllowedSchemes +TYPE: lookup +--DEFAULT-- +array ( + 'http' => true, + 'https' => true, + 'mailto' => true, + 'ftp' => true, + 'nntp' => true, + 'news' => true, + 'tel' => true, +) +--DESCRIPTION-- +Whitelist that defines the schemes that a URI is allowed to have. This +prevents XSS attacks from using pseudo-schemes like javascript or mocha. +There is also support for the data and file +URI schemes, but they are not enabled by default. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Base.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Base.txt new file mode 100644 index 0000000..ba47308 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Base.txt @@ -0,0 +1,17 @@ +URI.Base +TYPE: string/null +VERSION: 2.1.0 +DEFAULT: NULL +--DESCRIPTION-- + +

        + The base URI is the URI of the document this purified HTML will be + inserted into. This information is important if HTML Purifier needs + to calculate absolute URIs from relative URIs, such as when %URI.MakeAbsolute + is on. You may use a non-absolute URI for this value, but behavior + may vary (%URI.MakeAbsolute deals nicely with both absolute and + relative paths, but forwards-compatibility is not guaranteed). + Warning: If set, the scheme on this URI + overrides the one specified by %URI.DefaultScheme. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt new file mode 100644 index 0000000..981e443 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt @@ -0,0 +1,15 @@ +URI.DefaultScheme +TYPE: string/null +DEFAULT: 'http' +--DESCRIPTION-- + +

        + Defines through what scheme the output will be served, in order to + select the proper object validator when no scheme information is present. +

        + +

        + Starting with HTML Purifier 4.9.0, the default scheme can be null, in + which case we reject all URIs which do not have explicit schemes. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt new file mode 100644 index 0000000..523204c --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt @@ -0,0 +1,11 @@ +URI.DefinitionID +TYPE: string/null +VERSION: 2.1.0 +DEFAULT: NULL +--DESCRIPTION-- + +

        + Unique identifier for a custom-built URI definition. If you want + to add custom URIFilters, you must specify this value. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt new file mode 100644 index 0000000..a9c07b1 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt @@ -0,0 +1,11 @@ +URI.DefinitionRev +TYPE: int +VERSION: 2.1.0 +DEFAULT: 1 +--DESCRIPTION-- + +

        + Revision identifier for your custom definition. See + %HTML.DefinitionRev for details. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt new file mode 100644 index 0000000..b19ca1d --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt @@ -0,0 +1,14 @@ +URI.Disable +TYPE: bool +VERSION: 1.3.0 +DEFAULT: false +--DESCRIPTION-- + +

        + Disables all URIs in all forms. Not sure why you'd want to do that + (after all, the Internet's founded on the notion of a hyperlink). +

        + +--ALIASES-- +Attr.DisableURI +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt new file mode 100644 index 0000000..9132ea4 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt @@ -0,0 +1,11 @@ +URI.DisableExternal +TYPE: bool +VERSION: 1.2.0 +DEFAULT: false +--DESCRIPTION-- +Disables links to external websites. This is a highly effective anti-spam +and anti-pagerank-leech measure, but comes at a hefty price: nolinks or +images outside of your domain will be allowed. Non-linkified URIs will +still be preserved. If you want to be able to link to subdomains or use +absolute URIs, specify %URI.Host for your website. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt new file mode 100644 index 0000000..d74bc1e --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt @@ -0,0 +1,13 @@ +URI.DisableExternalResources +TYPE: bool +VERSION: 1.3.0 +DEFAULT: false +--DESCRIPTION-- +Disables the embedding of external resources, preventing users from +embedding things like images from other hosts. This prevents access +tracking (good for email viewers), bandwidth leeching, cross-site request +forging, goatse.cx posting, and other nasties, but also results in a loss +of end-user functionality (they can't directly post a pic they posted from +Flickr anymore). Use it if you don't have a robust user-content moderation +team. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt new file mode 100644 index 0000000..6c10614 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt @@ -0,0 +1,15 @@ +URI.DisableResources +TYPE: bool +VERSION: 4.2.0 +DEFAULT: false +--DESCRIPTION-- +

        + Disables embedding resources, essentially meaning no pictures. You can + still link to them though. See %URI.DisableExternalResources for why + this might be a good idea. +

        +

        + Note: While this directive has been available since 1.3.0, + it didn't actually start doing anything until 4.2.0. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Host.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Host.txt new file mode 100644 index 0000000..ba0e6bc --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Host.txt @@ -0,0 +1,19 @@ +URI.Host +TYPE: string/null +VERSION: 1.2.0 +DEFAULT: NULL +--DESCRIPTION-- + +

        + Defines the domain name of the server, so we can determine whether or + an absolute URI is from your website or not. Not strictly necessary, + as users should be using relative URIs to reference resources on your + website. It will, however, let you use absolute URIs to link to + subdomains of the domain you post here: i.e. example.com will allow + sub.example.com. However, higher up domains will still be excluded: + if you set %URI.Host to sub.example.com, example.com will be blocked. + Note: This directive overrides %URI.Base because + a given page may be on a sub-domain, but you wish HTML Purifier to be + more relaxed and allow some of the parent domains too. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt new file mode 100644 index 0000000..825fef2 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt @@ -0,0 +1,9 @@ +URI.HostBlacklist +TYPE: list +VERSION: 1.3.0 +DEFAULT: array() +--DESCRIPTION-- +List of strings that are forbidden in the host of any URI. Use it to kill +domain names of spam, etc. Note that it will catch anything in the domain, +so moo.com will catch moo.com.example.com. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt new file mode 100644 index 0000000..eb58c7f --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt @@ -0,0 +1,13 @@ +URI.MakeAbsolute +TYPE: bool +VERSION: 2.1.0 +DEFAULT: false +--DESCRIPTION-- + +

        + Converts all URIs into absolute forms. This is useful when the HTML + being filtered assumes a specific base path, but will actually be + viewed in a different context (and setting an alternate base URI is + not possible). %URI.Base must be set for this directive to work. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt new file mode 100644 index 0000000..bedd610 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt @@ -0,0 +1,83 @@ +URI.Munge +TYPE: string/null +VERSION: 1.3.0 +DEFAULT: NULL +--DESCRIPTION-- + +

        + Munges all browsable (usually http, https and ftp) + absolute URIs into another URI, usually a URI redirection service. + This directive accepts a URI, formatted with a %s where + the url-encoded original URI should be inserted (sample: + http://www.google.com/url?q=%s). +

        +

        + Uses for this directive: +

        +
          +
        • + Prevent PageRank leaks, while being fairly transparent + to users (you may also want to add some client side JavaScript to + override the text in the statusbar). Notice: + Many security experts believe that this form of protection does not deter spam-bots. +
        • +
        • + Redirect users to a splash page telling them they are leaving your + website. While this is poor usability practice, it is often mandated + in corporate environments. +
        • +
        +

        + Prior to HTML Purifier 3.1.1, this directive also enabled the munging + of browsable external resources, which could break things if your redirection + script was a splash page or used meta tags. To revert to + previous behavior, please use %URI.MungeResources. +

        +

        + You may want to also use %URI.MungeSecretKey along with this directive + in order to enforce what URIs your redirector script allows. Open + redirector scripts can be a security risk and negatively affect the + reputation of your domain name. +

        +

        + Starting with HTML Purifier 3.1.1, there is also these substitutions: +

        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        KeyDescriptionExample <a href="">
        %r1 - The URI embeds a resource
        (blank) - The URI is merely a link
        %nThe name of the tag this URI came froma
        %mThe name of the attribute this URI came fromhref
        %pThe name of the CSS property this URI came from, or blank if irrelevant
        +

        + Admittedly, these letters are somewhat arbitrary; the only stipulation + was that they couldn't be a through f. r is for resource (I would have preferred + e, but you take what you can get), n is for name, m + was picked because it came after n (and I couldn't use a), p is for + property. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt new file mode 100644 index 0000000..ed4b5b0 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt @@ -0,0 +1,17 @@ +URI.MungeResources +TYPE: bool +VERSION: 3.1.1 +DEFAULT: false +--DESCRIPTION-- +

        + If true, any URI munging directives like %URI.Munge + will also apply to embedded resources, such as <img src="">. + Be careful enabling this directive if you have a redirector script + that does not use the Location HTTP header; all of your images + and other embedded resources will break. +

        +

        + Warning: It is strongly advised you use this in conjunction + %URI.MungeSecretKey to mitigate the security risk of an open redirector. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt new file mode 100644 index 0000000..123b6e2 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt @@ -0,0 +1,30 @@ +URI.MungeSecretKey +TYPE: string/null +VERSION: 3.1.1 +DEFAULT: NULL +--DESCRIPTION-- +

        + This directive enables secure checksum generation along with %URI.Munge. + It should be set to a secure key that is not shared with anyone else. + The checksum can be placed in the URI using %t. Use of this checksum + affords an additional level of protection by allowing a redirector + to check if a URI has passed through HTML Purifier with this line: +

        + +
        $checksum === hash_hmac("sha256", $url, $secret_key)
        + +

        + If the output is TRUE, the redirector script should accept the URI. +

        + +

        + Please note that it would still be possible for an attacker to procure + secure hashes en-mass by abusing your website's Preview feature or the + like, but this service affords an additional level of protection + that should be combined with website blacklisting. +

        + +

        + Remember this has no effect if %URI.Munge is not on. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt new file mode 100644 index 0000000..8b387de --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt @@ -0,0 +1,9 @@ +URI.OverrideAllowedSchemes +TYPE: bool +DEFAULT: true +--DESCRIPTION-- +If this is set to true (which it is by default), you can override +%URI.AllowedSchemes by simply registering a HTMLPurifier_URIScheme to the +registry. If false, you will also have to update that directive in order +to add more schemes. +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.SafeIframeRegexp.txt b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.SafeIframeRegexp.txt new file mode 100644 index 0000000..7e1f227 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.SafeIframeRegexp.txt @@ -0,0 +1,22 @@ +URI.SafeIframeRegexp +TYPE: string/null +VERSION: 4.4.0 +DEFAULT: NULL +--DESCRIPTION-- +

        + A PCRE regular expression that will be matched against an iframe URI. This is + a relatively inflexible scheme, but works well enough for the most common + use-case of iframes: embedded video. This directive only has an effect if + %HTML.SafeIframe is enabled. Here are some example values: +

        +
          +
        • %^http://www.youtube.com/embed/% - Allow YouTube videos
        • +
        • %^http://player.vimeo.com/video/% - Allow Vimeo videos
        • +
        • %^http://(www.youtube.com/embed/|player.vimeo.com/video/)% - Allow both
        • +
        +

        + Note that this directive does not give you enough granularity to, say, disable + all autoplay videos. Pipe up on the HTML Purifier forums if this + is a capability you want. +

        +--# vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/info.ini b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/info.ini new file mode 100644 index 0000000..58e0ce4 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/info.ini @@ -0,0 +1,3 @@ +name = "HTML Purifier" + +; vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/EntityLookup/entities.ser b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/EntityLookup/entities.ser new file mode 100644 index 0000000..e8b0812 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/EntityLookup/entities.ser @@ -0,0 +1 @@ +a:253:{s:4:"fnof";s:2:"Æ’";s:5:"Alpha";s:2:"Α";s:4:"Beta";s:2:"Î’";s:5:"Gamma";s:2:"Γ";s:5:"Delta";s:2:"Δ";s:7:"Epsilon";s:2:"Ε";s:4:"Zeta";s:2:"Ζ";s:3:"Eta";s:2:"Η";s:5:"Theta";s:2:"Θ";s:4:"Iota";s:2:"Ι";s:5:"Kappa";s:2:"Κ";s:6:"Lambda";s:2:"Λ";s:2:"Mu";s:2:"Μ";s:2:"Nu";s:2:"Î";s:2:"Xi";s:2:"Ξ";s:7:"Omicron";s:2:"Ο";s:2:"Pi";s:2:"Π";s:3:"Rho";s:2:"Ρ";s:5:"Sigma";s:2:"Σ";s:3:"Tau";s:2:"Τ";s:7:"Upsilon";s:2:"Î¥";s:3:"Phi";s:2:"Φ";s:3:"Chi";s:2:"Χ";s:3:"Psi";s:2:"Ψ";s:5:"Omega";s:2:"Ω";s:5:"alpha";s:2:"α";s:4:"beta";s:2:"β";s:5:"gamma";s:2:"γ";s:5:"delta";s:2:"δ";s:7:"epsilon";s:2:"ε";s:4:"zeta";s:2:"ζ";s:3:"eta";s:2:"η";s:5:"theta";s:2:"θ";s:4:"iota";s:2:"ι";s:5:"kappa";s:2:"κ";s:6:"lambda";s:2:"λ";s:2:"mu";s:2:"μ";s:2:"nu";s:2:"ν";s:2:"xi";s:2:"ξ";s:7:"omicron";s:2:"ο";s:2:"pi";s:2:"Ï€";s:3:"rho";s:2:"Ï";s:6:"sigmaf";s:2:"Ï‚";s:5:"sigma";s:2:"σ";s:3:"tau";s:2:"Ï„";s:7:"upsilon";s:2:"Ï…";s:3:"phi";s:2:"φ";s:3:"chi";s:2:"χ";s:3:"psi";s:2:"ψ";s:5:"omega";s:2:"ω";s:8:"thetasym";s:2:"Ï‘";s:5:"upsih";s:2:"Ï’";s:3:"piv";s:2:"Ï–";s:4:"bull";s:3:"•";s:6:"hellip";s:3:"…";s:5:"prime";s:3:"′";s:5:"Prime";s:3:"″";s:5:"oline";s:3:"‾";s:5:"frasl";s:3:"â„";s:6:"weierp";s:3:"℘";s:5:"image";s:3:"â„‘";s:4:"real";s:3:"ℜ";s:5:"trade";s:3:"â„¢";s:7:"alefsym";s:3:"ℵ";s:4:"larr";s:3:"â†";s:4:"uarr";s:3:"↑";s:4:"rarr";s:3:"→";s:4:"darr";s:3:"↓";s:4:"harr";s:3:"↔";s:5:"crarr";s:3:"↵";s:4:"lArr";s:3:"â‡";s:4:"uArr";s:3:"⇑";s:4:"rArr";s:3:"⇒";s:4:"dArr";s:3:"⇓";s:4:"hArr";s:3:"⇔";s:6:"forall";s:3:"∀";s:4:"part";s:3:"∂";s:5:"exist";s:3:"∃";s:5:"empty";s:3:"∅";s:5:"nabla";s:3:"∇";s:4:"isin";s:3:"∈";s:5:"notin";s:3:"∉";s:2:"ni";s:3:"∋";s:4:"prod";s:3:"âˆ";s:3:"sum";s:3:"∑";s:5:"minus";s:3:"−";s:6:"lowast";s:3:"∗";s:5:"radic";s:3:"√";s:4:"prop";s:3:"âˆ";s:5:"infin";s:3:"∞";s:3:"ang";s:3:"∠";s:3:"and";s:3:"∧";s:2:"or";s:3:"∨";s:3:"cap";s:3:"∩";s:3:"cup";s:3:"∪";s:3:"int";s:3:"∫";s:6:"there4";s:3:"∴";s:3:"sim";s:3:"∼";s:4:"cong";s:3:"≅";s:5:"asymp";s:3:"≈";s:2:"ne";s:3:"≠";s:5:"equiv";s:3:"≡";s:2:"le";s:3:"≤";s:2:"ge";s:3:"≥";s:3:"sub";s:3:"⊂";s:3:"sup";s:3:"⊃";s:4:"nsub";s:3:"⊄";s:4:"sube";s:3:"⊆";s:4:"supe";s:3:"⊇";s:5:"oplus";s:3:"⊕";s:6:"otimes";s:3:"⊗";s:4:"perp";s:3:"⊥";s:4:"sdot";s:3:"â‹…";s:5:"lceil";s:3:"⌈";s:5:"rceil";s:3:"⌉";s:6:"lfloor";s:3:"⌊";s:6:"rfloor";s:3:"⌋";s:4:"lang";s:3:"〈";s:4:"rang";s:3:"〉";s:3:"loz";s:3:"â—Š";s:6:"spades";s:3:"â™ ";s:5:"clubs";s:3:"♣";s:6:"hearts";s:3:"♥";s:5:"diams";s:3:"♦";s:4:"quot";s:1:""";s:3:"amp";s:1:"&";s:2:"lt";s:1:"<";s:2:"gt";s:1:">";s:4:"apos";s:1:"'";s:5:"OElig";s:2:"Å’";s:5:"oelig";s:2:"Å“";s:6:"Scaron";s:2:"Å ";s:6:"scaron";s:2:"Å¡";s:4:"Yuml";s:2:"Ÿ";s:4:"circ";s:2:"ˆ";s:5:"tilde";s:2:"Ëœ";s:4:"ensp";s:3:" ";s:4:"emsp";s:3:" ";s:6:"thinsp";s:3:" ";s:4:"zwnj";s:3:"‌";s:3:"zwj";s:3:"â€";s:3:"lrm";s:3:"‎";s:3:"rlm";s:3:"â€";s:5:"ndash";s:3:"–";s:5:"mdash";s:3:"—";s:5:"lsquo";s:3:"‘";s:5:"rsquo";s:3:"’";s:5:"sbquo";s:3:"‚";s:5:"ldquo";s:3:"“";s:5:"rdquo";s:3:"â€";s:5:"bdquo";s:3:"„";s:6:"dagger";s:3:"†";s:6:"Dagger";s:3:"‡";s:6:"permil";s:3:"‰";s:6:"lsaquo";s:3:"‹";s:6:"rsaquo";s:3:"›";s:4:"euro";s:3:"€";s:4:"nbsp";s:2:" ";s:5:"iexcl";s:2:"¡";s:4:"cent";s:2:"¢";s:5:"pound";s:2:"£";s:6:"curren";s:2:"¤";s:3:"yen";s:2:"Â¥";s:6:"brvbar";s:2:"¦";s:4:"sect";s:2:"§";s:3:"uml";s:2:"¨";s:4:"copy";s:2:"©";s:4:"ordf";s:2:"ª";s:5:"laquo";s:2:"«";s:3:"not";s:2:"¬";s:3:"shy";s:2:"­";s:3:"reg";s:2:"®";s:4:"macr";s:2:"¯";s:3:"deg";s:2:"°";s:6:"plusmn";s:2:"±";s:4:"sup2";s:2:"²";s:4:"sup3";s:2:"³";s:5:"acute";s:2:"´";s:5:"micro";s:2:"µ";s:4:"para";s:2:"¶";s:6:"middot";s:2:"·";s:5:"cedil";s:2:"¸";s:4:"sup1";s:2:"¹";s:4:"ordm";s:2:"º";s:5:"raquo";s:2:"»";s:6:"frac14";s:2:"¼";s:6:"frac12";s:2:"½";s:6:"frac34";s:2:"¾";s:6:"iquest";s:2:"¿";s:6:"Agrave";s:2:"À";s:6:"Aacute";s:2:"Ã";s:5:"Acirc";s:2:"Â";s:6:"Atilde";s:2:"Ã";s:4:"Auml";s:2:"Ä";s:5:"Aring";s:2:"Ã…";s:5:"AElig";s:2:"Æ";s:6:"Ccedil";s:2:"Ç";s:6:"Egrave";s:2:"È";s:6:"Eacute";s:2:"É";s:5:"Ecirc";s:2:"Ê";s:4:"Euml";s:2:"Ë";s:6:"Igrave";s:2:"ÃŒ";s:6:"Iacute";s:2:"Ã";s:5:"Icirc";s:2:"ÃŽ";s:4:"Iuml";s:2:"Ã";s:3:"ETH";s:2:"Ã";s:6:"Ntilde";s:2:"Ñ";s:6:"Ograve";s:2:"Ã’";s:6:"Oacute";s:2:"Ó";s:5:"Ocirc";s:2:"Ô";s:6:"Otilde";s:2:"Õ";s:4:"Ouml";s:2:"Ö";s:5:"times";s:2:"×";s:6:"Oslash";s:2:"Ø";s:6:"Ugrave";s:2:"Ù";s:6:"Uacute";s:2:"Ú";s:5:"Ucirc";s:2:"Û";s:4:"Uuml";s:2:"Ü";s:6:"Yacute";s:2:"Ã";s:5:"THORN";s:2:"Þ";s:5:"szlig";s:2:"ß";s:6:"agrave";s:2:"à";s:6:"aacute";s:2:"á";s:5:"acirc";s:2:"â";s:6:"atilde";s:2:"ã";s:4:"auml";s:2:"ä";s:5:"aring";s:2:"Ã¥";s:5:"aelig";s:2:"æ";s:6:"ccedil";s:2:"ç";s:6:"egrave";s:2:"è";s:6:"eacute";s:2:"é";s:5:"ecirc";s:2:"ê";s:4:"euml";s:2:"ë";s:6:"igrave";s:2:"ì";s:6:"iacute";s:2:"í";s:5:"icirc";s:2:"î";s:4:"iuml";s:2:"ï";s:3:"eth";s:2:"ð";s:6:"ntilde";s:2:"ñ";s:6:"ograve";s:2:"ò";s:6:"oacute";s:2:"ó";s:5:"ocirc";s:2:"ô";s:6:"otilde";s:2:"õ";s:4:"ouml";s:2:"ö";s:6:"divide";s:2:"÷";s:6:"oslash";s:2:"ø";s:6:"ugrave";s:2:"ù";s:6:"uacute";s:2:"ú";s:5:"ucirc";s:2:"û";s:4:"uuml";s:2:"ü";s:6:"yacute";s:2:"ý";s:5:"thorn";s:2:"þ";s:4:"yuml";s:2:"ÿ";} \ No newline at end of file diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Filter/ExtractStyleBlocks.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Filter/ExtractStyleBlocks.php new file mode 100644 index 0000000..5af24c2 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Filter/ExtractStyleBlocks.php @@ -0,0 +1,341 @@ + blocks from input HTML, cleans them up + * using CSSTidy, and then places them in $purifier->context->get('StyleBlocks') + * so they can be used elsewhere in the document. + * + * @note + * See tests/HTMLPurifier/Filter/ExtractStyleBlocksTest.php for + * sample usage. + * + * @note + * This filter can also be used on stylesheets not included in the + * document--something purists would probably prefer. Just directly + * call HTMLPurifier_Filter_ExtractStyleBlocks->cleanCSS() + */ +class HTMLPurifier_Filter_ExtractStyleBlocks extends HTMLPurifier_Filter +{ + /** + * @type string + */ + public $name = 'ExtractStyleBlocks'; + + /** + * @type array + */ + private $_styleMatches = array(); + + /** + * @type csstidy + */ + private $_tidy; + + /** + * @type HTMLPurifier_AttrDef_HTML_ID + */ + private $_id_attrdef; + + /** + * @type HTMLPurifier_AttrDef_CSS_Ident + */ + private $_class_attrdef; + + /** + * @type HTMLPurifier_AttrDef_Enum + */ + private $_enum_attrdef; + + public function __construct() + { + $this->_tidy = new csstidy(); + $this->_tidy->set_cfg('lowercase_s', false); + $this->_id_attrdef = new HTMLPurifier_AttrDef_HTML_ID(true); + $this->_class_attrdef = new HTMLPurifier_AttrDef_CSS_Ident(); + $this->_enum_attrdef = new HTMLPurifier_AttrDef_Enum( + array( + 'first-child', + 'link', + 'visited', + 'active', + 'hover', + 'focus' + ) + ); + } + + /** + * Save the contents of CSS blocks to style matches + * @param array $matches preg_replace style $matches array + */ + protected function styleCallback($matches) + { + $this->_styleMatches[] = $matches[1]; + } + + /** + * Removes inline + // we must not grab foo in a font-family prop). + if ($config->get('Filter.ExtractStyleBlocks.Escaping')) { + $css = str_replace( + array('<', '>', '&'), + array('\3C ', '\3E ', '\26 '), + $css + ); + } + return $css; + } +} + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Filter/YouTube.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Filter/YouTube.php new file mode 100644 index 0000000..b90ddf7 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Filter/YouTube.php @@ -0,0 +1,65 @@ +]+>.+?' . + '(?:http:)?//www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?#s'; + $pre_replace = '\1'; + return preg_replace($pre_regex, $pre_replace, $html); + } + + /** + * @param string $html + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + */ + public function postFilter($html, $config, $context) + { + $post_regex = '#((?:v|cp)/[A-Za-z0-9\-_=]+)#'; + return preg_replace_callback($post_regex, array($this, 'postFilterCallback'), $html); + } + + /** + * @param $url + * @return string + */ + protected function armorUrl($url) + { + return str_replace('--', '--', $url); + } + + /** + * @param array $matches + * @return string + */ + protected function postFilterCallback($matches) + { + $url = $this->armorUrl($matches[1]); + return '' . + '' . + '' . + ''; + } +} + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Language/classes/en-x-test.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Language/classes/en-x-test.php new file mode 100644 index 0000000..a6f8d16 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Language/classes/en-x-test.php @@ -0,0 +1,9 @@ + 'HTML Purifier X' +); + +$errorNames = array(); + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Language/messages/en-x-testmini.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Language/messages/en-x-testmini.php new file mode 100644 index 0000000..b6d1c99 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Language/messages/en-x-testmini.php @@ -0,0 +1,14 @@ + 'HTML Purifier XNone' +); + +$errorNames = array(); + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Language/messages/en.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Language/messages/en.php new file mode 100644 index 0000000..1fa30bd --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Language/messages/en.php @@ -0,0 +1,55 @@ + 'HTML Purifier', +// for unit testing purposes + 'LanguageFactoryTest: Pizza' => 'Pizza', + 'LanguageTest: List' => '$1', + 'LanguageTest: Hash' => '$1.Keys; $1.Values', + 'Item separator' => ', ', + 'Item separator last' => ' and ', // non-Harvard style + + 'ErrorCollector: No errors' => 'No errors detected. However, because error reporting is still incomplete, there may have been errors that the error collector was not notified of; please inspect the output HTML carefully.', + 'ErrorCollector: At line' => ' at line $line', + 'ErrorCollector: Incidental errors' => 'Incidental errors', + 'Lexer: Unclosed comment' => 'Unclosed comment', + 'Lexer: Unescaped lt' => 'Unescaped less-than sign (<) should be <', + 'Lexer: Missing gt' => 'Missing greater-than sign (>), previous less-than sign (<) should be escaped', + 'Lexer: Missing attribute key' => 'Attribute declaration has no key', + 'Lexer: Missing end quote' => 'Attribute declaration has no end quote', + 'Lexer: Extracted body' => 'Removed document metadata tags', + 'Strategy_RemoveForeignElements: Tag transform' => '<$1> element transformed into $CurrentToken.Serialized', + 'Strategy_RemoveForeignElements: Missing required attribute' => '$CurrentToken.Compact element missing required attribute $1', + 'Strategy_RemoveForeignElements: Foreign element to text' => 'Unrecognized $CurrentToken.Serialized tag converted to text', + 'Strategy_RemoveForeignElements: Foreign element removed' => 'Unrecognized $CurrentToken.Serialized tag removed', + 'Strategy_RemoveForeignElements: Comment removed' => 'Comment containing "$CurrentToken.Data" removed', + 'Strategy_RemoveForeignElements: Foreign meta element removed' => 'Unrecognized $CurrentToken.Serialized meta tag and all descendants removed', + 'Strategy_RemoveForeignElements: Token removed to end' => 'Tags and text starting from $1 element where removed to end', + 'Strategy_RemoveForeignElements: Trailing hyphen in comment removed' => 'Trailing hyphen(s) in comment removed', + 'Strategy_RemoveForeignElements: Hyphens in comment collapsed' => 'Double hyphens in comments are not allowed, and were collapsed into single hyphens', + 'Strategy_MakeWellFormed: Unnecessary end tag removed' => 'Unnecessary $CurrentToken.Serialized tag removed', + 'Strategy_MakeWellFormed: Unnecessary end tag to text' => 'Unnecessary $CurrentToken.Serialized tag converted to text', + 'Strategy_MakeWellFormed: Tag auto closed' => '$1.Compact started on line $1.Line auto-closed by $CurrentToken.Compact', + 'Strategy_MakeWellFormed: Tag carryover' => '$1.Compact started on line $1.Line auto-continued into $CurrentToken.Compact', + 'Strategy_MakeWellFormed: Stray end tag removed' => 'Stray $CurrentToken.Serialized tag removed', + 'Strategy_MakeWellFormed: Stray end tag to text' => 'Stray $CurrentToken.Serialized tag converted to text', + 'Strategy_MakeWellFormed: Tag closed by element end' => '$1.Compact tag started on line $1.Line closed by end of $CurrentToken.Serialized', + 'Strategy_MakeWellFormed: Tag closed by document end' => '$1.Compact tag started on line $1.Line closed by end of document', + 'Strategy_FixNesting: Node removed' => '$CurrentToken.Compact node removed', + 'Strategy_FixNesting: Node excluded' => '$CurrentToken.Compact node removed due to descendant exclusion by ancestor element', + 'Strategy_FixNesting: Node reorganized' => 'Contents of $CurrentToken.Compact node reorganized to enforce its content model', + 'Strategy_FixNesting: Node contents removed' => 'Contents of $CurrentToken.Compact node removed', + 'AttrValidator: Attributes transformed' => 'Attributes on $CurrentToken.Compact transformed from $1.Keys to $2.Keys', + 'AttrValidator: Attribute removed' => '$CurrentAttr.Name attribute on $CurrentToken.Compact removed', +); + +$errorNames = array( + E_ERROR => 'Error', + E_WARNING => 'Warning', + E_NOTICE => 'Notice' +); + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Lexer/PH5P.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Lexer/PH5P.php new file mode 100644 index 0000000..6b281a5 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Lexer/PH5P.php @@ -0,0 +1,4788 @@ +normalize($html, $config, $context); + $new_html = $this->wrapHTML($new_html, $config, $context, false /* no div */); + try { + $parser = new HTML5($new_html); + $doc = $parser->save(); + } catch (DOMException $e) { + // Uh oh, it failed. Punt to DirectLex. + $lexer = new HTMLPurifier_Lexer_DirectLex(); + $context->register('PH5PError', $e); // save the error, so we can detect it + return $lexer->tokenizeHTML($html, $config, $context); // use original HTML + } + $tokens = array(); + $this->tokenizeDOM( + $doc->getElementsByTagName('html')->item(0)-> // + getElementsByTagName('body')->item(0) // + , + $tokens, $config + ); + return $tokens; + } +} + +/* + +Copyright 2007 Jeroen van der Meer + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +*/ + +class HTML5 +{ + private $data; + private $char; + private $EOF; + private $state; + private $tree; + private $token; + private $content_model; + private $escape = false; + private $entities = array( + 'AElig;', + 'AElig', + 'AMP;', + 'AMP', + 'Aacute;', + 'Aacute', + 'Acirc;', + 'Acirc', + 'Agrave;', + 'Agrave', + 'Alpha;', + 'Aring;', + 'Aring', + 'Atilde;', + 'Atilde', + 'Auml;', + 'Auml', + 'Beta;', + 'COPY;', + 'COPY', + 'Ccedil;', + 'Ccedil', + 'Chi;', + 'Dagger;', + 'Delta;', + 'ETH;', + 'ETH', + 'Eacute;', + 'Eacute', + 'Ecirc;', + 'Ecirc', + 'Egrave;', + 'Egrave', + 'Epsilon;', + 'Eta;', + 'Euml;', + 'Euml', + 'GT;', + 'GT', + 'Gamma;', + 'Iacute;', + 'Iacute', + 'Icirc;', + 'Icirc', + 'Igrave;', + 'Igrave', + 'Iota;', + 'Iuml;', + 'Iuml', + 'Kappa;', + 'LT;', + 'LT', + 'Lambda;', + 'Mu;', + 'Ntilde;', + 'Ntilde', + 'Nu;', + 'OElig;', + 'Oacute;', + 'Oacute', + 'Ocirc;', + 'Ocirc', + 'Ograve;', + 'Ograve', + 'Omega;', + 'Omicron;', + 'Oslash;', + 'Oslash', + 'Otilde;', + 'Otilde', + 'Ouml;', + 'Ouml', + 'Phi;', + 'Pi;', + 'Prime;', + 'Psi;', + 'QUOT;', + 'QUOT', + 'REG;', + 'REG', + 'Rho;', + 'Scaron;', + 'Sigma;', + 'THORN;', + 'THORN', + 'TRADE;', + 'Tau;', + 'Theta;', + 'Uacute;', + 'Uacute', + 'Ucirc;', + 'Ucirc', + 'Ugrave;', + 'Ugrave', + 'Upsilon;', + 'Uuml;', + 'Uuml', + 'Xi;', + 'Yacute;', + 'Yacute', + 'Yuml;', + 'Zeta;', + 'aacute;', + 'aacute', + 'acirc;', + 'acirc', + 'acute;', + 'acute', + 'aelig;', + 'aelig', + 'agrave;', + 'agrave', + 'alefsym;', + 'alpha;', + 'amp;', + 'amp', + 'and;', + 'ang;', + 'apos;', + 'aring;', + 'aring', + 'asymp;', + 'atilde;', + 'atilde', + 'auml;', + 'auml', + 'bdquo;', + 'beta;', + 'brvbar;', + 'brvbar', + 'bull;', + 'cap;', + 'ccedil;', + 'ccedil', + 'cedil;', + 'cedil', + 'cent;', + 'cent', + 'chi;', + 'circ;', + 'clubs;', + 'cong;', + 'copy;', + 'copy', + 'crarr;', + 'cup;', + 'curren;', + 'curren', + 'dArr;', + 'dagger;', + 'darr;', + 'deg;', + 'deg', + 'delta;', + 'diams;', + 'divide;', + 'divide', + 'eacute;', + 'eacute', + 'ecirc;', + 'ecirc', + 'egrave;', + 'egrave', + 'empty;', + 'emsp;', + 'ensp;', + 'epsilon;', + 'equiv;', + 'eta;', + 'eth;', + 'eth', + 'euml;', + 'euml', + 'euro;', + 'exist;', + 'fnof;', + 'forall;', + 'frac12;', + 'frac12', + 'frac14;', + 'frac14', + 'frac34;', + 'frac34', + 'frasl;', + 'gamma;', + 'ge;', + 'gt;', + 'gt', + 'hArr;', + 'harr;', + 'hearts;', + 'hellip;', + 'iacute;', + 'iacute', + 'icirc;', + 'icirc', + 'iexcl;', + 'iexcl', + 'igrave;', + 'igrave', + 'image;', + 'infin;', + 'int;', + 'iota;', + 'iquest;', + 'iquest', + 'isin;', + 'iuml;', + 'iuml', + 'kappa;', + 'lArr;', + 'lambda;', + 'lang;', + 'laquo;', + 'laquo', + 'larr;', + 'lceil;', + 'ldquo;', + 'le;', + 'lfloor;', + 'lowast;', + 'loz;', + 'lrm;', + 'lsaquo;', + 'lsquo;', + 'lt;', + 'lt', + 'macr;', + 'macr', + 'mdash;', + 'micro;', + 'micro', + 'middot;', + 'middot', + 'minus;', + 'mu;', + 'nabla;', + 'nbsp;', + 'nbsp', + 'ndash;', + 'ne;', + 'ni;', + 'not;', + 'not', + 'notin;', + 'nsub;', + 'ntilde;', + 'ntilde', + 'nu;', + 'oacute;', + 'oacute', + 'ocirc;', + 'ocirc', + 'oelig;', + 'ograve;', + 'ograve', + 'oline;', + 'omega;', + 'omicron;', + 'oplus;', + 'or;', + 'ordf;', + 'ordf', + 'ordm;', + 'ordm', + 'oslash;', + 'oslash', + 'otilde;', + 'otilde', + 'otimes;', + 'ouml;', + 'ouml', + 'para;', + 'para', + 'part;', + 'permil;', + 'perp;', + 'phi;', + 'pi;', + 'piv;', + 'plusmn;', + 'plusmn', + 'pound;', + 'pound', + 'prime;', + 'prod;', + 'prop;', + 'psi;', + 'quot;', + 'quot', + 'rArr;', + 'radic;', + 'rang;', + 'raquo;', + 'raquo', + 'rarr;', + 'rceil;', + 'rdquo;', + 'real;', + 'reg;', + 'reg', + 'rfloor;', + 'rho;', + 'rlm;', + 'rsaquo;', + 'rsquo;', + 'sbquo;', + 'scaron;', + 'sdot;', + 'sect;', + 'sect', + 'shy;', + 'shy', + 'sigma;', + 'sigmaf;', + 'sim;', + 'spades;', + 'sub;', + 'sube;', + 'sum;', + 'sup1;', + 'sup1', + 'sup2;', + 'sup2', + 'sup3;', + 'sup3', + 'sup;', + 'supe;', + 'szlig;', + 'szlig', + 'tau;', + 'there4;', + 'theta;', + 'thetasym;', + 'thinsp;', + 'thorn;', + 'thorn', + 'tilde;', + 'times;', + 'times', + 'trade;', + 'uArr;', + 'uacute;', + 'uacute', + 'uarr;', + 'ucirc;', + 'ucirc', + 'ugrave;', + 'ugrave', + 'uml;', + 'uml', + 'upsih;', + 'upsilon;', + 'uuml;', + 'uuml', + 'weierp;', + 'xi;', + 'yacute;', + 'yacute', + 'yen;', + 'yen', + 'yuml;', + 'yuml', + 'zeta;', + 'zwj;', + 'zwnj;' + ); + + const PCDATA = 0; + const RCDATA = 1; + const CDATA = 2; + const PLAINTEXT = 3; + + const DOCTYPE = 0; + const STARTTAG = 1; + const ENDTAG = 2; + const COMMENT = 3; + const CHARACTR = 4; + const EOF = 5; + + public function __construct($data) + { + $this->data = $data; + $this->char = -1; + $this->EOF = strlen($data); + $this->tree = new HTML5TreeConstructer; + $this->content_model = self::PCDATA; + + $this->state = 'data'; + + while ($this->state !== null) { + $this->{$this->state . 'State'}(); + } + } + + public function save() + { + return $this->tree->save(); + } + + private function char() + { + return ($this->char < $this->EOF) + ? $this->data[$this->char] + : false; + } + + private function character($s, $l = 0) + { + if ($s + $l < $this->EOF) { + if ($l === 0) { + return $this->data[$s]; + } else { + return substr($this->data, $s, $l); + } + } + } + + private function characters($char_class, $start) + { + return preg_replace('#^([' . $char_class . ']+).*#s', '\\1', substr($this->data, $start)); + } + + private function dataState() + { + // Consume the next input character + $this->char++; + $char = $this->char(); + + if ($char === '&' && ($this->content_model === self::PCDATA || $this->content_model === self::RCDATA)) { + /* U+0026 AMPERSAND (&) + When the content model flag is set to one of the PCDATA or RCDATA + states: switch to the entity data state. Otherwise: treat it as per + the "anything else" entry below. */ + $this->state = 'entityData'; + + } elseif ($char === '-') { + /* If the content model flag is set to either the RCDATA state or + the CDATA state, and the escape flag is false, and there are at + least three characters before this one in the input stream, and the + last four characters in the input stream, including this one, are + U+003C LESS-THAN SIGN, U+0021 EXCLAMATION MARK, U+002D HYPHEN-MINUS, + and U+002D HYPHEN-MINUS (""), + set the escape flag to false. */ + if (($this->content_model === self::RCDATA || + $this->content_model === self::CDATA) && $this->escape === true && + $this->character($this->char, 3) === '-->' + ) { + $this->escape = false; + } + + /* In any case, emit the input character as a character token. + Stay in the data state. */ + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => $char + ) + ); + + } elseif ($this->char === $this->EOF) { + /* EOF + Emit an end-of-file token. */ + $this->EOF(); + + } elseif ($this->content_model === self::PLAINTEXT) { + /* When the content model flag is set to the PLAINTEXT state + THIS DIFFERS GREATLY FROM THE SPEC: Get the remaining characters of + the text and emit it as a character token. */ + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => substr($this->data, $this->char) + ) + ); + + $this->EOF(); + + } else { + /* Anything else + THIS DIFFERS GREATLY FROM THE SPEC: Get as many character that + otherwise would also be treated as a character token and emit it + as a single character token. Stay in the data state. */ + $len = strcspn($this->data, '<&', $this->char); + $char = substr($this->data, $this->char, $len); + $this->char += $len - 1; + + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => $char + ) + ); + + $this->state = 'data'; + } + } + + private function entityDataState() + { + // Attempt to consume an entity. + $entity = $this->entity(); + + // If nothing is returned, emit a U+0026 AMPERSAND character token. + // Otherwise, emit the character token that was returned. + $char = (!$entity) ? '&' : $entity; + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => $char + ) + ); + + // Finally, switch to the data state. + $this->state = 'data'; + } + + private function tagOpenState() + { + switch ($this->content_model) { + case self::RCDATA: + case self::CDATA: + /* If the next input character is a U+002F SOLIDUS (/) character, + consume it and switch to the close tag open state. If the next + input character is not a U+002F SOLIDUS (/) character, emit a + U+003C LESS-THAN SIGN character token and switch to the data + state to process the next input character. */ + if ($this->character($this->char + 1) === '/') { + $this->char++; + $this->state = 'closeTagOpen'; + + } else { + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => '<' + ) + ); + + $this->state = 'data'; + } + break; + + case self::PCDATA: + // If the content model flag is set to the PCDATA state + // Consume the next input character: + $this->char++; + $char = $this->char(); + + if ($char === '!') { + /* U+0021 EXCLAMATION MARK (!) + Switch to the markup declaration open state. */ + $this->state = 'markupDeclarationOpen'; + + } elseif ($char === '/') { + /* U+002F SOLIDUS (/) + Switch to the close tag open state. */ + $this->state = 'closeTagOpen'; + + } elseif (preg_match('/^[A-Za-z]$/', $char)) { + /* U+0041 LATIN LETTER A through to U+005A LATIN LETTER Z + Create a new start tag token, set its tag name to the lowercase + version of the input character (add 0x0020 to the character's code + point), then switch to the tag name state. (Don't emit the token + yet; further details will be filled in before it is emitted.) */ + $this->token = array( + 'name' => strtolower($char), + 'type' => self::STARTTAG, + 'attr' => array() + ); + + $this->state = 'tagName'; + + } elseif ($char === '>') { + /* U+003E GREATER-THAN SIGN (>) + Parse error. Emit a U+003C LESS-THAN SIGN character token and a + U+003E GREATER-THAN SIGN character token. Switch to the data state. */ + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => '<>' + ) + ); + + $this->state = 'data'; + + } elseif ($char === '?') { + /* U+003F QUESTION MARK (?) + Parse error. Switch to the bogus comment state. */ + $this->state = 'bogusComment'; + + } else { + /* Anything else + Parse error. Emit a U+003C LESS-THAN SIGN character token and + reconsume the current input character in the data state. */ + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => '<' + ) + ); + + $this->char--; + $this->state = 'data'; + } + break; + } + } + + private function closeTagOpenState() + { + $next_node = strtolower($this->characters('A-Za-z', $this->char + 1)); + $the_same = count($this->tree->stack) > 0 && $next_node === end($this->tree->stack)->nodeName; + + if (($this->content_model === self::RCDATA || $this->content_model === self::CDATA) && + (!$the_same || ($the_same && (!preg_match( + '/[\t\n\x0b\x0c >\/]/', + $this->character($this->char + 1 + strlen($next_node)) + ) || $this->EOF === $this->char))) + ) { + /* If the content model flag is set to the RCDATA or CDATA states then + examine the next few characters. If they do not match the tag name of + the last start tag token emitted (case insensitively), or if they do but + they are not immediately followed by one of the following characters: + * U+0009 CHARACTER TABULATION + * U+000A LINE FEED (LF) + * U+000B LINE TABULATION + * U+000C FORM FEED (FF) + * U+0020 SPACE + * U+003E GREATER-THAN SIGN (>) + * U+002F SOLIDUS (/) + * EOF + ...then there is a parse error. Emit a U+003C LESS-THAN SIGN character + token, a U+002F SOLIDUS character token, and switch to the data state + to process the next input character. */ + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => 'state = 'data'; + + } else { + /* Otherwise, if the content model flag is set to the PCDATA state, + or if the next few characters do match that tag name, consume the + next input character: */ + $this->char++; + $char = $this->char(); + + if (preg_match('/^[A-Za-z]$/', $char)) { + /* U+0041 LATIN LETTER A through to U+005A LATIN LETTER Z + Create a new end tag token, set its tag name to the lowercase version + of the input character (add 0x0020 to the character's code point), then + switch to the tag name state. (Don't emit the token yet; further details + will be filled in before it is emitted.) */ + $this->token = array( + 'name' => strtolower($char), + 'type' => self::ENDTAG + ); + + $this->state = 'tagName'; + + } elseif ($char === '>') { + /* U+003E GREATER-THAN SIGN (>) + Parse error. Switch to the data state. */ + $this->state = 'data'; + + } elseif ($this->char === $this->EOF) { + /* EOF + Parse error. Emit a U+003C LESS-THAN SIGN character token and a U+002F + SOLIDUS character token. Reconsume the EOF character in the data state. */ + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => 'char--; + $this->state = 'data'; + + } else { + /* Parse error. Switch to the bogus comment state. */ + $this->state = 'bogusComment'; + } + } + } + + private function tagNameState() + { + // Consume the next input character: + $this->char++; + $char = $this->character($this->char); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + /* U+0009 CHARACTER TABULATION + U+000A LINE FEED (LF) + U+000B LINE TABULATION + U+000C FORM FEED (FF) + U+0020 SPACE + Switch to the before attribute name state. */ + $this->state = 'beforeAttributeName'; + + } elseif ($char === '>') { + /* U+003E GREATER-THAN SIGN (>) + Emit the current tag token. Switch to the data state. */ + $this->emitToken($this->token); + $this->state = 'data'; + + } elseif ($this->char === $this->EOF) { + /* EOF + Parse error. Emit the current tag token. Reconsume the EOF + character in the data state. */ + $this->emitToken($this->token); + + $this->char--; + $this->state = 'data'; + + } elseif ($char === '/') { + /* U+002F SOLIDUS (/) + Parse error unless this is a permitted slash. Switch to the before + attribute name state. */ + $this->state = 'beforeAttributeName'; + + } else { + /* Anything else + Append the current input character to the current tag token's tag name. + Stay in the tag name state. */ + $this->token['name'] .= strtolower($char); + $this->state = 'tagName'; + } + } + + private function beforeAttributeNameState() + { + // Consume the next input character: + $this->char++; + $char = $this->character($this->char); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + /* U+0009 CHARACTER TABULATION + U+000A LINE FEED (LF) + U+000B LINE TABULATION + U+000C FORM FEED (FF) + U+0020 SPACE + Stay in the before attribute name state. */ + $this->state = 'beforeAttributeName'; + + } elseif ($char === '>') { + /* U+003E GREATER-THAN SIGN (>) + Emit the current tag token. Switch to the data state. */ + $this->emitToken($this->token); + $this->state = 'data'; + + } elseif ($char === '/') { + /* U+002F SOLIDUS (/) + Parse error unless this is a permitted slash. Stay in the before + attribute name state. */ + $this->state = 'beforeAttributeName'; + + } elseif ($this->char === $this->EOF) { + /* EOF + Parse error. Emit the current tag token. Reconsume the EOF + character in the data state. */ + $this->emitToken($this->token); + + $this->char--; + $this->state = 'data'; + + } else { + /* Anything else + Start a new attribute in the current tag token. Set that attribute's + name to the current input character, and its value to the empty string. + Switch to the attribute name state. */ + $this->token['attr'][] = array( + 'name' => strtolower($char), + 'value' => null + ); + + $this->state = 'attributeName'; + } + } + + private function attributeNameState() + { + // Consume the next input character: + $this->char++; + $char = $this->character($this->char); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + /* U+0009 CHARACTER TABULATION + U+000A LINE FEED (LF) + U+000B LINE TABULATION + U+000C FORM FEED (FF) + U+0020 SPACE + Stay in the before attribute name state. */ + $this->state = 'afterAttributeName'; + + } elseif ($char === '=') { + /* U+003D EQUALS SIGN (=) + Switch to the before attribute value state. */ + $this->state = 'beforeAttributeValue'; + + } elseif ($char === '>') { + /* U+003E GREATER-THAN SIGN (>) + Emit the current tag token. Switch to the data state. */ + $this->emitToken($this->token); + $this->state = 'data'; + + } elseif ($char === '/' && $this->character($this->char + 1) !== '>') { + /* U+002F SOLIDUS (/) + Parse error unless this is a permitted slash. Switch to the before + attribute name state. */ + $this->state = 'beforeAttributeName'; + + } elseif ($this->char === $this->EOF) { + /* EOF + Parse error. Emit the current tag token. Reconsume the EOF + character in the data state. */ + $this->emitToken($this->token); + + $this->char--; + $this->state = 'data'; + + } else { + /* Anything else + Append the current input character to the current attribute's name. + Stay in the attribute name state. */ + $last = count($this->token['attr']) - 1; + $this->token['attr'][$last]['name'] .= strtolower($char); + + $this->state = 'attributeName'; + } + } + + private function afterAttributeNameState() + { + // Consume the next input character: + $this->char++; + $char = $this->character($this->char); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + /* U+0009 CHARACTER TABULATION + U+000A LINE FEED (LF) + U+000B LINE TABULATION + U+000C FORM FEED (FF) + U+0020 SPACE + Stay in the after attribute name state. */ + $this->state = 'afterAttributeName'; + + } elseif ($char === '=') { + /* U+003D EQUALS SIGN (=) + Switch to the before attribute value state. */ + $this->state = 'beforeAttributeValue'; + + } elseif ($char === '>') { + /* U+003E GREATER-THAN SIGN (>) + Emit the current tag token. Switch to the data state. */ + $this->emitToken($this->token); + $this->state = 'data'; + + } elseif ($char === '/' && $this->character($this->char + 1) !== '>') { + /* U+002F SOLIDUS (/) + Parse error unless this is a permitted slash. Switch to the + before attribute name state. */ + $this->state = 'beforeAttributeName'; + + } elseif ($this->char === $this->EOF) { + /* EOF + Parse error. Emit the current tag token. Reconsume the EOF + character in the data state. */ + $this->emitToken($this->token); + + $this->char--; + $this->state = 'data'; + + } else { + /* Anything else + Start a new attribute in the current tag token. Set that attribute's + name to the current input character, and its value to the empty string. + Switch to the attribute name state. */ + $this->token['attr'][] = array( + 'name' => strtolower($char), + 'value' => null + ); + + $this->state = 'attributeName'; + } + } + + private function beforeAttributeValueState() + { + // Consume the next input character: + $this->char++; + $char = $this->character($this->char); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + /* U+0009 CHARACTER TABULATION + U+000A LINE FEED (LF) + U+000B LINE TABULATION + U+000C FORM FEED (FF) + U+0020 SPACE + Stay in the before attribute value state. */ + $this->state = 'beforeAttributeValue'; + + } elseif ($char === '"') { + /* U+0022 QUOTATION MARK (") + Switch to the attribute value (double-quoted) state. */ + $this->state = 'attributeValueDoubleQuoted'; + + } elseif ($char === '&') { + /* U+0026 AMPERSAND (&) + Switch to the attribute value (unquoted) state and reconsume + this input character. */ + $this->char--; + $this->state = 'attributeValueUnquoted'; + + } elseif ($char === '\'') { + /* U+0027 APOSTROPHE (') + Switch to the attribute value (single-quoted) state. */ + $this->state = 'attributeValueSingleQuoted'; + + } elseif ($char === '>') { + /* U+003E GREATER-THAN SIGN (>) + Emit the current tag token. Switch to the data state. */ + $this->emitToken($this->token); + $this->state = 'data'; + + } else { + /* Anything else + Append the current input character to the current attribute's value. + Switch to the attribute value (unquoted) state. */ + $last = count($this->token['attr']) - 1; + $this->token['attr'][$last]['value'] .= $char; + + $this->state = 'attributeValueUnquoted'; + } + } + + private function attributeValueDoubleQuotedState() + { + // Consume the next input character: + $this->char++; + $char = $this->character($this->char); + + if ($char === '"') { + /* U+0022 QUOTATION MARK (") + Switch to the before attribute name state. */ + $this->state = 'beforeAttributeName'; + + } elseif ($char === '&') { + /* U+0026 AMPERSAND (&) + Switch to the entity in attribute value state. */ + $this->entityInAttributeValueState('double'); + + } elseif ($this->char === $this->EOF) { + /* EOF + Parse error. Emit the current tag token. Reconsume the character + in the data state. */ + $this->emitToken($this->token); + + $this->char--; + $this->state = 'data'; + + } else { + /* Anything else + Append the current input character to the current attribute's value. + Stay in the attribute value (double-quoted) state. */ + $last = count($this->token['attr']) - 1; + $this->token['attr'][$last]['value'] .= $char; + + $this->state = 'attributeValueDoubleQuoted'; + } + } + + private function attributeValueSingleQuotedState() + { + // Consume the next input character: + $this->char++; + $char = $this->character($this->char); + + if ($char === '\'') { + /* U+0022 QUOTATION MARK (') + Switch to the before attribute name state. */ + $this->state = 'beforeAttributeName'; + + } elseif ($char === '&') { + /* U+0026 AMPERSAND (&) + Switch to the entity in attribute value state. */ + $this->entityInAttributeValueState('single'); + + } elseif ($this->char === $this->EOF) { + /* EOF + Parse error. Emit the current tag token. Reconsume the character + in the data state. */ + $this->emitToken($this->token); + + $this->char--; + $this->state = 'data'; + + } else { + /* Anything else + Append the current input character to the current attribute's value. + Stay in the attribute value (single-quoted) state. */ + $last = count($this->token['attr']) - 1; + $this->token['attr'][$last]['value'] .= $char; + + $this->state = 'attributeValueSingleQuoted'; + } + } + + private function attributeValueUnquotedState() + { + // Consume the next input character: + $this->char++; + $char = $this->character($this->char); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + /* U+0009 CHARACTER TABULATION + U+000A LINE FEED (LF) + U+000B LINE TABULATION + U+000C FORM FEED (FF) + U+0020 SPACE + Switch to the before attribute name state. */ + $this->state = 'beforeAttributeName'; + + } elseif ($char === '&') { + /* U+0026 AMPERSAND (&) + Switch to the entity in attribute value state. */ + $this->entityInAttributeValueState(); + + } elseif ($char === '>') { + /* U+003E GREATER-THAN SIGN (>) + Emit the current tag token. Switch to the data state. */ + $this->emitToken($this->token); + $this->state = 'data'; + + } else { + /* Anything else + Append the current input character to the current attribute's value. + Stay in the attribute value (unquoted) state. */ + $last = count($this->token['attr']) - 1; + $this->token['attr'][$last]['value'] .= $char; + + $this->state = 'attributeValueUnquoted'; + } + } + + private function entityInAttributeValueState() + { + // Attempt to consume an entity. + $entity = $this->entity(); + + // If nothing is returned, append a U+0026 AMPERSAND character to the + // current attribute's value. Otherwise, emit the character token that + // was returned. + $char = (!$entity) + ? '&' + : $entity; + + $last = count($this->token['attr']) - 1; + $this->token['attr'][$last]['value'] .= $char; + } + + private function bogusCommentState() + { + /* Consume every character up to the first U+003E GREATER-THAN SIGN + character (>) or the end of the file (EOF), whichever comes first. Emit + a comment token whose data is the concatenation of all the characters + starting from and including the character that caused the state machine + to switch into the bogus comment state, up to and including the last + consumed character before the U+003E character, if any, or up to the + end of the file otherwise. (If the comment was started by the end of + the file (EOF), the token is empty.) */ + $data = $this->characters('^>', $this->char); + $this->emitToken( + array( + 'data' => $data, + 'type' => self::COMMENT + ) + ); + + $this->char += strlen($data); + + /* Switch to the data state. */ + $this->state = 'data'; + + /* If the end of the file was reached, reconsume the EOF character. */ + if ($this->char === $this->EOF) { + $this->char = $this->EOF - 1; + } + } + + private function markupDeclarationOpenState() + { + /* If the next two characters are both U+002D HYPHEN-MINUS (-) + characters, consume those two characters, create a comment token whose + data is the empty string, and switch to the comment state. */ + if ($this->character($this->char + 1, 2) === '--') { + $this->char += 2; + $this->state = 'comment'; + $this->token = array( + 'data' => null, + 'type' => self::COMMENT + ); + + /* Otherwise if the next seven chacacters are a case-insensitive match + for the word "DOCTYPE", then consume those characters and switch to the + DOCTYPE state. */ + } elseif (strtolower($this->character($this->char + 1, 7)) === 'doctype') { + $this->char += 7; + $this->state = 'doctype'; + + /* Otherwise, is is a parse error. Switch to the bogus comment state. + The next character that is consumed, if any, is the first character + that will be in the comment. */ + } else { + $this->char++; + $this->state = 'bogusComment'; + } + } + + private function commentState() + { + /* Consume the next input character: */ + $this->char++; + $char = $this->char(); + + /* U+002D HYPHEN-MINUS (-) */ + if ($char === '-') { + /* Switch to the comment dash state */ + $this->state = 'commentDash'; + + /* EOF */ + } elseif ($this->char === $this->EOF) { + /* Parse error. Emit the comment token. Reconsume the EOF character + in the data state. */ + $this->emitToken($this->token); + $this->char--; + $this->state = 'data'; + + /* Anything else */ + } else { + /* Append the input character to the comment token's data. Stay in + the comment state. */ + $this->token['data'] .= $char; + } + } + + private function commentDashState() + { + /* Consume the next input character: */ + $this->char++; + $char = $this->char(); + + /* U+002D HYPHEN-MINUS (-) */ + if ($char === '-') { + /* Switch to the comment end state */ + $this->state = 'commentEnd'; + + /* EOF */ + } elseif ($this->char === $this->EOF) { + /* Parse error. Emit the comment token. Reconsume the EOF character + in the data state. */ + $this->emitToken($this->token); + $this->char--; + $this->state = 'data'; + + /* Anything else */ + } else { + /* Append a U+002D HYPHEN-MINUS (-) character and the input + character to the comment token's data. Switch to the comment state. */ + $this->token['data'] .= '-' . $char; + $this->state = 'comment'; + } + } + + private function commentEndState() + { + /* Consume the next input character: */ + $this->char++; + $char = $this->char(); + + if ($char === '>') { + $this->emitToken($this->token); + $this->state = 'data'; + + } elseif ($char === '-') { + $this->token['data'] .= '-'; + + } elseif ($this->char === $this->EOF) { + $this->emitToken($this->token); + $this->char--; + $this->state = 'data'; + + } else { + $this->token['data'] .= '--' . $char; + $this->state = 'comment'; + } + } + + private function doctypeState() + { + /* Consume the next input character: */ + $this->char++; + $char = $this->char(); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + $this->state = 'beforeDoctypeName'; + + } else { + $this->char--; + $this->state = 'beforeDoctypeName'; + } + } + + private function beforeDoctypeNameState() + { + /* Consume the next input character: */ + $this->char++; + $char = $this->char(); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + // Stay in the before DOCTYPE name state. + + } elseif (preg_match('/^[a-z]$/', $char)) { + $this->token = array( + 'name' => strtoupper($char), + 'type' => self::DOCTYPE, + 'error' => true + ); + + $this->state = 'doctypeName'; + + } elseif ($char === '>') { + $this->emitToken( + array( + 'name' => null, + 'type' => self::DOCTYPE, + 'error' => true + ) + ); + + $this->state = 'data'; + + } elseif ($this->char === $this->EOF) { + $this->emitToken( + array( + 'name' => null, + 'type' => self::DOCTYPE, + 'error' => true + ) + ); + + $this->char--; + $this->state = 'data'; + + } else { + $this->token = array( + 'name' => $char, + 'type' => self::DOCTYPE, + 'error' => true + ); + + $this->state = 'doctypeName'; + } + } + + private function doctypeNameState() + { + /* Consume the next input character: */ + $this->char++; + $char = $this->char(); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + $this->state = 'AfterDoctypeName'; + + } elseif ($char === '>') { + $this->emitToken($this->token); + $this->state = 'data'; + + } elseif (preg_match('/^[a-z]$/', $char)) { + $this->token['name'] .= strtoupper($char); + + } elseif ($this->char === $this->EOF) { + $this->emitToken($this->token); + $this->char--; + $this->state = 'data'; + + } else { + $this->token['name'] .= $char; + } + + $this->token['error'] = ($this->token['name'] === 'HTML') + ? false + : true; + } + + private function afterDoctypeNameState() + { + /* Consume the next input character: */ + $this->char++; + $char = $this->char(); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + // Stay in the DOCTYPE name state. + + } elseif ($char === '>') { + $this->emitToken($this->token); + $this->state = 'data'; + + } elseif ($this->char === $this->EOF) { + $this->emitToken($this->token); + $this->char--; + $this->state = 'data'; + + } else { + $this->token['error'] = true; + $this->state = 'bogusDoctype'; + } + } + + private function bogusDoctypeState() + { + /* Consume the next input character: */ + $this->char++; + $char = $this->char(); + + if ($char === '>') { + $this->emitToken($this->token); + $this->state = 'data'; + + } elseif ($this->char === $this->EOF) { + $this->emitToken($this->token); + $this->char--; + $this->state = 'data'; + + } else { + // Stay in the bogus DOCTYPE state. + } + } + + private function entity() + { + $start = $this->char; + + // This section defines how to consume an entity. This definition is + // used when parsing entities in text and in attributes. + + // The behaviour depends on the identity of the next character (the + // one immediately after the U+0026 AMPERSAND character): + + switch ($this->character($this->char + 1)) { + // U+0023 NUMBER SIGN (#) + case '#': + + // The behaviour further depends on the character after the + // U+0023 NUMBER SIGN: + switch ($this->character($this->char + 1)) { + // U+0078 LATIN SMALL LETTER X + // U+0058 LATIN CAPITAL LETTER X + case 'x': + case 'X': + // Follow the steps below, but using the range of + // characters U+0030 DIGIT ZERO through to U+0039 DIGIT + // NINE, U+0061 LATIN SMALL LETTER A through to U+0066 + // LATIN SMALL LETTER F, and U+0041 LATIN CAPITAL LETTER + // A, through to U+0046 LATIN CAPITAL LETTER F (in other + // words, 0-9, A-F, a-f). + $char = 1; + $char_class = '0-9A-Fa-f'; + break; + + // Anything else + default: + // Follow the steps below, but using the range of + // characters U+0030 DIGIT ZERO through to U+0039 DIGIT + // NINE (i.e. just 0-9). + $char = 0; + $char_class = '0-9'; + break; + } + + // Consume as many characters as match the range of characters + // given above. + $this->char++; + $e_name = $this->characters($char_class, $this->char + $char + 1); + $entity = $this->character($start, $this->char); + $cond = strlen($e_name) > 0; + + // The rest of the parsing happens below. + break; + + // Anything else + default: + // Consume the maximum number of characters possible, with the + // consumed characters case-sensitively matching one of the + // identifiers in the first column of the entities table. + + $e_name = $this->characters('0-9A-Za-z;', $this->char + 1); + $len = strlen($e_name); + + for ($c = 1; $c <= $len; $c++) { + $id = substr($e_name, 0, $c); + $this->char++; + + if (in_array($id, $this->entities)) { + if ($e_name[$c - 1] !== ';') { + if ($c < $len && $e_name[$c] == ';') { + $this->char++; // consume extra semicolon + } + } + $entity = $id; + break; + } + } + + $cond = isset($entity); + // The rest of the parsing happens below. + break; + } + + if (!$cond) { + // If no match can be made, then this is a parse error. No + // characters are consumed, and nothing is returned. + $this->char = $start; + return false; + } + + // Return a character token for the character corresponding to the + // entity name (as given by the second column of the entities table). + return html_entity_decode('&' . rtrim($entity, ';') . ';', ENT_QUOTES, 'UTF-8'); + } + + private function emitToken($token) + { + $emit = $this->tree->emitToken($token); + + if (is_int($emit)) { + $this->content_model = $emit; + + } elseif ($token['type'] === self::ENDTAG) { + $this->content_model = self::PCDATA; + } + } + + private function EOF() + { + $this->state = null; + $this->tree->emitToken( + array( + 'type' => self::EOF + ) + ); + } +} + +class HTML5TreeConstructer +{ + public $stack = array(); + + private $phase; + private $mode; + private $dom; + private $foster_parent = null; + private $a_formatting = array(); + + private $head_pointer = null; + private $form_pointer = null; + + private $scoping = array('button', 'caption', 'html', 'marquee', 'object', 'table', 'td', 'th'); + private $formatting = array( + 'a', + 'b', + 'big', + 'em', + 'font', + 'i', + 'nobr', + 's', + 'small', + 'strike', + 'strong', + 'tt', + 'u' + ); + private $special = array( + 'address', + 'area', + 'base', + 'basefont', + 'bgsound', + 'blockquote', + 'body', + 'br', + 'center', + 'col', + 'colgroup', + 'dd', + 'dir', + 'div', + 'dl', + 'dt', + 'embed', + 'fieldset', + 'form', + 'frame', + 'frameset', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'head', + 'hr', + 'iframe', + 'image', + 'img', + 'input', + 'isindex', + 'li', + 'link', + 'listing', + 'menu', + 'meta', + 'noembed', + 'noframes', + 'noscript', + 'ol', + 'optgroup', + 'option', + 'p', + 'param', + 'plaintext', + 'pre', + 'script', + 'select', + 'spacer', + 'style', + 'tbody', + 'textarea', + 'tfoot', + 'thead', + 'title', + 'tr', + 'ul', + 'wbr' + ); + + // The different phases. + const INIT_PHASE = 0; + const ROOT_PHASE = 1; + const MAIN_PHASE = 2; + const END_PHASE = 3; + + // The different insertion modes for the main phase. + const BEFOR_HEAD = 0; + const IN_HEAD = 1; + const AFTER_HEAD = 2; + const IN_BODY = 3; + const IN_TABLE = 4; + const IN_CAPTION = 5; + const IN_CGROUP = 6; + const IN_TBODY = 7; + const IN_ROW = 8; + const IN_CELL = 9; + const IN_SELECT = 10; + const AFTER_BODY = 11; + const IN_FRAME = 12; + const AFTR_FRAME = 13; + + // The different types of elements. + const SPECIAL = 0; + const SCOPING = 1; + const FORMATTING = 2; + const PHRASING = 3; + + const MARKER = 0; + + public function __construct() + { + $this->phase = self::INIT_PHASE; + $this->mode = self::BEFOR_HEAD; + $this->dom = new DOMDocument; + + $this->dom->encoding = 'UTF-8'; + $this->dom->preserveWhiteSpace = true; + $this->dom->substituteEntities = true; + $this->dom->strictErrorChecking = false; + } + + // Process tag tokens + public function emitToken($token) + { + switch ($this->phase) { + case self::INIT_PHASE: + return $this->initPhase($token); + break; + case self::ROOT_PHASE: + return $this->rootElementPhase($token); + break; + case self::MAIN_PHASE: + return $this->mainPhase($token); + break; + case self::END_PHASE : + return $this->trailingEndPhase($token); + break; + } + } + + private function initPhase($token) + { + /* Initially, the tree construction stage must handle each token + emitted from the tokenisation stage as follows: */ + + /* A DOCTYPE token that is marked as being in error + A comment token + A start tag token + An end tag token + A character token that is not one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE + An end-of-file token */ + if ((isset($token['error']) && $token['error']) || + $token['type'] === HTML5::COMMENT || + $token['type'] === HTML5::STARTTAG || + $token['type'] === HTML5::ENDTAG || + $token['type'] === HTML5::EOF || + ($token['type'] === HTML5::CHARACTR && isset($token['data']) && + !preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) + ) { + /* This specification does not define how to handle this case. In + particular, user agents may ignore the entirety of this specification + altogether for such documents, and instead invoke special parse modes + with a greater emphasis on backwards compatibility. */ + + $this->phase = self::ROOT_PHASE; + return $this->rootElementPhase($token); + + /* A DOCTYPE token marked as being correct */ + } elseif (isset($token['error']) && !$token['error']) { + /* Append a DocumentType node to the Document node, with the name + attribute set to the name given in the DOCTYPE token (which will be + "HTML"), and the other attributes specific to DocumentType objects + set to null, empty lists, or the empty string as appropriate. */ + $doctype = new DOMDocumentType(null, null, 'HTML'); + + /* Then, switch to the root element phase of the tree construction + stage. */ + $this->phase = self::ROOT_PHASE; + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE */ + } elseif (isset($token['data']) && preg_match( + '/^[\t\n\x0b\x0c ]+$/', + $token['data'] + ) + ) { + /* Append that character to the Document node. */ + $text = $this->dom->createTextNode($token['data']); + $this->dom->appendChild($text); + } + } + + private function rootElementPhase($token) + { + /* After the initial phase, as each token is emitted from the tokenisation + stage, it must be processed as described in this section. */ + + /* A DOCTYPE token */ + if ($token['type'] === HTML5::DOCTYPE) { + // Parse error. Ignore the token. + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the Document object with the data + attribute set to the data given in the comment token. */ + $comment = $this->dom->createComment($token['data']); + $this->dom->appendChild($comment); + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE */ + } elseif ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Append that character to the Document node. */ + $text = $this->dom->createTextNode($token['data']); + $this->dom->appendChild($text); + + /* A character token that is not one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED + (FF), or U+0020 SPACE + A start tag token + An end tag token + An end-of-file token */ + } elseif (($token['type'] === HTML5::CHARACTR && + !preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) || + $token['type'] === HTML5::STARTTAG || + $token['type'] === HTML5::ENDTAG || + $token['type'] === HTML5::EOF + ) { + /* Create an HTMLElement node with the tag name html, in the HTML + namespace. Append it to the Document object. Switch to the main + phase and reprocess the current token. */ + $html = $this->dom->createElement('html'); + $this->dom->appendChild($html); + $this->stack[] = $html; + + $this->phase = self::MAIN_PHASE; + return $this->mainPhase($token); + } + } + + private function mainPhase($token) + { + /* Tokens in the main phase must be handled as follows: */ + + /* A DOCTYPE token */ + if ($token['type'] === HTML5::DOCTYPE) { + // Parse error. Ignore the token. + + /* A start tag token with the tag name "html" */ + } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'html') { + /* If this start tag token was not the first start tag token, then + it is a parse error. */ + + /* For each attribute on the token, check to see if the attribute + is already present on the top element of the stack of open elements. + If it is not, add the attribute and its corresponding value to that + element. */ + foreach ($token['attr'] as $attr) { + if (!$this->stack[0]->hasAttribute($attr['name'])) { + $this->stack[0]->setAttribute($attr['name'], $attr['value']); + } + } + + /* An end-of-file token */ + } elseif ($token['type'] === HTML5::EOF) { + /* Generate implied end tags. */ + $this->generateImpliedEndTags(); + + /* Anything else. */ + } else { + /* Depends on the insertion mode: */ + switch ($this->mode) { + case self::BEFOR_HEAD: + return $this->beforeHead($token); + break; + case self::IN_HEAD: + return $this->inHead($token); + break; + case self::AFTER_HEAD: + return $this->afterHead($token); + break; + case self::IN_BODY: + return $this->inBody($token); + break; + case self::IN_TABLE: + return $this->inTable($token); + break; + case self::IN_CAPTION: + return $this->inCaption($token); + break; + case self::IN_CGROUP: + return $this->inColumnGroup($token); + break; + case self::IN_TBODY: + return $this->inTableBody($token); + break; + case self::IN_ROW: + return $this->inRow($token); + break; + case self::IN_CELL: + return $this->inCell($token); + break; + case self::IN_SELECT: + return $this->inSelect($token); + break; + case self::AFTER_BODY: + return $this->afterBody($token); + break; + case self::IN_FRAME: + return $this->inFrameset($token); + break; + case self::AFTR_FRAME: + return $this->afterFrameset($token); + break; + case self::END_PHASE: + return $this->trailingEndPhase($token); + break; + } + } + } + + private function beforeHead($token) + { + /* Handle the token as follows: */ + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE */ + if ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Append the character to the current node. */ + $this->insertText($token['data']); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the current node with the data attribute + set to the data given in the comment token. */ + $this->insertComment($token['data']); + + /* A start tag token with the tag name "head" */ + } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'head') { + /* Create an element for the token, append the new element to the + current node and push it onto the stack of open elements. */ + $element = $this->insertElement($token); + + /* Set the head element pointer to this new element node. */ + $this->head_pointer = $element; + + /* Change the insertion mode to "in head". */ + $this->mode = self::IN_HEAD; + + /* A start tag token whose tag name is one of: "base", "link", "meta", + "script", "style", "title". Or an end tag with the tag name "html". + Or a character token that is not one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE. Or any other start tag token */ + } elseif ($token['type'] === HTML5::STARTTAG || + ($token['type'] === HTML5::ENDTAG && $token['name'] === 'html') || + ($token['type'] === HTML5::CHARACTR && !preg_match( + '/^[\t\n\x0b\x0c ]$/', + $token['data'] + )) + ) { + /* Act as if a start tag token with the tag name "head" and no + attributes had been seen, then reprocess the current token. */ + $this->beforeHead( + array( + 'name' => 'head', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + return $this->inHead($token); + + /* Any other end tag */ + } elseif ($token['type'] === HTML5::ENDTAG) { + /* Parse error. Ignore the token. */ + } + } + + private function inHead($token) + { + /* Handle the token as follows: */ + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE. + + THIS DIFFERS FROM THE SPEC: If the current node is either a title, style + or script element, append the character to the current node regardless + of its content. */ + if (($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) || ( + $token['type'] === HTML5::CHARACTR && in_array( + end($this->stack)->nodeName, + array('title', 'style', 'script') + )) + ) { + /* Append the character to the current node. */ + $this->insertText($token['data']); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the current node with the data attribute + set to the data given in the comment token. */ + $this->insertComment($token['data']); + + } elseif ($token['type'] === HTML5::ENDTAG && + in_array($token['name'], array('title', 'style', 'script')) + ) { + array_pop($this->stack); + return HTML5::PCDATA; + + /* A start tag with the tag name "title" */ + } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'title') { + /* Create an element for the token and append the new element to the + node pointed to by the head element pointer, or, if that is null + (innerHTML case), to the current node. */ + if ($this->head_pointer !== null) { + $element = $this->insertElement($token, false); + $this->head_pointer->appendChild($element); + + } else { + $element = $this->insertElement($token); + } + + /* Switch the tokeniser's content model flag to the RCDATA state. */ + return HTML5::RCDATA; + + /* A start tag with the tag name "style" */ + } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'style') { + /* Create an element for the token and append the new element to the + node pointed to by the head element pointer, or, if that is null + (innerHTML case), to the current node. */ + if ($this->head_pointer !== null) { + $element = $this->insertElement($token, false); + $this->head_pointer->appendChild($element); + + } else { + $this->insertElement($token); + } + + /* Switch the tokeniser's content model flag to the CDATA state. */ + return HTML5::CDATA; + + /* A start tag with the tag name "script" */ + } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'script') { + /* Create an element for the token. */ + $element = $this->insertElement($token, false); + $this->head_pointer->appendChild($element); + + /* Switch the tokeniser's content model flag to the CDATA state. */ + return HTML5::CDATA; + + /* A start tag with the tag name "base", "link", or "meta" */ + } elseif ($token['type'] === HTML5::STARTTAG && in_array( + $token['name'], + array('base', 'link', 'meta') + ) + ) { + /* Create an element for the token and append the new element to the + node pointed to by the head element pointer, or, if that is null + (innerHTML case), to the current node. */ + if ($this->head_pointer !== null) { + $element = $this->insertElement($token, false); + $this->head_pointer->appendChild($element); + array_pop($this->stack); + + } else { + $this->insertElement($token); + } + + /* An end tag with the tag name "head" */ + } elseif ($token['type'] === HTML5::ENDTAG && $token['name'] === 'head') { + /* If the current node is a head element, pop the current node off + the stack of open elements. */ + if ($this->head_pointer->isSameNode(end($this->stack))) { + array_pop($this->stack); + + /* Otherwise, this is a parse error. */ + } else { + // k + } + + /* Change the insertion mode to "after head". */ + $this->mode = self::AFTER_HEAD; + + /* A start tag with the tag name "head" or an end tag except "html". */ + } elseif (($token['type'] === HTML5::STARTTAG && $token['name'] === 'head') || + ($token['type'] === HTML5::ENDTAG && $token['name'] !== 'html') + ) { + // Parse error. Ignore the token. + + /* Anything else */ + } else { + /* If the current node is a head element, act as if an end tag + token with the tag name "head" had been seen. */ + if ($this->head_pointer->isSameNode(end($this->stack))) { + $this->inHead( + array( + 'name' => 'head', + 'type' => HTML5::ENDTAG + ) + ); + + /* Otherwise, change the insertion mode to "after head". */ + } else { + $this->mode = self::AFTER_HEAD; + } + + /* Then, reprocess the current token. */ + return $this->afterHead($token); + } + } + + private function afterHead($token) + { + /* Handle the token as follows: */ + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE */ + if ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Append the character to the current node. */ + $this->insertText($token['data']); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the current node with the data attribute + set to the data given in the comment token. */ + $this->insertComment($token['data']); + + /* A start tag token with the tag name "body" */ + } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'body') { + /* Insert a body element for the token. */ + $this->insertElement($token); + + /* Change the insertion mode to "in body". */ + $this->mode = self::IN_BODY; + + /* A start tag token with the tag name "frameset" */ + } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'frameset') { + /* Insert a frameset element for the token. */ + $this->insertElement($token); + + /* Change the insertion mode to "in frameset". */ + $this->mode = self::IN_FRAME; + + /* A start tag token whose tag name is one of: "base", "link", "meta", + "script", "style", "title" */ + } elseif ($token['type'] === HTML5::STARTTAG && in_array( + $token['name'], + array('base', 'link', 'meta', 'script', 'style', 'title') + ) + ) { + /* Parse error. Switch the insertion mode back to "in head" and + reprocess the token. */ + $this->mode = self::IN_HEAD; + return $this->inHead($token); + + /* Anything else */ + } else { + /* Act as if a start tag token with the tag name "body" and no + attributes had been seen, and then reprocess the current token. */ + $this->afterHead( + array( + 'name' => 'body', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + return $this->inBody($token); + } + } + + private function inBody($token) + { + /* Handle the token as follows: */ + + switch ($token['type']) { + /* A character token */ + case HTML5::CHARACTR: + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Append the token's character to the current node. */ + $this->insertText($token['data']); + break; + + /* A comment token */ + case HTML5::COMMENT: + /* Append a Comment node to the current node with the data + attribute set to the data given in the comment token. */ + $this->insertComment($token['data']); + break; + + case HTML5::STARTTAG: + switch ($token['name']) { + /* A start tag token whose tag name is one of: "script", + "style" */ + case 'script': + case 'style': + /* Process the token as if the insertion mode had been "in + head". */ + return $this->inHead($token); + break; + + /* A start tag token whose tag name is one of: "base", "link", + "meta", "title" */ + case 'base': + case 'link': + case 'meta': + case 'title': + /* Parse error. Process the token as if the insertion mode + had been "in head". */ + return $this->inHead($token); + break; + + /* A start tag token with the tag name "body" */ + case 'body': + /* Parse error. If the second element on the stack of open + elements is not a body element, or, if the stack of open + elements has only one node on it, then ignore the token. + (innerHTML case) */ + if (count($this->stack) === 1 || $this->stack[1]->nodeName !== 'body') { + // Ignore + + /* Otherwise, for each attribute on the token, check to see + if the attribute is already present on the body element (the + second element) on the stack of open elements. If it is not, + add the attribute and its corresponding value to that + element. */ + } else { + foreach ($token['attr'] as $attr) { + if (!$this->stack[1]->hasAttribute($attr['name'])) { + $this->stack[1]->setAttribute($attr['name'], $attr['value']); + } + } + } + break; + + /* A start tag whose tag name is one of: "address", + "blockquote", "center", "dir", "div", "dl", "fieldset", + "listing", "menu", "ol", "p", "ul" */ + case 'address': + case 'blockquote': + case 'center': + case 'dir': + case 'div': + case 'dl': + case 'fieldset': + case 'listing': + case 'menu': + case 'ol': + case 'p': + case 'ul': + /* If the stack of open elements has a p element in scope, + then act as if an end tag with the tag name p had been + seen. */ + if ($this->elementInScope('p')) { + $this->emitToken( + array( + 'name' => 'p', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + break; + + /* A start tag whose tag name is "form" */ + case 'form': + /* If the form element pointer is not null, ignore the + token with a parse error. */ + if ($this->form_pointer !== null) { + // Ignore. + + /* Otherwise: */ + } else { + /* If the stack of open elements has a p element in + scope, then act as if an end tag with the tag name p + had been seen. */ + if ($this->elementInScope('p')) { + $this->emitToken( + array( + 'name' => 'p', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* Insert an HTML element for the token, and set the + form element pointer to point to the element created. */ + $element = $this->insertElement($token); + $this->form_pointer = $element; + } + break; + + /* A start tag whose tag name is "li", "dd" or "dt" */ + case 'li': + case 'dd': + case 'dt': + /* If the stack of open elements has a p element in scope, + then act as if an end tag with the tag name p had been + seen. */ + if ($this->elementInScope('p')) { + $this->emitToken( + array( + 'name' => 'p', + 'type' => HTML5::ENDTAG + ) + ); + } + + $stack_length = count($this->stack) - 1; + + for ($n = $stack_length; 0 <= $n; $n--) { + /* 1. Initialise node to be the current node (the + bottommost node of the stack). */ + $stop = false; + $node = $this->stack[$n]; + $cat = $this->getElementCategory($node->tagName); + + /* 2. If node is an li, dd or dt element, then pop all + the nodes from the current node up to node, including + node, then stop this algorithm. */ + if ($token['name'] === $node->tagName || ($token['name'] !== 'li' + && ($node->tagName === 'dd' || $node->tagName === 'dt')) + ) { + for ($x = $stack_length; $x >= $n; $x--) { + array_pop($this->stack); + } + + break; + } + + /* 3. If node is not in the formatting category, and is + not in the phrasing category, and is not an address or + div element, then stop this algorithm. */ + if ($cat !== self::FORMATTING && $cat !== self::PHRASING && + $node->tagName !== 'address' && $node->tagName !== 'div' + ) { + break; + } + } + + /* Finally, insert an HTML element with the same tag + name as the token's. */ + $this->insertElement($token); + break; + + /* A start tag token whose tag name is "plaintext" */ + case 'plaintext': + /* If the stack of open elements has a p element in scope, + then act as if an end tag with the tag name p had been + seen. */ + if ($this->elementInScope('p')) { + $this->emitToken( + array( + 'name' => 'p', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + return HTML5::PLAINTEXT; + break; + + /* A start tag whose tag name is one of: "h1", "h2", "h3", "h4", + "h5", "h6" */ + case 'h1': + case 'h2': + case 'h3': + case 'h4': + case 'h5': + case 'h6': + /* If the stack of open elements has a p element in scope, + then act as if an end tag with the tag name p had been seen. */ + if ($this->elementInScope('p')) { + $this->emitToken( + array( + 'name' => 'p', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* If the stack of open elements has in scope an element whose + tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then + this is a parse error; pop elements from the stack until an + element with one of those tag names has been popped from the + stack. */ + while ($this->elementInScope(array('h1', 'h2', 'h3', 'h4', 'h5', 'h6'))) { + array_pop($this->stack); + } + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + break; + + /* A start tag whose tag name is "a" */ + case 'a': + /* If the list of active formatting elements contains + an element whose tag name is "a" between the end of the + list and the last marker on the list (or the start of + the list if there is no marker on the list), then this + is a parse error; act as if an end tag with the tag name + "a" had been seen, then remove that element from the list + of active formatting elements and the stack of open + elements if the end tag didn't already remove it (it + might not have if the element is not in table scope). */ + $leng = count($this->a_formatting); + + for ($n = $leng - 1; $n >= 0; $n--) { + if ($this->a_formatting[$n] === self::MARKER) { + break; + + } elseif ($this->a_formatting[$n]->nodeName === 'a') { + $this->emitToken( + array( + 'name' => 'a', + 'type' => HTML5::ENDTAG + ) + ); + break; + } + } + + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Insert an HTML element for the token. */ + $el = $this->insertElement($token); + + /* Add that element to the list of active formatting + elements. */ + $this->a_formatting[] = $el; + break; + + /* A start tag whose tag name is one of: "b", "big", "em", "font", + "i", "nobr", "s", "small", "strike", "strong", "tt", "u" */ + case 'b': + case 'big': + case 'em': + case 'font': + case 'i': + case 'nobr': + case 's': + case 'small': + case 'strike': + case 'strong': + case 'tt': + case 'u': + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Insert an HTML element for the token. */ + $el = $this->insertElement($token); + + /* Add that element to the list of active formatting + elements. */ + $this->a_formatting[] = $el; + break; + + /* A start tag token whose tag name is "button" */ + case 'button': + /* If the stack of open elements has a button element in scope, + then this is a parse error; act as if an end tag with the tag + name "button" had been seen, then reprocess the token. (We don't + do that. Unnecessary.) */ + if ($this->elementInScope('button')) { + $this->inBody( + array( + 'name' => 'button', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* Insert a marker at the end of the list of active + formatting elements. */ + $this->a_formatting[] = self::MARKER; + break; + + /* A start tag token whose tag name is one of: "marquee", "object" */ + case 'marquee': + case 'object': + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* Insert a marker at the end of the list of active + formatting elements. */ + $this->a_formatting[] = self::MARKER; + break; + + /* A start tag token whose tag name is "xmp" */ + case 'xmp': + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* Switch the content model flag to the CDATA state. */ + return HTML5::CDATA; + break; + + /* A start tag whose tag name is "table" */ + case 'table': + /* If the stack of open elements has a p element in scope, + then act as if an end tag with the tag name p had been seen. */ + if ($this->elementInScope('p')) { + $this->emitToken( + array( + 'name' => 'p', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* Change the insertion mode to "in table". */ + $this->mode = self::IN_TABLE; + break; + + /* A start tag whose tag name is one of: "area", "basefont", + "bgsound", "br", "embed", "img", "param", "spacer", "wbr" */ + case 'area': + case 'basefont': + case 'bgsound': + case 'br': + case 'embed': + case 'img': + case 'param': + case 'spacer': + case 'wbr': + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* Immediately pop the current node off the stack of open elements. */ + array_pop($this->stack); + break; + + /* A start tag whose tag name is "hr" */ + case 'hr': + /* If the stack of open elements has a p element in scope, + then act as if an end tag with the tag name p had been seen. */ + if ($this->elementInScope('p')) { + $this->emitToken( + array( + 'name' => 'p', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* Immediately pop the current node off the stack of open elements. */ + array_pop($this->stack); + break; + + /* A start tag whose tag name is "image" */ + case 'image': + /* Parse error. Change the token's tag name to "img" and + reprocess it. (Don't ask.) */ + $token['name'] = 'img'; + return $this->inBody($token); + break; + + /* A start tag whose tag name is "input" */ + case 'input': + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Insert an input element for the token. */ + $element = $this->insertElement($token, false); + + /* If the form element pointer is not null, then associate the + input element with the form element pointed to by the form + element pointer. */ + $this->form_pointer !== null + ? $this->form_pointer->appendChild($element) + : end($this->stack)->appendChild($element); + + /* Pop that input element off the stack of open elements. */ + array_pop($this->stack); + break; + + /* A start tag whose tag name is "isindex" */ + case 'isindex': + /* Parse error. */ + // w/e + + /* If the form element pointer is not null, + then ignore the token. */ + if ($this->form_pointer === null) { + /* Act as if a start tag token with the tag name "form" had + been seen. */ + $this->inBody( + array( + 'name' => 'body', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + /* Act as if a start tag token with the tag name "hr" had + been seen. */ + $this->inBody( + array( + 'name' => 'hr', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + /* Act as if a start tag token with the tag name "p" had + been seen. */ + $this->inBody( + array( + 'name' => 'p', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + /* Act as if a start tag token with the tag name "label" + had been seen. */ + $this->inBody( + array( + 'name' => 'label', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + /* Act as if a stream of character tokens had been seen. */ + $this->insertText( + 'This is a searchable index. ' . + 'Insert your search keywords here: ' + ); + + /* Act as if a start tag token with the tag name "input" + had been seen, with all the attributes from the "isindex" + token, except with the "name" attribute set to the value + "isindex" (ignoring any explicit "name" attribute). */ + $attr = $token['attr']; + $attr[] = array('name' => 'name', 'value' => 'isindex'); + + $this->inBody( + array( + 'name' => 'input', + 'type' => HTML5::STARTTAG, + 'attr' => $attr + ) + ); + + /* Act as if a stream of character tokens had been seen + (see below for what they should say). */ + $this->insertText( + 'This is a searchable index. ' . + 'Insert your search keywords here: ' + ); + + /* Act as if an end tag token with the tag name "label" + had been seen. */ + $this->inBody( + array( + 'name' => 'label', + 'type' => HTML5::ENDTAG + ) + ); + + /* Act as if an end tag token with the tag name "p" had + been seen. */ + $this->inBody( + array( + 'name' => 'p', + 'type' => HTML5::ENDTAG + ) + ); + + /* Act as if a start tag token with the tag name "hr" had + been seen. */ + $this->inBody( + array( + 'name' => 'hr', + 'type' => HTML5::ENDTAG + ) + ); + + /* Act as if an end tag token with the tag name "form" had + been seen. */ + $this->inBody( + array( + 'name' => 'form', + 'type' => HTML5::ENDTAG + ) + ); + } + break; + + /* A start tag whose tag name is "textarea" */ + case 'textarea': + $this->insertElement($token); + + /* Switch the tokeniser's content model flag to the + RCDATA state. */ + return HTML5::RCDATA; + break; + + /* A start tag whose tag name is one of: "iframe", "noembed", + "noframes" */ + case 'iframe': + case 'noembed': + case 'noframes': + $this->insertElement($token); + + /* Switch the tokeniser's content model flag to the CDATA state. */ + return HTML5::CDATA; + break; + + /* A start tag whose tag name is "select" */ + case 'select': + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* Change the insertion mode to "in select". */ + $this->mode = self::IN_SELECT; + break; + + /* A start or end tag whose tag name is one of: "caption", "col", + "colgroup", "frame", "frameset", "head", "option", "optgroup", + "tbody", "td", "tfoot", "th", "thead", "tr". */ + case 'caption': + case 'col': + case 'colgroup': + case 'frame': + case 'frameset': + case 'head': + case 'option': + case 'optgroup': + case 'tbody': + case 'td': + case 'tfoot': + case 'th': + case 'thead': + case 'tr': + // Parse error. Ignore the token. + break; + + /* A start or end tag whose tag name is one of: "event-source", + "section", "nav", "article", "aside", "header", "footer", + "datagrid", "command" */ + case 'event-source': + case 'section': + case 'nav': + case 'article': + case 'aside': + case 'header': + case 'footer': + case 'datagrid': + case 'command': + // Work in progress! + break; + + /* A start tag token not covered by the previous entries */ + default: + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + $this->insertElement($token, true, true); + break; + } + break; + + case HTML5::ENDTAG: + switch ($token['name']) { + /* An end tag with the tag name "body" */ + case 'body': + /* If the second element in the stack of open elements is + not a body element, this is a parse error. Ignore the token. + (innerHTML case) */ + if (count($this->stack) < 2 || $this->stack[1]->nodeName !== 'body') { + // Ignore. + + /* If the current node is not the body element, then this + is a parse error. */ + } elseif (end($this->stack)->nodeName !== 'body') { + // Parse error. + } + + /* Change the insertion mode to "after body". */ + $this->mode = self::AFTER_BODY; + break; + + /* An end tag with the tag name "html" */ + case 'html': + /* Act as if an end tag with tag name "body" had been seen, + then, if that token wasn't ignored, reprocess the current + token. */ + $this->inBody( + array( + 'name' => 'body', + 'type' => HTML5::ENDTAG + ) + ); + + return $this->afterBody($token); + break; + + /* An end tag whose tag name is one of: "address", "blockquote", + "center", "dir", "div", "dl", "fieldset", "listing", "menu", + "ol", "pre", "ul" */ + case 'address': + case 'blockquote': + case 'center': + case 'dir': + case 'div': + case 'dl': + case 'fieldset': + case 'listing': + case 'menu': + case 'ol': + case 'pre': + case 'ul': + /* If the stack of open elements has an element in scope + with the same tag name as that of the token, then generate + implied end tags. */ + if ($this->elementInScope($token['name'])) { + $this->generateImpliedEndTags(); + + /* Now, if the current node is not an element with + the same tag name as that of the token, then this + is a parse error. */ + // w/e + + /* If the stack of open elements has an element in + scope with the same tag name as that of the token, + then pop elements from this stack until an element + with that tag name has been popped from the stack. */ + for ($n = count($this->stack) - 1; $n >= 0; $n--) { + if ($this->stack[$n]->nodeName === $token['name']) { + $n = -1; + } + + array_pop($this->stack); + } + } + break; + + /* An end tag whose tag name is "form" */ + case 'form': + /* If the stack of open elements has an element in scope + with the same tag name as that of the token, then generate + implied end tags. */ + if ($this->elementInScope($token['name'])) { + $this->generateImpliedEndTags(); + + } + + if (end($this->stack)->nodeName !== $token['name']) { + /* Now, if the current node is not an element with the + same tag name as that of the token, then this is a parse + error. */ + // w/e + + } else { + /* Otherwise, if the current node is an element with + the same tag name as that of the token pop that element + from the stack. */ + array_pop($this->stack); + } + + /* In any case, set the form element pointer to null. */ + $this->form_pointer = null; + break; + + /* An end tag whose tag name is "p" */ + case 'p': + /* If the stack of open elements has a p element in scope, + then generate implied end tags, except for p elements. */ + if ($this->elementInScope('p')) { + $this->generateImpliedEndTags(array('p')); + + /* If the current node is not a p element, then this is + a parse error. */ + // k + + /* If the stack of open elements has a p element in + scope, then pop elements from this stack until the stack + no longer has a p element in scope. */ + for ($n = count($this->stack) - 1; $n >= 0; $n--) { + if ($this->elementInScope('p')) { + array_pop($this->stack); + + } else { + break; + } + } + } + break; + + /* An end tag whose tag name is "dd", "dt", or "li" */ + case 'dd': + case 'dt': + case 'li': + /* If the stack of open elements has an element in scope + whose tag name matches the tag name of the token, then + generate implied end tags, except for elements with the + same tag name as the token. */ + if ($this->elementInScope($token['name'])) { + $this->generateImpliedEndTags(array($token['name'])); + + /* If the current node is not an element with the same + tag name as the token, then this is a parse error. */ + // w/e + + /* If the stack of open elements has an element in scope + whose tag name matches the tag name of the token, then + pop elements from this stack until an element with that + tag name has been popped from the stack. */ + for ($n = count($this->stack) - 1; $n >= 0; $n--) { + if ($this->stack[$n]->nodeName === $token['name']) { + $n = -1; + } + + array_pop($this->stack); + } + } + break; + + /* An end tag whose tag name is one of: "h1", "h2", "h3", "h4", + "h5", "h6" */ + case 'h1': + case 'h2': + case 'h3': + case 'h4': + case 'h5': + case 'h6': + $elements = array('h1', 'h2', 'h3', 'h4', 'h5', 'h6'); + + /* If the stack of open elements has in scope an element whose + tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then + generate implied end tags. */ + if ($this->elementInScope($elements)) { + $this->generateImpliedEndTags(); + + /* Now, if the current node is not an element with the same + tag name as that of the token, then this is a parse error. */ + // w/e + + /* If the stack of open elements has in scope an element + whose tag name is one of "h1", "h2", "h3", "h4", "h5", or + "h6", then pop elements from the stack until an element + with one of those tag names has been popped from the stack. */ + while ($this->elementInScope($elements)) { + array_pop($this->stack); + } + } + break; + + /* An end tag whose tag name is one of: "a", "b", "big", "em", + "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u" */ + case 'a': + case 'b': + case 'big': + case 'em': + case 'font': + case 'i': + case 'nobr': + case 's': + case 'small': + case 'strike': + case 'strong': + case 'tt': + case 'u': + /* 1. Let the formatting element be the last element in + the list of active formatting elements that: + * is between the end of the list and the last scope + marker in the list, if any, or the start of the list + otherwise, and + * has the same tag name as the token. + */ + while (true) { + for ($a = count($this->a_formatting) - 1; $a >= 0; $a--) { + if ($this->a_formatting[$a] === self::MARKER) { + break; + + } elseif ($this->a_formatting[$a]->tagName === $token['name']) { + $formatting_element = $this->a_formatting[$a]; + $in_stack = in_array($formatting_element, $this->stack, true); + $fe_af_pos = $a; + break; + } + } + + /* If there is no such node, or, if that node is + also in the stack of open elements but the element + is not in scope, then this is a parse error. Abort + these steps. The token is ignored. */ + if (!isset($formatting_element) || ($in_stack && + !$this->elementInScope($token['name'])) + ) { + break; + + /* Otherwise, if there is such a node, but that node + is not in the stack of open elements, then this is a + parse error; remove the element from the list, and + abort these steps. */ + } elseif (isset($formatting_element) && !$in_stack) { + unset($this->a_formatting[$fe_af_pos]); + $this->a_formatting = array_merge($this->a_formatting); + break; + } + + /* 2. Let the furthest block be the topmost node in the + stack of open elements that is lower in the stack + than the formatting element, and is not an element in + the phrasing or formatting categories. There might + not be one. */ + $fe_s_pos = array_search($formatting_element, $this->stack, true); + $length = count($this->stack); + + for ($s = $fe_s_pos + 1; $s < $length; $s++) { + $category = $this->getElementCategory($this->stack[$s]->nodeName); + + if ($category !== self::PHRASING && $category !== self::FORMATTING) { + $furthest_block = $this->stack[$s]; + } + } + + /* 3. If there is no furthest block, then the UA must + skip the subsequent steps and instead just pop all + the nodes from the bottom of the stack of open + elements, from the current node up to the formatting + element, and remove the formatting element from the + list of active formatting elements. */ + if (!isset($furthest_block)) { + for ($n = $length - 1; $n >= $fe_s_pos; $n--) { + array_pop($this->stack); + } + + unset($this->a_formatting[$fe_af_pos]); + $this->a_formatting = array_merge($this->a_formatting); + break; + } + + /* 4. Let the common ancestor be the element + immediately above the formatting element in the stack + of open elements. */ + $common_ancestor = $this->stack[$fe_s_pos - 1]; + + /* 5. If the furthest block has a parent node, then + remove the furthest block from its parent node. */ + if ($furthest_block->parentNode !== null) { + $furthest_block->parentNode->removeChild($furthest_block); + } + + /* 6. Let a bookmark note the position of the + formatting element in the list of active formatting + elements relative to the elements on either side + of it in the list. */ + $bookmark = $fe_af_pos; + + /* 7. Let node and last node be the furthest block. + Follow these steps: */ + $node = $furthest_block; + $last_node = $furthest_block; + + while (true) { + for ($n = array_search($node, $this->stack, true) - 1; $n >= 0; $n--) { + /* 7.1 Let node be the element immediately + prior to node in the stack of open elements. */ + $node = $this->stack[$n]; + + /* 7.2 If node is not in the list of active + formatting elements, then remove node from + the stack of open elements and then go back + to step 1. */ + if (!in_array($node, $this->a_formatting, true)) { + unset($this->stack[$n]); + $this->stack = array_merge($this->stack); + + } else { + break; + } + } + + /* 7.3 Otherwise, if node is the formatting + element, then go to the next step in the overall + algorithm. */ + if ($node === $formatting_element) { + break; + + /* 7.4 Otherwise, if last node is the furthest + block, then move the aforementioned bookmark to + be immediately after the node in the list of + active formatting elements. */ + } elseif ($last_node === $furthest_block) { + $bookmark = array_search($node, $this->a_formatting, true) + 1; + } + + /* 7.5 If node has any children, perform a + shallow clone of node, replace the entry for + node in the list of active formatting elements + with an entry for the clone, replace the entry + for node in the stack of open elements with an + entry for the clone, and let node be the clone. */ + if ($node->hasChildNodes()) { + $clone = $node->cloneNode(); + $s_pos = array_search($node, $this->stack, true); + $a_pos = array_search($node, $this->a_formatting, true); + + $this->stack[$s_pos] = $clone; + $this->a_formatting[$a_pos] = $clone; + $node = $clone; + } + + /* 7.6 Insert last node into node, first removing + it from its previous parent node if any. */ + if ($last_node->parentNode !== null) { + $last_node->parentNode->removeChild($last_node); + } + + $node->appendChild($last_node); + + /* 7.7 Let last node be node. */ + $last_node = $node; + } + + /* 8. Insert whatever last node ended up being in + the previous step into the common ancestor node, + first removing it from its previous parent node if + any. */ + if ($last_node->parentNode !== null) { + $last_node->parentNode->removeChild($last_node); + } + + $common_ancestor->appendChild($last_node); + + /* 9. Perform a shallow clone of the formatting + element. */ + $clone = $formatting_element->cloneNode(); + + /* 10. Take all of the child nodes of the furthest + block and append them to the clone created in the + last step. */ + while ($furthest_block->hasChildNodes()) { + $child = $furthest_block->firstChild; + $furthest_block->removeChild($child); + $clone->appendChild($child); + } + + /* 11. Append that clone to the furthest block. */ + $furthest_block->appendChild($clone); + + /* 12. Remove the formatting element from the list + of active formatting elements, and insert the clone + into the list of active formatting elements at the + position of the aforementioned bookmark. */ + $fe_af_pos = array_search($formatting_element, $this->a_formatting, true); + unset($this->a_formatting[$fe_af_pos]); + $this->a_formatting = array_merge($this->a_formatting); + + $af_part1 = array_slice($this->a_formatting, 0, $bookmark - 1); + $af_part2 = array_slice($this->a_formatting, $bookmark, count($this->a_formatting)); + $this->a_formatting = array_merge($af_part1, array($clone), $af_part2); + + /* 13. Remove the formatting element from the stack + of open elements, and insert the clone into the stack + of open elements immediately after (i.e. in a more + deeply nested position than) the position of the + furthest block in that stack. */ + $fe_s_pos = array_search($formatting_element, $this->stack, true); + $fb_s_pos = array_search($furthest_block, $this->stack, true); + unset($this->stack[$fe_s_pos]); + + $s_part1 = array_slice($this->stack, 0, $fb_s_pos); + $s_part2 = array_slice($this->stack, $fb_s_pos + 1, count($this->stack)); + $this->stack = array_merge($s_part1, array($clone), $s_part2); + + /* 14. Jump back to step 1 in this series of steps. */ + unset($formatting_element, $fe_af_pos, $fe_s_pos, $furthest_block); + } + break; + + /* An end tag token whose tag name is one of: "button", + "marquee", "object" */ + case 'button': + case 'marquee': + case 'object': + /* If the stack of open elements has an element in scope whose + tag name matches the tag name of the token, then generate implied + tags. */ + if ($this->elementInScope($token['name'])) { + $this->generateImpliedEndTags(); + + /* Now, if the current node is not an element with the same + tag name as the token, then this is a parse error. */ + // k + + /* Now, if the stack of open elements has an element in scope + whose tag name matches the tag name of the token, then pop + elements from the stack until that element has been popped from + the stack, and clear the list of active formatting elements up + to the last marker. */ + for ($n = count($this->stack) - 1; $n >= 0; $n--) { + if ($this->stack[$n]->nodeName === $token['name']) { + $n = -1; + } + + array_pop($this->stack); + } + + $marker = end(array_keys($this->a_formatting, self::MARKER, true)); + + for ($n = count($this->a_formatting) - 1; $n > $marker; $n--) { + array_pop($this->a_formatting); + } + } + break; + + /* Or an end tag whose tag name is one of: "area", "basefont", + "bgsound", "br", "embed", "hr", "iframe", "image", "img", + "input", "isindex", "noembed", "noframes", "param", "select", + "spacer", "table", "textarea", "wbr" */ + case 'area': + case 'basefont': + case 'bgsound': + case 'br': + case 'embed': + case 'hr': + case 'iframe': + case 'image': + case 'img': + case 'input': + case 'isindex': + case 'noembed': + case 'noframes': + case 'param': + case 'select': + case 'spacer': + case 'table': + case 'textarea': + case 'wbr': + // Parse error. Ignore the token. + break; + + /* An end tag token not covered by the previous entries */ + default: + for ($n = count($this->stack) - 1; $n >= 0; $n--) { + /* Initialise node to be the current node (the bottommost + node of the stack). */ + $node = end($this->stack); + + /* If node has the same tag name as the end tag token, + then: */ + if ($token['name'] === $node->nodeName) { + /* Generate implied end tags. */ + $this->generateImpliedEndTags(); + + /* If the tag name of the end tag token does not + match the tag name of the current node, this is a + parse error. */ + // k + + /* Pop all the nodes from the current node up to + node, including node, then stop this algorithm. */ + for ($x = count($this->stack) - $n; $x >= $n; $x--) { + array_pop($this->stack); + } + + } else { + $category = $this->getElementCategory($node); + + if ($category !== self::SPECIAL && $category !== self::SCOPING) { + /* Otherwise, if node is in neither the formatting + category nor the phrasing category, then this is a + parse error. Stop this algorithm. The end tag token + is ignored. */ + return false; + } + } + } + break; + } + break; + } + } + + private function inTable($token) + { + $clear = array('html', 'table'); + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE */ + if ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Append the character to the current node. */ + $text = $this->dom->createTextNode($token['data']); + end($this->stack)->appendChild($text); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the current node with the data + attribute set to the data given in the comment token. */ + $comment = $this->dom->createComment($token['data']); + end($this->stack)->appendChild($comment); + + /* A start tag whose tag name is "caption" */ + } elseif ($token['type'] === HTML5::STARTTAG && + $token['name'] === 'caption' + ) { + /* Clear the stack back to a table context. */ + $this->clearStackToTableContext($clear); + + /* Insert a marker at the end of the list of active + formatting elements. */ + $this->a_formatting[] = self::MARKER; + + /* Insert an HTML element for the token, then switch the + insertion mode to "in caption". */ + $this->insertElement($token); + $this->mode = self::IN_CAPTION; + + /* A start tag whose tag name is "colgroup" */ + } elseif ($token['type'] === HTML5::STARTTAG && + $token['name'] === 'colgroup' + ) { + /* Clear the stack back to a table context. */ + $this->clearStackToTableContext($clear); + + /* Insert an HTML element for the token, then switch the + insertion mode to "in column group". */ + $this->insertElement($token); + $this->mode = self::IN_CGROUP; + + /* A start tag whose tag name is "col" */ + } elseif ($token['type'] === HTML5::STARTTAG && + $token['name'] === 'col' + ) { + $this->inTable( + array( + 'name' => 'colgroup', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + $this->inColumnGroup($token); + + /* A start tag whose tag name is one of: "tbody", "tfoot", "thead" */ + } elseif ($token['type'] === HTML5::STARTTAG && in_array( + $token['name'], + array('tbody', 'tfoot', 'thead') + ) + ) { + /* Clear the stack back to a table context. */ + $this->clearStackToTableContext($clear); + + /* Insert an HTML element for the token, then switch the insertion + mode to "in table body". */ + $this->insertElement($token); + $this->mode = self::IN_TBODY; + + /* A start tag whose tag name is one of: "td", "th", "tr" */ + } elseif ($token['type'] === HTML5::STARTTAG && + in_array($token['name'], array('td', 'th', 'tr')) + ) { + /* Act as if a start tag token with the tag name "tbody" had been + seen, then reprocess the current token. */ + $this->inTable( + array( + 'name' => 'tbody', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + return $this->inTableBody($token); + + /* A start tag whose tag name is "table" */ + } elseif ($token['type'] === HTML5::STARTTAG && + $token['name'] === 'table' + ) { + /* Parse error. Act as if an end tag token with the tag name "table" + had been seen, then, if that token wasn't ignored, reprocess the + current token. */ + $this->inTable( + array( + 'name' => 'table', + 'type' => HTML5::ENDTAG + ) + ); + + return $this->mainPhase($token); + + /* An end tag whose tag name is "table" */ + } elseif ($token['type'] === HTML5::ENDTAG && + $token['name'] === 'table' + ) { + /* If the stack of open elements does not have an element in table + scope with the same tag name as the token, this is a parse error. + Ignore the token. (innerHTML case) */ + if (!$this->elementInScope($token['name'], true)) { + return false; + + /* Otherwise: */ + } else { + /* Generate implied end tags. */ + $this->generateImpliedEndTags(); + + /* Now, if the current node is not a table element, then this + is a parse error. */ + // w/e + + /* Pop elements from this stack until a table element has been + popped from the stack. */ + while (true) { + $current = end($this->stack)->nodeName; + array_pop($this->stack); + + if ($current === 'table') { + break; + } + } + + /* Reset the insertion mode appropriately. */ + $this->resetInsertionMode(); + } + + /* An end tag whose tag name is one of: "body", "caption", "col", + "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr" */ + } elseif ($token['type'] === HTML5::ENDTAG && in_array( + $token['name'], + array( + 'body', + 'caption', + 'col', + 'colgroup', + 'html', + 'tbody', + 'td', + 'tfoot', + 'th', + 'thead', + 'tr' + ) + ) + ) { + // Parse error. Ignore the token. + + /* Anything else */ + } else { + /* Parse error. Process the token as if the insertion mode was "in + body", with the following exception: */ + + /* If the current node is a table, tbody, tfoot, thead, or tr + element, then, whenever a node would be inserted into the current + node, it must instead be inserted into the foster parent element. */ + if (in_array( + end($this->stack)->nodeName, + array('table', 'tbody', 'tfoot', 'thead', 'tr') + ) + ) { + /* The foster parent element is the parent element of the last + table element in the stack of open elements, if there is a + table element and it has such a parent element. If there is no + table element in the stack of open elements (innerHTML case), + then the foster parent element is the first element in the + stack of open elements (the html element). Otherwise, if there + is a table element in the stack of open elements, but the last + table element in the stack of open elements has no parent, or + its parent node is not an element, then the foster parent + element is the element before the last table element in the + stack of open elements. */ + for ($n = count($this->stack) - 1; $n >= 0; $n--) { + if ($this->stack[$n]->nodeName === 'table') { + $table = $this->stack[$n]; + break; + } + } + + if (isset($table) && $table->parentNode !== null) { + $this->foster_parent = $table->parentNode; + + } elseif (!isset($table)) { + $this->foster_parent = $this->stack[0]; + + } elseif (isset($table) && ($table->parentNode === null || + $table->parentNode->nodeType !== XML_ELEMENT_NODE) + ) { + $this->foster_parent = $this->stack[$n - 1]; + } + } + + $this->inBody($token); + } + } + + private function inCaption($token) + { + /* An end tag whose tag name is "caption" */ + if ($token['type'] === HTML5::ENDTAG && $token['name'] === 'caption') { + /* If the stack of open elements does not have an element in table + scope with the same tag name as the token, this is a parse error. + Ignore the token. (innerHTML case) */ + if (!$this->elementInScope($token['name'], true)) { + // Ignore + + /* Otherwise: */ + } else { + /* Generate implied end tags. */ + $this->generateImpliedEndTags(); + + /* Now, if the current node is not a caption element, then this + is a parse error. */ + // w/e + + /* Pop elements from this stack until a caption element has + been popped from the stack. */ + while (true) { + $node = end($this->stack)->nodeName; + array_pop($this->stack); + + if ($node === 'caption') { + break; + } + } + + /* Clear the list of active formatting elements up to the last + marker. */ + $this->clearTheActiveFormattingElementsUpToTheLastMarker(); + + /* Switch the insertion mode to "in table". */ + $this->mode = self::IN_TABLE; + } + + /* A start tag whose tag name is one of: "caption", "col", "colgroup", + "tbody", "td", "tfoot", "th", "thead", "tr", or an end tag whose tag + name is "table" */ + } elseif (($token['type'] === HTML5::STARTTAG && in_array( + $token['name'], + array( + 'caption', + 'col', + 'colgroup', + 'tbody', + 'td', + 'tfoot', + 'th', + 'thead', + 'tr' + ) + )) || ($token['type'] === HTML5::ENDTAG && + $token['name'] === 'table') + ) { + /* Parse error. Act as if an end tag with the tag name "caption" + had been seen, then, if that token wasn't ignored, reprocess the + current token. */ + $this->inCaption( + array( + 'name' => 'caption', + 'type' => HTML5::ENDTAG + ) + ); + + return $this->inTable($token); + + /* An end tag whose tag name is one of: "body", "col", "colgroup", + "html", "tbody", "td", "tfoot", "th", "thead", "tr" */ + } elseif ($token['type'] === HTML5::ENDTAG && in_array( + $token['name'], + array( + 'body', + 'col', + 'colgroup', + 'html', + 'tbody', + 'tfoot', + 'th', + 'thead', + 'tr' + ) + ) + ) { + // Parse error. Ignore the token. + + /* Anything else */ + } else { + /* Process the token as if the insertion mode was "in body". */ + $this->inBody($token); + } + } + + private function inColumnGroup($token) + { + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE */ + if ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Append the character to the current node. */ + $text = $this->dom->createTextNode($token['data']); + end($this->stack)->appendChild($text); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the current node with the data + attribute set to the data given in the comment token. */ + $comment = $this->dom->createComment($token['data']); + end($this->stack)->appendChild($comment); + + /* A start tag whose tag name is "col" */ + } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'col') { + /* Insert a col element for the token. Immediately pop the current + node off the stack of open elements. */ + $this->insertElement($token); + array_pop($this->stack); + + /* An end tag whose tag name is "colgroup" */ + } elseif ($token['type'] === HTML5::ENDTAG && + $token['name'] === 'colgroup' + ) { + /* If the current node is the root html element, then this is a + parse error, ignore the token. (innerHTML case) */ + if (end($this->stack)->nodeName === 'html') { + // Ignore + + /* Otherwise, pop the current node (which will be a colgroup + element) from the stack of open elements. Switch the insertion + mode to "in table". */ + } else { + array_pop($this->stack); + $this->mode = self::IN_TABLE; + } + + /* An end tag whose tag name is "col" */ + } elseif ($token['type'] === HTML5::ENDTAG && $token['name'] === 'col') { + /* Parse error. Ignore the token. */ + + /* Anything else */ + } else { + /* Act as if an end tag with the tag name "colgroup" had been seen, + and then, if that token wasn't ignored, reprocess the current token. */ + $this->inColumnGroup( + array( + 'name' => 'colgroup', + 'type' => HTML5::ENDTAG + ) + ); + + return $this->inTable($token); + } + } + + private function inTableBody($token) + { + $clear = array('tbody', 'tfoot', 'thead', 'html'); + + /* A start tag whose tag name is "tr" */ + if ($token['type'] === HTML5::STARTTAG && $token['name'] === 'tr') { + /* Clear the stack back to a table body context. */ + $this->clearStackToTableContext($clear); + + /* Insert a tr element for the token, then switch the insertion + mode to "in row". */ + $this->insertElement($token); + $this->mode = self::IN_ROW; + + /* A start tag whose tag name is one of: "th", "td" */ + } elseif ($token['type'] === HTML5::STARTTAG && + ($token['name'] === 'th' || $token['name'] === 'td') + ) { + /* Parse error. Act as if a start tag with the tag name "tr" had + been seen, then reprocess the current token. */ + $this->inTableBody( + array( + 'name' => 'tr', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + return $this->inRow($token); + + /* An end tag whose tag name is one of: "tbody", "tfoot", "thead" */ + } elseif ($token['type'] === HTML5::ENDTAG && + in_array($token['name'], array('tbody', 'tfoot', 'thead')) + ) { + /* If the stack of open elements does not have an element in table + scope with the same tag name as the token, this is a parse error. + Ignore the token. */ + if (!$this->elementInScope($token['name'], true)) { + // Ignore + + /* Otherwise: */ + } else { + /* Clear the stack back to a table body context. */ + $this->clearStackToTableContext($clear); + + /* Pop the current node from the stack of open elements. Switch + the insertion mode to "in table". */ + array_pop($this->stack); + $this->mode = self::IN_TABLE; + } + + /* A start tag whose tag name is one of: "caption", "col", "colgroup", + "tbody", "tfoot", "thead", or an end tag whose tag name is "table" */ + } elseif (($token['type'] === HTML5::STARTTAG && in_array( + $token['name'], + array('caption', 'col', 'colgroup', 'tbody', 'tfoor', 'thead') + )) || + ($token['type'] === HTML5::STARTTAG && $token['name'] === 'table') + ) { + /* If the stack of open elements does not have a tbody, thead, or + tfoot element in table scope, this is a parse error. Ignore the + token. (innerHTML case) */ + if (!$this->elementInScope(array('tbody', 'thead', 'tfoot'), true)) { + // Ignore. + + /* Otherwise: */ + } else { + /* Clear the stack back to a table body context. */ + $this->clearStackToTableContext($clear); + + /* Act as if an end tag with the same tag name as the current + node ("tbody", "tfoot", or "thead") had been seen, then + reprocess the current token. */ + $this->inTableBody( + array( + 'name' => end($this->stack)->nodeName, + 'type' => HTML5::ENDTAG + ) + ); + + return $this->mainPhase($token); + } + + /* An end tag whose tag name is one of: "body", "caption", "col", + "colgroup", "html", "td", "th", "tr" */ + } elseif ($token['type'] === HTML5::ENDTAG && in_array( + $token['name'], + array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr') + ) + ) { + /* Parse error. Ignore the token. */ + + /* Anything else */ + } else { + /* Process the token as if the insertion mode was "in table". */ + $this->inTable($token); + } + } + + private function inRow($token) + { + $clear = array('tr', 'html'); + + /* A start tag whose tag name is one of: "th", "td" */ + if ($token['type'] === HTML5::STARTTAG && + ($token['name'] === 'th' || $token['name'] === 'td') + ) { + /* Clear the stack back to a table row context. */ + $this->clearStackToTableContext($clear); + + /* Insert an HTML element for the token, then switch the insertion + mode to "in cell". */ + $this->insertElement($token); + $this->mode = self::IN_CELL; + + /* Insert a marker at the end of the list of active formatting + elements. */ + $this->a_formatting[] = self::MARKER; + + /* An end tag whose tag name is "tr" */ + } elseif ($token['type'] === HTML5::ENDTAG && $token['name'] === 'tr') { + /* If the stack of open elements does not have an element in table + scope with the same tag name as the token, this is a parse error. + Ignore the token. (innerHTML case) */ + if (!$this->elementInScope($token['name'], true)) { + // Ignore. + + /* Otherwise: */ + } else { + /* Clear the stack back to a table row context. */ + $this->clearStackToTableContext($clear); + + /* Pop the current node (which will be a tr element) from the + stack of open elements. Switch the insertion mode to "in table + body". */ + array_pop($this->stack); + $this->mode = self::IN_TBODY; + } + + /* A start tag whose tag name is one of: "caption", "col", "colgroup", + "tbody", "tfoot", "thead", "tr" or an end tag whose tag name is "table" */ + } elseif ($token['type'] === HTML5::STARTTAG && in_array( + $token['name'], + array('caption', 'col', 'colgroup', 'tbody', 'tfoot', 'thead', 'tr') + ) + ) { + /* Act as if an end tag with the tag name "tr" had been seen, then, + if that token wasn't ignored, reprocess the current token. */ + $this->inRow( + array( + 'name' => 'tr', + 'type' => HTML5::ENDTAG + ) + ); + + return $this->inCell($token); + + /* An end tag whose tag name is one of: "tbody", "tfoot", "thead" */ + } elseif ($token['type'] === HTML5::ENDTAG && + in_array($token['name'], array('tbody', 'tfoot', 'thead')) + ) { + /* If the stack of open elements does not have an element in table + scope with the same tag name as the token, this is a parse error. + Ignore the token. */ + if (!$this->elementInScope($token['name'], true)) { + // Ignore. + + /* Otherwise: */ + } else { + /* Otherwise, act as if an end tag with the tag name "tr" had + been seen, then reprocess the current token. */ + $this->inRow( + array( + 'name' => 'tr', + 'type' => HTML5::ENDTAG + ) + ); + + return $this->inCell($token); + } + + /* An end tag whose tag name is one of: "body", "caption", "col", + "colgroup", "html", "td", "th" */ + } elseif ($token['type'] === HTML5::ENDTAG && in_array( + $token['name'], + array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr') + ) + ) { + /* Parse error. Ignore the token. */ + + /* Anything else */ + } else { + /* Process the token as if the insertion mode was "in table". */ + $this->inTable($token); + } + } + + private function inCell($token) + { + /* An end tag whose tag name is one of: "td", "th" */ + if ($token['type'] === HTML5::ENDTAG && + ($token['name'] === 'td' || $token['name'] === 'th') + ) { + /* If the stack of open elements does not have an element in table + scope with the same tag name as that of the token, then this is a + parse error and the token must be ignored. */ + if (!$this->elementInScope($token['name'], true)) { + // Ignore. + + /* Otherwise: */ + } else { + /* Generate implied end tags, except for elements with the same + tag name as the token. */ + $this->generateImpliedEndTags(array($token['name'])); + + /* Now, if the current node is not an element with the same tag + name as the token, then this is a parse error. */ + // k + + /* Pop elements from this stack until an element with the same + tag name as the token has been popped from the stack. */ + while (true) { + $node = end($this->stack)->nodeName; + array_pop($this->stack); + + if ($node === $token['name']) { + break; + } + } + + /* Clear the list of active formatting elements up to the last + marker. */ + $this->clearTheActiveFormattingElementsUpToTheLastMarker(); + + /* Switch the insertion mode to "in row". (The current node + will be a tr element at this point.) */ + $this->mode = self::IN_ROW; + } + + /* A start tag whose tag name is one of: "caption", "col", "colgroup", + "tbody", "td", "tfoot", "th", "thead", "tr" */ + } elseif ($token['type'] === HTML5::STARTTAG && in_array( + $token['name'], + array( + 'caption', + 'col', + 'colgroup', + 'tbody', + 'td', + 'tfoot', + 'th', + 'thead', + 'tr' + ) + ) + ) { + /* If the stack of open elements does not have a td or th element + in table scope, then this is a parse error; ignore the token. + (innerHTML case) */ + if (!$this->elementInScope(array('td', 'th'), true)) { + // Ignore. + + /* Otherwise, close the cell (see below) and reprocess the current + token. */ + } else { + $this->closeCell(); + return $this->inRow($token); + } + + /* A start tag whose tag name is one of: "caption", "col", "colgroup", + "tbody", "td", "tfoot", "th", "thead", "tr" */ + } elseif ($token['type'] === HTML5::STARTTAG && in_array( + $token['name'], + array( + 'caption', + 'col', + 'colgroup', + 'tbody', + 'td', + 'tfoot', + 'th', + 'thead', + 'tr' + ) + ) + ) { + /* If the stack of open elements does not have a td or th element + in table scope, then this is a parse error; ignore the token. + (innerHTML case) */ + if (!$this->elementInScope(array('td', 'th'), true)) { + // Ignore. + + /* Otherwise, close the cell (see below) and reprocess the current + token. */ + } else { + $this->closeCell(); + return $this->inRow($token); + } + + /* An end tag whose tag name is one of: "body", "caption", "col", + "colgroup", "html" */ + } elseif ($token['type'] === HTML5::ENDTAG && in_array( + $token['name'], + array('body', 'caption', 'col', 'colgroup', 'html') + ) + ) { + /* Parse error. Ignore the token. */ + + /* An end tag whose tag name is one of: "table", "tbody", "tfoot", + "thead", "tr" */ + } elseif ($token['type'] === HTML5::ENDTAG && in_array( + $token['name'], + array('table', 'tbody', 'tfoot', 'thead', 'tr') + ) + ) { + /* If the stack of open elements does not have an element in table + scope with the same tag name as that of the token (which can only + happen for "tbody", "tfoot" and "thead", or, in the innerHTML case), + then this is a parse error and the token must be ignored. */ + if (!$this->elementInScope($token['name'], true)) { + // Ignore. + + /* Otherwise, close the cell (see below) and reprocess the current + token. */ + } else { + $this->closeCell(); + return $this->inRow($token); + } + + /* Anything else */ + } else { + /* Process the token as if the insertion mode was "in body". */ + $this->inBody($token); + } + } + + private function inSelect($token) + { + /* Handle the token as follows: */ + + /* A character token */ + if ($token['type'] === HTML5::CHARACTR) { + /* Append the token's character to the current node. */ + $this->insertText($token['data']); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the current node with the data + attribute set to the data given in the comment token. */ + $this->insertComment($token['data']); + + /* A start tag token whose tag name is "option" */ + } elseif ($token['type'] === HTML5::STARTTAG && + $token['name'] === 'option' + ) { + /* If the current node is an option element, act as if an end tag + with the tag name "option" had been seen. */ + if (end($this->stack)->nodeName === 'option') { + $this->inSelect( + array( + 'name' => 'option', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* A start tag token whose tag name is "optgroup" */ + } elseif ($token['type'] === HTML5::STARTTAG && + $token['name'] === 'optgroup' + ) { + /* If the current node is an option element, act as if an end tag + with the tag name "option" had been seen. */ + if (end($this->stack)->nodeName === 'option') { + $this->inSelect( + array( + 'name' => 'option', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* If the current node is an optgroup element, act as if an end tag + with the tag name "optgroup" had been seen. */ + if (end($this->stack)->nodeName === 'optgroup') { + $this->inSelect( + array( + 'name' => 'optgroup', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* An end tag token whose tag name is "optgroup" */ + } elseif ($token['type'] === HTML5::ENDTAG && + $token['name'] === 'optgroup' + ) { + /* First, if the current node is an option element, and the node + immediately before it in the stack of open elements is an optgroup + element, then act as if an end tag with the tag name "option" had + been seen. */ + $elements_in_stack = count($this->stack); + + if ($this->stack[$elements_in_stack - 1]->nodeName === 'option' && + $this->stack[$elements_in_stack - 2]->nodeName === 'optgroup' + ) { + $this->inSelect( + array( + 'name' => 'option', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* If the current node is an optgroup element, then pop that node + from the stack of open elements. Otherwise, this is a parse error, + ignore the token. */ + if ($this->stack[$elements_in_stack - 1] === 'optgroup') { + array_pop($this->stack); + } + + /* An end tag token whose tag name is "option" */ + } elseif ($token['type'] === HTML5::ENDTAG && + $token['name'] === 'option' + ) { + /* If the current node is an option element, then pop that node + from the stack of open elements. Otherwise, this is a parse error, + ignore the token. */ + if (end($this->stack)->nodeName === 'option') { + array_pop($this->stack); + } + + /* An end tag whose tag name is "select" */ + } elseif ($token['type'] === HTML5::ENDTAG && + $token['name'] === 'select' + ) { + /* If the stack of open elements does not have an element in table + scope with the same tag name as the token, this is a parse error. + Ignore the token. (innerHTML case) */ + if (!$this->elementInScope($token['name'], true)) { + // w/e + + /* Otherwise: */ + } else { + /* Pop elements from the stack of open elements until a select + element has been popped from the stack. */ + while (true) { + $current = end($this->stack)->nodeName; + array_pop($this->stack); + + if ($current === 'select') { + break; + } + } + + /* Reset the insertion mode appropriately. */ + $this->resetInsertionMode(); + } + + /* A start tag whose tag name is "select" */ + } elseif ($token['name'] === 'select' && + $token['type'] === HTML5::STARTTAG + ) { + /* Parse error. Act as if the token had been an end tag with the + tag name "select" instead. */ + $this->inSelect( + array( + 'name' => 'select', + 'type' => HTML5::ENDTAG + ) + ); + + /* An end tag whose tag name is one of: "caption", "table", "tbody", + "tfoot", "thead", "tr", "td", "th" */ + } elseif (in_array( + $token['name'], + array( + 'caption', + 'table', + 'tbody', + 'tfoot', + 'thead', + 'tr', + 'td', + 'th' + ) + ) && $token['type'] === HTML5::ENDTAG + ) { + /* Parse error. */ + // w/e + + /* If the stack of open elements has an element in table scope with + the same tag name as that of the token, then act as if an end tag + with the tag name "select" had been seen, and reprocess the token. + Otherwise, ignore the token. */ + if ($this->elementInScope($token['name'], true)) { + $this->inSelect( + array( + 'name' => 'select', + 'type' => HTML5::ENDTAG + ) + ); + + $this->mainPhase($token); + } + + /* Anything else */ + } else { + /* Parse error. Ignore the token. */ + } + } + + private function afterBody($token) + { + /* Handle the token as follows: */ + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE */ + if ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Process the token as it would be processed if the insertion mode + was "in body". */ + $this->inBody($token); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the first element in the stack of open + elements (the html element), with the data attribute set to the + data given in the comment token. */ + $comment = $this->dom->createComment($token['data']); + $this->stack[0]->appendChild($comment); + + /* An end tag with the tag name "html" */ + } elseif ($token['type'] === HTML5::ENDTAG && $token['name'] === 'html') { + /* If the parser was originally created in order to handle the + setting of an element's innerHTML attribute, this is a parse error; + ignore the token. (The element will be an html element in this + case.) (innerHTML case) */ + + /* Otherwise, switch to the trailing end phase. */ + $this->phase = self::END_PHASE; + + /* Anything else */ + } else { + /* Parse error. Set the insertion mode to "in body" and reprocess + the token. */ + $this->mode = self::IN_BODY; + return $this->inBody($token); + } + } + + private function inFrameset($token) + { + /* Handle the token as follows: */ + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + U+000D CARRIAGE RETURN (CR), or U+0020 SPACE */ + if ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Append the character to the current node. */ + $this->insertText($token['data']); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the current node with the data + attribute set to the data given in the comment token. */ + $this->insertComment($token['data']); + + /* A start tag with the tag name "frameset" */ + } elseif ($token['name'] === 'frameset' && + $token['type'] === HTML5::STARTTAG + ) { + $this->insertElement($token); + + /* An end tag with the tag name "frameset" */ + } elseif ($token['name'] === 'frameset' && + $token['type'] === HTML5::ENDTAG + ) { + /* If the current node is the root html element, then this is a + parse error; ignore the token. (innerHTML case) */ + if (end($this->stack)->nodeName === 'html') { + // Ignore + + } else { + /* Otherwise, pop the current node from the stack of open + elements. */ + array_pop($this->stack); + + /* If the parser was not originally created in order to handle + the setting of an element's innerHTML attribute (innerHTML case), + and the current node is no longer a frameset element, then change + the insertion mode to "after frameset". */ + $this->mode = self::AFTR_FRAME; + } + + /* A start tag with the tag name "frame" */ + } elseif ($token['name'] === 'frame' && + $token['type'] === HTML5::STARTTAG + ) { + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* Immediately pop the current node off the stack of open elements. */ + array_pop($this->stack); + + /* A start tag with the tag name "noframes" */ + } elseif ($token['name'] === 'noframes' && + $token['type'] === HTML5::STARTTAG + ) { + /* Process the token as if the insertion mode had been "in body". */ + $this->inBody($token); + + /* Anything else */ + } else { + /* Parse error. Ignore the token. */ + } + } + + private function afterFrameset($token) + { + /* Handle the token as follows: */ + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + U+000D CARRIAGE RETURN (CR), or U+0020 SPACE */ + if ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Append the character to the current node. */ + $this->insertText($token['data']); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the current node with the data + attribute set to the data given in the comment token. */ + $this->insertComment($token['data']); + + /* An end tag with the tag name "html" */ + } elseif ($token['name'] === 'html' && + $token['type'] === HTML5::ENDTAG + ) { + /* Switch to the trailing end phase. */ + $this->phase = self::END_PHASE; + + /* A start tag with the tag name "noframes" */ + } elseif ($token['name'] === 'noframes' && + $token['type'] === HTML5::STARTTAG + ) { + /* Process the token as if the insertion mode had been "in body". */ + $this->inBody($token); + + /* Anything else */ + } else { + /* Parse error. Ignore the token. */ + } + } + + private function trailingEndPhase($token) + { + /* After the main phase, as each token is emitted from the tokenisation + stage, it must be processed as described in this section. */ + + /* A DOCTYPE token */ + if ($token['type'] === HTML5::DOCTYPE) { + // Parse error. Ignore the token. + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the Document object with the data + attribute set to the data given in the comment token. */ + $comment = $this->dom->createComment($token['data']); + $this->dom->appendChild($comment); + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE */ + } elseif ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Process the token as it would be processed in the main phase. */ + $this->mainPhase($token); + + /* A character token that is not one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE. Or a start tag token. Or an end tag token. */ + } elseif (($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) || + $token['type'] === HTML5::STARTTAG || $token['type'] === HTML5::ENDTAG + ) { + /* Parse error. Switch back to the main phase and reprocess the + token. */ + $this->phase = self::MAIN_PHASE; + return $this->mainPhase($token); + + /* An end-of-file token */ + } elseif ($token['type'] === HTML5::EOF) { + /* OMG DONE!! */ + } + } + + private function insertElement($token, $append = true, $check = false) + { + // Proprietary workaround for libxml2's limitations with tag names + if ($check) { + // Slightly modified HTML5 tag-name modification, + // removing anything that's not an ASCII letter, digit, or hyphen + $token['name'] = preg_replace('/[^a-z0-9-]/i', '', $token['name']); + // Remove leading hyphens and numbers + $token['name'] = ltrim($token['name'], '-0..9'); + // In theory, this should ever be needed, but just in case + if ($token['name'] === '') { + $token['name'] = 'span'; + } // arbitrary generic choice + } + + $el = $this->dom->createElement($token['name']); + + foreach ($token['attr'] as $attr) { + if (!$el->hasAttribute($attr['name'])) { + $el->setAttribute($attr['name'], $attr['value']); + } + } + + $this->appendToRealParent($el); + $this->stack[] = $el; + + return $el; + } + + private function insertText($data) + { + $text = $this->dom->createTextNode($data); + $this->appendToRealParent($text); + } + + private function insertComment($data) + { + $comment = $this->dom->createComment($data); + $this->appendToRealParent($comment); + } + + private function appendToRealParent($node) + { + if ($this->foster_parent === null) { + end($this->stack)->appendChild($node); + + } elseif ($this->foster_parent !== null) { + /* If the foster parent element is the parent element of the + last table element in the stack of open elements, then the new + node must be inserted immediately before the last table element + in the stack of open elements in the foster parent element; + otherwise, the new node must be appended to the foster parent + element. */ + for ($n = count($this->stack) - 1; $n >= 0; $n--) { + if ($this->stack[$n]->nodeName === 'table' && + $this->stack[$n]->parentNode !== null + ) { + $table = $this->stack[$n]; + break; + } + } + + if (isset($table) && $this->foster_parent->isSameNode($table->parentNode)) { + $this->foster_parent->insertBefore($node, $table); + } else { + $this->foster_parent->appendChild($node); + } + + $this->foster_parent = null; + } + } + + private function elementInScope($el, $table = false) + { + if (is_array($el)) { + foreach ($el as $element) { + if ($this->elementInScope($element, $table)) { + return true; + } + } + + return false; + } + + $leng = count($this->stack); + + for ($n = 0; $n < $leng; $n++) { + /* 1. Initialise node to be the current node (the bottommost node of + the stack). */ + $node = $this->stack[$leng - 1 - $n]; + + if ($node->tagName === $el) { + /* 2. If node is the target node, terminate in a match state. */ + return true; + + } elseif ($node->tagName === 'table') { + /* 3. Otherwise, if node is a table element, terminate in a failure + state. */ + return false; + + } elseif ($table === true && in_array( + $node->tagName, + array( + 'caption', + 'td', + 'th', + 'button', + 'marquee', + 'object' + ) + ) + ) { + /* 4. Otherwise, if the algorithm is the "has an element in scope" + variant (rather than the "has an element in table scope" variant), + and node is one of the following, terminate in a failure state. */ + return false; + + } elseif ($node === $node->ownerDocument->documentElement) { + /* 5. Otherwise, if node is an html element (root element), terminate + in a failure state. (This can only happen if the node is the topmost + node of the stack of open elements, and prevents the next step from + being invoked if there are no more elements in the stack.) */ + return false; + } + + /* Otherwise, set node to the previous entry in the stack of open + elements and return to step 2. (This will never fail, since the loop + will always terminate in the previous step if the top of the stack + is reached.) */ + } + } + + private function reconstructActiveFormattingElements() + { + /* 1. If there are no entries in the list of active formatting elements, + then there is nothing to reconstruct; stop this algorithm. */ + $formatting_elements = count($this->a_formatting); + + if ($formatting_elements === 0) { + return false; + } + + /* 3. Let entry be the last (most recently added) element in the list + of active formatting elements. */ + $entry = end($this->a_formatting); + + /* 2. If the last (most recently added) entry in the list of active + formatting elements is a marker, or if it is an element that is in the + stack of open elements, then there is nothing to reconstruct; stop this + algorithm. */ + if ($entry === self::MARKER || in_array($entry, $this->stack, true)) { + return false; + } + + for ($a = $formatting_elements - 1; $a >= 0; true) { + /* 4. If there are no entries before entry in the list of active + formatting elements, then jump to step 8. */ + if ($a === 0) { + $step_seven = false; + break; + } + + /* 5. Let entry be the entry one earlier than entry in the list of + active formatting elements. */ + $a--; + $entry = $this->a_formatting[$a]; + + /* 6. If entry is neither a marker nor an element that is also in + thetack of open elements, go to step 4. */ + if ($entry === self::MARKER || in_array($entry, $this->stack, true)) { + break; + } + } + + while (true) { + /* 7. Let entry be the element one later than entry in the list of + active formatting elements. */ + if (isset($step_seven) && $step_seven === true) { + $a++; + $entry = $this->a_formatting[$a]; + } + + /* 8. Perform a shallow clone of the element entry to obtain clone. */ + $clone = $entry->cloneNode(); + + /* 9. Append clone to the current node and push it onto the stack + of open elements so that it is the new current node. */ + end($this->stack)->appendChild($clone); + $this->stack[] = $clone; + + /* 10. Replace the entry for entry in the list with an entry for + clone. */ + $this->a_formatting[$a] = $clone; + + /* 11. If the entry for clone in the list of active formatting + elements is not the last entry in the list, return to step 7. */ + if (end($this->a_formatting) !== $clone) { + $step_seven = true; + } else { + break; + } + } + } + + private function clearTheActiveFormattingElementsUpToTheLastMarker() + { + /* When the steps below require the UA to clear the list of active + formatting elements up to the last marker, the UA must perform the + following steps: */ + + while (true) { + /* 1. Let entry be the last (most recently added) entry in the list + of active formatting elements. */ + $entry = end($this->a_formatting); + + /* 2. Remove entry from the list of active formatting elements. */ + array_pop($this->a_formatting); + + /* 3. If entry was a marker, then stop the algorithm at this point. + The list has been cleared up to the last marker. */ + if ($entry === self::MARKER) { + break; + } + } + } + + private function generateImpliedEndTags($exclude = array()) + { + /* When the steps below require the UA to generate implied end tags, + then, if the current node is a dd element, a dt element, an li element, + a p element, a td element, a th element, or a tr element, the UA must + act as if an end tag with the respective tag name had been seen and + then generate implied end tags again. */ + $node = end($this->stack); + $elements = array_diff(array('dd', 'dt', 'li', 'p', 'td', 'th', 'tr'), $exclude); + + while (in_array(end($this->stack)->nodeName, $elements)) { + array_pop($this->stack); + } + } + + private function getElementCategory($node) + { + $name = $node->tagName; + if (in_array($name, $this->special)) { + return self::SPECIAL; + } elseif (in_array($name, $this->scoping)) { + return self::SCOPING; + } elseif (in_array($name, $this->formatting)) { + return self::FORMATTING; + } else { + return self::PHRASING; + } + } + + private function clearStackToTableContext($elements) + { + /* When the steps above require the UA to clear the stack back to a + table context, it means that the UA must, while the current node is not + a table element or an html element, pop elements from the stack of open + elements. If this causes any elements to be popped from the stack, then + this is a parse error. */ + while (true) { + $node = end($this->stack)->nodeName; + + if (in_array($node, $elements)) { + break; + } else { + array_pop($this->stack); + } + } + } + + private function resetInsertionMode() + { + /* 1. Let last be false. */ + $last = false; + $leng = count($this->stack); + + for ($n = $leng - 1; $n >= 0; $n--) { + /* 2. Let node be the last node in the stack of open elements. */ + $node = $this->stack[$n]; + + /* 3. If node is the first node in the stack of open elements, then + set last to true. If the element whose innerHTML attribute is being + set is neither a td element nor a th element, then set node to the + element whose innerHTML attribute is being set. (innerHTML case) */ + if ($this->stack[0]->isSameNode($node)) { + $last = true; + } + + /* 4. If node is a select element, then switch the insertion mode to + "in select" and abort these steps. (innerHTML case) */ + if ($node->nodeName === 'select') { + $this->mode = self::IN_SELECT; + break; + + /* 5. If node is a td or th element, then switch the insertion mode + to "in cell" and abort these steps. */ + } elseif ($node->nodeName === 'td' || $node->nodeName === 'th') { + $this->mode = self::IN_CELL; + break; + + /* 6. If node is a tr element, then switch the insertion mode to + "in row" and abort these steps. */ + } elseif ($node->nodeName === 'tr') { + $this->mode = self::IN_ROW; + break; + + /* 7. If node is a tbody, thead, or tfoot element, then switch the + insertion mode to "in table body" and abort these steps. */ + } elseif (in_array($node->nodeName, array('tbody', 'thead', 'tfoot'))) { + $this->mode = self::IN_TBODY; + break; + + /* 8. If node is a caption element, then switch the insertion mode + to "in caption" and abort these steps. */ + } elseif ($node->nodeName === 'caption') { + $this->mode = self::IN_CAPTION; + break; + + /* 9. If node is a colgroup element, then switch the insertion mode + to "in column group" and abort these steps. (innerHTML case) */ + } elseif ($node->nodeName === 'colgroup') { + $this->mode = self::IN_CGROUP; + break; + + /* 10. If node is a table element, then switch the insertion mode + to "in table" and abort these steps. */ + } elseif ($node->nodeName === 'table') { + $this->mode = self::IN_TABLE; + break; + + /* 11. If node is a head element, then switch the insertion mode + to "in body" ("in body"! not "in head"!) and abort these steps. + (innerHTML case) */ + } elseif ($node->nodeName === 'head') { + $this->mode = self::IN_BODY; + break; + + /* 12. If node is a body element, then switch the insertion mode to + "in body" and abort these steps. */ + } elseif ($node->nodeName === 'body') { + $this->mode = self::IN_BODY; + break; + + /* 13. If node is a frameset element, then switch the insertion + mode to "in frameset" and abort these steps. (innerHTML case) */ + } elseif ($node->nodeName === 'frameset') { + $this->mode = self::IN_FRAME; + break; + + /* 14. If node is an html element, then: if the head element + pointer is null, switch the insertion mode to "before head", + otherwise, switch the insertion mode to "after head". In either + case, abort these steps. (innerHTML case) */ + } elseif ($node->nodeName === 'html') { + $this->mode = ($this->head_pointer === null) + ? self::BEFOR_HEAD + : self::AFTER_HEAD; + + break; + + /* 15. If last is true, then set the insertion mode to "in body" + and abort these steps. (innerHTML case) */ + } elseif ($last) { + $this->mode = self::IN_BODY; + break; + } + } + } + + private function closeCell() + { + /* If the stack of open elements has a td or th element in table scope, + then act as if an end tag token with that tag name had been seen. */ + foreach (array('td', 'th') as $cell) { + if ($this->elementInScope($cell, true)) { + $this->inCell( + array( + 'name' => $cell, + 'type' => HTML5::ENDTAG + ) + ); + + break; + } + } + } + + public function save() + { + return $this->dom; + } +} diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer.php new file mode 100644 index 0000000..16acd41 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer.php @@ -0,0 +1,218 @@ +getAll(); + $context = new HTMLPurifier_Context(); + $this->generator = new HTMLPurifier_Generator($config, $context); + } + + /** + * Main function that renders object or aspect of that object + * @note Parameters vary depending on printer + */ + // function render() {} + + /** + * Returns a start tag + * @param string $tag Tag name + * @param array $attr Attribute array + * @return string + */ + protected function start($tag, $attr = array()) + { + return $this->generator->generateFromToken( + new HTMLPurifier_Token_Start($tag, $attr ? $attr : array()) + ); + } + + /** + * Returns an end tag + * @param string $tag Tag name + * @return string + */ + protected function end($tag) + { + return $this->generator->generateFromToken( + new HTMLPurifier_Token_End($tag) + ); + } + + /** + * Prints a complete element with content inside + * @param string $tag Tag name + * @param string $contents Element contents + * @param array $attr Tag attributes + * @param bool $escape whether or not to escape contents + * @return string + */ + protected function element($tag, $contents, $attr = array(), $escape = true) + { + return $this->start($tag, $attr) . + ($escape ? $this->escape($contents) : $contents) . + $this->end($tag); + } + + /** + * @param string $tag + * @param array $attr + * @return string + */ + protected function elementEmpty($tag, $attr = array()) + { + return $this->generator->generateFromToken( + new HTMLPurifier_Token_Empty($tag, $attr) + ); + } + + /** + * @param string $text + * @return string + */ + protected function text($text) + { + return $this->generator->generateFromToken( + new HTMLPurifier_Token_Text($text) + ); + } + + /** + * Prints a simple key/value row in a table. + * @param string $name Key + * @param mixed $value Value + * @return string + */ + protected function row($name, $value) + { + if (is_bool($value)) { + $value = $value ? 'On' : 'Off'; + } + return + $this->start('tr') . "\n" . + $this->element('th', $name) . "\n" . + $this->element('td', $value) . "\n" . + $this->end('tr'); + } + + /** + * Escapes a string for HTML output. + * @param string $string String to escape + * @return string + */ + protected function escape($string) + { + $string = HTMLPurifier_Encoder::cleanUTF8($string); + $string = htmlspecialchars($string, ENT_COMPAT, 'UTF-8'); + return $string; + } + + /** + * Takes a list of strings and turns them into a single list + * @param string[] $array List of strings + * @param bool $polite Bool whether or not to add an end before the last + * @return string + */ + protected function listify($array, $polite = false) + { + if (empty($array)) { + return 'None'; + } + $ret = ''; + $i = count($array); + foreach ($array as $value) { + $i--; + $ret .= $value; + if ($i > 0 && !($polite && $i == 1)) { + $ret .= ', '; + } + if ($polite && $i == 1) { + $ret .= 'and '; + } + } + return $ret; + } + + /** + * Retrieves the class of an object without prefixes, as well as metadata + * @param object $obj Object to determine class of + * @param string $sec_prefix Further prefix to remove + * @return string + */ + protected function getClass($obj, $sec_prefix = '') + { + static $five = null; + if ($five === null) { + $five = version_compare(PHP_VERSION, '5', '>='); + } + $prefix = 'HTMLPurifier_' . $sec_prefix; + if (!$five) { + $prefix = strtolower($prefix); + } + $class = str_replace($prefix, '', get_class($obj)); + $lclass = strtolower($class); + $class .= '('; + switch ($lclass) { + case 'enum': + $values = array(); + foreach ($obj->valid_values as $value => $bool) { + $values[] = $value; + } + $class .= implode(', ', $values); + break; + case 'css_composite': + $values = array(); + foreach ($obj->defs as $def) { + $values[] = $this->getClass($def, $sec_prefix); + } + $class .= implode(', ', $values); + break; + case 'css_multiple': + $class .= $this->getClass($obj->single, $sec_prefix) . ', '; + $class .= $obj->max; + break; + case 'css_denyelementdecorator': + $class .= $this->getClass($obj->def, $sec_prefix) . ', '; + $class .= $obj->element; + break; + case 'css_importantdecorator': + $class .= $this->getClass($obj->def, $sec_prefix); + if ($obj->allow) { + $class .= ', !important'; + } + break; + } + $class .= ')'; + return $class; + } +} + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer/CSSDefinition.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer/CSSDefinition.php new file mode 100644 index 0000000..afc8c18 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer/CSSDefinition.php @@ -0,0 +1,44 @@ +def = $config->getCSSDefinition(); + $ret = ''; + + $ret .= $this->start('div', array('class' => 'HTMLPurifier_Printer')); + $ret .= $this->start('table'); + + $ret .= $this->element('caption', 'Properties ($info)'); + + $ret .= $this->start('thead'); + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Property', array('class' => 'heavy')); + $ret .= $this->element('th', 'Definition', array('class' => 'heavy', 'style' => 'width:auto;')); + $ret .= $this->end('tr'); + $ret .= $this->end('thead'); + + ksort($this->def->info); + foreach ($this->def->info as $property => $obj) { + $name = $this->getClass($obj, 'AttrDef_'); + $ret .= $this->row($property, $name); + } + + $ret .= $this->end('table'); + $ret .= $this->end('div'); + + return $ret; + } +} + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer/ConfigForm.css b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer/ConfigForm.css new file mode 100644 index 0000000..7af30fc --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer/ConfigForm.css @@ -0,0 +1,10 @@ + +.hp-config {} + +.hp-config tbody th {text-align:right; padding-right:0.5em;} +.hp-config thead, .hp-config .namespace {background:#3C578C; color:#FFF;} +.hp-config .namespace th {text-align:center;} +.hp-config .verbose {display:none;} +.hp-config .controls {text-align:center;} + +/* vim: et sw=4 sts=4 */ diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer/ConfigForm.js b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer/ConfigForm.js new file mode 100644 index 0000000..83e0655 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer/ConfigForm.js @@ -0,0 +1,5 @@ +function toggleWriteability(id_of_patient, checked) { + document.getElementById(id_of_patient).disabled = checked; +} + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer/ConfigForm.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer/ConfigForm.php new file mode 100644 index 0000000..8897002 --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer/ConfigForm.php @@ -0,0 +1,451 @@ +docURL = $doc_url; + $this->name = $name; + $this->compress = $compress; + // initialize sub-printers + $this->fields[0] = new HTMLPurifier_Printer_ConfigForm_default(); + $this->fields[HTMLPurifier_VarParser::C_BOOL] = new HTMLPurifier_Printer_ConfigForm_bool(); + } + + /** + * Sets default column and row size for textareas in sub-printers + * @param $cols Integer columns of textarea, null to use default + * @param $rows Integer rows of textarea, null to use default + */ + public function setTextareaDimensions($cols = null, $rows = null) + { + if ($cols) { + $this->fields['default']->cols = $cols; + } + if ($rows) { + $this->fields['default']->rows = $rows; + } + } + + /** + * Retrieves styling, in case it is not accessible by webserver + */ + public static function getCSS() + { + return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.css'); + } + + /** + * Retrieves JavaScript, in case it is not accessible by webserver + */ + public static function getJavaScript() + { + return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.js'); + } + + /** + * Returns HTML output for a configuration form + * @param HTMLPurifier_Config|array $config Configuration object of current form state, or an array + * where [0] has an HTML namespace and [1] is being rendered. + * @param array|bool $allowed Optional namespace(s) and directives to restrict form to. + * @param bool $render_controls + * @return string + */ + public function render($config, $allowed = true, $render_controls = true) + { + if (is_array($config) && isset($config[0])) { + $gen_config = $config[0]; + $config = $config[1]; + } else { + $gen_config = $config; + } + + $this->config = $config; + $this->genConfig = $gen_config; + $this->prepareGenerator($gen_config); + + $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $config->def); + $all = array(); + foreach ($allowed as $key) { + list($ns, $directive) = $key; + $all[$ns][$directive] = $config->get($ns . '.' . $directive); + } + + $ret = ''; + $ret .= $this->start('table', array('class' => 'hp-config')); + $ret .= $this->start('thead'); + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Directive', array('class' => 'hp-directive')); + $ret .= $this->element('th', 'Value', array('class' => 'hp-value')); + $ret .= $this->end('tr'); + $ret .= $this->end('thead'); + foreach ($all as $ns => $directives) { + $ret .= $this->renderNamespace($ns, $directives); + } + if ($render_controls) { + $ret .= $this->start('tbody'); + $ret .= $this->start('tr'); + $ret .= $this->start('td', array('colspan' => 2, 'class' => 'controls')); + $ret .= $this->elementEmpty('input', array('type' => 'submit', 'value' => 'Submit')); + $ret .= '[Reset]'; + $ret .= $this->end('td'); + $ret .= $this->end('tr'); + $ret .= $this->end('tbody'); + } + $ret .= $this->end('table'); + return $ret; + } + + /** + * Renders a single namespace + * @param $ns String namespace name + * @param array $directives array of directives to values + * @return string + */ + protected function renderNamespace($ns, $directives) + { + $ret = ''; + $ret .= $this->start('tbody', array('class' => 'namespace')); + $ret .= $this->start('tr'); + $ret .= $this->element('th', $ns, array('colspan' => 2)); + $ret .= $this->end('tr'); + $ret .= $this->end('tbody'); + $ret .= $this->start('tbody'); + foreach ($directives as $directive => $value) { + $ret .= $this->start('tr'); + $ret .= $this->start('th'); + if ($this->docURL) { + $url = str_replace('%s', urlencode("$ns.$directive"), $this->docURL); + $ret .= $this->start('a', array('href' => $url)); + } + $attr = array('for' => "{$this->name}:$ns.$directive"); + + // crop directive name if it's too long + if (!$this->compress || (strlen($directive) < $this->compress)) { + $directive_disp = $directive; + } else { + $directive_disp = substr($directive, 0, $this->compress - 2) . '...'; + $attr['title'] = $directive; + } + + $ret .= $this->element( + 'label', + $directive_disp, + // component printers must create an element with this id + $attr + ); + if ($this->docURL) { + $ret .= $this->end('a'); + } + $ret .= $this->end('th'); + + $ret .= $this->start('td'); + $def = $this->config->def->info["$ns.$directive"]; + if (is_int($def)) { + $allow_null = $def < 0; + $type = abs($def); + } else { + $type = $def->type; + $allow_null = isset($def->allow_null); + } + if (!isset($this->fields[$type])) { + $type = 0; + } // default + $type_obj = $this->fields[$type]; + if ($allow_null) { + $type_obj = new HTMLPurifier_Printer_ConfigForm_NullDecorator($type_obj); + } + $ret .= $type_obj->render($ns, $directive, $value, $this->name, array($this->genConfig, $this->config)); + $ret .= $this->end('td'); + $ret .= $this->end('tr'); + } + $ret .= $this->end('tbody'); + return $ret; + } + +} + +/** + * Printer decorator for directives that accept null + */ +class HTMLPurifier_Printer_ConfigForm_NullDecorator extends HTMLPurifier_Printer +{ + /** + * Printer being decorated + * @type HTMLPurifier_Printer + */ + protected $obj; + + /** + * @param HTMLPurifier_Printer $obj Printer to decorate + */ + public function __construct($obj) + { + parent::__construct(); + $this->obj = $obj; + } + + /** + * @param string $ns + * @param string $directive + * @param string $value + * @param string $name + * @param HTMLPurifier_Config|array $config + * @return string + */ + public function render($ns, $directive, $value, $name, $config) + { + if (is_array($config) && isset($config[0])) { + $gen_config = $config[0]; + $config = $config[1]; + } else { + $gen_config = $config; + } + $this->prepareGenerator($gen_config); + + $ret = ''; + $ret .= $this->start('label', array('for' => "$name:Null_$ns.$directive")); + $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose')); + $ret .= $this->text(' Null/Disabled'); + $ret .= $this->end('label'); + $attr = array( + 'type' => 'checkbox', + 'value' => '1', + 'class' => 'null-toggle', + 'name' => "$name" . "[Null_$ns.$directive]", + 'id' => "$name:Null_$ns.$directive", + 'onclick' => "toggleWriteability('$name:$ns.$directive',checked)" // INLINE JAVASCRIPT!!!! + ); + if ($this->obj instanceof HTMLPurifier_Printer_ConfigForm_bool) { + // modify inline javascript slightly + $attr['onclick'] = + "toggleWriteability('$name:Yes_$ns.$directive',checked);" . + "toggleWriteability('$name:No_$ns.$directive',checked)"; + } + if ($value === null) { + $attr['checked'] = 'checked'; + } + $ret .= $this->elementEmpty('input', $attr); + $ret .= $this->text(' or '); + $ret .= $this->elementEmpty('br'); + $ret .= $this->obj->render($ns, $directive, $value, $name, array($gen_config, $config)); + return $ret; + } +} + +/** + * Swiss-army knife configuration form field printer + */ +class HTMLPurifier_Printer_ConfigForm_default extends HTMLPurifier_Printer +{ + /** + * @type int + */ + public $cols = 18; + + /** + * @type int + */ + public $rows = 5; + + /** + * @param string $ns + * @param string $directive + * @param string $value + * @param string $name + * @param HTMLPurifier_Config|array $config + * @return string + */ + public function render($ns, $directive, $value, $name, $config) + { + if (is_array($config) && isset($config[0])) { + $gen_config = $config[0]; + $config = $config[1]; + } else { + $gen_config = $config; + } + $this->prepareGenerator($gen_config); + // this should probably be split up a little + $ret = ''; + $def = $config->def->info["$ns.$directive"]; + if (is_int($def)) { + $type = abs($def); + } else { + $type = $def->type; + } + if (is_array($value)) { + switch ($type) { + case HTMLPurifier_VarParser::LOOKUP: + $array = $value; + $value = array(); + foreach ($array as $val => $b) { + $value[] = $val; + } + //TODO does this need a break? + case HTMLPurifier_VarParser::ALIST: + $value = implode(PHP_EOL, $value); + break; + case HTMLPurifier_VarParser::HASH: + $nvalue = ''; + foreach ($value as $i => $v) { + if (is_array($v)) { + // HACK + $v = implode(";", $v); + } + $nvalue .= "$i:$v" . PHP_EOL; + } + $value = $nvalue; + break; + default: + $value = ''; + } + } + if ($type === HTMLPurifier_VarParser::C_MIXED) { + return 'Not supported'; + $value = serialize($value); + } + $attr = array( + 'name' => "$name" . "[$ns.$directive]", + 'id' => "$name:$ns.$directive" + ); + if ($value === null) { + $attr['disabled'] = 'disabled'; + } + if (isset($def->allowed)) { + $ret .= $this->start('select', $attr); + foreach ($def->allowed as $val => $b) { + $attr = array(); + if ($value == $val) { + $attr['selected'] = 'selected'; + } + $ret .= $this->element('option', $val, $attr); + } + $ret .= $this->end('select'); + } elseif ($type === HTMLPurifier_VarParser::TEXT || + $type === HTMLPurifier_VarParser::ITEXT || + $type === HTMLPurifier_VarParser::ALIST || + $type === HTMLPurifier_VarParser::HASH || + $type === HTMLPurifier_VarParser::LOOKUP) { + $attr['cols'] = $this->cols; + $attr['rows'] = $this->rows; + $ret .= $this->start('textarea', $attr); + $ret .= $this->text($value); + $ret .= $this->end('textarea'); + } else { + $attr['value'] = $value; + $attr['type'] = 'text'; + $ret .= $this->elementEmpty('input', $attr); + } + return $ret; + } +} + +/** + * Bool form field printer + */ +class HTMLPurifier_Printer_ConfigForm_bool extends HTMLPurifier_Printer +{ + /** + * @param string $ns + * @param string $directive + * @param string $value + * @param string $name + * @param HTMLPurifier_Config|array $config + * @return string + */ + public function render($ns, $directive, $value, $name, $config) + { + if (is_array($config) && isset($config[0])) { + $gen_config = $config[0]; + $config = $config[1]; + } else { + $gen_config = $config; + } + $this->prepareGenerator($gen_config); + $ret = ''; + $ret .= $this->start('div', array('id' => "$name:$ns.$directive")); + + $ret .= $this->start('label', array('for' => "$name:Yes_$ns.$directive")); + $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose')); + $ret .= $this->text(' Yes'); + $ret .= $this->end('label'); + + $attr = array( + 'type' => 'radio', + 'name' => "$name" . "[$ns.$directive]", + 'id' => "$name:Yes_$ns.$directive", + 'value' => '1' + ); + if ($value === true) { + $attr['checked'] = 'checked'; + } + if ($value === null) { + $attr['disabled'] = 'disabled'; + } + $ret .= $this->elementEmpty('input', $attr); + + $ret .= $this->start('label', array('for' => "$name:No_$ns.$directive")); + $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose')); + $ret .= $this->text(' No'); + $ret .= $this->end('label'); + + $attr = array( + 'type' => 'radio', + 'name' => "$name" . "[$ns.$directive]", + 'id' => "$name:No_$ns.$directive", + 'value' => '0' + ); + if ($value === false) { + $attr['checked'] = 'checked'; + } + if ($value === null) { + $attr['disabled'] = 'disabled'; + } + $ret .= $this->elementEmpty('input', $attr); + + $ret .= $this->end('div'); + + return $ret; + } +} + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer/HTMLDefinition.php b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer/HTMLDefinition.php new file mode 100644 index 0000000..679d19b --- /dev/null +++ b/hesk/inc/htmlpurifier/standalone/HTMLPurifier/Printer/HTMLDefinition.php @@ -0,0 +1,324 @@ +config =& $config; + + $this->def = $config->getHTMLDefinition(); + + $ret .= $this->start('div', array('class' => 'HTMLPurifier_Printer')); + + $ret .= $this->renderDoctype(); + $ret .= $this->renderEnvironment(); + $ret .= $this->renderContentSets(); + $ret .= $this->renderInfo(); + + $ret .= $this->end('div'); + + return $ret; + } + + /** + * Renders the Doctype table + * @return string + */ + protected function renderDoctype() + { + $doctype = $this->def->doctype; + $ret = ''; + $ret .= $this->start('table'); + $ret .= $this->element('caption', 'Doctype'); + $ret .= $this->row('Name', $doctype->name); + $ret .= $this->row('XML', $doctype->xml ? 'Yes' : 'No'); + $ret .= $this->row('Default Modules', implode($doctype->modules, ', ')); + $ret .= $this->row('Default Tidy Modules', implode($doctype->tidyModules, ', ')); + $ret .= $this->end('table'); + return $ret; + } + + + /** + * Renders environment table, which is miscellaneous info + * @return string + */ + protected function renderEnvironment() + { + $def = $this->def; + + $ret = ''; + + $ret .= $this->start('table'); + $ret .= $this->element('caption', 'Environment'); + + $ret .= $this->row('Parent of fragment', $def->info_parent); + $ret .= $this->renderChildren($def->info_parent_def->child); + $ret .= $this->row('Block wrap name', $def->info_block_wrapper); + + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Global attributes'); + $ret .= $this->element('td', $this->listifyAttr($def->info_global_attr), null, 0); + $ret .= $this->end('tr'); + + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Tag transforms'); + $list = array(); + foreach ($def->info_tag_transform as $old => $new) { + $new = $this->getClass($new, 'TagTransform_'); + $list[] = "<$old> with $new"; + } + $ret .= $this->element('td', $this->listify($list)); + $ret .= $this->end('tr'); + + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Pre-AttrTransform'); + $ret .= $this->element('td', $this->listifyObjectList($def->info_attr_transform_pre)); + $ret .= $this->end('tr'); + + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Post-AttrTransform'); + $ret .= $this->element('td', $this->listifyObjectList($def->info_attr_transform_post)); + $ret .= $this->end('tr'); + + $ret .= $this->end('table'); + return $ret; + } + + /** + * Renders the Content Sets table + * @return string + */ + protected function renderContentSets() + { + $ret = ''; + $ret .= $this->start('table'); + $ret .= $this->element('caption', 'Content Sets'); + foreach ($this->def->info_content_sets as $name => $lookup) { + $ret .= $this->heavyHeader($name); + $ret .= $this->start('tr'); + $ret .= $this->element('td', $this->listifyTagLookup($lookup)); + $ret .= $this->end('tr'); + } + $ret .= $this->end('table'); + return $ret; + } + + /** + * Renders the Elements ($info) table + * @return string + */ + protected function renderInfo() + { + $ret = ''; + $ret .= $this->start('table'); + $ret .= $this->element('caption', 'Elements ($info)'); + ksort($this->def->info); + $ret .= $this->heavyHeader('Allowed tags', 2); + $ret .= $this->start('tr'); + $ret .= $this->element('td', $this->listifyTagLookup($this->def->info), array('colspan' => 2)); + $ret .= $this->end('tr'); + foreach ($this->def->info as $name => $def) { + $ret .= $this->start('tr'); + $ret .= $this->element('th', "<$name>", array('class' => 'heavy', 'colspan' => 2)); + $ret .= $this->end('tr'); + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Inline content'); + $ret .= $this->element('td', $def->descendants_are_inline ? 'Yes' : 'No'); + $ret .= $this->end('tr'); + if (!empty($def->excludes)) { + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Excludes'); + $ret .= $this->element('td', $this->listifyTagLookup($def->excludes)); + $ret .= $this->end('tr'); + } + if (!empty($def->attr_transform_pre)) { + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Pre-AttrTransform'); + $ret .= $this->element('td', $this->listifyObjectList($def->attr_transform_pre)); + $ret .= $this->end('tr'); + } + if (!empty($def->attr_transform_post)) { + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Post-AttrTransform'); + $ret .= $this->element('td', $this->listifyObjectList($def->attr_transform_post)); + $ret .= $this->end('tr'); + } + if (!empty($def->auto_close)) { + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Auto closed by'); + $ret .= $this->element('td', $this->listifyTagLookup($def->auto_close)); + $ret .= $this->end('tr'); + } + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Allowed attributes'); + $ret .= $this->element('td', $this->listifyAttr($def->attr), array(), 0); + $ret .= $this->end('tr'); + + if (!empty($def->required_attr)) { + $ret .= $this->row('Required attributes', $this->listify($def->required_attr)); + } + + $ret .= $this->renderChildren($def->child); + } + $ret .= $this->end('table'); + return $ret; + } + + /** + * Renders a row describing the allowed children of an element + * @param HTMLPurifier_ChildDef $def HTMLPurifier_ChildDef of pertinent element + * @return string + */ + protected function renderChildren($def) + { + $context = new HTMLPurifier_Context(); + $ret = ''; + $ret .= $this->start('tr'); + $elements = array(); + $attr = array(); + if (isset($def->elements)) { + if ($def->type == 'strictblockquote') { + $def->validateChildren(array(), $this->config, $context); + } + $elements = $def->elements; + } + if ($def->type == 'chameleon') { + $attr['rowspan'] = 2; + } elseif ($def->type == 'empty') { + $elements = array(); + } elseif ($def->type == 'table') { + $elements = array_flip( + array( + 'col', + 'caption', + 'colgroup', + 'thead', + 'tfoot', + 'tbody', + 'tr' + ) + ); + } + $ret .= $this->element('th', 'Allowed children', $attr); + + if ($def->type == 'chameleon') { + + $ret .= $this->element( + 'td', + 'Block: ' . + $this->escape($this->listifyTagLookup($def->block->elements)), + null, + 0 + ); + $ret .= $this->end('tr'); + $ret .= $this->start('tr'); + $ret .= $this->element( + 'td', + 'Inline: ' . + $this->escape($this->listifyTagLookup($def->inline->elements)), + null, + 0 + ); + + } elseif ($def->type == 'custom') { + + $ret .= $this->element( + 'td', + '' . ucfirst($def->type) . ': ' . + $def->dtd_regex + ); + + } else { + $ret .= $this->element( + 'td', + '' . ucfirst($def->type) . ': ' . + $this->escape($this->listifyTagLookup($elements)), + null, + 0 + ); + } + $ret .= $this->end('tr'); + return $ret; + } + + /** + * Listifies a tag lookup table. + * @param array $array Tag lookup array in form of array('tagname' => true) + * @return string + */ + protected function listifyTagLookup($array) + { + ksort($array); + $list = array(); + foreach ($array as $name => $discard) { + if ($name !== '#PCDATA' && !isset($this->def->info[$name])) { + continue; + } + $list[] = $name; + } + return $this->listify($list); + } + + /** + * Listifies a list of objects by retrieving class names and internal state + * @param array $array List of objects + * @return string + * @todo Also add information about internal state + */ + protected function listifyObjectList($array) + { + ksort($array); + $list = array(); + foreach ($array as $obj) { + $list[] = $this->getClass($obj, 'AttrTransform_'); + } + return $this->listify($list); + } + + /** + * Listifies a hash of attributes to AttrDef classes + * @param array $array Array hash in form of array('attrname' => HTMLPurifier_AttrDef) + * @return string + */ + protected function listifyAttr($array) + { + ksort($array); + $list = array(); + foreach ($array as $name => $obj) { + if ($obj === false) { + continue; + } + $list[] = "$name = " . $this->getClass($obj, 'AttrDef_') . ''; + } + return $this->listify($list); + } + + /** + * Creates a heavy header row + * @param string $text + * @param int $num + * @return string + */ + protected function heavyHeader($text, $num = 1) + { + $ret = ''; + $ret .= $this->start('tr'); + $ret .= $this->element('th', $text, array('colspan' => $num, 'class' => 'heavy')); + $ret .= $this->end('tr'); + return $ret; + } +} + +// vim: et sw=4 sts=4 diff --git a/hesk/inc/index.htm b/hesk/inc/index.htm new file mode 100644 index 0000000..d79f2c9 --- /dev/null +++ b/hesk/inc/index.htm @@ -0,0 +1,8 @@ + + +403 Forbidden + +

        Forbidden

        +You don't have permission to access this folder.

        +


        + \ No newline at end of file diff --git a/hesk/inc/jscolor/index.htm b/hesk/inc/jscolor/index.htm new file mode 100644 index 0000000..d79f2c9 --- /dev/null +++ b/hesk/inc/jscolor/index.htm @@ -0,0 +1,8 @@ + + +403 Forbidden + +

        Forbidden

        +You don't have permission to access this folder.

        +


        + \ No newline at end of file diff --git a/hesk/inc/jscolor/jscolor.min.js b/hesk/inc/jscolor/jscolor.min.js new file mode 100644 index 0000000..2a7a788 --- /dev/null +++ b/hesk/inc/jscolor/jscolor.min.js @@ -0,0 +1,10 @@ +/** + * jscolor - JavaScript Color Picker + * + * @link http://jscolor.com + * @license For open source use: GPLv3 + * For commercial use: JSColor Commercial License + * @author Jan Odvarko + * + * See usage examples at http://jscolor.com/examples/ + */"use strict";window.jscolor||(window.jscolor=function(){var e={register:function(){e.attachDOMReadyEvent(e.init),e.attachEvent(document,"mousedown",e.onDocumentMouseDown),e.attachEvent(document,"touchstart",e.onDocumentTouchStart),e.attachEvent(window,"resize",e.onWindowResize)},init:function(){e.jscolor.lookupClass&&e.jscolor.installByClassName(e.jscolor.lookupClass)},tryInstallOnElements:function(t,n){var r=new RegExp("(^|\\s)("+n+")(\\s*(\\{[^}]*\\})|\\s|$)","i");for(var i=0;is[u]?-r[u]+n[u]+i[u]/2>s[u]/2&&n[u]+i[u]-o[u]>=0?n[u]+i[u]-o[u]:n[u]:n[u],-r[a]+n[a]+i[a]+o[a]-l+l*f>s[a]?-r[a]+n[a]+i[a]/2>s[a]/2&&n[a]+i[a]-l-l*f>=0?n[a]+i[a]-l-l*f:n[a]+i[a]-l+l*f:n[a]+i[a]-l+l*f>=0?n[a]+i[a]-l+l*f:n[a]+i[a]-l-l*f];var h=c[u],p=c[a],d=t.fixed?"fixed":"absolute",v=(c[0]+o[0]>n[0]||c[0]2)switch(e.mode.charAt(2).toLowerCase()){case"s":return"s";case"v":return"v"}return null},onDocumentMouseDown:function(t){t||(t=window.event);var n=t.target||t.srcElement;n._jscLinkedInstance?n._jscLinkedInstance.showOnClick&&n._jscLinkedInstance.show():n._jscControlName?e.onControlPointerStart(t,n,n._jscControlName,"mouse"):e.picker&&e.picker.owner&&e.picker.owner.hide()},onDocumentTouchStart:function(t){t||(t=window.event);var n=t.target||t.srcElement;n._jscLinkedInstance?n._jscLinkedInstance.showOnClick&&n._jscLinkedInstance.show():n._jscControlName?e.onControlPointerStart(t,n,n._jscControlName,"touch"):e.picker&&e.picker.owner&&e.picker.owner.hide()},onWindowResize:function(t){e.redrawPosition()},onParentScroll:function(t){e.picker&&e.picker.owner&&e.picker.owner.hide()},_pointerMoveEvent:{mouse:"mousemove",touch:"touchmove"},_pointerEndEvent:{mouse:"mouseup",touch:"touchend"},_pointerOrigin:null,_capturedTarget:null,onControlPointerStart:function(t,n,r,i){var s=n._jscInstance;e.preventDefault(t),e.captureTarget(n);var o=function(s,o){e.attachGroupEvent("drag",s,e._pointerMoveEvent[i],e.onDocumentPointerMove(t,n,r,i,o)),e.attachGroupEvent("drag",s,e._pointerEndEvent[i],e.onDocumentPointerEnd(t,n,r,i))};o(document,[0,0]);if(window.parent&&window.frameElement){var u=window.frameElement.getBoundingClientRect(),a=[-u.left,-u.top];o(window.parent.window.document,a)}var f=e.getAbsPointerPos(t),l=e.getRelPointerPos(t);e._pointerOrigin={x:f.x-l.x,y:f.y-l.y};switch(r){case"pad":switch(e.getSliderComponent(s)){case"s":s.hsv[1]===0&&s.fromHSV(null,100,null);break;case"v":s.hsv[2]===0&&s.fromHSV(null,null,100)}e.setPad(s,t,0,0);break;case"sld":e.setSld(s,t,0)}e.dispatchFineChange(s)},onDocumentPointerMove:function(t,n,r,i,s){return function(t){var i=n._jscInstance;switch(r){case"pad":t||(t=window.event),e.setPad(i,t,s[0],s[1]),e.dispatchFineChange(i);break;case"sld":t||(t=window.event),e.setSld(i,t,s[1]),e.dispatchFineChange(i)}}},onDocumentPointerEnd:function(t,n,r,i){return function(t){var r=n._jscInstance;e.detachGroupEvents("drag"),e.releaseTarget(),e.dispatchChange(r)}},dispatchChange:function(t){t.valueElement&&e.isElementType(t.valueElement,"input")&&e.fireEvent(t.valueElement,"change")},dispatchFineChange:function(e){if(e.onFineChange){var t;typeof e.onFineChange=="string"?t=new Function(e.onFineChange):t=e.onFineChange,t.call(e)}},setPad:function(t,n,r,i){var s=e.getAbsPointerPos(n),o=r+s.x-e._pointerOrigin.x-t.padding-t.insetWidth,u=i+s.y-e._pointerOrigin.y-t.padding-t.insetWidth,a=o*(360/(t.width-1)),f=100-u*(100/(t.height-1));switch(e.getPadYComponent(t)){case"s":t.fromHSV(a,f,null,e.leaveSld);break;case"v":t.fromHSV(a,null,f,e.leaveSld)}},setSld:function(t,n,r){var i=e.getAbsPointerPos(n),s=r+i.y-e._pointerOrigin.y-t.padding-t.insetWidth,o=100-s*(100/(t.height-1));switch(e.getSliderComponent(t)){case"s":t.fromHSV(null,o,null,e.leavePad);break;case"v":t.fromHSV(null,null,o,e.leavePad)}},_vmlNS:"jsc_vml_",_vmlCSS:"jsc_vml_css_",_vmlReady:!1,initVML:function(){if(!e._vmlReady){var t=document;t.namespaces[e._vmlNS]||t.namespaces.add(e._vmlNS,"urn:schemas-microsoft-com:vml");if(!t.styleSheets[e._vmlCSS]){var n=["shape","shapetype","group","background","path","formulas","handles","fill","stroke","shadow","textbox","textpath","imagedata","line","polyline","curve","rect","roundrect","oval","arc","image"],r=t.createStyleSheet();r.owningElement.id=e._vmlCSS;for(var i=0;i=3&&(s=r[0].match(i))&&(o=r[1].match(i))&&(u=r[2].match(i))){var a=parseFloat((s[1]||"0")+(s[2]||"")),f=parseFloat((o[1]||"0")+(o[2]||"")),l=parseFloat((u[1]||"0")+(u[2]||""));return this.fromRGB(a,f,l,t),!0}}return!1},this.toString=function(){return(256|Math.round(this.rgb[0])).toString(16).substr(1)+(256|Math.round(this.rgb[1])).toString(16).substr(1)+(256|Math.round(this.rgb[2])).toString(16).substr(1)},this.toHEXString=function(){return"#"+this.toString().toUpperCase()},this.toRGBString=function(){return"rgb("+Math.round(this.rgb[0])+","+Math.round(this.rgb[1])+","+Math.round(this.rgb[2])+")"},this.isLight=function(){return.213*this.rgb[0]+.715*this.rgb[1]+.072*this.rgb[2]>127.5},this._processParentElementsInDOM=function(){if(this._linkedElementsProcessed)return;this._linkedElementsProcessed=!0;var t=this.targetElement;do{var n=e.getStyle(t);n&&n.position.toLowerCase()==="fixed"&&(this.fixed=!0),t!==this.targetElement&&(t._jscEventsAttached||(e.attachEvent(t,"scroll",e.onParentScroll),t._jscEventsAttached=!0))}while((t=t.parentNode)&&!e.isElementType(t,"body"))};if(typeof t=="string"){var h=t,p=document.getElementById(h);p?this.targetElement=p:e.warn("Could not find target element with ID '"+h+"'")}else t?this.targetElement=t:e.warn("Invalid target element: '"+t+"'");if(this.targetElement._jscLinkedInstance){e.warn("Cannot link jscolor twice to the same element. Skipping.");return}this.targetElement._jscLinkedInstance=this,this.valueElement=e.fetchElement(this.valueElement),this.styleElement=e.fetchElement(this.styleElement);var d=this,v=this.container?e.fetchElement(this.container):document.getElementsByTagName("body")[0],m=3;if(e.isElementType(this.targetElement,"button"))if(this.targetElement.onclick){var g=this.targetElement.onclick;this.targetElement.onclick=function(e){return g.call(this,e),!1}}else this.targetElement.onclick=function(){return!1};if(this.valueElement&&e.isElementType(this.valueElement,"input")){var y=function(){d.fromString(d.valueElement.value,e.leaveValue),e.dispatchFineChange(d)};e.attachEvent(this.valueElement,"keyup",y),e.attachEvent(this.valueElement,"input",y),e.attachEvent(this.valueElement,"blur",c),this.valueElement.setAttribute("autocomplete","off")}this.styleElement&&(this.styleElement._jscOrigStyle={backgroundImage:this.styleElement.style.backgroundImage,backgroundColor:this.styleElement.style.backgroundColor,color:this.styleElement.style.color}),this.value?this.fromString(this.value)||this.exportColor():this.importColor()}};return e.jscolor.lookupClass="jscolor",e.jscolor.installByClassName=function(t){var n=document.getElementsByTagName("input"),r=document.getElementsByTagName("button");e.tryInstallOnElements(n,t),e.tryInstallOnElements(r,t)},e.register(),e.jscolor}()); \ No newline at end of file diff --git a/hesk/inc/knowledgebase_functions.inc.php b/hesk/inc/knowledgebase_functions.inc.php new file mode 100644 index 0000000..294ee0f --- /dev/null +++ b/hesk/inc/knowledgebase_functions.inc.php @@ -0,0 +1,229 @@ + $hesk_settings['kb_substrart']) + { + // The quick but not 100% accurate way (number of chars displayed may be lower than the limit) + return hesk_mb_substr($txt, 0, $hesk_settings['kb_substrart']) . '...'; + + // If you want a more accurate, but also slower way, use this instead + // return hesk_htmlentities( hesk_mb_substr( hesk_html_entity_decode($txt), 0, $hesk_settings['kb_substrart'] ) ) . '...'; + } + + return $txt; +} // END hesk_kbArticleContentPreview() + + +function hesk_kbTopArticles($how_many, $index = 1) +{ + global $hesk_settings, $hesklang; + + $articles = array(); + // Index page or KB main page? + if ($index) + { + // Disabled? + if (!$hesk_settings['kb_index_popart']) + { + return $articles; + } + } + else + { + // Disabled? + if (!$hesk_settings['kb_popart']) + { + return $articles; + } + } + + /* Get list of articles from the database */ + $res = hesk_dbQuery("SELECT `t1`.`id`,`t1`.`subject`,`t1`.`views`, `t1`.`content`, `t2`.`name` AS `category`, `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`='0' AND `t2`.`type`='0' + ORDER BY `t1`.`sticky` DESC, `t1`.`views` DESC, `t1`.`art_order` ASC LIMIT ".intval($how_many)); + + $articles = array(); + + // Remember what articles are printed for "Top" so we don't print them again in "Latest" + $hesk_settings['kb_top_articles_printed'] = array(); + + while ($article = hesk_dbFetchAssoc($res)) + { + $hesk_settings['kb_top_articles_printed'][] = $article['id']; + $article['content_preview'] = hesk_kbArticleContentPreview($article['content']); + $articles[] = $article; + } + + return $articles; +} // END hesk_kbTopArticles() + + +function hesk_kbLatestArticles($how_many, $index = 1) +{ + global $hesk_settings, $hesklang; + + $articles = array(); + // Index page or KB main page? + if ($index) + { + // Disabled? + if ( ! $hesk_settings['kb_index_latest']) + { + return $articles; + } + + // Show title in italics + $font_weight = 'i'; + } + else + { + // Disabled? + if ( ! $hesk_settings['kb_latest']) + { + return $articles; + } + + // Show title in bold + $font_weight = 'b'; + } + + // Don't include articles that have already been printed under "Top" articles + $sql_top = ''; + if (isset($hesk_settings['kb_top_articles_printed']) && count($hesk_settings['kb_top_articles_printed'])) + { + $sql_top = ' AND `t1`.`id` NOT IN ('.implode(',', $hesk_settings['kb_top_articles_printed']).')'; + } + + /* Get list of articles from the database */ + $res = hesk_dbQuery("SELECT `t1`.`id`,`t1`.`subject`,`t1`.`dt`,`t1`.`views`, `t1`.`content`, `t1`.`rating`, `t2`.`name` AS `category` 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`='0' AND `t2`.`type`='0' {$sql_top} + ORDER BY `t1`.`dt` DESC LIMIT ".intval($how_many)); + + while ($article = hesk_dbFetchAssoc($res)) + { + $article['content_preview'] = hesk_kbArticleContentPreview($article['content']); + $articles[] = $article; + } + + return $articles; +} // END hesk_kbLatestArticles() + + +function hesk_kbSearchLarge($admin = '') +{ + global $hesk_settings, $hesklang; + + $action = 'knowledgebase.php'; + + if ($admin) + { + if ( ! $hesk_settings['kb_search']) + { + return ''; + } + $action = 'knowledgebase_private.php'; + } + elseif ($hesk_settings['kb_search'] != 2) + { + return ''; + } + ?> +
        +
        + +
        + + +
        +
        + + + + + +
        + + + +
        +
        + + +
        +
        + + + $tmpdir, + "AttachmentsDir" => $tmpdir, + ); + + if ( array_key_exists($varname,$config) ) + { + return $config[$varname]; + } + return FALSE; +} + +function parser($eml_file='') +{ + $tempdir = get_config('TempDir'); + if ( ! is_dir($tempdir) ) + { + die('The temporary directory "'.$tempdir.'" doesn\'t exist.'); + } + + // get a unique temporary file name + $tmpfilepath = tempnam($tempdir, strval(mt_rand(1000,9999))); + + if (defined('HESK_IMAP')) + { + global $imap, $email_number; + @file_put_contents($tmpfilepath, imap_fetchbody($imap, $email_number, "")); + } + else + { + // read the mail that is forwarded to the script + // then save the mail to a temporary file + save_forward_mail($tmpfilepath, $eml_file); + } + + if(file_exists($tmpfilepath) === FALSE) + { + die('Failed to save the mail as '.$tmpfilepath.'.'); + } + + $ret = analyze($tmpfilepath,$tempdir); + //die (print_r($ret)); + return $ret; +} + + +function analyze($tmpfilepath,$tempdir) +{ + $mime=new mime_parser_class; + + $mime->mbox = 0; + $mime->decode_bodies = 1; + $mime->ignore_syntax_errors = 1; + $mime->track_lines = 0; + + $parameters=array( + 'File'=>$tmpfilepath, + 'SaveBody'=>$tempdir, + ); + + /* only process the first email */ + if($mime->Decode($parameters, $decoded)) + { + if($mime->decode_bodies) + { + if($mime->Analyze($decoded[0], $results)) + { + #echo "MIME:\n\n"; + #print_r($results); + #echo "\nEND MIME\n\n"; + return process_results($results,$tempdir) ; + } + else + { + echo 'MIME message analyse error: '.$mime->error."\n"; + } + } + } + return False; +} + + +function process_addrname_pairs($email_info) +{ + $result = array(); + + foreach($email_info as $info) + { + $address = ""; + $name = ""; + $encoding = ""; + if ( array_key_exists("address", $info) ) + { + $address = $info["address"]; + } + if ( array_key_exists("name", $info) ) + { + $name = $info["name"]; + } + if ( array_key_exists("encoding", $info) ) + { + $encoding = $info["encoding"]; + } + + $result[] = array("address"=>$address, "name"=>$name, "encoding"=>$encoding); + } + + return $result; +} + + +function process_attachments($attachments) +{ + $result = array(); + foreach($attachments as $key => $info) + { + $orig_name = ""; + $size = 0; + $stored_name = ""; + $type = ""; + + if ( array_key_exists("Type", $info) ) + { + $type = $info["Type"]; + } + + if ( array_key_exists("FileName", $info) ) + { + $orig_name = $info["FileName"]; + } + elseif ($type == 'message') + { + $orig_name = ($key + 1) . ".msg"; + } + + if ( ! strlen($orig_name)) + { + continue; + } + + if ( array_key_exists("Data", $info) ) + { + $data = $info["Data"]; + $size = strlen($data); + + if ($size == 0) + { + continue; + } + + $attachsdir = get_config("AttachmentsDir"); + + if ( ! is_dir($attachsdir) ) + { + die('The attachments directory "'.$attachsdir.'" doesn\'t exist.'); + } + + $stored_name = save_attachment($attachsdir,getFileExtension($orig_name),$data); + } + else + { + $stored_name = $info['DataFile']; + $size = filesize($stored_name); + } + + $result[] = array("orig_name"=>$orig_name,"size"=>$size,"stored_name"=>$stored_name,"type"=>$type); + } + + return $result; +} + +/* +save an attachment file into the predefined directory. +return stored name +*/ +function save_attachment($dir,$extension,$data) +{ + $dir = rtrim($dir,"/\\"); /* " */ + + $path = ""; + $stored_name = ""; + do + { + $stored_name = date("YmdHis")."_".strval(mt_rand()).".".$extension; + $path = $dir . "/" . $stored_name; + } while(file_exists($path)); + + $fp = fopen($path,"w"); + if($fp === FALSE) + { + die("Cannot save file ".$path." ."); + } + fwrite($fp,$data); + fclose($fp); + + return $stored_name; +} + +function process_results($result,$tempdir) +{ + global $hesk_settings; + + $r = array(); + + // from address and name + $r["from"] = process_addrname_pairs($result["From"]); + + // to address and name + $r["to"] = process_addrname_pairs($result["To"]); + + // cc address and name + if( array_key_exists("Cc", $result) ) + { + $r["cc"] = process_addrname_pairs($result["Cc"]); + } + else + { + $r["cc"] = array(); + } + + // bcc address and name + if( array_key_exists("Bcc", $result) ) + { + $r["bcc"] = process_addrname_pairs($result["Bcc"]); + } + else + { + $r["bcc"] = array(); + } + + // reply-to address and name + if( array_key_exists("Reply-to", $result) ) + { + $r["reply-to"] = process_addrname_pairs($result["Reply-to"]); + } + else + { + $r["reply-to"] = array(); + } + + // subject and subject encoding + $r["subject"] = $result["Subject"]; + $r["subject_encoding"] = isset($result["SubjectEncoding"]) ? strtoupper($result["SubjectEncoding"]) : ""; + + // Message encoding + $r["encoding"] = isset($result["Encoding"]) ? strtoupper($result["Encoding"]) : ""; + + // If message is saved in a file get it from the file + if ( ! isset($result["Data"]) ) + { + $result["Data"] = ( isset($result["DataFile"]) && ! ( isset($result["FileDisposition"]) && $result["FileDisposition"] == "attachment") ) ? file_get_contents($result["DataFile"]) : ""; + } + + // Convert to UTF-8 before processing further + if ($r["encoding"] != "" && $r["encoding"] != 'UTF-8') + { + $result["Data"] = $result["Data"] == "" ? "" : iconv($r["encoding"], 'UTF-8', $result["Data"]); + $r["encoding"] = 'UTF-8'; + } + + // the message shall be converted to text if it is in html + if ( $result["Type"] === "html" ) + { + $r["message"] = convert_html_to_text($result["Data"]); + } + else + { + $r["message"] = $result["Data"]; + } + + // Fix for inline attachments + if (isset($result["FileDisposition"]) && ($result["FileDisposition"] == "attachment" || $result["FileDisposition"] == "inline")) + { + $r["message"] = ""; + } + + // Message attachments + $r["attachments"] = array(); + + if ($hesk_settings['attachments']) + { + // Attachment with no message + if ( isset($result["FileDisposition"]) && ($result["FileDisposition"] == "attachment" || $result["FileDisposition"] == "inline")) + { + $tmp = array(); + $tmp[0]['FileDisposition'] = "attachment"; + + if ( isset($result["Type"]) ) + { + $tmp[0]['Type'] = $result["Type"]; + } + + if ( isset($result["SubType"]) ) + { + $tmp[0]['SubType'] = $result["SubType"]; + } + + if ( isset($result["Description"]) ) + { + $tmp[0]['Description'] = $result["Description"]; + } + + if ( isset($result["DataFile"]) ) + { + $tmp[0]['DataFile'] = $result["DataFile"]; + } + + if ( isset($result["FileName"]) ) + { + $tmp[0]['FileName'] = $result["FileName"]; + } + + $r["attachments"] = array_merge($r["attachments"], process_attachments($tmp) ); + } + + // File attachments + if ( array_key_exists("Attachments", $result) ) + { + $r["attachments"] = array_merge($r["attachments"], process_attachments($result["Attachments"]) ); + } + + // Save embedded files (for example embedded images) + if ($hesk_settings['save_embedded'] && array_key_exists("Related", $result) ) + { + $r["attachments"] = array_merge($r["attachments"], process_attachments($result["Related"]) ); + } + } + + // Name of the temporary folder + $r["tempdir"] = $tempdir; + + return $r; +} + +/* + save the forwarded mail to a temporary file + no return value +*/ +function save_forward_mail($tmpfilepath, $eml_file) +{ + // create a temporary file + $tmpfp = fopen($tmpfilepath,"w"); + + // Just a line used for testing + // $eml_file = 'C:\\Users\\4N\\Desktop\\test.txt'; + + // open the stdin as a file handle or input file + $fp = $eml_file ? fopen($eml_file, "r") : fopen("php://stdin", "r"); + $fileContent = @stream_get_contents($fp); + fwrite($tmpfp, $fileContent); + + fclose($tmpfp); +} + + + +#test(); + +function test() +{ + $results = parser(); + + print_r($results); + exit(); + + // from address and name + echo "from :\n"; + echo $results["from"][0]["address"]."\n"; + echo $results["from"][0]["name"]."\n"; + + echo "\nto :\n"; + foreach( $results["to"] as $to ){ + echo $to["address"]."\n"; + echo $to["name"]."\n"; + } + + echo "\nreply-to :\n"; + foreach( $results["reply-to"] as $to ){ + echo $to["address"]."\n"; + echo $to["name"]."\n"; + } + + echo "\ncc :\n"; + foreach( $results["cc"] as $to ){ + echo $to["address"]."\n"; + echo $to["name"]."\n"; + } + + echo "\nbcc :\n"; + foreach( $results["bcc"] as $to ){ + echo $to["address"]."\n"; + echo $to["name"]."\n"; + } + + echo "\nsubject :\n"; + echo $results["subject"]."\n"; + + echo "\nmessage :\n"; + echo $results["message"]."\n"; + + echo "\nattachments :\n"; + foreach( $results["attachments"] as $attach ){ + echo $attach["orig_name"]."\n"; + echo $attach["size"]."\n"; + echo $attach["stored_name"]."\n"; + echo $attach["type"]."\n"; + } + +} + + +function deleteAll($directory, $empty = false) +{ + if(substr($directory,-1) == "/") + { + $directory = substr($directory,0,-1); + } + + if(!file_exists($directory) || !is_dir($directory)) + { + return false; + } + elseif( ! is_readable($directory)) + { + return false; + } + else + { + $directoryHandle = opendir($directory); + + while ($contents = readdir($directoryHandle)) + { + if($contents != '.' && $contents != '..') + { + $path = $directory . "/" . $contents; + + if(is_dir($path)) + { + deleteAll($path); + } + else + { + @unlink($path); + } + } + } + + closedir($directoryHandle); + + if($empty == false) + { + if(!rmdir($directory)) + { + return false; + } + } + + return true; + } +} + + +function convert_html_to_text($data) +{ + $html2text = new html2text($data); + $h2t = & ref_new($html2text); + + // Simply call the get_text() method for the class to convert + // the HTML to the plain text. Store it into the variable. + $text = $h2t->get_text(); + return $text; +} + + +class html2text +{ + /** + * Contains the HTML content to convert. + * + * @var string $html + * @access public + */ + var $html; + + /** + * Contains the converted, formatted text. + * + * @var string $text + * @access public + */ + var $text; + + /** + * Maximum width of the formatted text, in columns. + * + * Set this value to 0 (or less) to ignore word wrapping + * and not constrain text to a fixed-width column. + * + * @var integer $width + * @access public + */ + var $width = 70; + + /** + * List of preg* regular expression patterns to search for, + * used in conjunction with $replace. + * + * @var array $search + * @access public + * @see $replace + */ + var $search = array( + "/\r/", // Non-legal carriage return + "/[\n\t]+/", // Newlines and tabs + '/[ ]{2,}/', // Runs of spaces, pre-handling + '/]*>.*?<\/script>/i', // + + +403 Forbidden + +

        Forbidden

        +You don't have permission to access this folder.

        +


        + \ No newline at end of file diff --git a/hesk/inc/recaptcha/recaptchalib_v2.php b/hesk/inc/recaptcha/recaptchalib_v2.php new file mode 100644 index 0000000..7cd9988 --- /dev/null +++ b/hesk/inc/recaptcha/recaptchalib_v2.php @@ -0,0 +1,154 @@ +" . self::$_signupUrl . ""); + } + $this->_secret=$secret; + } + + /** + * Encodes the given data into a query string format. + * + * @param array $data array of string elements to be encoded. + * + * @return string - encoded request. + */ + private function _encodeQS($data) + { + $req = ""; + foreach ($data as $key => $value) { + $req .= $key . '=' . urlencode(stripslashes($value)) . '&'; + } + + // Cut the last '&' + $req=substr($req, 0, strlen($req)-1); + return $req; + } + + /** + * Submits an HTTP GET to a reCAPTCHA server. + * + * @param string $path url path to recaptcha server. + * @param array $data array of parameters to be sent. + * + * @return array response + */ + private function _submitHTTPGet($path, $data) + { + $req = $this->_encodeQS($data); + + // Try using cURL + if ( function_exists('curl_init') ) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $path); + curl_setopt($ch, CURLOPT_POST, count($data) ); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data, '', '&') ); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); + $response = curl_exec($ch); + curl_close($ch); + return $response; + } + + // Default to file_get_contents + $response = file_get_contents($path . $req); + return $response; + } + + /** + * Calls the reCAPTCHA siteverify API to verify whether the user passes + * CAPTCHA test. + * + * @param string $remoteIp IP address of end user. + * @param string $response response string from recaptcha verification. + * + * @return ReCaptchaResponse + */ + public function verifyResponse($remoteIp, $response) + { + // Discard empty solution submissions + if ($response == null || strlen($response) == 0) { + $recaptchaResponse = new ReCaptchaResponse(); + $recaptchaResponse->success = false; + $recaptchaResponse->errorCodes = 'missing-input'; + return $recaptchaResponse; + } + + $getResponse = $this->_submitHttpGet( + self::$_siteVerifyUrl, + array ( + 'secret' => $this->_secret, + 'remoteip' => $remoteIp, + 'v' => self::$_version, + 'response' => $response + ) + ); + $answers = json_decode($getResponse, true); + $recaptchaResponse = new ReCaptchaResponse(); + + if (trim($answers ['success']) == true) { + $recaptchaResponse->success = true; + } else { + $recaptchaResponse->success = false; + $recaptchaResponse->errorCodes = $answers [error-codes]; + } + + return $recaptchaResponse; + } +} diff --git a/hesk/inc/reporting_functions.inc.php b/hesk/inc/reporting_functions.inc.php new file mode 100644 index 0000000..6eb2aaa --- /dev/null +++ b/hesk/inc/reporting_functions.inc.php @@ -0,0 +1,147 @@ + 59) + { + $m = floor($s / 60) + $m; + $s = intval($s % 60); + } + + // Convert minutes to hours if 60 or more minutes + if ($m > 59) + { + $h = floor($m / 60) + $h; + $m = intval($m % 60); + } + + // That's it, let's send out formatted time string + return str_pad($h, 2, "0", STR_PAD_LEFT) . ':' . str_pad($m, 2, "0", STR_PAD_LEFT) . ':' . str_pad($s, 2, "0", STR_PAD_LEFT); + +} // END hesk_SecondsToHHMMSS() + + +function hesk_parseXML($msg) +{ + $from = array('/\([^\<]*)\<\/a\>/i', '/\([^\<]*)\<\/a\>/i'); + $to = array("$1", "$1"); + $msg = preg_replace($from,$to,$msg); + $msg = preg_replace('/
        \s*/',"\n",$msg); + $msg = trim($msg); + return $msg; +} // END hesk_parseXML() + + +function dateweek($weeknumber,$business=0) +{ + $x = strtotime("last Monday"); + $Year = date("Y",$x); + $Month = date("m",$x); + $Day = date("d",$x); + + if ($Month < 2 && $Day < 8) + { + $Year = $Year--; + $Month = $Month--; + } + + if ($Month > 1 && $Day < 8) + { + $Month = $Month--; + } + //DATE BEGINN OF THE WEEK ( Monday ) + $Day = $Day+7*$weeknumber; + $dt[0]=date('Y-m-d', mktime(0, 0, 0, $Month, $Day, $Year)); + + if ($business) + { + //DATE END OF BUSINESS WEEK ( Friday ) + $Day = $Day+4; + $dt[1]=date('Y-m-d', mktime(0, 0, 0, $Month, $Day, $Year)); + } + else + { + //DATE END OF THE WEEK ( Sunday ) + $Day = $Day+6; + $dt[1]=date('Y-m-d', mktime(0, 0, 0, $Month, $Day, $Year)); + } + + return $dt; +} // END dateweek() + + +function DateArray($s,$e) +{ + $start = strtotime($s); + $end = strtotime($e); + $da = array(); + $loop = 0; + while ($loop < 10000 && $start <= $end) + { + $loop++; + $da[] = date('Y-m-d', $start); + $start = strtotime('+1 day', $start); + } + return $da; +} // END DateArray() + + +function MonthsArray($s,$e) +{ + $start = date('Y-m-01', strtotime($s)); + $end = date('Y-m-01', strtotime($e)); + $mt = array(); + while ($start <= $end) + { + $mt[] = $start; + $start = date('Y-m-01',strtotime("+1 month", strtotime($start))); + } + return $mt; +} // END MonthsArray() + + +function hesk_getOldestDate() +{ + global $hesk_settings, $hesklang, $date_from, $date_to; + + $res = hesk_dbQuery("SELECT `dt` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` ORDER BY `dt` ASC LIMIT 1"); + + if (hesk_dbNumRows($res) == 1) + { + $row = hesk_dbFetchAssoc($res); + return date('Y-m-d', strtotime($row['dt']) ); + } + else + { + return date('Y-m-d'); + } + +} // END hesk_getOldestDate() diff --git a/hesk/inc/secimg.inc.php b/hesk/inc/secimg.inc.php new file mode 100644 index 0000000..e1d5c91 --- /dev/null +++ b/hesk/inc/secimg.inc.php @@ -0,0 +1,82 @@ +code = ''; + $this->key = $key; + } // End PJ_SecurityImage + + function encrypt($plain_text) + { + $this->code = trim(sha1($plain_text.$this->key)); + } // End encrypt + + function checkCode($mystring,$checksum) + { + $this->encrypt($mystring); + if ($this->code == $checksum) + return true; + else + return false; + } // End checkCode + + function printImage($random_number) + { + $im = @imagecreate(150, 40) or die("Cannot Initialize new GD image stream"); + $background_color = imagecolorallocate($im, mt_rand(0,100), mt_rand(0,100), mt_rand(0,100)); + + for ($i=0;$icode; + } // End get + +} // End class PJ_SecurityImage diff --git a/hesk/inc/setup_functions.inc.php b/hesk/inc/setup_functions.inc.php new file mode 100644 index 0000000..e67539c --- /dev/null +++ b/hesk/inc/setup_functions.inc.php @@ -0,0 +1,597 @@ + $hesklang['ms01'], + 'Feb' => $hesklang['ms02'], + 'Mar' => $hesklang['ms03'], + 'Apr' => $hesklang['ms04'], + 'May' => $hesklang['ms05'], + 'Jun' => $hesklang['ms06'], + 'Jul' => $hesklang['ms07'], + 'Aug' => $hesklang['ms08'], + 'Sep' => $hesklang['ms09'], + 'Oct' => $hesklang['ms10'], + 'Nov' => $hesklang['ms11'], + 'Dec' => $hesklang['ms12'] + ); + + return str_replace(array_keys($translate_months_short), array_values($translate_months_short), $timezone_list); +} // END hesk_translate_timezone_list() + + +function hesk_generate_timezone_list() +{ + static $regions = array( + DateTimeZone::AFRICA, + DateTimeZone::AMERICA, + DateTimeZone::ANTARCTICA, + DateTimeZone::ASIA, + DateTimeZone::ATLANTIC, + DateTimeZone::AUSTRALIA, + DateTimeZone::EUROPE, + DateTimeZone::INDIAN, + DateTimeZone::PACIFIC, + ); + + $timezones = array(); + foreach( $regions as $region ) + { + $timezones = array_merge( $timezones, DateTimeZone::listIdentifiers( $region ) ); + } + + $timezone_offsets = array(); + foreach( $timezones as $timezone ) + { + $tz = new DateTimeZone($timezone); + $timezone_offsets[$timezone] = $tz->getOffset(new DateTime); + } + + // sort timezone by timezone name + ksort($timezone_offsets); + //asort($timezone_offsets); // <-- use this to sort by time offset from UTC instead + + // Add UTC as the first element + $timezone_offsets = array('UTC' => 0) + $timezone_offsets; + + $timezone_list = array(); + foreach( $timezone_offsets as $timezone => $offset ) + { + $offset_prefix = $offset < 0 ? '-' : '+'; + $offset_formatted = gmdate( 'H:i', abs($offset) ); + + $pretty_offset = "UTC{$offset_prefix}{$offset_formatted}"; + + $t = new DateTimeZone($timezone); + $c = new DateTime(null, $t); + $current_time = $c->format('d M Y, H:i'); + + $timezone_list[$timezone] = "{$timezone} - {$current_time}"; + } + + return $timezone_list; +} // END hesk_generate_timezone_list() + + +function hesk_testMySQL() +{ + global $hesk_settings, $hesklang, $set, $mysql_error, $mysql_log; + + define('REQUIRE_MYSQL_VERSION','5.0.7'); + + // Use MySQLi extension to connect? + $use_mysqli = function_exists('mysqli_connect') ? true : false; + + // Get variables + $set['db_host'] = hesk_input( hesk_POST('s_db_host'), $hesklang['err_dbhost']); + $set['db_name'] = hesk_input( hesk_POST('s_db_name'), $hesklang['err_dbname']); + $set['db_user'] = hesk_input( hesk_POST('s_db_user'), $hesklang['err_dbuser']); + $set['db_pass'] = hesk_input( hesk_POST('s_db_pass') ); + $set['db_pfix'] = preg_replace('/[^0-9a-zA-Z_]/', '', hesk_POST('s_db_pfix', 'hesk_') ); + + // Allow & in password + $set['db_pass'] = str_replace('&', '&', $set['db_pass']); + + // MySQL tables used by HESK + $tables = array( + $set['db_pfix'].'attachments', + $set['db_pfix'].'banned_emails', + $set['db_pfix'].'banned_ips', + $set['db_pfix'].'categories', + $set['db_pfix'].'kb_articles', + $set['db_pfix'].'kb_attachments', + $set['db_pfix'].'kb_categories', + $set['db_pfix'].'logins', + $set['db_pfix'].'mail', + $set['db_pfix'].'notes', + $set['db_pfix'].'online', + $set['db_pfix'].'pipe_loops', + $set['db_pfix'].'replies', + $set['db_pfix'].'reply_drafts', + $set['db_pfix'].'reset_password', + $set['db_pfix'].'service_messages', + $set['db_pfix'].'std_replies', + $set['db_pfix'].'tickets', + $set['db_pfix'].'ticket_templates', + $set['db_pfix'].'users', + ); + + $connection_OK = false; + $mysql_error = ''; + + ob_start(); + + // Connect to MySQL + if ($use_mysqli) + { + // Do we need a special port? Check and connect to the database + if ( strpos($set['db_host'], ':') ) + { + list($set['db_host_no_port'], $set['db_port']) = explode(':', $set['db_host']); + $set_link = mysqli_connect($set['db_host_no_port'], $set['db_user'], $set['db_pass'], $set['db_name'], intval($set['db_port']) ); + } + else + { + $set_link = mysqli_connect($set['db_host'], $set['db_user'], $set['db_pass'], $set['db_name']); + } + + if ( ! $set_link) + { + ob_end_clean(); + $mysql_error = $hesklang['err_dbconn']; + $mysql_log = "(".mysqli_connect_errno().") ".mysqli_connect_error(); + return false; + } + + $res = mysqli_query($set_link, 'SHOW TABLES FROM `'.mysqli_real_escape_string($set_link, $set['db_name']).'`'); + while ($row = mysqli_fetch_row($res)) + { + foreach($tables as $k => $v) + { + if ($v == $row[0]) + { + unset($tables[$k]); + break; + } + } + } + + // Get MySQL version + $mysql_version = mysqli_fetch_assoc( mysqli_query($set_link, 'SELECT VERSION() AS version') ); + + // Close connections + mysqli_close($set_link); + } + else + { + $set_link = mysql_connect($set['db_host'], $set['db_user'], $set['db_pass']); + + if ( ! $set_link) + { + ob_end_clean(); + $mysql_error = $hesklang['err_dbconn']; + $mysql_log = mysql_error(); + return false; + } + + // Select database + if ( ! mysql_select_db($set['db_name'], $set_link) ) + { + ob_end_clean(); + $mysql_error = $hesklang['err_dbsele']; + $mysql_log = mysql_error(); + return false; + } + + $res = mysql_query('SHOW TABLES FROM `'.mysql_real_escape_string($set['db_name']).'`', $set_link); + while ($row = mysql_fetch_row($res)) + { + foreach($tables as $k => $v) + { + if ($v == $row[0]) + { + unset($tables[$k]); + break; + } + } + } + + // Get MySQL version + $mysql_version = mysql_fetch_assoc( mysql_query('SELECT VERSION() AS version') ); + + // Close connections + mysql_close($set_link); + } + + // Check MySQL version + if ( version_compare($mysql_version['version'], REQUIRE_MYSQL_VERSION, '<') ) + { + ob_end_clean(); + $mysql_error = $hesklang['err_dbversion'] . ' ' . $mysql_version['version']; + $mysql_log = ''; + return false; + } + + // Check PHP version for the mysql(i)_set_charset function + $set['db_vrsn'] = ( version_compare(PHP_VERSION, '5.2.3') >= 0 ) ? 1 : 0; + + // Some tables weren't found, show an error + if (count($tables) > 0) + { + ob_end_clean(); + $mysql_error = $hesklang['err_dpi2'].'

        '.implode(',
        ', $tables); + $mysql_log = ''; + return false; + } + else + { + $connection_OK = true; + } + + ob_end_clean(); + + return $connection_OK; +} // END hesk_testMySQL() + + +function hesk_testPOP3($check_old_settings=false) +{ + global $hesk_settings, $hesklang, $set; + + $set['pop3_host_name'] = hesk_input( hesk_POST('s_pop3_host_name', 'mail.example.com') ); + $set['pop3_host_port'] = intval( hesk_POST('s_pop3_host_port', 110) ); + $set['pop3_tls'] = empty($_POST['s_pop3_tls']) ? 0 : 1; + $set['pop3_keep'] = empty($_POST['s_pop3_keep']) ? 0 : 1; + $set['pop3_user'] = hesk_input( hesk_POST('s_pop3_user') ); + $set['pop3_password'] = hesk_input( hesk_POST('s_pop3_password') ); + + // Are new settings the same as old? If yes, skip testing connection, assume it works + if ($check_old_settings) + { + $set['tmp_pop3_host_name'] = hesk_input( hesk_POST('tmp_pop3_host_name', 'mail.example.com') ); + $set['tmp_pop3_host_port'] = intval( hesk_POST('tmp_pop3_host_port', 110) ); + $set['tmp_pop3_tls'] = empty($_POST['tmp_pop3_tls']) ? 0 : 1; + $set['tmp_pop3_keep'] = empty($_POST['tmp_pop3_keep']) ? 0 : 1; + $set['tmp_pop3_user'] = hesk_input( hesk_POST('tmp_pop3_user') ); + $set['tmp_pop3_password'] = hesk_input( hesk_POST('tmp_pop3_password') ); + + if ( + $set['tmp_pop3_host_name'] != 'mail.example.com' && // Default setting + $set['tmp_pop3_host_name'] == $set['pop3_host_name'] && + $set['tmp_pop3_host_port'] == $set['pop3_host_port'] && + $set['tmp_pop3_tls'] == $set['pop3_tls'] && + $set['tmp_pop3_keep'] == $set['pop3_keep'] && + $set['tmp_pop3_user'] == $set['pop3_user'] && + $set['tmp_pop3_password'] == $set['pop3_password'] + ) + { + return true; + } + } + + // Initiate POP3 class and set parameters + require_once(HESK_PATH . 'inc/mail/pop3.php'); + $pop3 = new pop3_class; + $pop3->hostname = $set['pop3_host_name']; + $pop3->port = $set['pop3_host_port']; + $pop3->tls = $set['pop3_tls']; + $pop3->debug = 1; + + $connection_OK = false; + + ob_start(); + + // Connect to POP3 + if(($error=$pop3->Open())=="") + { + // Authenticate + if(($error=$pop3->Login($set['pop3_user'], hesk_htmlspecialchars_decode(stripslashes($set['pop3_password']))))=="") + { + if(($error=$pop3->Close()) == "") + { + // Connection OK + $connection_OK = true; + } + } + } + + if($error != '') + { + global $pop3_error, $pop3_log; + $pop3_error = $error; + $pop3_log = ob_get_contents(); + } + + ob_end_clean(); + + return $connection_OK; +} // END hesk_testPOP3() + + +function hesk_testSMTP($check_old_settings=false) +{ + global $hesk_settings, $hesklang, $set; + + // Get variables + $set['smtp_host_name'] = hesk_input( hesk_POST('s_smtp_host_name', 'localhost') ); + $set['smtp_host_port'] = intval( hesk_POST('s_smtp_host_port', 25) ); + $set['smtp_timeout'] = intval( hesk_POST('s_smtp_timeout', 10) ); + $set['smtp_ssl'] = empty($_POST['s_smtp_ssl']) ? 0 : 1; + $set['smtp_tls'] = empty($_POST['s_smtp_tls']) ? 0 : 1; + $set['smtp_user'] = hesk_input( hesk_POST('s_smtp_user') ); + $set['smtp_password'] = hesk_input( hesk_POST('s_smtp_password') ); + + // Are new settings the same as old? If yes, skip testing connection, assume it works + if ($check_old_settings) + { + $set['tmp_smtp_host_name'] = hesk_input( hesk_POST('tmp_smtp_host_name', 'localhost') ); + $set['tmp_smtp_host_port'] = intval( hesk_POST('tmp_smtp_host_port', 25) ); + $set['tmp_smtp_timeout'] = intval( hesk_POST('tmp_smtp_timeout', 10) ); + $set['tmp_smtp_ssl'] = empty($_POST['tmp_smtp_ssl']) ? 0 : 1; + $set['tmp_smtp_tls'] = empty($_POST['tmp_smtp_tls']) ? 0 : 1; + $set['tmp_smtp_user'] = hesk_input( hesk_POST('tmp_smtp_user') ); + $set['tmp_smtp_password'] = hesk_input( hesk_POST('tmp_smtp_password') ); + + if ( + $set['tmp_smtp_host_name'] != 'mail.example.com' && // Default setting + $set['tmp_smtp_host_name'] == $set['smtp_host_name'] && + $set['tmp_smtp_host_port'] == $set['smtp_host_port'] && + $set['tmp_smtp_timeout'] == $set['smtp_timeout'] && + $set['tmp_smtp_ssl'] == $set['smtp_ssl'] && + $set['tmp_smtp_tls'] == $set['smtp_tls'] && + $set['tmp_smtp_user'] == $set['smtp_user'] && + $set['tmp_smtp_password'] == $set['smtp_password'] + ) + { + return true; + } + } + + // Initiate SMTP class and set parameters + require_once(HESK_PATH . 'inc/mail/smtp.php'); + $smtp = new smtp_class; + $smtp->host_name = $set['smtp_host_name']; + $smtp->host_port = $set['smtp_host_port']; + $smtp->timeout = $set['smtp_timeout']; + $smtp->ssl = $set['smtp_ssl']; + $smtp->start_tls = $set['smtp_tls']; + $smtp->user = $set['smtp_user']; + $smtp->password = hesk_htmlspecialchars_decode(stripslashes($set['smtp_password'])); + $smtp->debug = 1; + + if (strlen($set['smtp_user']) || strlen($set['smtp_password'])) + { + require_once(HESK_PATH . 'inc/mail/sasl/sasl.php'); + } + + $connection_OK = false; + + ob_start(); + + // Test connection + if ($smtp->Connect()) + { + // SMTP connect successful + $connection_OK = true; + $smtp->Disconnect(); + } + else + { + global $smtp_error, $smtp_log; + $smtp_error = ucfirst($smtp->error); + $smtp_log = ob_get_contents(); + } + + $smtp_log = ob_get_contents(); + ob_end_clean(); + + return $connection_OK; +} // END hesk_testSMTP() + + +function hesk_testIMAP($check_old_settings=false) +{ + global $hesk_settings, $hesklang, $set; + + $set['imap_host_name'] = hesk_input( hesk_POST('s_imap_host_name', 'mail.example.com') ); + $set['imap_host_port'] = intval( hesk_POST('s_imap_host_port', 993) ); + $set['imap_enc'] = hesk_POST('s_imap_enc'); + $set['imap_enc'] = ($set['imap_enc'] == 'ssl' || $set['imap_enc'] == 'tls') ? $set['imap_enc'] : ''; + $set['imap_keep'] = empty($_POST['s_imap_keep']) ? 0 : 1; + $set['imap_user'] = hesk_input( hesk_POST('s_imap_user') ); + $set['imap_password'] = hesk_input( hesk_POST('s_imap_password') ); + + // Are new settings the same as old? If yes, skip testing connection, assume it works + if ($check_old_settings) + { + $set['tmp_imap_host_name'] = hesk_input( hesk_POST('tmp_imap_host_name', 'mail.example.com') ); + $set['tmp_imap_host_port'] = intval( hesk_POST('tmp_imap_host_port', 993) ); + $set['tmp_imap_enc'] = hesk_POST('s_imap_enc'); + $set['tmp_imap_enc'] = ($set['tmp_imap_enc'] == 'ssl' || $set['tmp_imap_enc'] == 'tls') ? $set['tmp_imap_enc'] : ''; + $set['tmp_imap_keep'] = empty($_POST['tmp_imap_keep']) ? 0 : 1; + $set['tmp_imap_user'] = hesk_input( hesk_POST('tmp_imap_user') ); + $set['tmp_imap_password'] = hesk_input( hesk_POST('tmp_imap_password') ); + + if ( + $set['tmp_imap_host_name'] != 'mail.example.com' && // Default setting + $set['tmp_imap_host_name'] == $set['imap_host_name'] && + $set['tmp_imap_host_port'] == $set['imap_host_port'] && + $set['tmp_imap_enc'] == $set['imap_enc'] && + $set['tmp_imap_keep'] == $set['imap_keep'] && + $set['tmp_imap_user'] == $set['imap_user'] && + $set['tmp_imap_password'] == $set['imap_password'] + ) + { + return true; + } + } + + $connection_OK = false; + + ob_start(); + + // IMAP mailbox based on required encryption + switch ($set['imap_enc']) + { + case 'ssl': + $set['imap_mailbox'] = '{'.$set['imap_host_name'].':'.$set['imap_host_port'].'/imap/ssl/novalidate-cert}'; + break; + case 'tls': + $set['imap_mailbox'] = '{'.$set['imap_host_name'].':'.$set['imap_host_port'].'/imap/tls/novalidate-cert}'; + break; + default: + $set['imap_mailbox'] = '{'.$set['imap_host_name'].':'.$set['imap_host_port'].'}'; + } + + $set['imap_password'] = hesk_htmlspecialchars_decode(stripslashes($set['imap_password'])); + + // Connect to IMAP + $imap = @imap_open($set['imap_mailbox'], $set['imap_user'], $set['imap_password']); + + // Connection successful? + if ($imap !== false) + { + // Try reading the mailbox + imap_search($imap, 'UNSEEN'); + + // Close IMAP connection + imap_close($imap); + } + + // Any error messages? + if($errors = imap_errors()) + { + global $imap_error, $imap_log; + + $imap_error = end($errors); + reset($errors); + + $imap_log = ''; + + foreach ($errors as $error) + { + $imap_log .= hesk_htmlspecialchars($error) . "\n"; + } + } + else + { + // Connection OK + $connection_OK = true; + } + + ob_end_clean(); + + return $connection_OK; +} // END hesk_testIMAP() + + +function hesk_generate_SPAM_question() +{ + $useChars = 'AEUYBDGHJLMNPRSTVWXZ23456789'; + $ac = $useChars[mt_rand(0,27)]; + for($i=1;$i<5;$i++) + { + $ac .= $useChars[mt_rand(0,27)]; + } + + $animals = array('dog','cat','cow','pig','elephant','tiger','chicken','bird','fish','alligator','monkey','mouse','lion','turtle','crocodile','duck','gorilla','horse','penguin','dolphin','rabbit','sheep','snake','spider'); + $not_animals = array('ball','window','house','tree','earth','money','rocket','sun','star','shirt','snow','rain','air','candle','computer','desk','coin','TV','paper','bell','car','baloon','airplane','phone','water','space'); + + $keys = array_rand($animals,2); + $my_animals[] = $animals[$keys[0]]; + $my_animals[] = $animals[$keys[1]]; + + $keys = array_rand($not_animals,2); + $my_not_animals[] = $not_animals[$keys[0]]; + $my_not_animals[] = $not_animals[$keys[1]]; + + $my_animals[] = $my_not_animals[0]; + $my_not_animals[] = $my_animals[0]; + + $e = mt_rand(1,9); + $f = $e + 1; + $d = mt_rand(1,9); + $s = intval($e + $d); + + if ($e == $d) + { + $d ++; + $h = $d; + $l = $e; + } + elseif ($e < $d) + { + $h = $d; + $l = $e; + } + else + { + $h = $e; + $l = $d; + } + + $spam_questions = array( + $f => 'What is the next number after '.$e.'? (Use only digits to answer)', + 'white' => 'What color is snow? (give a 1 word answer to show you are a human)', + 'green' => 'What color is grass? (give a 1 word answer to show you are a human)', + 'blue' => 'What color is water? (give a 1 word answer to show you are a human)', + $ac => 'Access code (type '.$ac.' here):', + $ac => 'Type '.$ac.' here to fight SPAM:', + $s => 'Solve this equation to show you are human: '.$e.' + '.$d.' = ', + $my_animals[2] => 'Which of these is not an animal: ' . implode(', ',hesk_randomize_array($my_animals)), + $my_not_animals[2] => 'Which of these is an animal: ' . implode(', ',hesk_randomize_array($my_not_animals)), + $h => 'Which number is higher '.$e.' or '.$d.':', + $l => 'Which number is lower '.$e.' or '.$d.':', + 'no' => 'Are you a robot? (yes or no)', + 'yes' => 'Are you a human? (yes or no)' + ); + + $r = array_rand($spam_questions); + $ask = $spam_questions[$r]; + $ans = $r; + + return array($ask,$ans); +} // END hesk_generate_SPAM_question() + + +function hesk_randomize_array($array) +{ + $rand_items = array_rand($array, count($array)); + $new_array = array(); + foreach($rand_items as $value) + { + $new_array[$value] = $array[$value]; + } + + return $new_array; +} // END hesk_randomize_array() + + +function hesk_checkMinMax($myint,$min,$max,$defval) +{ + if ($myint > $max || $myint < $min) + { + return $defval; + } + return $myint; +} // END hesk_checkMinMax() diff --git a/hesk/inc/show_admin_nav.inc.php b/hesk/inc/show_admin_nav.inc.php new file mode 100644 index 0000000..49e1320 --- /dev/null +++ b/hesk/inc/show_admin_nav.inc.php @@ -0,0 +1,504 @@ + + +
        +
        + +
        +
        +
        +
        + + + +
        + +
        +
        + +
        +
        +

        + + + + +

        +
        +
        +
        + +
        + +
        +
        +
        +
        +
        + + + +
        +
        +'; + hesk_show_notice($hesklang['mma2'], $hesklang['mma1'], false); +} + +// Show a notice if we are in "Knowledgebase only" mode +if ( hesk_check_kb_only(false) ) +{ + echo '
        '; + hesk_show_notice($hesklang['kbo2'], $hesklang['kbo1'], false); +} +?> diff --git a/hesk/inc/show_search_form.inc.php b/hesk/inc/show_search_form.inc.php new file mode 100644 index 0000000..08482f4 --- /dev/null +++ b/hesk/inc/show_search_form.inc.php @@ -0,0 +1,487 @@ + 'CRITICAL', + 1 => 'HIGH', + 2 => 'MEDIUM', + 3 => 'LOW', + ); +} + +if ( ! isset($what) ) +{ + $what = 'trackid'; +} + +if ( ! isset($owner_input) ) +{ + $owner_input = 0; +} + +if ( ! isset($date_input) ) +{ + $date_input = ''; +} + +/* 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); +$can_view_ass_by = hesk_checkPermission('can_view_ass_by', 0); + +/* Category options */ +$category_options = ''; +if ( isset($hesk_settings['categories']) && count($hesk_settings['categories']) ) +{ + foreach ($hesk_settings['categories'] as $row['id'] => $row['name']) + { + $row['name'] = (hesk_mb_strlen($row['name']) > 30) ? hesk_mb_substr($row['name'],0,30) . '...' : $row['name']; + $selected = ($row['id'] == $category) ? 'selected="selected"' : ''; + $category_options .= ''; + } +} +else +{ + $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)) + { + $row['name'] = (hesk_mb_strlen($row['name']) > 30) ? hesk_mb_substr($row['name'],0,30) . '...' : $row['name']; + $selected = ($row['id'] == $category) ? 'selected="selected"' : ''; + $category_options .= ''; + } +} + +/* List of staff */ +if (($can_view_ass_others || $can_view_ass_by) && ! isset($admins)) +{ + $admins = array(); + $res2 = hesk_dbQuery("SELECT `id`,`name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` ORDER BY `name` ASC"); + while ($row=hesk_dbFetchAssoc($res2)) + { + $admins[$row['id']]=$row['name']; + } +} + +$more = empty($_GET['more']) ? 0 : 1; +$more2 = empty($_GET['more2']) ? 0 : 1; + +#echo "SQL: $sql"; +?> + + +

        +
        +
        +
        +
        + +
        +
        +
        + +
        +
        +
        +
        +
        + + +
        +
        +
        +
        +
        + +
        +
        +
        +
        + > + +
        +
        + > + +
        +
        + > + +
        +
        + > + +
        +
        +
        +
        +
        +
        + +
        +
        +
        +
        + > + +
        + +
        + > + +
        + + +
        + > + +
        + +
        + > + +
        +
        +
        +
        +
        +
        + +
        +
        +
        + +
        + > + +
        + +
        +
        +
        +
        +
        + +
        +
        +
        +
        + > + +
        + +
        + > + +
        + +
        + > + +
        +
        + > + +
        +
        +
        +
        +
        +
        + +
        +
        + +
        +
        +
        +
        + +
        +
        + + +
        +
        +
        +
        + +
        +
        +
        +
        + > + +
        +
        + > + +
        +
        +
        +
        +
        +
        + +
        +
        +
        +
        + > + +
        +
        + +   + () +
        +
        +
        +
        +
        +
        + + + +
        +
        +
        +
        +
        + + + + +

        +
        +
        +
        +
        + +
        +
        + > +
        +
        +
        +
        + +
        +
        + +
        +
        +
        +
        + + +
        +
        +
        +
        +
        + +
        +
        + +
        +
        + +
        +
        + +
        +
        + +
        +
        + +
        +
        + +
        +
        +
        +
        + + + type="text" class="datepicker"> +
        +
        > + + + + + + +
        +
        +
        +
        +
        +
        + +
        +
        +
        +
        + > + +
        + +
        + > + +
        + +
        + > + +
        + +
        + > + +
        +
        +
        +
        +
        +
        + +
        +
        + + +
        +
        +
        +
        + + + +
        +
        +
        +
        +
        + + + diff --git a/hesk/inc/statuses.inc.php b/hesk/inc/statuses.inc.php new file mode 100644 index 0000000..b68c847 --- /dev/null +++ b/hesk/inc/statuses.inc.php @@ -0,0 +1,229 @@ + $hesklang['open'], + 'class' => 'open', + ); + // 1 = CUSTOMER REPLIED + $hesk_settings['statuses'][1] = array( + 'name' => $hesklang['wait_reply'], + 'class' => 'waitingreply', + ); + // 2 = STAFF REPLIED + $hesk_settings['statuses'][2] = array( + 'name' => $hesklang['replied'], + 'class' => 'replied', + ); + // 3 = RESOLVED + $hesk_settings['statuses'][3] = array( + 'name' => $hesklang['closed'], + 'class' => 'resolved', + ); + // 4 = IN PROGRESS + $hesk_settings['statuses'][4] = array( + 'name' => $hesklang['in_progress'], + 'class' => 'inprogress', + ); + // 5 = ON HOLD + $hesk_settings['statuses'][5] = array( + 'name' => $hesklang['on_hold'], + 'class' => 'onhold', + ); + + // Make sure we have database connection + hesk_load_database_functions(); + hesk_dbConnect(); + + $res = hesk_dbQuery("SELECT `id`, `name`, `color`, `can_customers_change` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_statuses` ORDER BY `id` ASC"); + while ($row = hesk_dbFetchAssoc($res)) + { + // Let's set status name for current language (or the first one we find) + $names = json_decode($row['name'], true); + $row['name'] = (isset($names[$hesk_settings['language']])) ? $names[$hesk_settings['language']] : reset($names); + + // Add to statuses array + $hesk_settings['statuses'][$row['id']] = array( + 'name' => $row['name'], + 'color' => '#'.$row['color'], + 'can_customers_change' => $row['can_customers_change'], + ); + } + + // Try to cache results + if ($use_cache && (is_dir($cache_dir) || ( @mkdir($cache_dir, 0777) && is_writable($cache_dir) ) ) ) + { + // Is there an index.htm file? + if ( ! file_exists($cache_dir.'index.htm')) + { + @file_put_contents($cache_dir.'index.htm', ''); + } + + // Write data + @file_put_contents($cache_file, ' $v) + { + if ($k == $ignore_status) + { + continue; + } + elseif ($k == 3) + { + if ($can_resolve) + { + $last = ''; + } + } + else + { + $options .= ''; + } + } + + return $options . $last; + +} // END hesk_get_status_select() + + +function hesk_get_status_checkboxes($selected = array()) +{ + global $hesk_settings; + + $i = 0; + + echo '
        '; + + $has_row = false; + foreach ($hesk_settings['statuses'] as $k => $v) { + if ($i % 3 === 0) { + echo '
        '; + $has_row = true; + } + + echo ' +
        + + +
        '; + + if ($i % 3 === 2) { + echo '
        '; + $has_row = false; + } + + $i++; + } + if ($has_row) echo '
        '; + echo '
    '; +} // END hesk_get_status_select() + + +function hesk_get_status_name($status) +{ + global $hesk_settings, $hesklang; + return isset($hesk_settings['statuses'][$status]['name']) ? $hesk_settings['statuses'][$status]['name'] : $hesklang['unknown']; +} // END hesk_get_status_name() + + +function hesk_get_admin_ticket_status($status, $append = '') +{ + return hesk_get_ticket_status($status, $append, 0); +} // END hesk_get_admin_ticket_status() + + +function hesk_get_ticket_status($status, $append = '', $check_change = 1) +{ + global $hesk_settings, $hesklang; + + // Is this a valid status? + if ( ! isset($hesk_settings['statuses'][$status]['name'])) + { + return $hesklang['unknown']; + } + + // In the customer side check if this status can be changed + if ($check_change && ! hesk_can_customer_change_status($status)) + { + if (isset($hesk_settings['statuses'][$status]['color'])) + { + return ''.$hesk_settings['statuses'][$status]['name'].''; + } + + return $hesk_settings['statuses'][$status]['name']; + } + + // Is this a default status? Use style class to add color + if (isset($hesk_settings['statuses'][$status]['class'])) + { + return ''.$hesk_settings['statuses'][$status]['name'].'' . $append; + } + + // Does this status have a color code? + if (isset($hesk_settings['statuses'][$status]['color'])) + { + return ''.$hesk_settings['statuses'][$status]['name'].'' . $append; + } + + // Just return the name if nothing matches + return $hesk_settings['statuses'][$status]['name'] . $append; + +} // END hesk_get_ticket_status() + + +function hesk_can_customer_change_status($status) +{ + global $hesk_settings; + return ( ! isset($hesk_settings['statuses'][$status]['can_customers_change']) || $hesk_settings['statuses'][$status]['can_customers_change'] == '1') ? true : false; +} // END hesk_get_ticket_status() diff --git a/hesk/inc/tabs/index.htm b/hesk/inc/tabs/index.htm new file mode 100644 index 0000000..d79f2c9 --- /dev/null +++ b/hesk/inc/tabs/index.htm @@ -0,0 +1,8 @@ + + +403 Forbidden + +

    Forbidden

    +You don't have permission to access this folder.

    +


    + \ No newline at end of file diff --git a/hesk/inc/tabs/tabber-minimized.js b/hesk/inc/tabs/tabber-minimized.js new file mode 100644 index 0000000..e8029f5 --- /dev/null +++ b/hesk/inc/tabs/tabber-minimized.js @@ -0,0 +1,40 @@ +/* Copyright (c) 2006 Patrick Fitzgerald */ + +function tabberObj(argsObj) +{var arg;this.div=null;this.classMain="tabber";this.classMainLive="tabberlive";this.classTab="tabbertab";this.classTabDefault="tabbertabdefault";this.classNav="tabbernav";this.classTabHide="tabbertabhide";this.classNavActive="tabberactive";this.titleElements=['h2','h3','h4','h5','h6'];this.titleElementsStripHTML=true;this.removeTitle=true;this.addLinkId=false;this.linkIdFormat='nav';for(arg in argsObj){this[arg]=argsObj[arg];} +this.REclassMain=new RegExp('\\b'+this.classMain+'\\b','gi');this.REclassMainLive=new RegExp('\\b'+this.classMainLive+'\\b','gi');this.REclassTab=new RegExp('\\b'+this.classTab+'\\b','gi');this.REclassTabDefault=new RegExp('\\b'+this.classTabDefault+'\\b','gi');this.REclassTabHide=new RegExp('\\b'+this.classTabHide+'\\b','gi');this.tabs=new Array();if(this.div){this.init(this.div);this.div=null;}} +tabberObj.prototype.init=function(e) +{var +childNodes,i,i2,t,defaultTab=0,DOM_ul,DOM_li,DOM_a,aId,headingElement;if(!document.getElementsByTagName){return false;} +if(e.id){this.id=e.id;} +this.tabs.length=0;childNodes=e.childNodes;for(i=0;i/gi," ");t.headingText=t.headingText.replace(/<[^>]+>/g,"");} +break;}}} +if(!t.headingText){t.headingText=i+1;} +DOM_li=document.createElement("li");t.li=DOM_li;DOM_a=document.createElement("a");DOM_a.appendChild(document.createTextNode(t.headingText));DOM_a.href="javascript:void(null);";DOM_a.title=t.headingText;DOM_a.name=t.headingText;DOM_a.onclick=this.navClick;DOM_a.tabber=this;DOM_a.tabberIndex=i;if(this.addLinkId&&this.linkIdFormat){aId=this.linkIdFormat;aId=aId.replace(//gi,this.id);aId=aId.replace(//gi,i);aId=aId.replace(//gi,i+1);aId=aId.replace(//gi,t.headingText.replace(/[^a-zA-Z0-9\-]/gi,''));DOM_a.id=aId;} +DOM_li.appendChild(DOM_a);DOM_ul.appendChild(DOM_li);} +e.insertBefore(DOM_ul,e.firstChild);e.className=e.className.replace(this.REclassMain,this.classMainLive);this.tabShow(defaultTab);if(typeof this.onLoad=='function'){this.onLoad({tabber:this});} +return this;};tabberObj.prototype.navClick=function(event) +{var +rVal,a,self,tabberIndex,onClickArgs;a=this;if(!a.tabber){return false;} +self=a.tabber;tabberIndex=a.tabberIndex;a.blur();if(typeof self.onClick=='function'){onClickArgs={'tabber':self,'index':tabberIndex,'event':event};if(!event){onClickArgs.event=window.event;} +rVal=self.onClick(onClickArgs);if(rVal===false){return false;}} +self.tabShow(tabberIndex);return false;};tabberObj.prototype.tabHideAll=function() +{var i;for(i=0;i 0) +{ + + /* This query string will be used to browse pages */ + if ($href == 'show_tickets.php') + { + #$query = 'status='.$status; + + $query = ''; + $query .= 's' . implode('=1&s',array_keys($status)) . '=1'; + $query .= '&p' . implode('=1&p',array_keys($priority)) . '=1'; + + $query .= '&category='.$category; + $query .= '&sort='.$sort; + $query .= '&asc='.$asc; + $query .= '&limit='.$maxresults; + $query .= '&archive='.$archive[1]; + $query .= '&s_my='.$s_my[1]; + $query .= '&s_ot='.$s_ot[1]; + $query .= '&s_un='.$s_un[1]; + + $query .= '&cot='.$cot; + $query .= '&g='.$group; + + $query .= '&page='; + } + else + { + $query = 'q='.$q; + $query .= '&what='.$what; + $query .= '&category='.$category; + $query .= '&owner='.$owner_input; + $query .= '&dt='.urlencode($date_input); + $query .= '&sort='.$sort; + $query .= '&asc='.$asc; + $query .= '&limit='.$maxresults; + $query .= '&archive='.$archive[2]; + $query .= '&s_my='.$s_my[2]; + $query .= '&s_ot='.$s_ot[2]; + $query .= '&s_un='.$s_un[2]; + $query .= '&page='; + } + $query_for_pagination = $query; + + $pages = ceil($total/$maxresults) or $pages = 1; + if ($page > $pages) + { + $page = $pages; + } + $limit_down = ($page * $maxresults) - $maxresults; + + $prev_page = ($page - 1 <= 0) ? 0 : $page - 1; + $next_page = ($page + 1 > $pages) ? 0 : $page + 1; + + /* We have the full SQL query now, get tickets */ + $sql .= " LIMIT ".hesk_dbEscape($limit_down)." , ".hesk_dbEscape($maxresults)." "; + $result = hesk_dbQuery($sql); + + /* Uncomment for debugging */ + # echo "SQL: $sql\n
    "; + + /* This query string will be used to order and reverse display */ + if ($href == 'show_tickets.php') + { + #$query = 'status='.$status; + + $query = ''; + $query .= 's' . implode('=1&s',array_keys($status)) . '=1'; + $query .= '&p' . implode('=1&p',array_keys($priority)) . '=1'; + + $query .= '&category='.$category; + #$query .= '&asc='.(isset($is_default) ? 1 : $asc_rev); + $query .= '&limit='.$maxresults; + $query .= '&archive='.$archive[1]; + $query .= '&s_my='.$s_my[1]; + $query .= '&s_ot='.$s_ot[1]; + $query .= '&s_un='.$s_un[1]; + $query .= '&page=1'; + #$query .= '&sort='; + + $query .= '&cot='.$cot; + $query .= '&g='.$group; + + } + else + { + $query = 'q='.$q; + $query .= '&what='.$what; + $query .= '&category='.$category; + $query .= '&owner='.$owner_input; + $query .= '&dt='.urlencode($date_input); + #$query .= '&asc='.$asc; + $query .= '&limit='.$maxresults; + $query .= '&archive='.$archive[2]; + $query .= '&s_my='.$s_my[2]; + $query .= '&s_ot='.$s_ot[2]; + $query .= '&s_un='.$s_un[2]; + $query .= '&page=1'; + #$query .= '&sort='; + } + + $query .= '&asc='; + + /* Print the table with tickets */ + $random=rand(10000,99999); + + $modal_id = hesk_generate_delete_modal($hesklang['confirm'], + $hesklang['confirm_execute'], + "javascript:document.getElementById('delete-tickets-form').submit()", + $hesklang['confirm']); + ?> + +
    + + + + + '; + + $group_tmp = ''; + $is_table = 0; + $space = 0; + + while ($ticket=hesk_dbFetchAssoc($result)) + { + // Are we grouping tickets? + if ($group) + { + require(HESK_PATH . 'inc/print_group.inc.php'); + } + + // Set owner (needed for row title) + $owner = ''; + $first_line = '(' . $hesklang['unas'] . ')'." \n\n"; + if ($ticket['owner'] == $_SESSION['id']) + { + $owner = ' + + '; + $first_line = $hesklang['tasy2'] . " \n\n"; + } + elseif ($ticket['owner']) + { + if (!isset($admins[$ticket['owner']])) + { + $admins[$ticket['owner']] = $hesklang['e_udel']; + } + $owner = ' + + '; + $first_line = $hesklang['taso3'] . ' ' . $admins[$ticket['owner']] . " \n\n"; + } + + // Prepare ticket priority + switch ($ticket['priority']) + { + case 0: + $ticket['priority'] = 'critical'; + break; + case 1: + $ticket['priority'] = 'high'; + break; + case 2: + $ticket['priority'] = 'medium'; + break; + default: + $ticket['priority'] = 'low'; + } + + // Set message (needed for row title) + $ticket['message'] = $first_line . hesk_mb_substr(strip_tags($ticket['message']),0,200).'...'; + + // Start ticket row + echo ' + + +
    + + +
    + + '; + + // Print sequential ID and link it to the ticket page + if ( hesk_show_column('id') ) + { + echo ''.$ticket['id'].''; + } + + // Print tracking ID and link it to the ticket page + if ( hesk_show_column('trackid') ) + { + echo ' + + '; + } + + // Print date submitted + if ( hesk_show_column('dt') ) + { + switch ($hesk_settings['submittedformat']) + { + case 1: + $ticket['dt'] = hesk_formatDate($ticket['dt']); + break; + case 2: + $ticket['dt'] = hesk_time_lastchange($ticket['dt']); + break; + default: + $ticket['dt'] = hesk_time_since( strtotime($ticket['dt']) ); + } + echo ''.$ticket['dt'].''; + } + + // Print last modified + if ( hesk_show_column('lastchange') ) + { + switch ($hesk_settings['updatedformat']) + { + case 1: + $ticket['lastchange'] = hesk_formatDate($ticket['lastchange']); + break; + case 2: + $ticket['lastchange'] = hesk_time_lastchange($ticket['lastchange']); + break; + default: + $ticket['lastchange'] = hesk_time_since( strtotime($ticket['lastchange']) ); + } + echo ''.$ticket['lastchange'].''; + } + + // Print ticket category + if ( hesk_show_column('category') ) + { + $ticket['category'] = isset($hesk_settings['categories'][$ticket['category']]) ? $hesk_settings['categories'][$ticket['category']] : $hesklang['catd']; + echo ''.$ticket['category'].''; + } + + // Print customer name + if ( hesk_show_column('name') ) + { + echo ''.$ticket['name'].''; + } + + // Print customer email + if ( hesk_show_column('email') ) + { + echo ''.$hesklang['clickemail'].''; + } + + // Print subject and link to the ticket page + if ( hesk_show_column('subject') ) + { + echo ''.($ticket['archive'] ? ' + + ' : '').$owner.''.$ticket['subject'].''; + } + + // Print ticket status + if ( hesk_show_column('status') ) + { + echo '' . hesk_get_admin_ticket_status($ticket['status']) . ' '; + } + + // Print ticket owner + if ( hesk_show_column('owner') ) + { + if ($ticket['owner']) + { + $ticket['owner'] = isset($admins[$ticket['owner']]) ? $admins[$ticket['owner']] : $hesklang['unas']; + } + else + { + $ticket['owner'] = $hesklang['unas']; + } + echo ''.$ticket['owner'].''; + } + + // Print number of all replies + if ( hesk_show_column('replies') ) + { + echo ''.$ticket['replies'].''; + } + + // Print number of staff replies + if ( hesk_show_column('staffreplies') ) + { + echo ''.$ticket['staffreplies'].''; + } + + // Print last replier + if ( hesk_show_column('lastreplier') ) + { + if ($ticket['lastreplier']) + { + $ticket['repliername'] = isset($admins[$ticket['replierid']]) ? $admins[$ticket['replierid']] : $hesklang['staff']; + } + else + { + $ticket['repliername'] = $ticket['name']; + } + echo ''.$ticket['repliername'].''; + } + + // Print time worked + if ( hesk_show_column('time_worked') ) + { + echo ''.$ticket['time_worked'].''; + } + + // Print custom fields + foreach ($hesk_settings['custom_fields'] as $key => $value) + { + if ($value['use'] && hesk_show_column($key) ) + { + echo ''.($value['type'] == 'date' ? hesk_custom_date_display_format($ticket[$key], $value['value']['date_format']) : $ticket[$key]).''; + } + } + + // End ticket row + echo ' + + + + + '; + + } // End while + ?> + + + +
    + +

    +
    + +
    +
    + +
    + + + + +
    + +
    + + + +
    + +
    + + + +
    + +
    +
    + +
    + +
    + + + + +
    + + +
    + +
    + + +
    +
    + +
    + 0 +else +{ + if (isset($is_search) || $href == 'find_tickets.php') + { + hesk_show_notice($hesklang['no_tickets_crit']); + } + else + { + echo '

     
     '.$hesklang['no_tickets_open'].'
     

    '; + } +} + + +function hesk_print_list_head() +{ + global $hesk_settings, $href, $query, $sort_possible, $hesklang; + ?> +
    + + + + + + +
    + ' . $hesk_settings['possible_ticket_list'][$field] . ' + +
    +
    + '; + } + ?> + + + + + O: $original (".date('Y-m-d H:i:s',$original).")"; + return "0".$hesklang['abbr']['second']; + } + + $since = $mysql_time - $original; + + // $j saves performing the count function each time around the loop + for ($i = 0, $j = count($chunks); $i < $j; $i++) { + + $seconds = $chunks[$i][0]; + $name = $chunks[$i][1]; + + // finding the biggest chunk (if the chunk fits, break) + if (($count = floor($since / $seconds)) != 0) { + // DEBUG print "\n"; + break; + } + } + + $print = "$count{$name}"; + + if ($i + 1 < $j) { + // now getting the second item + $seconds2 = $chunks[$i + 1][0]; + $name2 = $chunks[$i + 1][1]; + + // add second item if it's greater than 0 + if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) { + $print .= "$count2{$name2}"; + } + } + return $print; +} // END hesk_time_since() + + +function hesk_time_lastchange($original) +{ + global $hesk_settings, $hesklang; + + // Save time format setting so we can restore it later + $copy = $hesk_settings['timeformat']; + + // We need this time format for this function + $hesk_settings['timeformat'] = 'Y-m-d H:i:s'; + + // Get HESK time-adjusted start of today if not already + if ( ! defined('HESK_TIME_TODAY') ) + { + // Adjust for HESK time and define constants for alter use + define('HESK_TIME_TODAY', date('Y-m-d 00:00:00', hesk_date(NULL, false, false, false) ) ); + define('HESK_TIME_YESTERDAY', date('Y-m-d 00:00:00', strtotime(HESK_TIME_TODAY)-86400) ) ; + } + + // Adjust HESK time difference and get day name + $ticket_time = hesk_date($original, true); + + if ($ticket_time >= HESK_TIME_TODAY) + { + // For today show HH:MM + $day = substr($ticket_time, 11, 5); + } + elseif ($ticket_time >= HESK_TIME_YESTERDAY) + { + // For yesterday show word "Yesterday" + $day = $hesklang['r2']; + } + else + { + // For other days show DD MMM YY + list($y, $m, $d) = explode('-', substr($ticket_time, 0, 10) ); + $day = '' . $d . ' ' . $hesklang['ms'.$m] . ' ' . substr($y, 2) . ''; + } + + // Restore original time format setting + $hesk_settings['timeformat'] = $copy; + + // Return value to display + return $day; + +} // END hesk_time_lastchange() diff --git a/hesk/inc/timer/hesk_timer.js b/hesk/inc/timer/hesk_timer.js new file mode 100644 index 0000000..9477c03 --- /dev/null +++ b/hesk/inc/timer/hesk_timer.js @@ -0,0 +1,71 @@ +// 0/1 = start/end +// 2 = state +// 3 = length, ms +// 4 = timer +// 5 = epoch +// 6 = disp el + +var t=[0, 0, 0, 0, 0, 0]; + +function ss() +{ + t[t[2]]=(new Date()).valueOf(); + t[2]=1-t[2]; + + if (0==t[2]) + { + clearInterval(t[4]); + t[3]+=t[1]-t[0]; + t[4]=t[1]=t[0]=0; + disp(); + } + else + { + t[4]=setInterval(disp, 43); + } +} + +function r() +{ + if (t[2]) ss(); + t[4]=t[3]=t[2]=t[1]=t[0]=0; + t[5]=new Date(1970, 1, 1, 0, 0, 0, 0).valueOf(); + t[6].value='00:00:00'; +} + +function force_stop() +{ + t[t[2]]=(new Date()).valueOf(); + t[2]=1-t[2]; + + if (0==t[2]) + { + clearInterval(t[4]); + t[3]+=t[1]-t[0]; + t[4]=t[1]=t[0]=0; + disp(); + } +} + +function timer_running() { + return 0!=t[2]; +} + +function disp() +{ + if (t[2]) t[1]=(new Date()).valueOf(); + t[6].value=format(t[3]+t[1]-t[0]); +} + +function format(ms) +{ + var d=new Date(ms+t[5]).toString().replace(/.*([0-9][0-9]:[0-9][0-9]:[0-9][0-9]).*/, '$1'); + return d; +} + +function load_timer(display_element, h, m, s) +{ + t[5]=new Date(1970, 1, 1, h, m, s, 0).valueOf(); + t[6]=document.getElementById(display_element); + disp(); +} diff --git a/hesk/inc/timer/index.htm b/hesk/inc/timer/index.htm new file mode 100644 index 0000000..d79f2c9 --- /dev/null +++ b/hesk/inc/timer/index.htm @@ -0,0 +1,8 @@ + + +403 Forbidden + +

    Forbidden

    +You don't have permission to access this folder.

    +


    + \ No newline at end of file diff --git a/hesk/inc/tiny_mce/5.2.0/jquery.tinymce.min.js b/hesk/inc/tiny_mce/5.2.0/jquery.tinymce.min.js new file mode 100644 index 0000000..5a6ef56 --- /dev/null +++ b/hesk/inc/tiny_mce/5.2.0/jquery.tinymce.min.js @@ -0,0 +1,91 @@ +/** + * Copyright (c) Tiny Technologies, Inc. All rights reserved. + * Licensed under the LGPL or a commercial license. + * For LGPL see License.txt in the project root for license information. + * For commercial licenses see https://www.tiny.cloud/ + */ +/** + * Jquery integration plugin. + * + * @class tinymce.core.JqueryIntegration + * @private + */ +!function(){var f,c,u,p,d,s=[];d="undefined"!=typeof global?global:window,p=d.jQuery;function v(){ +// Reference to tinymce needs to be lazily evaluated since tinymce +// might be loaded through the compressor or other means +return d.tinymce}p.fn.tinymce=function(o){var e,t,i,l=this,r=""; +// No match then just ignore the call +if(!l.length)return l; +// Get editor instance +if(!o)return v()?v().get(l[0].id):null;l.css("visibility","hidden");function n(){var a=[],c=0; +// Apply patches to the jQuery object, only once +u||(m(),u=!0), +// Create an editor instance for each matched node +l.each(function(e,t){var n,i=t.id,r=o.oninit; +// Generate unique id for target element if needed +i||(t.id=i=v().DOM.uniqueId()), +// Only init the editor once +v().get(i)||( +// Create editor instance and render it +n=v().createEditor(i,o),a.push(n),n.on("init",function(){var e,t=r;l.css("visibility",""), +// Run this if the oninit setting is defined +// this logic will fire the oninit callback ones each +// matched editor instance is initialized +r&&++c==a.length&&("string"==typeof t&&(e=-1===t.indexOf(".")?null:v().resolve(t.replace(/\.\w+$/,"")),t=v().resolve(t)), +// Call the oninit function with the object +t.apply(e||v(),a))}))}), +// Render the editor instances in a separate loop since we +// need to have the full editors array used in the onInit calls +p.each(a,function(e,t){t.render()})} +// Load TinyMCE on demand, if we need to +if(d.tinymce||c||!(e=o.script_url)) +// Delay the init call until tinymce is loaded +1===c?s.push(n):n();else{c=1,t=e.substring(0,e.lastIndexOf("/")), +// Check if it's a dev/src version they want to load then +// make sure that all plugins, themes etc are loaded in source mode as well +-1!=e.indexOf(".min")&&(r=".min"), +// Setup tinyMCEPreInit object this will later be used by the TinyMCE +// core script to locate other resources like CSS files, dialogs etc +// You can also predefined a tinyMCEPreInit object and then it will use that instead +d.tinymce=d.tinyMCEPreInit||{base:t,suffix:r}, +// url contains gzip then we assume it's a compressor +-1!=e.indexOf("gzip")&&(i=o.language||"en",e=e+(/\?/.test(e)?"&":"?")+"js=true&core=true&suffix="+escape(r)+"&themes="+escape(o.theme||"modern")+"&plugins="+escape(o.plugins||"")+"&languages="+(i||""), +// Check if compressor script is already loaded otherwise setup a basic one +d.tinyMCE_GZ||(d.tinyMCE_GZ={start:function(){function n(e){v().ScriptLoader.markDone(v().baseURI.toAbsolute(e))} +// Add core languages +n("langs/"+i+".js"), +// Add themes with languages +n("themes/"+o.theme+"/theme"+r+".js"),n("themes/"+o.theme+"/langs/"+i+".js"), +// Add plugins with languages +p.each(o.plugins.split(","),function(e,t){t&&(n("plugins/"+t+"/plugin"+r+".js"),n("plugins/"+t+"/langs/"+i+".js"))})},end:function(){}}));var a=document.createElement("script");a.type="text/javascript",a.onload=a.onreadystatechange=function(e){e=e||window.event,2===c||"load"!=e.type&&!/complete|loaded/.test(a.readyState)||(v().dom.Event.domLoaded=1,c=2, +// Execute callback after mainscript has been loaded and before the initialization occurs +o.script_loaded&&o.script_loaded(),n(),p.each(s,function(e,t){t()}))},a.src=e,document.body.appendChild(a)}return l}, +// Add :tinymce pseudo selector this will select elements that has been converted into editor instances +// it's now possible to use things like $('*:tinymce') to get all TinyMCE bound elements. +p.extend(p.expr[":"],{tinymce:function(e){var t;return!!(e.id&&"tinymce"in d&&(t=v().get(e.id))&&t.editorManager===v())}}); +// This function patches internal jQuery functions so that if +// you for example remove an div element containing an editor it's +// automatically destroyed by the TinyMCE API +var m=function(){function r(e){ +// If the function is remove +"remove"===e&&this.each(function(e,t){var n=u(t);n&&n.remove()}),this.find("span.mceEditor,div.mceEditor").each(function(e,t){var n=v().get(t.id.replace(/_parent$/,""));n&&n.remove()})}function o(i){var e,t=this; +// Handle set value +/*jshint eqnull:true */if(null!=i)r.call(t), +// Saves the contents before get/set value of textarea/div +t.each(function(e,t){var n;(n=v().get(t.id))&&n.setContent(i)});else if(0])*>/g,""):n.getContent({save:!0}):a.apply(p(t),r)}),i}}), +// Makes it possible to use $('#id').append("content"); to append contents to the TinyMCE editor iframe +p.each(["append","prepend"],function(e,t){var n=s[t]=p.fn[t],r="prepend"===t;p.fn[t]=function(i){var e=this;return l(e)?i!==f?("string"==typeof i&&e.filter(":tinymce").each(function(e,t){var n=u(t);n&&n.setContent(r?i+n.getContent():n.getContent()+i)}),n.apply(e.not(":tinymce"),arguments),e):void 0:n.apply(e,arguments)}}), +// Makes sure that the editor instance gets properly destroyed when the parent element is removed +p.each(["remove","replaceWith","replaceAll","empty"],function(e,t){var n=s[t]=p.fn[t];p.fn[t]=function(){return r.call(this,t),n.apply(this,arguments)}}),s.attr=p.fn.attr, +// Makes sure that $('#tinymce_id').attr('value') gets the editors current HTML contents +p.fn.attr=function(e,t){var n=this,i=arguments;if(!e||"value"!==e||!l(n))return s.attr.apply(n,i);if(t!==f)return o.call(n.filter(":tinymce"),t),s.attr.apply(n.not(":tinymce"),i),n;// return original set for chaining +var r=n[0],a=u(r);return a?a.getContent({save:!0}):s.attr.apply(p(r),i)}}}(); \ No newline at end of file diff --git a/hesk/inc/tiny_mce/5.2.0/langs/readme.md b/hesk/inc/tiny_mce/5.2.0/langs/readme.md new file mode 100644 index 0000000..a52bf03 --- /dev/null +++ b/hesk/inc/tiny_mce/5.2.0/langs/readme.md @@ -0,0 +1,3 @@ +This is where language files should be placed. + +Please DO NOT translate these directly use this service: https://www.transifex.com/projects/p/tinymce/ diff --git a/hesk/inc/tiny_mce/5.2.0/license.txt b/hesk/inc/tiny_mce/5.2.0/license.txt new file mode 100644 index 0000000..b17fc90 --- /dev/null +++ b/hesk/inc/tiny_mce/5.2.0/license.txt @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/hesk/inc/tiny_mce/5.2.0/plugins/advlist/plugin.min.js b/hesk/inc/tiny_mce/5.2.0/plugins/advlist/plugin.min.js new file mode 100644 index 0000000..a07d3e3 --- /dev/null +++ b/hesk/inc/tiny_mce/5.2.0/plugins/advlist/plugin.min.js @@ -0,0 +1,9 @@ +/** + * Copyright (c) Tiny Technologies, Inc. All rights reserved. + * Licensed under the LGPL or a commercial license. + * For LGPL see License.txt in the project root for license information. + * For commercial licenses see https://www.tiny.cloud/ + * + * Version: 5.2.0 (2020-02-13) + */ +!function(){"use strict";function n(){}function o(n){return function(){return n}}function t(){return d}var e,r=tinymce.util.Tools.resolve("tinymce.PluginManager"),u=tinymce.util.Tools.resolve("tinymce.util.Tools"),l=function(n,t,e){var r="UL"===t?"InsertUnorderedList":"InsertOrderedList";n.execCommand(r,!1,!1===e?null:{"list-style-type":e})},i=function(e){e.addCommand("ApplyUnorderedListStyle",function(n,t){l(e,"UL",t["list-style-type"])}),e.addCommand("ApplyOrderedListStyle",function(n,t){l(e,"OL",t["list-style-type"])})},c=function(n){var t=n.getParam("advlist_number_styles","default,lower-alpha,lower-greek,lower-roman,upper-alpha,upper-roman");return t?t.split(/[ ,]/):[]},s=function(n){var t=n.getParam("advlist_bullet_styles","default,circle,square");return t?t.split(/[ ,]/):[]},f=o(!1),a=o(!0),d=(e={fold:function(n,t){return n()},is:f,isSome:f,isNone:a,getOr:m,getOrThunk:p,getOrDie:function(n){throw new Error(n||"error: getOrDie called on none.")},getOrNull:o(null),getOrUndefined:o(undefined),or:m,orThunk:p,map:t,each:n,bind:t,exists:f,forall:a,filter:t,equals:g,equals_:g,toArray:function(){return[]},toString:o("none()")},Object.freeze&&Object.freeze(e),e);function g(n){return n.isNone()}function p(n){return n()}function m(n){return n}function y(n,t,e){var r=function(n,t){for(var e=0;ey(e)&&(i=o+g);var l=z(e);if(l&&l]*>((\xa0| |[ \t]|]*>)+?|)|
    $","i").test(e)}function i(t){var e=parseInt(v.getItem(o(t)+"time"),10)||0;return!((new Date).getTime()-e>function(t){return r(t.settings.autosave_retention,"20m")}(t))||(g(t,!1),!1)}function u(t){var e=o(t);!a(t)&&t.isDirty()&&(v.setItem(e+"draft",t.getContent({format:"raw",no_events:!0})),v.setItem(e+"time",(new Date).getTime().toString()),function(t){t.fire("StoreDraft")}(t))}function s(t){var e=o(t);i(t)&&(t.setContent(v.getItem(e+"draft"),{format:"raw"}),function(t){t.fire("RestoreDraft")}(t))}function c(t,e){var n=function(t){return r(t.settings.autosave_interval,"30s")}(t);e.get()||(m.setInterval(function(){t.removed||u(t)},n),e.set(!0))}function f(t){t.undoManager.transact(function(){s(t),g(t)}),t.focus()}var l=function(t){function e(){return n}var n=t;return{get:e,set:function(t){n=t},clone:function(){return l(e())}}},t=tinymce.util.Tools.resolve("tinymce.PluginManager"),m=tinymce.util.Tools.resolve("tinymce.util.Delay"),v=tinymce.util.Tools.resolve("tinymce.util.LocalStorage"),d=tinymce.util.Tools.resolve("tinymce.util.Tools"),g=function(t,e){var n=o(t);v.removeItem(n+"draft"),v.removeItem(n+"time"),!1!==e&&function(t){t.fire("RemoveDraft")}(t)};function y(r){for(var o=[],t=1;t(.*?)<\/a>/gi,"[url=$1]$2[/url]"),o(/(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]"),o(/(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]"),o(/(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]"),o(/(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]"),o(/(.*?)<\/span>/gi,"[color=$1]$2[/color]"),o(/(.*?)<\/font>/gi,"[color=$1]$2[/color]"),o(/(.*?)<\/span>/gi,"[size=$1]$2[/size]"),o(/(.*?)<\/font>/gi,"$1"),o(//gi,"[img]$1[/img]"),o(/(.*?)<\/span>/gi,"[code]$1[/code]"),o(/(.*?)<\/span>/gi,"[quote]$1[/quote]"),o(/(.*?)<\/strong>/gi,"[code][b]$1[/b][/code]"),o(/(.*?)<\/strong>/gi,"[quote][b]$1[/b][/quote]"),o(/(.*?)<\/em>/gi,"[code][i]$1[/i][/code]"),o(/(.*?)<\/em>/gi,"[quote][i]$1[/i][/quote]"),o(/(.*?)<\/u>/gi,"[code][u]$1[/u][/code]"),o(/(.*?)<\/u>/gi,"[quote][u]$1[/u][/quote]"),o(/<\/(strong|b)>/gi,"[/b]"),o(/<(strong|b)>/gi,"[b]"),o(/<\/(em|i)>/gi,"[/i]"),o(/<(em|i)>/gi,"[i]"),o(/<\/u>/gi,"[/u]"),o(/(.*?)<\/span>/gi,"[u]$1[/u]"),o(//gi,"[u]"),o(/]*>/gi,"[quote]"),o(/<\/blockquote>/gi,"[/quote]"),o(/
    /gi,"\n"),o(//gi,"\n"),o(/
    /gi,"\n"),o(/

    /gi,""),o(/<\/p>/gi,"\n"),o(/ |\u00a0/gi," "),o(/"/gi,'"'),o(/</gi,"<"),o(/>/gi,">"),o(/&/gi,"&"),t},i=function(t){t=e.trim(t);function o(o,e){t=t.replace(o,e)}return o(/\n/gi,"
    "),o(/\[b\]/gi,""),o(/\[\/b\]/gi,""),o(/\[i\]/gi,""),o(/\[\/i\]/gi,""),o(/\[u\]/gi,""),o(/\[\/u\]/gi,""),o(/\[url=([^\]]+)\](.*?)\[\/url\]/gi,'$2'),o(/\[url\](.*?)\[\/url\]/gi,'$1'),o(/\[img\](.*?)\[\/img\]/gi,''),o(/\[color=(.*?)\](.*?)\[\/color\]/gi,'$2'),o(/\[code\](.*?)\[\/code\]/gi,'$1 '),o(/\[quote.*?\](.*?)\[\/quote\]/gi,'$1 '),t};!function n(){o.add("bbcode",function(o){o.on("BeforeSetContent",function(o){o.content=i(o.content)}),o.on("PostProcess",function(o){o.set&&(o.content=i(o.content)),o.get&&(o.content=t(o.content))})})}()}(); \ No newline at end of file diff --git a/hesk/inc/tiny_mce/5.2.0/plugins/charmap/plugin.min.js b/hesk/inc/tiny_mce/5.2.0/plugins/charmap/plugin.min.js new file mode 100644 index 0000000..a19df5b --- /dev/null +++ b/hesk/inc/tiny_mce/5.2.0/plugins/charmap/plugin.min.js @@ -0,0 +1,9 @@ +/** + * Copyright (c) Tiny Technologies, Inc. All rights reserved. + * Licensed under the LGPL or a commercial license. + * For LGPL see License.txt in the project root for license information. + * For commercial licenses see https://www.tiny.cloud/ + * + * Version: 5.2.0 (2020-02-13) + */ +!function(c){"use strict";function n(){}function i(n){return function(){return n}}function e(){return m}var r,t=tinymce.util.Tools.resolve("tinymce.PluginManager"),a=function(n,e){return n.fire("insertCustomChar",{chr:e})},u=function(n,e){var r=a(n,e).chr;n.execCommand("mceInsertContent",!1,r)},o=tinymce.util.Tools.resolve("tinymce.util.Tools"),s=function(n){return n.settings.charmap},l=function(n){return n.settings.charmap_append},f=i(!1),g=i(!0),m=(r={fold:function(n,e){return n()},is:f,isSome:f,isNone:g,getOr:p,getOrThunk:d,getOrDie:function(n){throw new Error(n||"error: getOrDie called on none.")},getOrNull:i(null),getOrUndefined:i(undefined),or:p,orThunk:d,map:e,each:n,bind:e,exists:f,forall:g,filter:e,equals:h,equals_:h,toArray:function(){return[]},toString:i("none()")},Object.freeze&&Object.freeze(r),r);function h(n){return n.isNone()}function d(n){return n()}function p(n){return n}function y(e){return function(n){return function(n){if(null===n)return"null";var e=typeof n;return"object"==e&&(Array.prototype.isPrototypeOf(n)||n.constructor&&"Array"===n.constructor.name)?"array":"object"==e&&(String.prototype.isPrototypeOf(n)||n.constructor&&"String"===n.constructor.name)?"string":e}(n)===e}}function w(n,e){for(var r=n.length,t=new Array(r),a=0;a>=?|<<=?|->|([-+&|:])\1|[?:~]|[-+*/%&|^!=<>]=?/,number:/(?:\b0x(?:[\da-f]+\.?[\da-f]*|\.[\da-f]+)(?:p[+-]?\d+)?|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?)[ful]*/i}),Prism.languages.insertBefore("c","string",{macro:{pattern:/(^\s*)#\s*[a-z]+(?:[^\r\n\\]|\\(?:\r\n|[\s\S]))*/im,lookbehind:!0,alias:"property",inside:{string:{pattern:/(#\s*include\s*)(?:<.+?>|("|')(?:\\?.)+?\2)/,lookbehind:!0},directive:{pattern:/(#\s*)\b(?:define|defined|elif|else|endif|error|ifdef|ifndef|if|import|include|line|pragma|undef|using)\b/,lookbehind:!0,alias:"keyword"}}},constant:/\b(?:__FILE__|__LINE__|__DATE__|__TIME__|__TIMESTAMP__|__func__|EOF|NULL|SEEK_CUR|SEEK_END|SEEK_SET|stdin|stdout|stderr)\b/}),delete Prism.languages.c["boolean"]},{}],2:[function(e,n,t){Prism.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|interface|extends|implements|trait|instanceof|new)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,"boolean":/\b(?:true|false)\b/,"function":/\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/}},{}],3:[function(e,t,n){(function(e){var n=function(u){var c=/\blang(?:uage)?-([\w-]+)\b/i,n=0,E={manual:u.Prism&&u.Prism.manual,disableWorkerMessageHandler:u.Prism&&u.Prism.disableWorkerMessageHandler,util:{encode:function(e){return e instanceof O?new O(e.type,E.util.encode(e.content),e.alias):Array.isArray(e)?e.map(E.util.encode):e.replace(/&/g,"&").replace(/e.length)return;if(!(w instanceof O)){if(g&&b!=n.length-1){if(c.lastIndex=y,!(F=c.exec(e)))break;for(var v=F.index+(d&&F[1]?F[1].length:0),k=F.index+F[0].length,x=b,_=y,A=n.length;x"+t.content+""},!u.document)return u.addEventListener&&(E.disableWorkerMessageHandler||u.addEventListener("message",function(e){var n=JSON.parse(e.data),t=n.language,r=n.code,a=n.immediateClose;u.postMessage(E.highlight(r,E.languages[t],t)),a&&u.close()},!1)),E;var e=E.util.currentScript();if(e&&(E.filename=e.src,e.hasAttribute("data-manual")&&(E.manual=!0)),!E.manual){var t=function(){E.manual||E.highlightAll()},r=document.readyState;"loading"===r||"interactive"===r&&e&&e.defer?document.addEventListener("DOMContentLoaded",t):window.requestAnimationFrame?window.requestAnimationFrame(t):window.setTimeout(t,16)}return E}("undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{});void 0!==t&&t.exports&&(t.exports=n),void 0!==e&&(e.Prism=n)}).call(this,void 0!==w?w:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],4:[function(e,n,t){Prism.languages.cpp=Prism.languages.extend("c",{"class-name":{pattern:/(\b(?:class|enum|struct)\s+)\w+/,lookbehind:!0},keyword:/\b(?:alignas|alignof|asm|auto|bool|break|case|catch|char|char16_t|char32_t|class|compl|const|constexpr|const_cast|continue|decltype|default|delete|do|double|dynamic_cast|else|enum|explicit|export|extern|float|for|friend|goto|if|inline|int|int8_t|int16_t|int32_t|int64_t|uint8_t|uint16_t|uint32_t|uint64_t|long|mutable|namespace|new|noexcept|nullptr|operator|private|protected|public|register|reinterpret_cast|return|short|signed|sizeof|static|static_assert|static_cast|struct|switch|template|this|thread_local|throw|try|typedef|typeid|typename|union|unsigned|using|virtual|void|volatile|wchar_t|while)\b/,number:{pattern:/(?:\b0b[01']+|\b0x(?:[\da-f']+\.?[\da-f']*|\.[\da-f']+)(?:p[+-]?[\d']+)?|(?:\b[\d']+\.?[\d']*|\B\.[\d']+)(?:e[+-]?[\d']+)?)[ful]*/i,greedy:!0},operator:/>>=?|<<=?|->|([-+&|:])\1|[?:~]|[-+*/%&|^!=<>]=?|\b(?:and|and_eq|bitand|bitor|not|not_eq|or|or_eq|xor|xor_eq)\b/,"boolean":/\b(?:true|false)\b/}),Prism.languages.insertBefore("cpp","string",{"raw-string":{pattern:/R"([^()\\ ]{0,16})\([\s\S]*?\)\1"/,alias:"string",greedy:!0}})},{}],5:[function(e,n,t){Prism.languages.csharp=Prism.languages.extend("clike",{keyword:/\b(?:abstract|add|alias|as|ascending|async|await|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|descending|do|double|dynamic|else|enum|event|explicit|extern|false|finally|fixed|float|for|foreach|from|get|global|goto|group|if|implicit|in|int|interface|internal|into|is|join|let|lock|long|namespace|new|null|object|operator|orderby|out|override|params|partial|private|protected|public|readonly|ref|remove|return|sbyte|sealed|select|set|short|sizeof|stackalloc|static|string|struct|switch|this|throw|true|try|typeof|uint|ulong|unchecked|unsafe|ushort|using|value|var|virtual|void|volatile|where|while|yield)\b/,string:[{pattern:/@("|')(?:\1\1|\\[\s\S]|(?!\1)[^\\])*\1/,greedy:!0},{pattern:/("|')(?:\\.|(?!\1)[^\\\r\n])*?\1/,greedy:!0}],"class-name":[{pattern:/\b[A-Z]\w*(?:\.\w+)*\b(?=\s+\w+)/,inside:{punctuation:/\./}},{pattern:/(\[)[A-Z]\w*(?:\.\w+)*\b/,lookbehind:!0,inside:{punctuation:/\./}},{pattern:/(\b(?:class|interface)\s+[A-Z]\w*(?:\.\w+)*\s*:\s*)[A-Z]\w*(?:\.\w+)*\b/,lookbehind:!0,inside:{punctuation:/\./}},{pattern:/((?:\b(?:class|interface|new)\s+)|(?:catch\s+\())[A-Z]\w*(?:\.\w+)*\b/,lookbehind:!0,inside:{punctuation:/\./}}],number:/\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)f?/i,operator:/>>=?|<<=?|[-=]>|([-+&|?])\1|~|[-+*/%&|^!=<>]=?/,punctuation:/\?\.?|::|[{}[\];(),.:]/}),Prism.languages.insertBefore("csharp","class-name",{"generic-method":{pattern:/\w+\s*<[^>\r\n]+?>\s*(?=\()/,inside:{"function":/^\w+/,"class-name":{pattern:/\b[A-Z]\w*(?:\.\w+)*\b/,inside:{punctuation:/\./}},keyword:Prism.languages.csharp.keyword,punctuation:/[<>(),.:]/}},preprocessor:{pattern:/(^\s*)#.*/m,lookbehind:!0,alias:"property",inside:{directive:{pattern:/(\s*#)\b(?:define|elif|else|endif|endregion|error|if|line|pragma|region|undef|warning)\b/,lookbehind:!0,alias:"keyword"}}}}),Prism.languages.dotnet=Prism.languages.cs=Prism.languages.csharp},{}],6:[function(e,n,t){!function(e){var n=/("|')(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/;e.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:/@[\w-]+[\s\S]*?(?:;|(?=\s*\{))/,inside:{rule:/@[\w-]+/}},url:{pattern:RegExp("url\\((?:"+n.source+"|[^\n\r()]*)\\)","i"),inside:{"function":/^url/i,punctuation:/^\(|\)$/}},selector:RegExp("[^{}\\s](?:[^{};\"']|"+n.source+")*?(?=\\s*\\{)"),string:{pattern:n,greedy:!0},property:/[-_a-z\xA0-\uFFFF][-\w\xA0-\uFFFF]*(?=\s*:)/i,important:/!important\b/i,"function":/[-a-z0-9]+(?=\()/i,punctuation:/[(){};:,]/},e.languages.css.atrule.inside.rest=e.languages.css;var t=e.languages.markup;t&&(t.tag.addInlined("style","css"),e.languages.insertBefore("inside","attr-value",{"style-attr":{pattern:/\s*style=("|')(?:\\[\s\S]|(?!\1)[^\\])*\1/i,inside:{"attr-name":{pattern:/^\s*style/i,inside:t.tag.inside},punctuation:/^\s*=\s*['"]|['"]\s*$/,"attr-value":{pattern:/.+/i,inside:e.languages.css}},alias:"language-css"}},t.tag))}(Prism)},{}],7:[function(e,n,t){var r,a,i;r=Prism,a=/\b(?:abstract|assert|boolean|break|byte|case|catch|char|class|const|continue|default|do|double|else|enum|exports|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|module|native|new|null|open|opens|package|private|protected|provides|public|requires|return|short|static|strictfp|super|switch|synchronized|this|throw|throws|to|transient|transitive|try|uses|var|void|volatile|while|with|yield)\b/,i=/\b[A-Z](?:\w*[a-z]\w*)?\b/,r.languages.java=r.languages.extend("clike",{"class-name":[i,/\b[A-Z]\w*(?=\s+\w+\s*[;,=())])/],keyword:a,"function":[r.languages.clike["function"],{pattern:/(\:\:)[a-z_]\w*/,lookbehind:!0}],number:/\b0b[01][01_]*L?\b|\b0x[\da-f_]*\.?[\da-f_p+-]+\b|(?:\b\d[\d_]*\.?[\d_]*|\B\.\d[\d_]*)(?:e[+-]?\d[\d_]*)?[dfl]?/i,operator:{pattern:/(^|[^.])(?:<<=?|>>>?=?|->|--|\+\+|&&|\|\||::|[?:~]|[-+*/%&|^!=<>]=?)/m,lookbehind:!0}}),r.languages.insertBefore("java","string",{"triple-quoted-string":{pattern:/"""[ \t]*[\r\n](?:(?:"|"")?(?:\\.|[^"\\]))*"""/,greedy:!0,alias:"string"}}),r.languages.insertBefore("java","class-name",{annotation:{alias:"punctuation",pattern:/(^|[^.])@\w+/,lookbehind:!0},namespace:{pattern:/(\b(?:exports|import(?:\s+static)?|module|open|opens|package|provides|requires|to|transitive|uses|with)\s+)[a-z]\w*(?:\.[a-z]\w*)+/,lookbehind:!0,inside:{punctuation:/\./}},generics:{pattern:/<(?:[\w\s,.&?]|<(?:[\w\s,.&?]|<(?:[\w\s,.&?]|<[\w\s,.&?]*>)*>)*>)*>/,inside:{"class-name":i,keyword:a,punctuation:/[<>(),.:]/,operator:/[?&|]/}}})},{}],8:[function(e,n,t){Prism.languages.javascript=Prism.languages.extend("clike",{"class-name":[Prism.languages.clike["class-name"],{pattern:/(^|[^$\w\xA0-\uFFFF])[_$A-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\.(?:prototype|constructor))/,lookbehind:!0}],keyword:[{pattern:/((?:^|})\s*)(?:catch|finally)\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],number:/\b(?:(?:0[xX](?:[\dA-Fa-f](?:_[\dA-Fa-f])?)+|0[bB](?:[01](?:_[01])?)+|0[oO](?:[0-7](?:_[0-7])?)+)n?|(?:\d(?:_\d)?)+n|NaN|Infinity)\b|(?:\b(?:\d(?:_\d)?)+\.?(?:\d(?:_\d)?)*|\B\.(?:\d(?:_\d)?)+)(?:[Ee][+-]?(?:\d(?:_\d)?)+)?/,"function":/#?[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,operator:/--|\+\+|\*\*=?|=>|&&|\|\||[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?[.?]?|[~:]/}),Prism.languages.javascript["class-name"][0].pattern=/(\b(?:class|interface|extends|implements|instanceof|new)\s+)[\w.\\]+/,Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:/((?:^|[^$\w\xA0-\uFFFF."'\])\s])\s*)\/(?:\[(?:[^\]\\\r\n]|\\.)*]|\\.|[^/\\\[\r\n])+\/[gimyus]{0,6}(?=(?:\s|\/\*[\s\S]*?\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/,lookbehind:!0,greedy:!0},"function-variable":{pattern:/#?[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)\s*=>))/,alias:"function"},parameter:[{pattern:/(function(?:\s+[_$A-Za-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)?\s*\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\))/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*=>)/i,inside:Prism.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\)\s*=>)/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:[_$A-Za-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*\s*)\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\)\s*\{)/,lookbehind:!0,inside:Prism.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/}),Prism.languages.insertBefore("javascript","string",{"template-string":{pattern:/`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})+}|(?!\${)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})+}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\${|}$/,alias:"punctuation"},rest:Prism.languages.javascript}},string:/[\s\S]+/}}}),Prism.languages.markup&&Prism.languages.markup.tag.addInlined("script","javascript"),Prism.languages.js=Prism.languages.javascript},{}],9:[function(e,n,t){function b(e,n){return"___"+e.toUpperCase()+n+"___"}var y;y=Prism,Object.defineProperties(y.languages["markup-templating"]={},{buildPlaceholders:{value:function(r,a,e,i){if(r.language===a){var s=r.tokenStack=[];r.code=r.code.replace(e,function(e){if("function"==typeof i&&!i(e))return e;for(var n,t=s.length;-1!==r.code.indexOf(n=b(a,t));)++t;return s[t]=e,n}),r.grammar=y.languages.markup}}},tokenizePlaceholders:{value:function(d,g){if(d.language===g&&d.tokenStack){d.grammar=y.languages[g];var m=0,f=Object.keys(d.tokenStack);!function h(e){for(var n=0;n=f.length);n++){var t=e[n];if("string"==typeof t||t.content&&"string"==typeof t.content){var r=f[m],a=d.tokenStack[r],i="string"==typeof t?t:t.content,s=b(g,r),o=i.indexOf(s);if(-1/,prolog:/<\?[\s\S]+?\?>/,doctype:{pattern:/"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:(?!)*\]\s*)?>/i,greedy:!0},cdata://i,tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/i,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/i,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/i,inside:{punctuation:[/^=/,{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:/&#?[\da-z]{1,8};/i},Prism.languages.markup.tag.inside["attr-value"].inside.entity=Prism.languages.markup.entity,Prism.hooks.add("wrap",function(e){"entity"===e.type&&(e.attributes.title=e.content.replace(/&/,"&"))}),Object.defineProperty(Prism.languages.markup.tag,"addInlined",{value:function(e,n){var t={};t["language-"+n]={pattern:/(^$)/i,lookbehind:!0,inside:Prism.languages[n]},t.cdata=/^$/i;var r={"included-cdata":{pattern://i,inside:t}};r["language-"+n]={pattern:/[\s\S]+/,inside:Prism.languages[n]};var a={};a[e]={pattern:RegExp(/(<__[\s\S]*?>)(?:\s*|[\s\S])*?(?=<\/__>)/.source.replace(/__/g,e),"i"),lookbehind:!0,greedy:!0,inside:r},Prism.languages.insertBefore("markup","cdata",a)}}),Prism.languages.xml=Prism.languages.extend("markup",{}),Prism.languages.html=Prism.languages.markup,Prism.languages.mathml=Prism.languages.markup,Prism.languages.svg=Prism.languages.markup},{}],11:[function(e,n,t){!function(n){n.languages.php=n.languages.extend("clike",{keyword:/\b(?:__halt_compiler|abstract|and|array|as|break|callable|case|catch|class|clone|const|continue|declare|default|die|do|echo|else|elseif|empty|enddeclare|endfor|endforeach|endif|endswitch|endwhile|eval|exit|extends|final|finally|for|foreach|function|global|goto|if|implements|include|include_once|instanceof|insteadof|interface|isset|list|namespace|new|or|parent|print|private|protected|public|require|require_once|return|static|switch|throw|trait|try|unset|use|var|while|xor|yield)\b/i,"boolean":{pattern:/\b(?:false|true)\b/i,alias:"constant"},constant:[/\b[A-Z_][A-Z0-9_]*\b/,/\b(?:null)\b/i],comment:{pattern:/(^|[^\\])(?:\/\*[\s\S]*?\*\/|\/\/.*)/,lookbehind:!0}}),n.languages.insertBefore("php","string",{"shell-comment":{pattern:/(^|[^\\])#.*/,lookbehind:!0,alias:"comment"}}),n.languages.insertBefore("php","comment",{delimiter:{pattern:/\?>$|^<\?(?:php(?=\s)|=)?/i,alias:"important"}}),n.languages.insertBefore("php","keyword",{variable:/\$+(?:\w+\b|(?={))/i,"package":{pattern:/(\\|namespace\s+|use\s+)[\w\\]+/,lookbehind:!0,inside:{punctuation:/\\/}}}),n.languages.insertBefore("php","operator",{property:{pattern:/(->)[\w]+/,lookbehind:!0}});var e={pattern:/{\$(?:{(?:{[^{}]+}|[^{}]+)}|[^{}])+}|(^|[^\\{])\$+(?:\w+(?:\[.+?]|->\w+)*)/,lookbehind:!0,inside:n.languages.php};n.languages.insertBefore("php","string",{"nowdoc-string":{pattern:/<<<'([^']+)'(?:\r\n?|\n)(?:.*(?:\r\n?|\n))*?\1;/,greedy:!0,alias:"string",inside:{delimiter:{pattern:/^<<<'[^']+'|[a-z_]\w*;$/i,alias:"symbol",inside:{punctuation:/^<<<'?|[';]$/}}}},"heredoc-string":{pattern:/<<<(?:"([^"]+)"(?:\r\n?|\n)(?:.*(?:\r\n?|\n))*?\1;|([a-z_]\w*)(?:\r\n?|\n)(?:.*(?:\r\n?|\n))*?\2;)/i,greedy:!0,alias:"string",inside:{delimiter:{pattern:/^<<<(?:"[^"]+"|[a-z_]\w*)|[a-z_]\w*;$/i,alias:"symbol",inside:{punctuation:/^<<<"?|[";]$/}},interpolation:e}},"single-quoted-string":{pattern:/'(?:\\[\s\S]|[^\\'])*'/,greedy:!0,alias:"string"},"double-quoted-string":{pattern:/"(?:\\[\s\S]|[^\\"])*"/,greedy:!0,alias:"string",inside:{interpolation:e}}}),delete n.languages.php.string,n.hooks.add("before-tokenize",function(e){if(/<\?/.test(e.code)){n.languages["markup-templating"].buildPlaceholders(e,"php",/<\?(?:[^"'/#]|\/(?![*/])|("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|(?:\/\/|#)(?:[^?\n\r]|\?(?!>))*(?=$|\?>|[\r\n])|\/\*[\s\S]*?(?:\*\/|$))*?(?:\?>|$)/gi)}}),n.hooks.add("after-tokenize",function(e){n.languages["markup-templating"].tokenizePlaceholders(e,"php")})}(Prism)},{}],12:[function(e,n,t){Prism.languages.python={comment:{pattern:/(^|[^\\])#.*/,lookbehind:!0},"string-interpolation":{pattern:/(?:f|rf|fr)(?:("""|''')[\s\S]+?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,greedy:!0,inside:{interpolation:{pattern:/((?:^|[^{])(?:{{)*){(?!{)(?:[^{}]|{(?!{)(?:[^{}]|{(?!{)(?:[^{}])+})+})+}/,lookbehind:!0,inside:{"format-spec":{pattern:/(:)[^:(){}]+(?=}$)/,lookbehind:!0},"conversion-option":{pattern:/![sra](?=[:}]$)/,alias:"punctuation"},rest:null}},string:/[\s\S]+/}},"triple-quoted-string":{pattern:/(?:[rub]|rb|br)?("""|''')[\s\S]+?\1/i,greedy:!0,alias:"string"},string:{pattern:/(?:[rub]|rb|br)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,greedy:!0},"function":{pattern:/((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,lookbehind:!0},"class-name":{pattern:/(\bclass\s+)\w+/i,lookbehind:!0},decorator:{pattern:/(^\s*)@\w+(?:\.\w+)*/im,lookbehind:!0,alias:["annotation","punctuation"],inside:{punctuation:/\./}},keyword:/\b(?:and|as|assert|async|await|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,builtin:/\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,"boolean":/\b(?:True|False|None)\b/,number:/(?:\b(?=\d)|\B(?=\.))(?:0[bo])?(?:(?:\d|0x[\da-f])[\da-f]*\.?\d*|\.\d+)(?:e[+-]?\d+)?j?\b/i,operator:/[-+%=]=?|!=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,punctuation:/[{}[\];(),.:]/},Prism.languages.python["string-interpolation"].inside.interpolation.inside.rest=Prism.languages.python,Prism.languages.py=Prism.languages.python},{}],13:[function(e,n,t){!function(e){e.languages.ruby=e.languages.extend("clike",{comment:[/#.*/,{pattern:/^=begin\s[\s\S]*?^=end/m,greedy:!0}],"class-name":{pattern:/(\b(?:class)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:alias|and|BEGIN|begin|break|case|class|def|define_method|defined|do|each|else|elsif|END|end|ensure|extend|for|if|in|include|module|new|next|nil|not|or|prepend|protected|private|public|raise|redo|require|rescue|retry|return|self|super|then|throw|undef|unless|until|when|while|yield)\b/});var n={pattern:/#\{[^}]+\}/,inside:{delimiter:{pattern:/^#\{|\}$/,alias:"tag"},rest:e.languages.ruby}};delete e.languages.ruby["function"],e.languages.insertBefore("ruby","keyword",{regex:[{pattern:/%r([^a-zA-Z0-9\s{(\[<])(?:(?!\1)[^\\]|\\[\s\S])*\1[gim]{0,3}/,greedy:!0,inside:{interpolation:n}},{pattern:/%r\((?:[^()\\]|\\[\s\S])*\)[gim]{0,3}/,greedy:!0,inside:{interpolation:n}},{pattern:/%r\{(?:[^#{}\\]|#(?:\{[^}]+\})?|\\[\s\S])*\}[gim]{0,3}/,greedy:!0,inside:{interpolation:n}},{pattern:/%r\[(?:[^\[\]\\]|\\[\s\S])*\][gim]{0,3}/,greedy:!0,inside:{interpolation:n}},{pattern:/%r<(?:[^<>\\]|\\[\s\S])*>[gim]{0,3}/,greedy:!0,inside:{interpolation:n}},{pattern:/(^|[^/])\/(?!\/)(?:\[.+?]|\\.|[^/\\\r\n])+\/[gim]{0,3}(?=\s*(?:$|[\r\n,.;})]))/,lookbehind:!0,greedy:!0}],variable:/[@$]+[a-zA-Z_]\w*(?:[?!]|\b)/,symbol:{pattern:/(^|[^:]):[a-zA-Z_]\w*(?:[?!]|\b)/,lookbehind:!0},"method-definition":{pattern:/(\bdef\s+)[\w.]+/,lookbehind:!0,inside:{"function":/\w+$/,rest:e.languages.ruby}}}),e.languages.insertBefore("ruby","number",{builtin:/\b(?:Array|Bignum|Binding|Class|Continuation|Dir|Exception|FalseClass|File|Stat|Fixnum|Float|Hash|Integer|IO|MatchData|Method|Module|NilClass|Numeric|Object|Proc|Range|Regexp|String|Struct|TMS|Symbol|ThreadGroup|Thread|Time|TrueClass)\b/,constant:/\b[A-Z]\w*(?:[?!]|\b)/}),e.languages.ruby.string=[{pattern:/%[qQiIwWxs]?([^a-zA-Z0-9\s{(\[<])(?:(?!\1)[^\\]|\\[\s\S])*\1/,greedy:!0,inside:{interpolation:n}},{pattern:/%[qQiIwWxs]?\((?:[^()\\]|\\[\s\S])*\)/,greedy:!0,inside:{interpolation:n}},{pattern:/%[qQiIwWxs]?\{(?:[^#{}\\]|#(?:\{[^}]+\})?|\\[\s\S])*\}/,greedy:!0,inside:{interpolation:n}},{pattern:/%[qQiIwWxs]?\[(?:[^\[\]\\]|\\[\s\S])*\]/,greedy:!0,inside:{interpolation:n}},{pattern:/%[qQiIwWxs]?<(?:[^<>\\]|\\[\s\S])*>/,greedy:!0,inside:{interpolation:n}},{pattern:/("|')(?:#\{[^}]+\}|\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0,inside:{interpolation:n}}],e.languages.rb=e.languages.ruby}(Prism)},{}],14:[function(e,n,t){var r=e("prismjs/components/prism-core");e("prismjs/components/prism-clike"),e("prismjs/components/prism-markup-templating"),e("prismjs/components/prism-c"),e("prismjs/components/prism-cpp"),e("prismjs/components/prism-csharp"),e("prismjs/components/prism-css"),e("prismjs/components/prism-java"),e("prismjs/components/prism-javascript"),e("prismjs/components/prism-markup"),e("prismjs/components/prism-php"),e("prismjs/components/prism-python"),e("prismjs/components/prism-ruby"),n.exports={boltExport:r}},{"prismjs/components/prism-c":1,"prismjs/components/prism-clike":2,"prismjs/components/prism-core":3,"prismjs/components/prism-cpp":4,"prismjs/components/prism-csharp":5,"prismjs/components/prism-css":6,"prismjs/components/prism-java":7,"prismjs/components/prism-javascript":8,"prismjs/components/prism-markup":10,"prismjs/components/prism-markup-templating":9,"prismjs/components/prism-php":11,"prismjs/components/prism-python":12,"prismjs/components/prism-ruby":13}]},{},[14])(14)});var a=window.Prism;window.Prism=e}(undefined,b,y,undefined);function v(e){var n=e.selection?e.selection.getNode():null;return f.isCodeSample(n)?g.some(n):g.none()}var k,x=y.exports.boltExport,_=function(e){return e.getParam("codesample_languages")},A=function(e){return e.getParam("codesample_global_prismjs",!1,"boolean")},F=function(e){return h.Prism&&A(e)?h.Prism:x},P=v,S=function(n,t,r){n.undoManager.transact(function(){var e=v(n);return r=m.DOM.encode(r),e.fold(function(){n.insertContent('

    '+r+"
    "),n.selection.select(n.$("#__new").removeAttr("id")[0])},function(e){n.dom.setAttrib(e,"class","language-"+t),e.innerHTML=r,F(n).highlightElement(e),n.selection.select(e)})})},j=function(e){return v(e).fold(function(){return""},function(e){return e.textContent})},$=function(e){var n=_(e);return n||[{text:"HTML/XML",value:"markup"},{text:"JavaScript",value:"javascript"},{text:"CSS",value:"css"},{text:"PHP",value:"php"},{text:"Ruby",value:"ruby"},{text:"Python",value:"python"},{text:"Java",value:"java"},{text:"C",value:"c"},{text:"C#",value:"csharp"},{text:"C++",value:"cpp"}]},C=function(e,t){return P(e).fold(function(){return t},function(e){var n=e.className.match(/language-(\w+)/);return n?n[1]:t})},E=(k="function",function(e){return function(e){if(null===e)return"null";var n=typeof e;return"object"==n&&(Array.prototype.isPrototypeOf(e)||e.constructor&&"Array"===e.constructor.name)?"array":"object"==n&&(String.prototype.isPrototypeOf(e)||e.constructor&&"String"===e.constructor.name)?"string":n}(e)===k}),O=Array.prototype.slice,z=(E(Array.from)&&Array.from,function(t){var e=$(t),n=function(e){return 0===e.length?g.none():g.some(e[0])}(e).fold(function(){return""},function(e){return e.value}),r=C(t,n),a=j(t);t.windowManager.open({title:"Insert/Edit Code Sample",size:"large",body:{type:"panel",items:[{type:"selectbox",name:"language",label:"Language",items:e},{type:"textarea",name:"code",label:"Code view"}]},buttons:[{type:"cancel",name:"cancel",text:"Cancel"},{type:"submit",name:"save",text:"Save",primary:!0}],initialData:{language:r,code:a},onSubmit:function(e){var n=e.getData();S(t,n.language,n.code),e.close()}})}),N=function(n){n.addCommand("codesample",function(){var e=n.selection.getNode();n.selection.isCollapsed()||f.isCodeSample(e)?z(n):n.formatter.toggle("code")})},T=function(t){var a=t.$;t.on("PreProcess",function(e){a("pre[contenteditable=false]",e.node).filter(f.trimArg(f.isCodeSample)).each(function(e,n){var t=a(n),r=n.textContent;t.attr("class",a.trim(t.attr("class"))),t.removeAttr("contentEditable"),t.empty().append(a("").each(function(){this.textContent=r}))})}),t.on("SetContent",function(){var e=a("pre").filter(f.trimArg(f.isCodeSample)).filter(function(e,n){return"false"!==n.contentEditable});e.length&&t.undoManager.transact(function(){e.each(function(e,n){a(n).find("br").each(function(e,n){n.parentNode.replaceChild(t.getDoc().createTextNode("\n"),n)}),n.contentEditable="false",n.innerHTML=t.dom.encode(n.textContent),F(t).highlightElement(n),n.className=a.trim(n.className)})})})},B=function(t){t.ui.registry.addToggleButton("codesample",{icon:"code-sample",tooltip:"Insert/edit code sample",onAction:function(){return z(t)},onSetup:function(e){function n(){e.setActive(function(e){var n=e.selection.getStart();return e.dom.is(n,'pre[class*="language-"]')}(t))}return t.on("NodeChange",n),function(){return t.off("NodeChange",n)}}}),t.ui.registry.addMenuItem("codesample",{text:"Code sample...",icon:"code-sample",onAction:function(){return z(t)}})};!function M(){a.add("codesample",function(n){T(n),B(n),N(n),n.on("dblclick",function(e){f.isCodeSample(e.target)&&z(n)})})}()}(window); \ No newline at end of file diff --git a/hesk/inc/tiny_mce/5.2.0/plugins/colorpicker/plugin.min.js b/hesk/inc/tiny_mce/5.2.0/plugins/colorpicker/plugin.min.js new file mode 100644 index 0000000..d08758f --- /dev/null +++ b/hesk/inc/tiny_mce/5.2.0/plugins/colorpicker/plugin.min.js @@ -0,0 +1,9 @@ +/** + * Copyright (c) Tiny Technologies, Inc. All rights reserved. + * Licensed under the LGPL or a commercial license. + * For LGPL see License.txt in the project root for license information. + * For commercial licenses see https://www.tiny.cloud/ + * + * Version: 5.2.0 (2020-02-13) + */ +!function(o){"use strict";var i=tinymce.util.Tools.resolve("tinymce.PluginManager");!function n(){i.add("colorpicker",function(){o.console.warn("Color picker plugin is now built in to the core editor, please remove it from your editor configuration")})}()}(window); \ No newline at end of file diff --git a/hesk/inc/tiny_mce/5.2.0/plugins/contextmenu/plugin.min.js b/hesk/inc/tiny_mce/5.2.0/plugins/contextmenu/plugin.min.js new file mode 100644 index 0000000..3df2511 --- /dev/null +++ b/hesk/inc/tiny_mce/5.2.0/plugins/contextmenu/plugin.min.js @@ -0,0 +1,9 @@ +/** + * Copyright (c) Tiny Technologies, Inc. All rights reserved. + * Licensed under the LGPL or a commercial license. + * For LGPL see License.txt in the project root for license information. + * For commercial licenses see https://www.tiny.cloud/ + * + * Version: 5.2.0 (2020-02-13) + */ +!function(n){"use strict";var o=tinymce.util.Tools.resolve("tinymce.PluginManager");!function e(){o.add("contextmenu",function(){n.console.warn("Context menu plugin is now built in to the core editor, please remove it from your editor configuration")})}()}(window); \ No newline at end of file diff --git a/hesk/inc/tiny_mce/5.2.0/plugins/directionality/plugin.min.js b/hesk/inc/tiny_mce/5.2.0/plugins/directionality/plugin.min.js new file mode 100644 index 0000000..0d601b5 --- /dev/null +++ b/hesk/inc/tiny_mce/5.2.0/plugins/directionality/plugin.min.js @@ -0,0 +1,9 @@ +/** + * Copyright (c) Tiny Technologies, Inc. All rights reserved. + * Licensed under the LGPL or a commercial license. + * For LGPL see License.txt in the project root for license information. + * For commercial licenses see https://www.tiny.cloud/ + * + * Version: 5.2.0 (2020-02-13) + */ +!function(i){"use strict";function n(){}function u(n){return function(){return n}}function t(){return a}var e,r=tinymce.util.Tools.resolve("tinymce.PluginManager"),c=tinymce.util.Tools.resolve("tinymce.util.Tools"),o=function(n,t){var e,r=n.dom,o=n.selection.getSelectedBlocks();o.length&&(e=r.getAttrib(o[0],"dir"),c.each(o,function(n){r.getParent(n.parentNode,'*[dir="'+t+'"]',r.getRoot())||r.setAttrib(n,"dir",e!==t?t:null)}),n.nodeChanged())},d=function(n){n.addCommand("mceDirectionLTR",function(){o(n,"ltr")}),n.addCommand("mceDirectionRTL",function(){o(n,"rtl")})},f=u(!1),l=u(!0),a=(e={fold:function(n,t){return n()},is:f,isSome:f,isNone:l,getOr:s,getOrThunk:N,getOrDie:function(n){throw new Error(n||"error: getOrDie called on none.")},getOrNull:u(null),getOrUndefined:u(undefined),or:s,orThunk:N,map:t,each:n,bind:t,exists:f,forall:l,filter:t,equals:m,equals_:m,toArray:function(){return[]},toString:u("none()")},Object.freeze&&Object.freeze(e),e);function m(n){return n.isNone()}function N(n){return n()}function s(n){return n}function g(n,t){var e=n.dom(),r=i.window.getComputedStyle(e).getPropertyValue(t),o=""!==r||function(n){var t=A(n)?n.dom().parentNode:n.dom();return t!==undefined&&null!==t&&t.ownerDocument.body.contains(t)}(n)?r:w(e,t);return null===o?undefined:o}function T(t,r){return function(e){function n(n){var t=p.fromDom(n.element);e.setActive(function(n){return"rtl"===g(n,"direction")?"rtl":"ltr"}(t)===r)}return t.on("NodeChange",n),function(){return t.off("NodeChange",n)}}}var E,O,y=function(e){function n(){return o}function t(n){return n(e)}var r=u(e),o={fold:function(n,t){return t(e)},is:function(n){return e===n},isSome:l,isNone:f,getOr:r,getOrThunk:r,getOrDie:r,getOrNull:r,getOrUndefined:r,or:n,orThunk:n,map:function(n){return y(n(e))},each:function(n){n(e)},bind:t,exists:t,forall:t,filter:function(n){return n(e)?o:a},toArray:function(){return[e]},toString:function(){return"some("+e+")"},equals:function(n){return n.is(e)},equals_:function(n,t){return n.fold(f,function(n){return t(e,n)})}};return o},D=function(n){return null===n||n===undefined?a:y(n)},h=function(n){if(null===n||n===undefined)throw new Error("Node cannot be null or undefined");return{dom:u(n)}},p={fromHtml:function(n,t){var e=(t||i.document).createElement("div");if(e.innerHTML=n,!e.hasChildNodes()||1Could not load emoticons

    "}]},buttons:[{type:"cancel",text:"Close",primary:!0}],initialData:{pattern:"",results:[]}}),a.focus(U),a.unblock()}))},B=function(n,t){function e(){return R(n,t)}n.ui.registry.addButton("emoticons",{tooltip:"Emoticons",icon:"emoji",onAction:e}),n.ui.registry.addMenuItem("emoticons",{text:"Emoticons...",icon:"emoji",onAction:e})};!function G(){r.add("emoticons",function(n,t){var e=F(n,t),r=q(n),o=h(n,e,r);B(n,o),function(r,o){r.ui.registry.addAutocompleter("emoticons",{ch:":",columns:"auto",minChars:2,fetch:function(t,e){return o.waitForLoad().then(function(){var n=o.listAll();return d(n,t,A.some(e))})},onAction:function(n,t,e){r.selection.setRng(t),r.insertContent(e),n.hide()}})}(n,o)})}()}(window); \ No newline at end of file diff --git a/hesk/inc/tiny_mce/5.2.0/plugins/fullpage/plugin.min.js b/hesk/inc/tiny_mce/5.2.0/plugins/fullpage/plugin.min.js new file mode 100644 index 0000000..7ef1075 --- /dev/null +++ b/hesk/inc/tiny_mce/5.2.0/plugins/fullpage/plugin.min.js @@ -0,0 +1,9 @@ +/** + * Copyright (c) Tiny Technologies, Inc. All rights reserved. + * Licensed under the LGPL or a commercial license. + * For LGPL see License.txt in the project root for license information. + * For commercial licenses see https://www.tiny.cloud/ + * + * Version: 5.2.0 (2020-02-13) + */ +!function(m){"use strict";function f(t){return n({validate:!1,root_name:"#document"}).parse(t,{format:"xhtml"})}function g(t){return t.replace(/<\/?[A-Z]+/g,function(t){return t.toLowerCase()})}var i=function(t){function e(){return n}var n=t;return{get:e,set:function(t){n=t},clone:function(){return i(e())}}},t=tinymce.util.Tools.resolve("tinymce.PluginManager"),e=function(){return(e=Object.assign||function(t){for(var e,n=1,i=arguments.length;n")},_=f,b=function(t,e){var n,i,l=f(e),r={};function o(t,e){return t.attr(e)||""}return r.fontface=a(t),r.fontsize=c(t),7===(n=l.firstChild).type&&(r.xml_pi=!0,(i=/encoding="([^"]+)"/.exec(n.value))&&(r.docencoding=i[1])),(n=l.getAll("#doctype")[0])&&(r.doctype=""),(n=l.getAll("title")[0])&&n.firstChild&&(r.title=n.firstChild.value),p.each(l.getAll("meta"),function(t){var e,n=t.attr("name"),i=t.attr("http-equiv");n?r[n.toLowerCase()]=t.attr("content"):"Content-Type"===i&&(e=/charset\s*=\s*(.*)\s*/gi.exec(t.attr("content")))&&(r.docencoding=e[1])}),(n=l.getAll("html")[0])&&(r.langcode=o(n,"lang")||o(n,"xml:lang")),r.stylesheets=[],p.each(l.getAll("link"),function(t){"stylesheet"===t.attr("rel")&&r.stylesheets.push(t.attr("href"))}),(n=l.getAll("body")[0])&&(r.langdir=o(n,"dir"),r.style=o(n,"style"),r.visited_color=o(n,"vlink"),r.link_color=o(n,"link"),r.active_color=o(n,"alink")),r},x=function(t,r,e){var o,n,i,a,l,c=t.dom;function s(t,e,n){t.attr(e,n||undefined)}function u(t){n.firstChild?n.insert(t,n.firstChild):n.append(t)}o=f(e),(n=o.getAll("head")[0])||(a=o.getAll("html")[0],n=new y("head",1),a.firstChild?a.insert(n,a.firstChild,!0):a.append(n)),a=o.firstChild,r.xml_pi?(l='version="1.0"',r.docencoding&&(l+=' encoding="'+r.docencoding+'"'),7!==a.type&&(a=new y("xml",7),o.insert(a,o.firstChild,!0)),a.value=l):a&&7===a.type&&a.remove(),a=o.getAll("#doctype")[0],r.doctype?(a||(a=new y("#doctype",10),r.xml_pi?o.insert(a,o.firstChild):u(a)),a.value=r.doctype.substring(9,r.doctype.length-1)):a&&a.remove(),a=null,p.each(o.getAll("meta"),function(t){"Content-Type"===t.attr("http-equiv")&&(a=t)}),r.docencoding?(a||((a=new y("meta",1)).attr("http-equiv","Content-Type"),a.shortEnded=!0,u(a)),a.attr("content","text/html; charset="+r.docencoding)):a&&a.remove(),a=o.getAll("title")[0],r.title?(a?a.empty():u(a=new y("title",1)),a.append(new y("#text",3)).value=r.title):a&&a.remove(),p.each("keywords,description,author,copyright,robots".split(","),function(t){var e,n,i=o.getAll("meta"),l=r[t];for(e=0;e"))},l=function(i,l){var r=b(i,l.get()),t=e(e({},{title:"",keywords:"",description:"",robots:"",author:"",docencoding:""}),r);i.windowManager.open({title:"Metadata and Document Properties",size:"normal",body:{type:"panel",items:[{name:"title",type:"input",label:"Title"},{name:"keywords",type:"input",label:"Keywords"},{name:"description",type:"input",label:"Description"},{name:"robots",type:"input",label:"Robots"},{name:"author",type:"input",label:"Author"},{name:"docencoding",type:"input",label:"Encoding"}]},buttons:[{type:"cancel",name:"cancel",text:"Cancel"},{type:"submit",name:"save",text:"Save",primary:!0}],initialData:t,onSubmit:function(t){var e=t.getData(),n=x(i,p.extend(r,e),l.get());l.set(n),t.close()}})},k=function(t,e){t.addCommand("mceFullPageProperties",function(){l(t,e)})},C=function(t,e){return p.each(t,function(t){e=e.replace(t,function(t){return"\x3c!--mce:protected "+escape(t)+"--\x3e"})}),e},A=function(t){return t.replace(//g,function(t,e){return unescape(e)})},w=p.each,P=function(t){var e,n="",i="";if(r(t)){var l=o(t);n+='\n'}return n+=d(t),n+="\n\n\n",(e=u(t))&&(n+=""+e+"\n"),(e=o(t))&&(n+='\n'),(e=a(t))&&(i+="font-family: "+e+";"),(e=c(t))&&(i+="font-size: "+e+";"),(e=s(t))&&(i+="color: "+e+";"),n+="\n\n"},T=function(e,n,i){e.on("BeforeSetContent",function(t){!function(t,e,n,i){var l,r,o,a,c="",s=t.dom;if(!(i.selection||(o=C(t.settings.protect,i.content),"raw"===i.format&&e.get()||i.source_view&&v(t)))){0!==o.length||i.source_view||(o=p.trim(e.get())+"\n"+p.trim(o)+"\n"+p.trim(n.get())),-1!==(l=(o=o.replace(/<(\/?)BODY/gi,"<$1body")).indexOf("",l),e.set(g(o.substring(0,l+1))),-1===(r=o.indexOf("\n")),a=_(e.get()),w(a.getAll("style"),function(t){t.firstChild&&(c+=t.firstChild.value)});var u=a.getAll("body")[0];u&&s.setAttribs(t.getBody(),{style:u.attr("style")||"",dir:u.attr("dir")||"",vLink:u.attr("vlink")||"",link:u.attr("link")||"",aLink:u.attr("alink")||""}),s.remove("fullpage_styles");var d=t.getDoc().getElementsByTagName("head")[0];if(c)s.add(d,"style",{id:"fullpage_styles"}).appendChild(m.document.createTextNode(c));var f={};p.each(d.getElementsByTagName("link"),function(t){"stylesheet"===t.rel&&t.getAttribute("data-mce-fullpage")&&(f[t.href]=t)}),p.each(a.getAll("link"),function(t){var e=t.attr("href");if(!e)return!0;f[e]||"stylesheet"!==t.attr("rel")||s.add(d,"link",{rel:"stylesheet",text:"text/css",href:e,"data-mce-fullpage":"1"}),delete f[e]}),p.each(f,function(t){t.parentNode.removeChild(t)})}}(e,n,i,t)}),e.on("GetContent",function(t){!function(t,e,n,i){i.selection||i.source_view&&v(t)||(i.content=A(p.trim(e)+"\n"+p.trim(i.content)+"\n"+p.trim(n)))}(e,n.get(),i.get(),t)})},O=function(t){t.ui.registry.addButton("fullpage",{tooltip:"Metadata and document properties",icon:"document-properties",onAction:function(){t.execCommand("mceFullPageProperties")}}),t.ui.registry.addMenuItem("fullpage",{text:"Metadata and document properties",icon:"document-properties",onAction:function(){t.execCommand("mceFullPageProperties")}})};!function D(){t.add("fullpage",function(t){var e=i(""),n=i("");k(t,e),O(t),T(t,e,n)})}()}(window); \ No newline at end of file diff --git a/hesk/inc/tiny_mce/5.2.0/plugins/fullscreen/plugin.min.js b/hesk/inc/tiny_mce/5.2.0/plugins/fullscreen/plugin.min.js new file mode 100644 index 0000000..6eb913e --- /dev/null +++ b/hesk/inc/tiny_mce/5.2.0/plugins/fullscreen/plugin.min.js @@ -0,0 +1,9 @@ +/** + * Copyright (c) Tiny Technologies, Inc. All rights reserved. + * Licensed under the LGPL or a commercial license. + * For LGPL see License.txt in the project root for license information. + * For commercial licenses see https://www.tiny.cloud/ + * + * Version: 5.2.0 (2020-02-13) + */ +!function(d){"use strict";function t(){}function m(n){return function(){return n}}function n(){return f}var e,u=function(n){function e(){return r}var r=n;return{get:e,set:function(n){r=n},clone:function(){return u(e())}}},r=tinymce.util.Tools.resolve("tinymce.PluginManager"),o=function(n){return{isFullscreen:function(){return null!==n.get()}}},c=m(!1),i=m(!0),f=(e={fold:function(n,e){return n()},is:c,isSome:c,isNone:i,getOr:l,getOrThunk:a,getOrDie:function(n){throw new Error(n||"error: getOrDie called on none.")},getOrNull:m(null),getOrUndefined:m(undefined),or:l,orThunk:a,map:n,each:t,bind:n,exists:c,forall:i,filter:n,equals:s,equals_:s,toArray:function(){return[]},toString:m("none()")},Object.freeze&&Object.freeze(e),e);function s(n){return n.isNone()}function a(n){return n()}function l(n){return n}function h(){return function(n){function e(){r.get().each(n)}var r=u(Y.none());return{clear:function(){e(),r.set(Y.none())},isSet:function(){return r.get().isSome()},set:function(n){e(),r.set(Y.some(n))}}}(function(n){n.unbind()})}function v(e){return function(n){return function(n){if(null===n)return"null";var e=typeof n;return"object"==e&&(Array.prototype.isPrototypeOf(n)||n.constructor&&"Array"===n.constructor.name)?"array":"object"==e&&(String.prototype.isPrototypeOf(n)||n.constructor&&"String"===n.constructor.name)?"string":e}(n)===e}}function g(n,e){for(var r=n.length,t=new Array(r),o=0;o${name}');return{name:"plugins",title:"Plugins",items:[{type:"htmlpanel",presets:"document",html:[(n=e,null==n?"":'
    '+function(t){var e=function(e){var t=F(e.plugins);return e.settings.forced_plugins===undefined?t:function(e,t){for(var n=[],o=0,a=e.length;o"+r(t,e)+""}),o=n.length,a=n.join("");return"

    "+U.translate(["Plugins installed ({0}):",o])+"

      "+a+"
    "}(n)+"
    "),(t=y(["Accessibility Checker","Advanced Code Editor","Advanced Tables","Case Change","Checklist","Tiny Comments","Tiny Drive","Enhanced Media Embed","Format Painter","Link Checker","Mentions","MoxieManager","Page Embed","Permanent Pen","PowerPaste","Spell Checker Pro"],function(e){return"
  • "+U.translate(e)+"
  • "}).join(""),'

    '+U.translate("Premium plugins:")+"

    ")].join("")}]}},N=tinymce.util.Tools.resolve("tinymce.EditorManager"),L=function(){var e,t,n='TinyMCE '+(e=N.majorVersion,t=N.minorVersion,0===e.indexOf("@")?"X.X.X":e+"."+t)+"";return{name:"versions",title:"Version",items:[{type:"htmlpanel",html:"

    "+U.translate(["You are using {0}",n])+"

    ",presets:"document"}]}},B=function(){return{name:"keyboardnav",title:"Keyboard Navigation",items:[{type:"htmlpanel",presets:"document",html:"

    Editor UI keyboard navigation

    \n\n

    Activating keyboard navigation

    \n\n

    The sections of the outer UI of the editor - the menubar, toolbar, sidebar and footer - are all keyboard navigable. As such, there are multiple ways to activate keyboard navigation:

    \n
      \n
    • Focus the menubar: Alt + F9 (Windows) or ⌥F9 (MacOS)
    • \n
    • Focus the toolbar: Alt + F10 (Windows) or ⌥F10 (MacOS)
    • \n
    • Focus the footer: Alt + F11 (Windows) or ⌥F11 (MacOS)
    • \n
    \n\n

    Focusing the menubar or toolbar will start keyboard navigation at the first item in the menubar or toolbar, which will be highlighted with a gray background. Focusing the footer will start keyboard navigation at the first item in the element path, which will be highlighted with an underline.

    \n\n

    Moving between UI sections

    \n\n

    When keyboard navigation is active, pressing tab will move the focus to the next major section of the UI, where applicable. These sections are:

    \n
      \n
    • the menubar
    • \n
    • each group of the toolbar
    • \n
    • the sidebar
    • \n
    • the element path in the footer
    • \n
    • the wordcount toggle button in the footer
    • \n
    • the branding link in the footer
    • \n
    \n\n

    Pressing shift + tab will move backwards through the same sections, except when moving from the footer to the toolbar. Focusing the element path then pressing shift + tab will move focus to the first toolbar group, not the last.

    \n\n

    Moving within UI sections

    \n\n

    Keyboard navigation within UI sections can usually be achieved using the left and right arrow keys. This includes:

    \n
      \n
    • moving between menus in the menubar
    • \n
    • moving between buttons in a toolbar group
    • \n
    • moving between items in the element path
    • \n
    \n\n

    In all these UI sections, keyboard navigation will cycle within the section. For example, focusing the last button in a toolbar group then pressing right arrow will move focus to the first item in the same toolbar group.

    \n\n

    Executing buttons

    \n\n

    To execute a button, navigate the selection to the desired button and hit space or enter.

    \n\n

    Opening, navigating and closing menus

    \n\n

    When focusing a menubar button or a toolbar button with a menu, pressing space, enter or down arrow will open the menu. When the menu opens the first item will be selected. To move up or down the menu, press the up or down arrow key respectively. This is the same for submenus, which can also be opened and closed using the left and right arrow keys.

    \n\n

    To close any active menu, hit the escape key. When a menu is closed the selection will be restored to its previous selection. This also works for closing submenus.

    \n\n

    Context toolbars and menus

    \n\n

    To focus an open context toolbar such as the table context toolbar, press Ctrl + F9 (Windows) or ⌃F9 (MacOS).

    \n\n

    Context toolbar navigation is the same as toolbar navigation, and context menu navigation is the same as standard menu navigation.

    \n\n

    Dialog navigation

    \n\n

    There are two types of dialog UIs in TinyMCE: tabbed dialogs and non-tabbed dialogs.

    \n\n

    When a non-tabbed dialog is opened, the first interactive component in the dialog will be focused. Users can navigate between interactive components by pressing tab. This includes any footer buttons. Navigation will cycle back to the first dialog component if tab is pressed while focusing the last component in the dialog. Pressing shift + tab will navigate backwards.

    \n\n

    When a tabbed dialog is opened, the first button in the tab menu is focused. Pressing tab will navigate to the first interactive component in that tab, and will cycle through the tab\u2019s components, the footer buttons, then back to the tab button. To switch to another tab, focus the tab button for the current tab, then use the arrow keys to cycle through the tab buttons.

    "}]}};!function z(){t.add("help",function(e){var t=a({}),n=function(n){return{addTab:function(e){var t=n.get();t[e.name]=e,n.set(t)}}}(t),o=A(e,t);return s(e,o),i(e,o),e.shortcuts.add("Alt+0","Open help dialog","mceHelp"),n})}()}(); \ No newline at end of file diff --git a/hesk/inc/tiny_mce/5.2.0/plugins/hr/plugin.min.js b/hesk/inc/tiny_mce/5.2.0/plugins/hr/plugin.min.js new file mode 100644 index 0000000..4660378 --- /dev/null +++ b/hesk/inc/tiny_mce/5.2.0/plugins/hr/plugin.min.js @@ -0,0 +1,9 @@ +/** + * Copyright (c) Tiny Technologies, Inc. All rights reserved. + * Licensed under the LGPL or a commercial license. + * For LGPL see License.txt in the project root for license information. + * For commercial licenses see https://www.tiny.cloud/ + * + * Version: 5.2.0 (2020-02-13) + */ +!function(){"use strict";var n=tinymce.util.Tools.resolve("tinymce.PluginManager"),o=function(n){n.addCommand("InsertHorizontalRule",function(){n.execCommand("mceInsertContent",!1,"
    ")})},t=function(n){n.ui.registry.addButton("hr",{icon:"horizontal-rule",tooltip:"Horizontal line",onAction:function(){return n.execCommand("InsertHorizontalRule")}}),n.ui.registry.addMenuItem("hr",{icon:"horizontal-rule",text:"Horizontal line",onAction:function(){return n.execCommand("InsertHorizontalRule")}})};!function e(){n.add("hr",function(n){o(n),t(n)})}()}(); \ No newline at end of file diff --git a/hesk/inc/tiny_mce/5.2.0/plugins/image/plugin.min.js b/hesk/inc/tiny_mce/5.2.0/plugins/image/plugin.min.js new file mode 100644 index 0000000..dabe6ff --- /dev/null +++ b/hesk/inc/tiny_mce/5.2.0/plugins/image/plugin.min.js @@ -0,0 +1,9 @@ +/** + * Copyright (c) Tiny Technologies, Inc. All rights reserved. + * Licensed under the LGPL or a commercial license. + * For LGPL see License.txt in the project root for license information. + * For commercial licenses see https://www.tiny.cloud/ + * + * Version: 5.2.0 (2020-02-13) + */ +!function(s){"use strict";function o(){}function a(t){return function(){return t}}function t(t){return t}function e(){return l}var n,r=tinymce.util.Tools.resolve("tinymce.PluginManager"),u=a(!1),c=a(!0),l=(n={fold:function(t,e){return t()},is:u,isSome:u,isNone:c,getOr:d,getOrThunk:f,getOrDie:function(t){throw new Error(t||"error: getOrDie called on none.")},getOrNull:a(null),getOrUndefined:a(undefined),or:d,orThunk:f,map:e,each:o,bind:e,exists:u,forall:c,filter:e,equals:i,equals_:i,toArray:function(){return[]},toString:a("none()")},Object.freeze&&Object.freeze(n),n);function i(t){return t.isNone()}function f(t){return t()}function d(t){return t}function m(e){return function(t){return function(t){if(null===t)return"null";var e=typeof t;return"object"==e&&(Array.prototype.isPrototypeOf(t)||t.constructor&&"Array"===t.constructor.name)?"array":"object"==e&&(String.prototype.isPrototypeOf(t)||t.constructor&&"String"===t.constructor.name)?"string":e}(t)===e}}function T(t){for(var e=[],n=0,r=t.length;n'+n+"")}else e.insertContent(i(e,t))},g=i,y=function(e){e.addCommand("mceInsertDate",function(){p(e,t(e))}),e.addCommand("mceInsertTime",function(){p(e,o(e))})},M=tinymce.util.Tools.resolve("tinymce.util.Tools"),S=function(e){function t(){return n}var n=e;return{get:t,set:function(e){n=e},clone:function(){return S(t())}}},v=function(n){var t=u(n),r=S(c(n));n.ui.registry.addSplitButton("insertdatetime",{icon:"insert-time",tooltip:"Insert date/time",select:function(e){return e===r.get()},fetch:function(e){e(M.map(t,function(e){return{type:"choiceitem",text:g(n,e),value:e}}))},onAction:function(){for(var e=[],t=0;t]+>[^<]+<\/a>$/.test(n)||-1===n.indexOf("href=")))},ln=U,sn=function(n,t){return function(n){return n.replace(/\uFEFF/g,"")}(t?t.innerText||t.textContent:n.getContent({format:"text"}))},dn=D,mn=R,hn={sanitize:function(n){return B(K)(n)},sanitizeWith:B,createUi:function(t,e){return function(n){return{name:t,type:"selectbox",label:e,items:n}}},getValue:K},pn=function(n){function t(){return e}var e=n;return{get:t,set:function(n){e=n},clone:function(){return pn(t())}}},gn=function(n,r){function e(n,t){var e=function(n,t){return"link"===t?n.catalogs.link:"anchor"===t?n.catalogs.anchor:X.none()}(r,t.name).getOr([]);return V(o.get(),t.name,e,n)}var o=pn(n.text);return{onChange:function(n,t){return"url"===t.name?function(n){if(o.get().length<=0){var t=n.url.meta.text!==undefined?n.url.meta.text:n.url.value,e=n.url.meta.title!==undefined?n.url.meta.title:"";return X.some({text:t,title:e})}return X.none()}(n()):I(["anchor","link"],t.name)?e(n(),t):("text"===t.name&&o.set(n().text),X.none())}}},vn={},yn={exports:vn};W=undefined,H=vn,$=yn,G=undefined,function(n){"object"==typeof H&&void 0!==$?$.exports=n():"function"==typeof W&&W.amd?W([],n):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).EphoxContactWrapper=n()}(function(){return function l(i,u,c){function a(t,n){if(!u[t]){if(!i[t]){var e="function"==typeof G&&G;if(!n&&e)return e(t,!0);if(f)return f(t,!0);var r=new Error("Cannot find module '"+t+"'");throw r.code="MODULE_NOT_FOUND",r}var o=u[t]={exports:{}};i[t][0].call(o.exports,function(n){return a(i[t][1][n]||n)},o,o.exports,l,i,u,c)}return u[t].exports}for(var f="function"==typeof G&&G,n=0;ne.length?ne(t,e,n):ee(t,e,n)},[]);return S(n).map(function(e){return e.list})}(e.contentDocument,n).toArray()}function de(e){var n=g(Zn.getSelectedListItems(e),Ln.fromDom);return A(N(n,t(re)),N(function(e){var n=Xe.call(e,0);return n.reverse(),n}(n),t(re)),function(e,n){return{start:e,end:n}})}function le(t,e,r){var n=function(e,n){var t=Ge(!1);return g(e,function(e){return{sourceList:e,entries:ot(0,n,t,e)}})}(e,de(t));p(n,function(e){!function(e,n){p(v(e,ie),function(e){return function(e,n){switch(e){case"Indent":n.depth++;break;case"Outdent":n.depth--;break;case"Flatten":n.depth=0}}(n,e)})}(e.entries,r);var n=function(n,e){return y(function(e,n){if(0===e.length)return[];for(var t=n(e[0]),r=[],o=[],i=0,u=e.length;i=e.childNodes.length?t.data.length:0}:t.previousSibling&&Un(t.previousSibling)?{container:t.previousSibling,offset:t.previousSibling.data.length}:t.nextSibling&&Un(t.nextSibling)?{container:t.nextSibling,offset:0}:{container:e,offset:n}}function ve(e,n){var t=g(Zn.getSelectedListRoots(e),Ln.fromDom),r=g(Zn.getSelectedDlItems(e),Ln.fromDom),o=!1;if(t.length||r.length){var i=e.selection.getBookmark();le(e,t,n),ge(e,n,r),e.selection.moveToBookmark(i),e.selection.setRng(st(e.selection.getRng())),e.nodeChanged(),o=!0}return o}function he(e){return ve(e,"Indent")}function Ne(e){return ve(e,"Outdent")}function ye(e){return ve(e,"Flatten")}function Se(e){return/\btox\-/.test(e.className)}function Oe(e){switch(e){case"UL":return"ToggleUlList";case"OL":return"ToggleOlList";case"DL":return"ToggleDLList"}}function Ce(t,e){Mn.each(e,function(e,n){t.setAttribute(n,e)})}function be(e,n,t){!function(e,n,t){var r=t["list-style-type"]?t["list-style-type"]:null;e.setStyle(n,"list-style-type",r)}(e,n,t),function(e,n,t){Ce(n,t["list-attributes"]),Mn.each(e.select("li",n),function(e){Ce(e,t["list-item-attributes"])})}(e,n,t)}function Le(e,n,t,r){var o,i;for(o=n[t?"startContainer":"endContainer"],i=n[t?"startOffset":"endOffset"],1===o.nodeType&&(o=o.childNodes[Math.min(i,o.childNodes.length-1)]||o),!t&&Wn(o.nextSibling)&&(o=o.nextSibling);o.parentNode!==r;){if(Kn(e,o))return o;if(/^(TD|TH)$/.test(o.parentNode.nodeName))return o;o=o.parentNode}return o}function Te(r,o,i){void 0===i&&(i={});var e,n=r.selection.getRng(!0),u="LI",t=Zn.getClosestListRootElm(r,r.selection.getStart(!0)),a=r.dom;"false"!==a.getContentEditable(r.selection.getNode())&&("DL"===(o=o.toUpperCase())&&(u="DT"),e=dt(n),Mn.each(function(t,e,r){for(var o,i=[],u=t.dom,n=Le(t,e,!0,r),a=Le(t,e,!1,r),s=[],c=n;c&&(s.push(c),c!==a);c=c.nextSibling);return Mn.each(s,function(e){if(Kn(t,e))return i.push(e),void(o=null);if(u.isBlock(e)||Wn(e))return Wn(e)&&u.remove(e),void(o=null);var n=e.nextSibling;ct.isBookmarkNode(e)&&(Kn(t,n)||!n&&e.parentNode===r)?o=null:(o||(o=u.create("p"),e.parentNode.insertBefore(o,e),i.push(o)),o.appendChild(e))}),i}(r,n,t),function(e){var n,t;(t=e.previousSibling)&&Fn(t)&&t.nodeName===o&&function(e,n,t){var r=e.getStyle(n,"list-style-type"),o=t?t["list-style-type"]:"";return r===(o=null===o?"":o)}(a,t,i)?(n=t,e=a.rename(e,u),t.appendChild(e)):(n=a.create(o),e.parentNode.insertBefore(n,e),n.appendChild(e),e=a.rename(e,u)),function(t,r,e){Mn.each(e,function(e){var n;return t.setStyle(r,((n={})[e]="",n))})}(a,e,["margin","margin-right","margin-bottom","margin-left","margin-top","padding","padding-right","padding-bottom","padding-left","padding-top"]),be(a,n,i),mt(r.dom,n)}),r.selection.setRng(lt(e)))}function De(e,n,t){return function(e,n){return e&&n&&Fn(e)&&e.nodeName===n.nodeName}(n,t)&&function(e,n,t){return e.getStyle(n,"list-style-type",!0)===e.getStyle(t,"list-style-type",!0)}(e,n,t)&&function(e,n){return e.className===n.className}(n,t)}function Ee(n,e,t,r,o){if(e.nodeName!==r||gt(o)){var i=dt(n.selection.getRng(!0));Mn.each([e].concat(t),function(e){!function(e,n,t,r){if(n.nodeName!==t){var o=e.dom.rename(n,t);be(e.dom,o,r),j(e,Oe(t),o)}else be(e.dom,n,r),j(e,Oe(t),n)}(n,e,r,o)}),n.selection.setRng(lt(i))}else ye(n)}function we(e,n){var t,r=n.parentNode;"LI"===r.nodeName&&r.firstChild===n&&((t=r.previousSibling)&&"LI"===t.nodeName?(t.appendChild(n),Qn(e,r)&&vt.remove(r)):vt.setStyle(r,"listStyleType","none")),Fn(r)&&(t=r.previousSibling)&&"LI"===t.nodeName&&t.appendChild(n)}function ke(e,n,t,r){var o=n.startContainer,i=n.startOffset;if(Un(o)&&(t?i"}(n):"application/x-shockwave-flash"===n.sourcemime?function(e){var t='';return e.poster&&(t+=''),t+=""}(n):-1!==n.sourcemime.indexOf("audio")?function(e,t){return t?t(e):'"}(n,o):"script"===n.type?function(e){return'"; + + return $html; + } + + /** + * Prints a node of the menu + * + * @access private + */ + function _nodeToHTML($nodeObj, $prefix, $return = 'newNode', $currentDepth = 0, $maxDepthPrefix = null) + { + $prefix = empty($maxDepthPrefix) ? $prefix : $maxDepthPrefix; + + $expanded = $this->isDynamic ? ($nodeObj->expanded ? 'true' : 'false') : 'true'; + $isDynamic = $this->isDynamic ? ($nodeObj->isDynamic ? 'true' : 'false') : 'false'; + $html = sprintf("\t %s = %s.addItem(new TreeNode('%s', '%s', %s, %s, %s, %s, '%s', '%s', %s));\n", + $return, + $prefix, + str_replace("'", "\\'", $nodeObj->text), + str_replace("'", "\\'", $nodeObj->menu_icons), + !empty($nodeObj->icon) ? "'" . $nodeObj->icon . "'" : 'null', + !empty($nodeObj->link) ? "'" . $nodeObj->link . "'" : 'null', + $expanded, + $isDynamic, + $nodeObj->cssClass, + $nodeObj->linkTarget, + !empty($nodeObj->expandedIcon) ? "'" . $nodeObj->expandedIcon . "'" : 'null'); + + foreach ($nodeObj->events as $event => $handler) { + $html .= sprintf("\t %s.setEvent('%s', '%s');\n", + $return, + $event, + str_replace(array("\r", "\n", "'"), array('\r', '\n', "\'"), $handler)); + } + + if ($this->maxDepth > 0 AND $currentDepth == $this->maxDepth) { + $maxDepthPrefix = $prefix; + } + + /** + * Loop through subnodes + */ + if (!empty($nodeObj->items)) { + for ($i=0; $iitems); $i++) { + $html .= $this->_nodeToHTML($nodeObj->items[$i], $return, $return . '_' . ($i + 1), $currentDepth + 1, $maxDepthPrefix); + } + } + + return $html; + } +} // End class HTML_TreeMenu_DHTML + + +/** +* HTML_TreeMenu_Listbox class +* +* This class presents the menu as a listbox +*/ +class HTML_TreeMenu_Listbox extends HTML_TreeMenu_Presentation +{ + /** + * The text that is displayed in the first option + * @var string + */ + var $promoText; + + /** + * The character used for indentation + * @var string + */ + var $indentChar; + + /** + * How many of the indent chars to use + * per indentation level + * @var integer + */ + var $indentNum; + + /** + * Target for the links generated + * @var string + */ + var $linkTarget; + + /** + * Constructor + * + * @param object $structure The menu structure + * @param array $options Options whic affect the display of the listbox. + * These can consist of: + * o promoText The text that appears at the the top of the listbox + * Defaults to "Select..." + * o indentChar The character to use for indenting the nodes + * Defaults to " " + * o indentNum How many of the indentChars to use per indentation level + * Defaults to 2 + * o linkTarget Target for the links. Defaults to "_self" + * o submitText Text for the submit button. Defaults to "Go" + */ + function __construct($structure, $options = array()) + { + $this->menu = &$structure; + + $this->promoText = 'Select...'; + $this->indentChar = ' '; + $this->indentNum = 2; + $this->linkTarget = '_self'; + $this->submitText = 'Go'; + + foreach ($options as $option => $value) { + $this->$option = $value; + } + } + + /** + * Returns the HTML generated + */ + function toHTML() + { + static $count = 0; + $nodeHTML = ''; + + /** + * Loop through subnodes + */ + if (isset($this->menu->items)) { + for ($i=0; $imenu->items); $i++) { + $nodeHTML .= $this->_nodeToHTML($this->menu->items[$i]); + } + } + + if (!defined('HESK_ALREADY')) + { + define('HESK_ALREADY',1); + } + return $nodeHTML; + } + + /** + * Returns HTML for a single node + * + * @access private + */ + function _nodeToHTML($node, $prefix = '') + { + /* Generate unique select option IDs for Hesk */ + if (defined('HESK_ALREADY')) + { + $myID = $node->hesk_select; + $myID.= '_2'; + } + else + { + $myID = $node->hesk_select; + } + + /* Select default option? */ + if (isset($node->hesk_parent) && $node->hesk_catid == $node->hesk_parent) + { + $mySelect = ' selected="selected"'; + } + elseif (isset($node->hesk_selected) && $node->hesk_selected == 1) + { + $mySelect = ' selected="selected"'; + } + else + { + $mySelect = ''; + } + + $html = sprintf('', $node->hesk_catid, $myID, $mySelect, $prefix, $node->text_short); + + /** + * Loop through subnodes + */ + if (isset($node->items)) { + for ($i=0; $iitems); $i++) { + $html .= $this->_nodeToHTML($node->items[$i], $prefix . str_repeat($this->indentChar, $this->indentNum)); + } + } + + return $html; + } +} // End class HTML_TreeMenu_Listbox diff --git a/hesk/inc/treemenu/TreeMenu_v25.js b/hesk/inc/treemenu/TreeMenu_v25.js new file mode 100644 index 0000000..a9cf111 --- /dev/null +++ b/hesk/inc/treemenu/TreeMenu_v25.js @@ -0,0 +1,701 @@ +// +-----------------------------------------------------------------------+ +// | Copyright (c) 2002-2005, Richard Heyes, Harald Radi | +// | All rights reserved. | +// | | +// | Redistribution and use in source and binary forms, with or without | +// | modification, are permitted provided that the following conditions | +// | are met: | +// | | +// | o Redistributions of source code must retain the above copyright | +// | notice, this list of conditions and the following disclaimer. | +// | o Redistributions in binary form must reproduce the above copyright | +// | notice, this list of conditions and the following disclaimer in the | +// | documentation and/or other materials provided with the distribution.| +// | o The names of the authors may not be used to endorse or promote | +// | products derived from this software without specific prior written | +// | permission. | +// | | +// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | +// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | +// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | +// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | +// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | +// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | +// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | +// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | +// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | +// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | +// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | +// | | +// +-----------------------------------------------------------------------+ +// | Author: Richard Heyes | +// | Harald Radi | +// +-----------------------------------------------------------------------+ +// +// $Id: TreeMenu.js,v 1.22 2006/12/14 12:07:34 cweiske Exp $ + +// Modified 20.04.2013 by Klemen (www.hesk.com) + +/** +* Function to create copies of objects which are +* normally passed around by references (Arrays for example) +*/ +function arrayCopy(input) +{ + var output = new Array(input.length); + + for (i in input) { + if (typeof(input[i]) == 'array') { + output[i] = arrayCopy(input[i]); + } else { + output[i] = input[i]; + } + } + + return output; +} + +/** +* TreeMenu class +*/ + function TreeMenu(iconpath, myname, linkTarget, defaultClass, usePersistence, noTopLevelImages) + { + // Properties + this.iconpath = iconpath; + this.myname = myname; + this.linkTarget = linkTarget; + this.defaultClass = defaultClass; + this.usePersistence = usePersistence; + this.noTopLevelImages = noTopLevelImages; + this.n = new Array(); + this.output = ''; + + this.nodeRefs = new Array(); + this.branches = new Array(); + this.branchStatus = new Array(); + this.layerRelations = new Array(); + this.childParents = new Array(); + this.cookieStatuses = new Array(); + + this.preloadImages(); + } + +/** +* Adds a node to the tree +*/ + TreeMenu.prototype.addItem = function (newNode) + { + newIndex = this.n.length; + this.n[newIndex] = newNode; + + return this.n[newIndex]; + } + +/** +* Preload images hack for Mozilla +*/ + TreeMenu.prototype.preloadImages = function () + { + var plustop = new Image; plustop.src = this.iconpath + '/plustop.gif'; + var plusbottom = new Image; plusbottom.src = this.iconpath + '/plusbottom.gif'; + var plus = new Image; plus.src = this.iconpath + '/plus.gif'; + + var minustop = new Image; minustop.src = this.iconpath + '/minustop.gif'; + var minusbottom = new Image; minusbottom.src = this.iconpath + '/minusbottom.gif'; + var minus = new Image; minus.src = this.iconpath + '/minus.gif'; + + var branchtop = new Image; branchtop.src = this.iconpath + '/branchtop.gif'; + var branchbottom = new Image; branchbottom.src = this.iconpath + '/branchbottom.gif'; + var branch = new Image; branch.src = this.iconpath + '/branch.gif'; + + var linebottom = new Image; linebottom.src = this.iconpath + '/linebottom.gif'; + var line = new Image; line.src = this.iconpath + '/line.gif'; + } + +/** +* Main function that draws the menu and assigns it +* to the layer (or document.write()s it) +*/ + TreeMenu.prototype.drawMenu = function ()// OPTIONAL ARGS: nodes = [], level = [], prepend = '', expanded = false, visbility = 'inline', parentLayerID = null + { + /** + * Necessary variables + */ + var output = ''; + var modifier = ''; + var layerID = ''; + var parentLayerID = ''; + + /** + * Parse any optional arguments + */ + var nodes = arguments[0] ? arguments[0] : this.n + var level = arguments[1] ? arguments[1] : []; + var prepend = arguments[2] ? arguments[2] : ''; + var expanded = arguments[3] ? arguments[3] : false; + var visibility = arguments[4] ? arguments[4] : 'inline'; + var parentLayerID = arguments[5] ? arguments[5] : null; + + var currentlevel = level.length; + + for (var i=0; i 1 ? "top" : 'single'; + } else if(i == (nodes.length-1)) { + modifier = "bottom"; + } else { + modifier = ""; + } + + /** + * Single root branch is always expanded + */ + if (!this.doesMenu() || (parentLayerID == null && (nodes.length == 1 || this.noTopLevelImages))) { + expanded = true; + + } else if (nodes[i].expanded) { + expanded = true; + + } else { + expanded = false; + } + + /** + * Make sure visibility is correct based on parent status + */ + visibility = this.checkParentVisibility(layerID) ? visibility : 'none'; + + /** + * Setup branch status and build an indexed array + * of branch layer ids + */ + if (nodes[i].n.length > 0) { + this.branchStatus[layerID] = expanded; + this.branches[this.branches.length] = layerID; + } + + /** + * Setup toggle relationship + */ + if (!this.layerRelations[parentLayerID]) { + this.layerRelations[parentLayerID] = new Array(); + } + this.layerRelations[parentLayerID][this.layerRelations[parentLayerID].length] = layerID; + + /** + * Branch images + */ + var gifname = nodes[i].n.length && this.doesMenu() && nodes[i].isDynamic ? (expanded ? 'minus' : 'plus') : 'branch'; + var iconName = expanded && nodes[i].expandedIcon ? nodes[i].expandedIcon : nodes[i].icon; + var iconimg = nodes[i].icon ? this.stringFormat('', this.iconpath, iconName, layerID) : ''; + + /** + * Add event handlers + */ + var eventHandlers = ""; + for (j in nodes[i].events) { + eventHandlers += this.stringFormat('{0}="{1}" ', j, nodes[i].events[j]); + } + + /** + * Build the html to write to the document + * IMPORTANT: + * document.write()ing the string: '
    ', layerID, visibility, (nodes[i].cssClass ? nodes[i].cssClass : this.defaultClass)) : this.stringFormat('
    ', nodes[i].cssClass ? nodes[i].cssClass : this.defaultClass); + var onMDown = this.doesMenu() && nodes[i].n.length && nodes[i].isDynamic ? this.stringFormat('onmousedown="{0}.toggleBranch(\'{1}\', true)" style="cursor: pointer; cursor: hand"', this.myname, layerID) : ''; + var imgTag = this.stringFormat('', this.iconpath, gifname, modifier, layerID, onMDown); + var linkTarget= nodes[i].linkTarget ? nodes[i].linkTarget : this.linkTarget; + var linkStart = nodes[i].link ? this.stringFormat('', nodes[i].link, linkTarget) : ''; + + var linkEnd = nodes[i].link ? '' : ''; + + this.output += this.stringFormat('{0}{1}{2}{3}{4}{5}{6}{7}
    ', + layerTag, + nodes[i].menu_icons, + prepend, + parentLayerID == null && (nodes.length == 1 || this.noTopLevelImages) ? '' : imgTag, + iconimg, + linkStart, + eventHandlers, + nodes[i].title, + linkEnd); + + /** + * Traverse sub nodes ? + */ + if (nodes[i].n.length) { + /** + * Determine what to prepend. If there is only one root + * node then the prepend to pass to children is nothing. + * Otherwise it depends on where we are in the tree. + */ + if (parentLayerID == null && (nodes.length == 1 || this.noTopLevelImages)) { + var newPrepend = ''; + + } else if (i < (nodes.length - 1)) { + var newPrepend = prepend + this.stringFormat('', this.iconpath); + + } else { + var newPrepend = prepend + this.stringFormat('', this.iconpath); + } + + this.drawMenu(nodes[i].n, + arrayCopy(level), + newPrepend, + nodes[i].expanded, + expanded ? 'inline' : 'none', + layerID); + } + } + } + +/** +* Writes the output generated by drawMenu() to the page +*/ + TreeMenu.prototype.writeOutput = function () + { + document.write(this.output); + } + +/** +* Toggles a branches visible status. Called from resetBranches() +* and also when a +/- graphic is clicked. +*/ + TreeMenu.prototype.toggleBranch = function (layerID, updateStatus) // OPTIONAL ARGS: fireEvents = true + { + var currentDisplay = this.getLayer(layerID).style.display; + var newDisplay = (this.branchStatus[layerID] && currentDisplay == 'inline') ? 'none' : 'inline'; + var fireEvents = arguments[2] != null ? arguments[2] : true; + + for (var i=0; i= 5)); + var is_gecko = (agt.indexOf('gecko') != -1); + + + var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1)); + var is_ie4 = (is_ie && (is_major == 4) && (agt.indexOf("msie 4")!=-1) ); + var is_ie4up = (is_ie && (is_major >= 4)); + + var is_opera = (agt.indexOf("opera") != -1); + var is_opera7 = (is_opera && is_major >= 7) || agt.indexOf("opera 7") != -1; + + // Patch from Harald Fielker + if (agt.indexOf('konqueror') != -1) { + var is_nav = false; + var is_nav6up = false; + var is_gecko = false; + var is_ie = true; + var is_ie4 = true; + var is_ie4up = true; + } +//--> end hide JavaScript \ No newline at end of file diff --git a/hesk/inc/treemenu/index.htm b/hesk/inc/treemenu/index.htm new file mode 100644 index 0000000..d79f2c9 --- /dev/null +++ b/hesk/inc/treemenu/index.htm @@ -0,0 +1,8 @@ + + +403 Forbidden + +

    Forbidden

    +You don't have permission to access this folder.

    +


    + \ No newline at end of file diff --git a/hesk/inc/users_online.inc.php b/hesk/inc/users_online.inc.php new file mode 100644 index 0000000..9c33ca9 --- /dev/null +++ b/hesk/inc/users_online.inc.php @@ -0,0 +1,134 @@ + + + + '; + $i = ''; + foreach ($hesk_settings['users_online'] as $tmp) + { + $i .= ''; + $i .= ($tmp['id'] == $_SESSION['id']) ? $tmp['name'] : '' . $tmp['name'] . ''; + $i .= ', '; + } + echo substr($i,0,-2); + echo '
    '; + +} // END hesk_printOnline() + + +function hesk_listOnline($list_names=1) +{ + global $hesk_settings, $hesklang, $hesk_db_link; + + $users_online = array(); + + /* Clean expired entries */ + hesk_cleanOnline(); + + /* Get a list of online users */ + /* --> With names */ + if ($list_names) + { + $res = hesk_dbQuery("SELECT `t1`.`user_id` , `t2`.`name` , `t2`.`isadmin` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."online` AS `t1` INNER JOIN `".hesk_dbEscape($hesk_settings['db_pfix'])."users` AS `t2` ON `t1`.`user_id` = `t2`.`id`"); + while ($tmp = hesk_dbFetchAssoc($res)) + { + $users_online[$tmp['user_id']] = array( + 'id' => $tmp['user_id'], + 'name' => $tmp['name'], + 'isadmin' => $tmp['isadmin'] + ); + } + } + /* --> Without names */ + else + { + $res = hesk_dbQuery("SELECT `user_id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."online`"); + while ($tmp = hesk_dbFetchAssoc($res)) + { + $users_online[] = $tmp['user_id']; + } + } + + return $users_online; + +} // END hesk_listOnline() + + +function hesk_setOnline($user_id) +{ + global $hesk_settings, $hesklang, $hesk_db_link; + + /* If already online just update... */ + hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."online` SET `tmp` = `tmp` + 1 WHERE `user_id` = '".intval($user_id)."'"); + + /* ... else insert a new entry */ + if ( ! hesk_dbAffectedRows() ) + { + hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."online` (`user_id`) VALUES (".intval($user_id).") "); + } + + return true; + +} // END hesk_setOnline() + + +function hesk_setOffline($user_id) +{ + global $hesk_settings, $hesklang, $hesk_db_link; + + /* If already online just update... */ + hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."online` WHERE `user_id` = '".intval($user_id)."'"); + + return true; + +} // END hesk_setOffline() + + +function hesk_cleanOnline() +{ + global $hesk_settings, $hesklang, $hesk_db_link; + + /* Delete old rows from the database */ + hesk_dbQuery("DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."online` WHERE `dt` < ( NOW() - INTERVAL ".intval($hesk_settings['online_min'])." MINUTE) "); + + return true; +} // END hesk_cleanOnline() diff --git a/hesk/inc/zip/Zip.php b/hesk/inc/zip/Zip.php new file mode 100644 index 0000000..e584971 --- /dev/null +++ b/hesk/inc/zip/Zip.php @@ -0,0 +1,700 @@ + + * @copyright 2009-2013 A. Grandt + * @license GNU LGPL, Attribution required for commercial implementations, requested for everything else. + * @link http://www.phpclasses.org/package/6110 + * @link https://github.com/Grandt/PHPZip + * @version 1.37 + */ +class Zip { + const VERSION = 1.37; + + const ZIP_LOCAL_FILE_HEADER = "\x50\x4b\x03\x04"; // Local file header signature + const ZIP_CENTRAL_FILE_HEADER = "\x50\x4b\x01\x02"; // Central file header signature + const ZIP_END_OF_CENTRAL_DIRECTORY = "\x50\x4b\x05\x06\x00\x00\x00\x00"; //end of Central directory record + + const EXT_FILE_ATTR_DIR = "\x10\x00\xFF\x41"; + const EXT_FILE_ATTR_FILE = "\x00\x00\xFF\x81"; + + const ATTR_VERSION_TO_EXTRACT = "\x14\x00"; // Version needed to extract + const ATTR_MADE_BY_VERSION = "\x1E\x03"; // Made By Version + + private $zipMemoryThreshold = 1048576; // Autocreate tempfile if the zip data exceeds 1048576 bytes (1 MB) + + private $zipData = NULL; + private $zipFile = NULL; + private $zipComment = NULL; + private $cdRec = array(); // central directory + private $offset = 0; + private $isFinalized = FALSE; + private $addExtraField = TRUE; + + private $streamChunkSize = 65536; + private $streamFilePath = NULL; + private $streamTimeStamp = NULL; + private $streamComment = NULL; + private $streamFile = NULL; + private $streamData = NULL; + private $streamFileLength = 0; + + /** + * Constructor. + * + * @param boolean $useZipFile Write temp zip data to tempFile? Default FALSE + */ + function __construct($useZipFile = FALSE) { + if ($useZipFile) { + $this->zipFile = tmpfile(); + } else { + $this->zipData = ""; + } + } + + function __destruct() { + if (is_resource($this->zipFile)) { + fclose($this->zipFile); + } + $this->zipData = NULL; + } + + /** + * Extra fields on the Zip directory records are Unix time codes needed for compatibility on the default Mac zip archive tool. + * These are enabled as default, as they do no harm elsewhere and only add 26 bytes per file added. + * + * @param bool $setExtraField TRUE (default) will enable adding of extra fields, anything else will disable it. + */ + function setExtraField($setExtraField = TRUE) { + $this->addExtraField = ($setExtraField === TRUE); + } + + /** + * Set Zip archive comment. + * + * @param String $newComment New comment. NULL to clear. + * @return bool $success + */ + public function setComment($newComment = NULL) { + if ($this->isFinalized) { + return FALSE; + } + $this->zipComment = $newComment; + + return TRUE; + } + + /** + * Set zip file to write zip data to. + * This will cause all present and future data written to this class to be written to this file. + * This can be used at any time, even after the Zip Archive have been finalized. Any previous file will be closed. + * Warning: If the given file already exists, it will be overwritten. + * + * @param String $fileName + * @return bool $success + */ + public function setZipFile($fileName) { + if (is_file($fileName)) { + unlink($fileName); + } + $fd=fopen($fileName, "x+b"); + if (is_resource($this->zipFile)) { + rewind($this->zipFile); + while (!feof($this->zipFile)) { + fwrite($fd, fread($this->zipFile, $this->streamChunkSize)); + } + + fclose($this->zipFile); + } else { + fwrite($fd, $this->zipData); + $this->zipData = NULL; + } + $this->zipFile = $fd; + + return TRUE; + } + + /** + * Add an empty directory entry to the zip archive. + * Basically this is only used if an empty directory is added. + * + * @param String $directoryPath Directory Path and name to be added to the archive. + * @param int $timestamp (Optional) Timestamp for the added directory, if omitted or set to 0, the current time will be used. + * @param String $fileComment (Optional) Comment to be added to the archive for this directory. To use fileComment, timestamp must be given. + * @return bool $success + */ + public function addDirectory($directoryPath, $timestamp = 0, $fileComment = NULL) { + if ($this->isFinalized) { + return FALSE; + } + $directoryPath = str_replace("\\", "/", $directoryPath); + $directoryPath = rtrim($directoryPath, "/"); + + if (strlen($directoryPath) > 0) { + $this->buildZipEntry($directoryPath.'/', $fileComment, "\x00\x00", "\x00\x00", $timestamp, "\x00\x00\x00\x00", 0, 0, self::EXT_FILE_ATTR_DIR); + return TRUE; + } + return FALSE; + } + + /** + * Add a file to the archive at the specified location and file name. + * + * @param String $data File data. + * @param String $filePath Filepath and name to be used in the archive. + * @param int $timestamp (Optional) Timestamp for the added file, if omitted or set to 0, the current time will be used. + * @param String $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given. + * @return bool $success + */ + public function addFile($data, $filePath, $timestamp = 0, $fileComment = NULL) { + if ($this->isFinalized) { + return FALSE; + } + + if (is_resource($data) && get_resource_type($data) == "stream") { + $this->addLargeFile($data, $filePath, $timestamp, $fileComment); + return FALSE; + } + + $gzType = "\x08\x00"; // Compression type 8 = deflate + $gpFlags = "\x00\x00"; // General Purpose bit flags for compression type 8 it is: 0=Normal, 1=Maximum, 2=Fast, 3=super fast compression. + $dataLength = strlen($data); + $fileCRC32 = pack("V", crc32($data)); + + $gzData = gzcompress($data); + $gzData = substr(substr($gzData, 0, strlen($gzData) - 4), 2); // gzcompress adds a 2 byte header and 4 byte CRC we can't use. + // The 2 byte header does contain useful data, though in this case the 2 parameters we'd be interrested in will always be 8 for compression type, and 2 for General purpose flag. + $gzLength = strlen($gzData); + + if ($gzLength >= $dataLength) { + $gzLength = $dataLength; + $gzData = $data; + $gzType = "\x00\x00"; // Compression type 0 = stored + $gpFlags = "\x00\x00"; // Compression type 0 = stored + } + + if (!is_resource($this->zipFile) && ($this->offset + $gzLength) > $this->zipMemoryThreshold) { + $this->zipflush(); + } + + $this->buildZipEntry($filePath, $fileComment, $gpFlags, $gzType, $timestamp, $fileCRC32, $gzLength, $dataLength, self::EXT_FILE_ATTR_FILE); + + $this->zipwrite($gzData); + + return TRUE; + } + + /** + * Add the content to a directory. + * + * @author Adam Schmalhofer + * @author A. Grandt + * + * @param String $realPath Path on the file system. + * @param String $zipPath Filepath and name to be used in the archive. + * @param bool $recursive Add content recursively, default is TRUE. + * @param bool $followSymlinks Follow and add symbolic links, if they are accessible, default is TRUE. + * @param array &$addedFiles Reference to the added files, this is used to prevent duplicates, efault is an empty array. + * If you start the function by parsing an array, the array will be populated with the realPath + * and zipPath kay/value pairs added to the archive by the function. + */ + public function addDirectoryContent($realPath, $zipPath, $recursive = TRUE, $followSymlinks = TRUE, &$addedFiles = array()) { + if (file_exists($realPath) && !isset($addedFiles[realpath($realPath)])) { + if (is_dir($realPath)) { + $this->addDirectory($zipPath); + } + + $addedFiles[realpath($realPath)] = $zipPath; + + $iter = new DirectoryIterator($realPath); + foreach ($iter as $file) { + if ($file->isDot()) { + continue; + } + $newRealPath = $file->getPathname(); + $newZipPath = self::pathJoin($zipPath, $file->getFilename()); + + if (file_exists($newRealPath) && ($followSymlinks === TRUE || !is_link($newRealPath))) { + if ($file->isFile()) { + $addedFiles[realpath($newRealPath)] = $newZipPath; + $this->addLargeFile($newRealPath, $newZipPath); + } else if ($recursive === TRUE) { + $this->addDirectoryContent($newRealPath, $newZipPath, $recursive); + } else { + $this->addDirectory($zipPath); + } + } + } + } + } + + /** + * Add a file to the archive at the specified location and file name. + * + * @param String $dataFile File name/path. + * @param String $filePath Filepath and name to be used in the archive. + * @param int $timestamp (Optional) Timestamp for the added file, if omitted or set to 0, the current time will be used. + * @param String $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given. + * @return bool $success + */ + public function addLargeFile($dataFile, $filePath, $timestamp = 0, $fileComment = NULL) { + if ($this->isFinalized) { + return FALSE; + } + + if (is_string($dataFile) && is_file($dataFile)) { + $this->processFile($dataFile, $filePath, $timestamp, $fileComment); + } else if (is_resource($dataFile) && get_resource_type($dataFile) == "stream") { + $fh = $dataFile; + $this->openStream($filePath, $timestamp, $fileComment); + + while (!feof($fh)) { + $this->addStreamData(fread($fh, $this->streamChunkSize)); + } + $this->closeStream($this->addExtraField); + } + return TRUE; + } + + /** + * Create a stream to be used for large entries. + * + * @param String $filePath Filepath and name to be used in the archive. + * @param int $timestamp (Optional) Timestamp for the added file, if omitted or set to 0, the current time will be used. + * @param String $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given. + * @return bool $success + */ + public function openStream($filePath, $timestamp = 0, $fileComment = null) { + if (!function_exists('sys_get_temp_dir')) { + die ("ERROR: Zip " . self::VERSION . " requires PHP version 5.2.1 or above if large files are used."); + } + + if ($this->isFinalized) { + return FALSE; + } + + $this->zipflush(); + + if (strlen($this->streamFilePath) > 0) { + closeStream(); + } + + $this->streamFile = tempnam(sys_get_temp_dir(), 'Zip'); + $this->streamData = fopen($this->streamFile, "wb"); + $this->streamFilePath = $filePath; + $this->streamTimestamp = $timestamp; + $this->streamFileComment = $fileComment; + $this->streamFileLength = 0; + + return TRUE; + } + /** + * Add data to the open stream. + * + * @param String $data + * @return $length bytes added or FALSE if the archive is finalized or there are no open stream. + */ + public function addStreamData($data) { + if ($this->isFinalized || strlen($this->streamFilePath) == 0) { + return FALSE; + } + + $length = fwrite($this->streamData, $data, strlen($data)); + if ($length != strlen($data)) { + die ("

    Length mismatch

    \n"); + } + $this->streamFileLength += $length; + + return $length; + } + + /** + * Close the current stream. + * + * @return bool $success + */ + public function closeStream() { + if ($this->isFinalized || strlen($this->streamFilePath) == 0) { + return FALSE; + } + + fflush($this->streamData); + fclose($this->streamData); + + $this->processFile($this->streamFile, $this->streamFilePath, $this->streamTimestamp, $this->streamFileComment); + + $this->streamData = null; + $this->streamFilePath = null; + $this->streamTimestamp = null; + $this->streamFileComment = null; + $this->streamFileLength = 0; + + // Windows is a little slow at times, so a millisecond later, we can unlink this. + unlink($this->streamFile); + + $this->streamFile = null; + + return TRUE; + } + + private function processFile($dataFile, $filePath, $timestamp = 0, $fileComment = null) { + if ($this->isFinalized) { + return FALSE; + } + + $tempzip = tempnam(sys_get_temp_dir(), 'ZipStream'); + + $zip = new ZipArchive; + if ($zip->open($tempzip) === TRUE) { + $zip->addFile($dataFile, 'file'); + $zip->close(); + } + + $file_handle = fopen($tempzip, "rb"); + $stats = fstat($file_handle); + $eof = $stats['size']-72; + + fseek($file_handle, 6); + + $gpFlags = fread($file_handle, 2); + $gzType = fread($file_handle, 2); + fread($file_handle, 4); + $fileCRC32 = fread($file_handle, 4); + $v = unpack("Vval", fread($file_handle, 4)); + $gzLength = $v['val']; + $v = unpack("Vval", fread($file_handle, 4)); + $dataLength = $v['val']; + + $this->buildZipEntry($filePath, $fileComment, $gpFlags, $gzType, $timestamp, $fileCRC32, $gzLength, $dataLength, self::EXT_FILE_ATTR_FILE); + + fseek($file_handle, 34); + $pos = 34; + + while (!feof($file_handle) && $pos < $eof) { + $datalen = $this->streamChunkSize; + if ($pos + $this->streamChunkSize > $eof) { + $datalen = $eof-$pos; + } + $data = fread($file_handle, $datalen); + $pos += $datalen; + + $this->zipwrite($data); + + flush(); + } + + fclose($file_handle); + + unlink($tempzip); + } + + /** + * Close the archive. + * A closed archive can no longer have new files added to it. + * + * @return bool $success + */ + public function finalize() { + if (!$this->isFinalized) { + if (strlen($this->streamFilePath) > 0) { + $this->closeStream(); + } + $cd = implode("", $this->cdRec); + + $cdRecSize = pack("v", sizeof($this->cdRec)); + $cdRec = $cd . self::ZIP_END_OF_CENTRAL_DIRECTORY + . $cdRecSize . $cdRecSize + . pack("VV", strlen($cd), $this->offset); + if (!empty($this->zipComment)) { + $cdRec .= pack("v", strlen($this->zipComment)) . $this->zipComment; + } else { + $cdRec .= "\x00\x00"; + } + + $this->zipwrite($cdRec); + + $this->isFinalized = TRUE; + $cd = NULL; + $this->cdRec = NULL; + + return TRUE; + } + return FALSE; + } + + /** + * Get the handle ressource for the archive zip file. + * If the zip haven't been finalized yet, this will cause it to become finalized + * + * @return zip file handle + */ + public function getZipFile() { + if (!$this->isFinalized) { + $this->finalize(); + } + + $this->zipflush(); + + rewind($this->zipFile); + + return $this->zipFile; + } + + /** + * Get the zip file contents + * If the zip haven't been finalized yet, this will cause it to become finalized + * + * @return zip data + */ + public function getZipData() { + if (!$this->isFinalized) { + $this->finalize(); + } + if (!is_resource($this->zipFile)) { + return $this->zipData; + } else { + rewind($this->zipFile); + $filestat = fstat($this->zipFile); + return fread($this->zipFile, $filestat['size']); + } + } + + /** + * Send the archive as a zip download + * + * @param String $fileName The name of the Zip archive, ie. "archive.zip". + * @param String $contentType Content mime type. Optional, defaults to "application/zip". + * @return bool $success + */ + function sendZip($fileName, $contentType = "application/zip") { + if (!$this->isFinalized) { + $this->finalize(); + } + + $headerFile = null; + $headerLine = null; + if (!headers_sent($headerFile, $headerLine) or die("

    Error: Unable to send file $fileName. HTML Headers have already been sent from $headerFile in line $headerLine

    ")) { + if ((ob_get_contents() === FALSE || ob_get_contents() == '') or die("\n

    Error: Unable to send file $fileName.epub. Output buffer contains the following text (typically warnings or errors):
    " . ob_get_contents() . "

    ")) { + if (ini_get('zlib.output_compression')) { + ini_set('zlib.output_compression', 'Off'); + } + + header("Pragma: public"); + header("Last-Modified: " . gmdate("D, d M Y H:i:s T")); + header("Expires: 0"); + header("Accept-Ranges: bytes"); + header("Connection: close"); + header("Content-Type: " . $contentType); + header('Content-Disposition: attachment; filename="' . $fileName . '";'); + header("Content-Transfer-Encoding: binary"); + header("Content-Length: ". $this->getArchiveSize()); + + if (!is_resource($this->zipFile)) { + echo $this->zipData; + } else { + rewind($this->zipFile); + + while (!feof($this->zipFile)) { + echo fread($this->zipFile, $this->streamChunkSize); + } + } + } + return TRUE; + } + return FALSE; + } + + /** + * Return the current size of the archive + * + * @return $size Size of the archive + */ + public function getArchiveSize() { + if (!is_resource($this->zipFile)) { + return strlen($this->zipData); + } + $filestat = fstat($this->zipFile); + + return $filestat['size']; + } + + /** + * Calculate the 2 byte dostime used in the zip entries. + * + * @param int $timestamp + * @return 2-byte encoded DOS Date + */ + private function getDosTime($timestamp = 0) { + $timestamp = (int)$timestamp; + $oldTZ = @date_default_timezone_get(); + date_default_timezone_set('UTC'); + $date = ($timestamp == 0 ? getdate() : getdate($timestamp)); + date_default_timezone_set($oldTZ); + if ($date["year"] >= 1980) { + return pack("V", (($date["mday"] + ($date["mon"] << 5) + (($date["year"]-1980) << 9)) << 16) | + (($date["seconds"] >> 1) + ($date["minutes"] << 5) + ($date["hours"] << 11))); + } + return "\x00\x00\x00\x00"; + } + + /** + * Build the Zip file structures + * + * @param String $filePath + * @param String $fileComment + * @param String $gpFlags + * @param String $gzType + * @param int $timestamp + * @param string $fileCRC32 + * @param int $gzLength + * @param int $dataLength + * @param integer $extFileAttr Use self::EXT_FILE_ATTR_FILE for files, self::EXT_FILE_ATTR_DIR for Directories. + */ + private function buildZipEntry($filePath, $fileComment, $gpFlags, $gzType, $timestamp, $fileCRC32, $gzLength, $dataLength, $extFileAttr) { + $filePath = str_replace("\\", "/", $filePath); + $fileCommentLength = (empty($fileComment) ? 0 : strlen($fileComment)); + $timestamp = (int)$timestamp; + $timestamp = ($timestamp == 0 ? time() : $timestamp); + + $dosTime = $this->getDosTime($timestamp); + $tsPack = pack("V", $timestamp); + + $ux = "\x75\x78\x0B\x00\x01\x04\xE8\x03\x00\x00\x04\x00\x00\x00\x00"; + + if (!isset($gpFlags) || strlen($gpFlags) != 2) { + $gpFlags = "\x00\x00"; + } + + $isFileUTF8 = mb_check_encoding($filePath, "UTF-8") && !mb_check_encoding($filePath, "ASCII"); + $isCommentUTF8 = !empty($fileComment) && mb_check_encoding($fileComment, "UTF-8") && !mb_check_encoding($fileComment, "ASCII"); + if ($isFileUTF8 || $isCommentUTF8) { + $flag = 0; + $gpFlagsV = unpack("vflags", $gpFlags); + if (isset($gpFlagsV['flags'])) { + $flag = $gpFlagsV['flags']; + } + $gpFlags = pack("v", $flag | (1 << 11)); + } + + $header = $gpFlags . $gzType . $dosTime. $fileCRC32 + . pack("VVv", $gzLength, $dataLength, strlen($filePath)); // File name length + + $zipEntry = self::ZIP_LOCAL_FILE_HEADER; + $zipEntry .= self::ATTR_VERSION_TO_EXTRACT; + $zipEntry .= $header; + $zipEntry .= pack("v", ($this->addExtraField ? 28 : 0)); // Extra field length + $zipEntry .= $filePath; // FileName + // Extra fields + if ($this->addExtraField) { + $zipEntry .= "\x55\x54\x09\x00\x03" . $tsPack . $tsPack . $ux; + } + $this->zipwrite($zipEntry); + + $cdEntry = self::ZIP_CENTRAL_FILE_HEADER; + $cdEntry .= self::ATTR_MADE_BY_VERSION; + $cdEntry .= ($dataLength === 0 ? "\x0A\x00" : self::ATTR_VERSION_TO_EXTRACT); + $cdEntry .= $header; + $cdEntry .= pack("v", ($this->addExtraField ? 24 : 0)); // Extra field length + $cdEntry .= pack("v", $fileCommentLength); // File comment length + $cdEntry .= "\x00\x00"; // Disk number start + $cdEntry .= "\x00\x00"; // internal file attributes + $cdEntry .= $extFileAttr; // External file attributes + $cdEntry .= pack("V", $this->offset); // Relative offset of local header + $cdEntry .= $filePath; // FileName + // Extra fields + if ($this->addExtraField) { + $cdEntry .= "\x55\x54\x05\x00\x03" . $tsPack . $ux; + } + if (!empty($fileComment)) { + $cdEntry .= $fileComment; // Comment + } + + $this->cdRec[] = $cdEntry; + $this->offset += strlen($zipEntry) + $gzLength; + } + + private function zipwrite($data) { + if (!is_resource($this->zipFile)) { + $this->zipData .= $data; + } else { + fwrite($this->zipFile, $data); + fflush($this->zipFile); + } + } + + private function zipflush() { + if (!is_resource($this->zipFile)) { + $this->zipFile = tmpfile(); + fwrite($this->zipFile, $this->zipData); + $this->zipData = NULL; + } + } + + /** + * Join $file to $dir path, and clean up any excess slashes. + * + * @param String $dir + * @param String $file + */ + public static function pathJoin($dir, $file) { + if (empty($dir) || empty($file)) { + return self::getRelativePath($dir . $file); + } + return self::getRelativePath($dir . '/' . $file); + } + + /** + * Clean up a path, removing any unnecessary elements such as /./, // or redundant ../ segments. + * If the path starts with a "/", it is deemed an absolute path and any /../ in the beginning is stripped off. + * The returned path will not end in a "/". + * + * @param String $path The path to clean up + * @return String the clean path + */ + public static function getRelativePath($path) { + $path = preg_replace("#/+\.?/+#", "/", str_replace("\\", "/", $path)); + $dirs = explode("/", rtrim(preg_replace('#^(?:\./)+#', '', $path), '/')); + + $offset = 0; + $sub = 0; + $subOffset = 0; + $root = ""; + + if (empty($dirs[0])) { + $root = "/"; + $dirs = array_splice($dirs, 1); + } else if (preg_match("#[A-Za-z]:#", $dirs[0])) { + $root = strtoupper($dirs[0]) . "/"; + $dirs = array_splice($dirs, 1); + } + + $newDirs = array(); + foreach ($dirs as $dir) { + if ($dir !== "..") { + $subOffset--; + $newDirs[++$offset] = $dir; + } else { + $subOffset++; + if (--$offset < 0) { + $offset = 0; + if ($subOffset > $sub) { + $sub++; + } + } + } + } + + if (empty($root)) { + $root = str_repeat("../", $sub); + } + return $root . implode("/", array_slice($newDirs, 0, $offset)); + } +} +?> \ No newline at end of file diff --git a/hesk/inc/zip/index.htm b/hesk/inc/zip/index.htm new file mode 100644 index 0000000..d79f2c9 --- /dev/null +++ b/hesk/inc/zip/index.htm @@ -0,0 +1,8 @@ + + +403 Forbidden + +

    Forbidden

    +You don't have permission to access this folder.

    +


    + \ No newline at end of file diff --git a/hesk/inc/zip/pclzip.lib.php b/hesk/inc/zip/pclzip.lib.php new file mode 100644 index 0000000..c31f7a2 --- /dev/null +++ b/hesk/inc/zip/pclzip.lib.php @@ -0,0 +1,5695 @@ +zipname = $p_zipname; + $this->zip_fd = 0; + $this->magic_quotes_status = -1; + + // ----- Return + return; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // create($p_filelist, $p_add_dir="", $p_remove_dir="") + // create($p_filelist, $p_option, $p_option_value, ...) + // Description : + // This method supports two different synopsis. The first one is historical. + // This method creates a Zip Archive. The Zip file is created in the + // filesystem. The files and directories indicated in $p_filelist + // are added in the archive. See the parameters description for the + // supported format of $p_filelist. + // When a directory is in the list, the directory and its content is added + // in the archive. + // In this synopsis, the function takes an optional variable list of + // options. See bellow the supported options. + // Parameters : + // $p_filelist : An array containing file or directory names, or + // a string containing one filename or one directory name, or + // a string containing a list of filenames and/or directory + // names separated by spaces. + // $p_add_dir : A path to add before the real path of the archived file, + // in order to have it memorized in the archive. + // $p_remove_dir : A path to remove from the real path of the file to archive, + // in order to have a shorter path memorized in the archive. + // When $p_add_dir and $p_remove_dir are set, $p_remove_dir + // is removed first, before $p_add_dir is added. + // Options : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_COMMENT : + // PCLZIP_CB_PRE_ADD : + // PCLZIP_CB_POST_ADD : + // Return Values : + // 0 on failure, + // The list of the added files, with a status of the add action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function create($p_filelist) + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Set default values + $v_options = array(); + $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove from the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_ADD => 'optional', + PCLZIP_CB_POST_ADD => 'optional', + PCLZIP_OPT_NO_COMPRESSION => 'optional', + PCLZIP_OPT_COMMENT => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + //, PCLZIP_OPT_CRYPT => 'optional' + )); + if ($v_result != 1) { + return 0; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } + else if ($v_size > 2) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, + "Invalid number / type of arguments"); + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Init + $v_string_list = array(); + $v_att_list = array(); + $v_filedescr_list = array(); + $p_result_list = array(); + + // ----- Look if the $p_filelist is really an array + if (is_array($p_filelist)) { + + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; + } + + // ----- The list is a list of string names + else { + $v_string_list = $p_filelist; + } + } + + // ----- Look if the $p_filelist is a string + else if (is_string($p_filelist)) { + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); + } + + // ----- Invalid variable type for $p_filelist + else { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist"); + return 0; + } + + // ----- Reformat the string list + if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + if ($v_string != '') { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } + else { + } + } + } + + // ----- For each file in the list check the attributes + $v_supported_attributes + = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' + ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' + ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' + ,PCLZIP_ATT_FILE_MTIME => 'optional' + ,PCLZIP_ATT_FILE_CONTENT => 'optional' + ,PCLZIP_ATT_FILE_COMMENT => 'optional' + ); + foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, + $v_filedescr_list[], + $v_options, + $v_supported_attributes); + if ($v_result != 1) { + return 0; + } + } + + // ----- Expand the filelist (expand directories) + $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Call the create fct + $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Return + return $p_result_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // add($p_filelist, $p_add_dir="", $p_remove_dir="") + // add($p_filelist, $p_option, $p_option_value, ...) + // Description : + // This method supports two synopsis. The first one is historical. + // This methods add the list of files in an existing archive. + // If a file with the same name already exists, it is added at the end of the + // archive, the first one is still present. + // If the archive does not exist, it is created. + // Parameters : + // $p_filelist : An array containing file or directory names, or + // a string containing one filename or one directory name, or + // a string containing a list of filenames and/or directory + // names separated by spaces. + // $p_add_dir : A path to add before the real path of the archived file, + // in order to have it memorized in the archive. + // $p_remove_dir : A path to remove from the real path of the file to archive, + // in order to have a shorter path memorized in the archive. + // When $p_add_dir and $p_remove_dir are set, $p_remove_dir + // is removed first, before $p_add_dir is added. + // Options : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_COMMENT : + // PCLZIP_OPT_ADD_COMMENT : + // PCLZIP_OPT_PREPEND_COMMENT : + // PCLZIP_CB_PRE_ADD : + // PCLZIP_CB_POST_ADD : + // Return Values : + // 0 on failure, + // The list of the added files, with a status of the add action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function add($p_filelist) + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Set default values + $v_options = array(); + $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_ADD => 'optional', + PCLZIP_CB_POST_ADD => 'optional', + PCLZIP_OPT_NO_COMPRESSION => 'optional', + PCLZIP_OPT_COMMENT => 'optional', + PCLZIP_OPT_ADD_COMMENT => 'optional', + PCLZIP_OPT_PREPEND_COMMENT => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + //, PCLZIP_OPT_CRYPT => 'optional' + )); + if ($v_result != 1) { + return 0; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Init + $v_string_list = array(); + $v_att_list = array(); + $v_filedescr_list = array(); + $p_result_list = array(); + + // ----- Look if the $p_filelist is really an array + if (is_array($p_filelist)) { + + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; + } + + // ----- The list is a list of string names + else { + $v_string_list = $p_filelist; + } + } + + // ----- Look if the $p_filelist is a string + else if (is_string($p_filelist)) { + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); + } + + // ----- Invalid variable type for $p_filelist + else { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist"); + return 0; + } + + // ----- Reformat the string list + if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } + } + + // ----- For each file in the list check the attributes + $v_supported_attributes + = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' + ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' + ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' + ,PCLZIP_ATT_FILE_MTIME => 'optional' + ,PCLZIP_ATT_FILE_CONTENT => 'optional' + ,PCLZIP_ATT_FILE_COMMENT => 'optional' + ); + foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, + $v_filedescr_list[], + $v_options, + $v_supported_attributes); + if ($v_result != 1) { + return 0; + } + } + + // ----- Expand the filelist (expand directories) + $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Call the create fct + $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Return + return $p_result_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : listContent() + // Description : + // This public method, gives the list of the files and directories, with their + // properties. + // The properties of each entries in the list are (used also in other functions) : + // filename : Name of the file. For a create or add action it is the filename + // given by the user. For an extract function it is the filename + // of the extracted file. + // stored_filename : Name of the file / directory stored in the archive. + // size : Size of the stored file. + // compressed_size : Size of the file's data compressed in the archive + // (without the headers overhead) + // mtime : Last known modification date of the file (UNIX timestamp) + // comment : Comment associated with the file + // folder : true | false + // index : index of the file in the archive + // status : status of the action (depending of the action) : + // Values are : + // ok : OK ! + // filtered : the file / dir is not extracted (filtered by user) + // already_a_directory : the file can not be extracted because a + // directory with the same name already exists + // write_protected : the file can not be extracted because a file + // with the same name already exists and is + // write protected + // newer_exist : the file was not extracted because a newer file exists + // path_creation_fail : the file is not extracted because the folder + // does not exist and can not be created + // write_error : the file was not extracted because there was a + // error while writing the file + // read_error : the file was not extracted because there was a error + // while reading the file + // invalid_header : the file was not extracted because of an archive + // format error (bad file header) + // Note that each time a method can continue operating when there + // is an action error on a file, the error is only logged in the file status. + // Return Values : + // 0 on an unrecoverable failure, + // The list of the files in the archive. + // -------------------------------------------------------------------------------- + function listContent() + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Call the extracting fct + $p_list = array(); + if (($v_result = $this->privList($p_list)) != 1) + { + unset($p_list); + return(0); + } + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // extract($p_path="./", $p_remove_path="") + // extract([$p_option, $p_option_value, ...]) + // Description : + // This method supports two synopsis. The first one is historical. + // This method extract all the files / directories from the archive to the + // folder indicated in $p_path. + // If you want to ignore the 'root' part of path of the memorized files + // you can indicate this in the optional $p_remove_path parameter. + // By default, if a newer file with the same name already exists, the + // file is not extracted. + // + // If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions + // are used, the path indicated in PCLZIP_OPT_ADD_PATH is append + // at the end of the path value of PCLZIP_OPT_PATH. + // Parameters : + // $p_path : Path where the files and directories are to be extracted + // $p_remove_path : First part ('root' part) of the memorized path + // (if any similar) to remove while extracting. + // Options : + // PCLZIP_OPT_PATH : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_CB_PRE_EXTRACT : + // PCLZIP_CB_POST_EXTRACT : + // Return Values : + // 0 or a negative value on failure, + // The list of the extracted files, with a status of the action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function extract() + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Set default values + $v_options = array(); +// $v_path = "./"; + $v_path = ''; + $v_remove_path = ""; + $v_remove_all_path = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Default values for option + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; + + // ----- Look for arguments + if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional' + ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' + ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + )); + if ($v_result != 1) { + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Trace + + // ----- Call the extracting fct + $p_list = array(); + $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, + $v_remove_all_path, $v_options); + if ($v_result < 1) { + unset($p_list); + return(0); + } + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + + // -------------------------------------------------------------------------------- + // Function : + // extractByIndex($p_index, $p_path="./", $p_remove_path="") + // extractByIndex($p_index, [$p_option, $p_option_value, ...]) + // Description : + // This method supports two synopsis. The first one is historical. + // This method is doing a partial extract of the archive. + // The extracted files or folders are identified by their index in the + // archive (from 0 to n). + // Note that if the index identify a folder, only the folder entry is + // extracted, not all the files included in the archive. + // Parameters : + // $p_index : A single index (integer) or a string of indexes of files to + // extract. The form of the string is "0,4-6,8-12" with only numbers + // and '-' for range or ',' to separate ranges. No spaces or ';' + // are allowed. + // $p_path : Path where the files and directories are to be extracted + // $p_remove_path : First part ('root' part) of the memorized path + // (if any similar) to remove while extracting. + // Options : + // PCLZIP_OPT_PATH : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and + // not as files. + // The resulting content is in a new field 'content' in the file + // structure. + // This option must be used alone (any other options are ignored). + // PCLZIP_CB_PRE_EXTRACT : + // PCLZIP_CB_POST_EXTRACT : + // Return Values : + // 0 on failure, + // The list of the extracted files, with a status of the action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + //function extractByIndex($p_index, options...) + function extractByIndex($p_index) + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Set default values + $v_options = array(); +// $v_path = "./"; + $v_path = ''; + $v_remove_path = ""; + $v_remove_all_path = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Default values for option + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional' + ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' + ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + )); + if ($v_result != 1) { + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) { + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; + } + else { + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } + } + + // ----- Trace + + // ----- Trick + // Here I want to reuse extractByRule(), so I need to parse the $p_index + // with privParseOptions() + $v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index); + $v_options_trick = array(); + $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, + array (PCLZIP_OPT_BY_INDEX => 'optional' )); + if ($v_result != 1) { + return 0; + } + $v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX]; + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Call the extracting fct + if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) { + return(0); + } + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // delete([$p_option, $p_option_value, ...]) + // Description : + // This method removes files from the archive. + // If no parameters are given, then all the archive is emptied. + // Parameters : + // None or optional arguments. + // Options : + // PCLZIP_OPT_BY_INDEX : + // PCLZIP_OPT_BY_NAME : + // PCLZIP_OPT_BY_EREG : + // PCLZIP_OPT_BY_PREG : + // Return Values : + // 0 on failure, + // The list of the files which are still present in the archive. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function delete() + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Set default values + $v_options = array(); + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Look for arguments + if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional' )); + if ($v_result != 1) { + return 0; + } + } + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Call the delete fct + $v_list = array(); + if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) { + $this->privSwapBackMagicQuotes(); + unset($v_list); + return(0); + } + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : deleteByIndex() + // Description : + // ***** Deprecated ***** + // delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered. + // -------------------------------------------------------------------------------- + function deleteByIndex($p_index) + { + + $p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index); + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : properties() + // Description : + // This method gives the properties of the archive. + // The properties are : + // nb : Number of files in the archive + // comment : Comment associated with the archive file + // status : not_exist, ok + // Parameters : + // None + // Return Values : + // 0 on failure, + // An array with the archive properties. + // -------------------------------------------------------------------------------- + function properties() + { + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + $this->privSwapBackMagicQuotes(); + return(0); + } + + // ----- Default properties + $v_prop = array(); + $v_prop['comment'] = ''; + $v_prop['nb'] = 0; + $v_prop['status'] = 'not_exist'; + + // ----- Look if file exists + if (@is_file($this->zipname)) + { + // ----- Open the zip file + if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) + { + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + + // ----- Return + return 0; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privSwapBackMagicQuotes(); + return 0; + } + + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Set the user attributes + $v_prop['comment'] = $v_central_dir['comment']; + $v_prop['nb'] = $v_central_dir['entries']; + $v_prop['status'] = 'ok'; + } + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_prop; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : duplicate() + // Description : + // This method creates an archive by copying the content of an other one. If + // the archive already exist, it is replaced by the new one without any warning. + // Parameters : + // $p_archive : The filename of a valid archive, or + // a valid PclZip object. + // Return Values : + // 1 on success. + // 0 or a negative value on error (error code). + // -------------------------------------------------------------------------------- + function duplicate($p_archive) + { + $v_result = 1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Look if the $p_archive is a PclZip object + if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) + { + + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive->zipname); + } + + // ----- Look if the $p_archive is a string (so a filename) + else if (is_string($p_archive)) + { + + // ----- Check that $p_archive is a valid zip file + // TBC : Should also check the archive format + if (!is_file($p_archive)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'"); + $v_result = PCLZIP_ERR_MISSING_FILE; + } + else { + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive); + } + } + + // ----- Invalid variable + else + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : merge() + // Description : + // This method merge the $p_archive_to_add archive at the end of the current + // one ($this). + // If the archive ($this) does not exist, the merge becomes a duplicate. + // If the $p_archive_to_add archive does not exist, the merge is a success. + // Parameters : + // $p_archive_to_add : It can be directly the filename of a valid zip archive, + // or a PclZip object archive. + // Return Values : + // 1 on success, + // 0 or negative values on error (see below). + // -------------------------------------------------------------------------------- + function merge($p_archive_to_add) + { + $v_result = 1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Look if the $p_archive_to_add is a PclZip object + if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) + { + + // ----- Merge the archive + $v_result = $this->privMerge($p_archive_to_add); + } + + // ----- Look if the $p_archive_to_add is a string (so a filename) + else if (is_string($p_archive_to_add)) + { + + // ----- Create a temporary archive + $v_object_archive = new PclZip($p_archive_to_add); + + // ----- Merge the archive + $v_result = $this->privMerge($v_object_archive); + } + + // ----- Invalid variable + else + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + + + // -------------------------------------------------------------------------------- + // Function : errorCode() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function errorCode() + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + return(PclErrorCode()); + } + else { + return($this->error_code); + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : errorName() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function errorName($p_with_code=false) + { + $v_name = array ( PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR', + PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL', + PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL', + PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER', + PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE', + PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG', + PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP', + PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE', + PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL', + PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION', + PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT', + PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL', + PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL', + PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM', + PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', + PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE', + PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE', + PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', + PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION' + ,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE' + ,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION' + ); + + if (isset($v_name[$this->error_code])) { + $v_value = $v_name[$this->error_code]; + } + else { + $v_value = 'NoName'; + } + + if ($p_with_code) { + return($v_value.' ('.$this->error_code.')'); + } + else { + return($v_value); + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : errorInfo() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function errorInfo($p_full=false) + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + return(PclErrorString()); + } + else { + if ($p_full) { + return($this->errorName(true)." : ".$this->error_string); + } + else { + return($this->error_string." [code ".$this->error_code."]"); + } + } + } + // -------------------------------------------------------------------------------- + + +// -------------------------------------------------------------------------------- +// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS ***** +// ***** ***** +// ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY ***** +// -------------------------------------------------------------------------------- + + + + // -------------------------------------------------------------------------------- + // Function : privCheckFormat() + // Description : + // This method check that the archive exists and is a valid zip archive. + // Several level of check exists. (futur) + // Parameters : + // $p_level : Level of check. Default 0. + // 0 : Check the first bytes (magic codes) (default value)) + // 1 : 0 + Check the central directory (futur) + // 2 : 1 + Check each file header (futur) + // Return Values : + // true on success, + // false on error, the error code is set. + // -------------------------------------------------------------------------------- + function privCheckFormat($p_level=0) + { + $v_result = true; + + // ----- Reset the file system cache + clearstatcache(); + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Look if the file exits + if (!is_file($this->zipname)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'"); + return(false); + } + + // ----- Check that the file is readeable + if (!is_readable($this->zipname)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'"); + return(false); + } + + // ----- Check the magic code + // TBC + + // ----- Check the central header + // TBC + + // ----- Check each file header + // TBC + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privParseOptions() + // Description : + // This internal methods reads the variable list of arguments ($p_options_list, + // $p_size) and generate an array with the options and values ($v_result_list). + // $v_requested_options contains the options that can be present and those that + // must be present. + // $v_requested_options is an array, with the option value as key, and 'optional', + // or 'mandatory' as value. + // Parameters : + // See above. + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false) + { + $v_result=1; + + // ----- Read the options + $i=0; + while ($i<$p_size) { + + // ----- Check if the option is supported + if (!isset($v_requested_options[$p_options_list[$i]])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for next option + switch ($p_options_list[$i]) { + // ----- Look for options that request a path value + case PCLZIP_OPT_PATH : + case PCLZIP_OPT_REMOVE_PATH : + case PCLZIP_OPT_ADD_PATH : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE); + $i++; + break; + + case PCLZIP_OPT_TEMP_FILE_THRESHOLD : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + return PclZip::errorCode(); + } + + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); + return PclZip::errorCode(); + } + + // ----- Check the value + $v_value = $p_options_list[$i+1]; + if ((!is_integer($v_value)) || ($v_value<0)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + return PclZip::errorCode(); + } + + // ----- Get the value (and convert it in bytes) + $v_result_list[$p_options_list[$i]] = $v_value*1048576; + $i++; + break; + + case PCLZIP_OPT_TEMP_FILE_ON : + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); + return PclZip::errorCode(); + } + + $v_result_list[$p_options_list[$i]] = true; + break; + + case PCLZIP_OPT_TEMP_FILE_OFF : + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'"); + return PclZip::errorCode(); + } + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'"); + return PclZip::errorCode(); + } + + $v_result_list[$p_options_list[$i]] = true; + break; + + case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if ( is_string($p_options_list[$i+1]) + && ($p_options_list[$i+1] != '')) { + $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE); + $i++; + } + else { + } + break; + + // ----- Look for options that request an array of string for value + case PCLZIP_OPT_BY_NAME : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1]; + } + else if (is_array($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + $i++; + break; + + // ----- Look for options that request an EREG or PREG expression + case PCLZIP_OPT_BY_EREG : + // ereg() is deprecated starting with PHP 5.3. Move PCLZIP_OPT_BY_EREG + // to PCLZIP_OPT_BY_PREG + $p_options_list[$i] = PCLZIP_OPT_BY_PREG; + case PCLZIP_OPT_BY_PREG : + //case PCLZIP_OPT_CRYPT : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + $i++; + break; + + // ----- Look for options that takes a string + case PCLZIP_OPT_COMMENT : + case PCLZIP_OPT_ADD_COMMENT : + case PCLZIP_OPT_PREPEND_COMMENT : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, + "Missing parameter value for option '" + .PclZipUtilOptionText($p_options_list[$i]) + ."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, + "Wrong parameter value for option '" + .PclZipUtilOptionText($p_options_list[$i]) + ."'"); + + // ----- Return + return PclZip::errorCode(); + } + $i++; + break; + + // ----- Look for options that request an array of index + case PCLZIP_OPT_BY_INDEX : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_work_list = array(); + if (is_string($p_options_list[$i+1])) { + + // ----- Remove spaces + $p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', ''); + + // ----- Parse items + $v_work_list = explode(",", $p_options_list[$i+1]); + } + else if (is_integer($p_options_list[$i+1])) { + $v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1]; + } + else if (is_array($p_options_list[$i+1])) { + $v_work_list = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Reduce the index list + // each index item in the list must be a couple with a start and + // an end value : [0,3], [5-5], [8-10], ... + // ----- Check the format of each item + $v_sort_flag=false; + $v_sort_value=0; + for ($j=0; $j= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + $i++; + break; + + // ----- Look for options that request a call-back + case PCLZIP_CB_PRE_EXTRACT : + case PCLZIP_CB_POST_EXTRACT : + case PCLZIP_CB_PRE_ADD : + case PCLZIP_CB_POST_ADD : + /* for futur use + case PCLZIP_CB_PRE_DELETE : + case PCLZIP_CB_POST_DELETE : + case PCLZIP_CB_PRE_LIST : + case PCLZIP_CB_POST_LIST : + */ + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_function_name = $p_options_list[$i+1]; + + // ----- Check that the value is a valid existing function + if (!function_exists($v_function_name)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Set the attribute + $v_result_list[$p_options_list[$i]] = $v_function_name; + $i++; + break; + + default : + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, + "Unknown parameter '" + .$p_options_list[$i]."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Next options + $i++; + } + + // ----- Look for mandatory options + if ($v_requested_options !== false) { + for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { + // ----- Look for mandatory option + if ($v_requested_options[$key] == 'mandatory') { + // ----- Look if present + if (!isset($v_result_list[$key])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); + + // ----- Return + return PclZip::errorCode(); + } + } + } + } + + // ----- Look for default values + if (!isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { + + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privOptionDefaultThreshold() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privOptionDefaultThreshold(&$p_options) + { + $v_result=1; + + if (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) + || isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) { + return $v_result; + } + + // ----- Get 'memory_limit' configuration value + $v_memory_limit = ini_get('memory_limit'); + $v_memory_limit = trim($v_memory_limit); + $last = strtolower(substr($v_memory_limit, -1)); + + if($last == 'g') + //$v_memory_limit = $v_memory_limit*1024*1024*1024; + $v_memory_limit = $v_memory_limit*1073741824; + if($last == 'm') + //$v_memory_limit = $v_memory_limit*1024*1024; + $v_memory_limit = $v_memory_limit*1048576; + if($last == 'k') + $v_memory_limit = $v_memory_limit*1024; + + $p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit*PCLZIP_TEMPORARY_FILE_RATIO); + + + // ----- Sanity check : No threshold if value lower than 1M + if ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] < 1048576) { + unset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privFileDescrParseAtt() + // Description : + // Parameters : + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options=false) + { + $v_result=1; + + // ----- For each file in the list check the attributes + foreach ($p_file_list as $v_key => $v_value) { + + // ----- Check if the option is supported + if (!isset($v_requested_options[$v_key])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for attribute + switch ($v_key) { + case PCLZIP_ATT_FILE_NAME : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['filename'] = PclZipUtilPathReduction($v_value); + + if ($p_filedescr['filename'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + break; + + case PCLZIP_ATT_FILE_NEW_SHORT_NAME : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value); + + if ($p_filedescr['new_short_name'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + break; + + case PCLZIP_ATT_FILE_NEW_FULL_NAME : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value); + + if ($p_filedescr['new_full_name'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + break; + + // ----- Look for options that takes a string + case PCLZIP_ATT_FILE_COMMENT : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['comment'] = $v_value; + break; + + case PCLZIP_ATT_FILE_MTIME : + if (!is_integer($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". Integer expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['mtime'] = $v_value; + break; + + case PCLZIP_ATT_FILE_CONTENT : + $p_filedescr['content'] = $v_value; + break; + + default : + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, + "Unknown parameter '".$v_key."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for mandatory options + if ($v_requested_options !== false) { + for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { + // ----- Look for mandatory option + if ($v_requested_options[$key] == 'mandatory') { + // ----- Look if present + if (!isset($p_file_list[$key])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); + return PclZip::errorCode(); + } + } + } + } + + // end foreach + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privFileDescrExpand() + // Description : + // This method look for each item of the list to see if its a file, a folder + // or a string to be added as file. For any other type of files (link, other) + // just ignore the item. + // Then prepare the information that will be stored for that file. + // When its a folder, expand the folder with all the files that are in that + // folder (recursively). + // Parameters : + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + function privFileDescrExpand(&$p_filedescr_list, &$p_options) + { + $v_result=1; + + // ----- Create a result list + $v_result_list = array(); + + // ----- Look each entry + for ($i=0; $iprivCalculateStoredFilename($v_descr, $p_options); + + // ----- Add the descriptor in result list + $v_result_list[sizeof($v_result_list)] = $v_descr; + + // ----- Look for folder + if ($v_descr['type'] == 'folder') { + // ----- List of items in folder + $v_dirlist_descr = array(); + $v_dirlist_nb = 0; + if ($v_folder_handler = @opendir($v_descr['filename'])) { + while (($v_item_handler = @readdir($v_folder_handler)) !== false) { + + // ----- Skip '.' and '..' + if (($v_item_handler == '.') || ($v_item_handler == '..')) { + continue; + } + + // ----- Compose the full filename + $v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'].'/'.$v_item_handler; + + // ----- Look for different stored filename + // Because the name of the folder was changed, the name of the + // files/sub-folders also change + if (($v_descr['stored_filename'] != $v_descr['filename']) + && (!isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))) { + if ($v_descr['stored_filename'] != '') { + $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'].'/'.$v_item_handler; + } + else { + $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler; + } + } + + $v_dirlist_nb++; + } + + @closedir($v_folder_handler); + } + else { + // TBC : unable to open folder in read mode + } + + // ----- Expand each element of the list + if ($v_dirlist_nb != 0) { + // ----- Expand + if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) { + return $v_result; + } + + // ----- Concat the resulting list + $v_result_list = array_merge($v_result_list, $v_dirlist_descr); + } + else { + } + + // ----- Free local array + unset($v_dirlist_descr); + } + } + + // ----- Get the result list + $p_filedescr_list = $v_result_list; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCreate() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privCreate($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result=1; + $v_list_detail = array(); + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the file in write mode + if (($v_result = $this->privOpenFd('wb')) != 1) + { + // ----- Return + return $v_result; + } + + // ----- Add the list of files + $v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options); + + // ----- Close + $this->privCloseFd(); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAdd() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privAdd($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result=1; + $v_list_detail = array(); + + // ----- Look if the archive exists or is empty + if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0)) + { + + // ----- Do a create + $v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options); + + // ----- Return + return $v_result; + } + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the zip file + if (($v_result=$this->privOpenFd('rb')) != 1) + { + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + // ----- Go to beginning of File + @rewind($this->zip_fd); + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Open the temporary file in write mode + if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) + { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = $v_central_dir['offset']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Swap the file descriptor + // Here is a trick : I swap the temporary fd with the zip fd, in order to use + // the following methods on the temporary fil and not the real archive + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Add the files + $v_header_list = array(); + if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) + { + fclose($v_zip_temp_fd); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($this->zip_fd); + + // ----- Copy the block of file headers from the old archive + $v_size = $v_central_dir['size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($v_zip_temp_fd, $v_read_size); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Create the Central Dir files header + for ($i=0, $v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { + fclose($v_zip_temp_fd); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + $v_count++; + } + + // ----- Transform the header to a 'usable' info + $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + // ----- Zip file comment + $v_comment = $v_central_dir['comment']; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) { + $v_comment = $v_comment.$p_options[PCLZIP_OPT_ADD_COMMENT]; + } + if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT].$v_comment; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($this->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1) + { + // ----- Reset the file list + unset($v_header_list); + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + + // ----- Swap back the file descriptor + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Close + $this->privCloseFd(); + + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privOpenFd() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privOpenFd($p_mode) + { + $v_result=1; + + // ----- Look if already open + if ($this->zip_fd != 0) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Open the zip file + if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCloseFd() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privCloseFd() + { + $v_result=1; + + if ($this->zip_fd != 0) + @fclose($this->zip_fd); + $this->zip_fd = 0; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddList() + // Description : + // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is + // different from the real path of the file. This is usefull if you want to have PclTar + // running in any directory, and memorize relative path from an other directory. + // Parameters : + // $p_list : An array containing the file or directory names to add in the tar + // $p_result_list : list of added files with their properties (specially the status field) + // $p_add_dir : Path to add in the filename path archived + // $p_remove_dir : Path to remove in the filename path archived + // Return Values : + // -------------------------------------------------------------------------------- +// function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options) + function privAddList($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result=1; + + // ----- Add the files + $v_header_list = array(); + if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) + { + // ----- Return + return $v_result; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($this->zip_fd); + + // ----- Create the Central Dir files header + for ($i=0,$v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { + // ----- Return + return $v_result; + } + $v_count++; + } + + // ----- Transform the header to a 'usable' info + $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + // ----- Zip file comment + $v_comment = ''; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($this->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1) + { + // ----- Reset the file list + unset($v_header_list); + + // ----- Return + return $v_result; + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFileList() + // Description : + // Parameters : + // $p_filedescr_list : An array containing the file description + // or directory names to add in the zip + // $p_result_list : list of added files with their properties (specially the status field) + // Return Values : + // -------------------------------------------------------------------------------- + function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result=1; + $v_header = array(); + + // ----- Recuperate the current number of elt in list + $v_nb = sizeof($p_result_list); + + // ----- Loop on the files + for ($j=0; ($jprivAddFile($p_filedescr_list[$j], $v_header, + $p_options); + if ($v_result != 1) { + return $v_result; + } + + // ----- Store the file infos + $p_result_list[$v_nb++] = $v_header; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privAddFile($p_filedescr, &$p_header, &$p_options) + { + $v_result=1; + + // ----- Working variable + $p_filename = $p_filedescr['filename']; + + // TBC : Already done in the fileAtt check ... ? + if ($p_filename == "") { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for a stored different filename + /* TBC : Removed + if (isset($p_filedescr['stored_filename'])) { + $v_stored_filename = $p_filedescr['stored_filename']; + } + else { + $v_stored_filename = $p_filedescr['stored_filename']; + } + */ + + // ----- Set the file properties + clearstatcache(); + $p_header['version'] = 20; + $p_header['version_extracted'] = 10; + $p_header['flag'] = 0; + $p_header['compression'] = 0; + $p_header['crc'] = 0; + $p_header['compressed_size'] = 0; + $p_header['filename_len'] = strlen($p_filename); + $p_header['extra_len'] = 0; + $p_header['disk'] = 0; + $p_header['internal'] = 0; + $p_header['offset'] = 0; + $p_header['filename'] = $p_filename; +// TBC : Removed $p_header['stored_filename'] = $v_stored_filename; + $p_header['stored_filename'] = $p_filedescr['stored_filename']; + $p_header['extra'] = ''; + $p_header['status'] = 'ok'; + $p_header['index'] = -1; + + // ----- Look for regular file + if ($p_filedescr['type']=='file') { + $p_header['external'] = 0x00000000; + $p_header['size'] = filesize($p_filename); + } + + // ----- Look for regular folder + else if ($p_filedescr['type']=='folder') { + $p_header['external'] = 0x00000010; + $p_header['mtime'] = filemtime($p_filename); + $p_header['size'] = filesize($p_filename); + } + + // ----- Look for virtual file + else if ($p_filedescr['type'] == 'virtual_file') { + $p_header['external'] = 0x00000000; + $p_header['size'] = strlen($p_filedescr['content']); + } + + + // ----- Look for filetime + if (isset($p_filedescr['mtime'])) { + $p_header['mtime'] = $p_filedescr['mtime']; + } + else if ($p_filedescr['type'] == 'virtual_file') { + $p_header['mtime'] = time(); + } + else { + $p_header['mtime'] = filemtime($p_filename); + } + + // ------ Look for file comment + if (isset($p_filedescr['comment'])) { + $p_header['comment_len'] = strlen($p_filedescr['comment']); + $p_header['comment'] = $p_filedescr['comment']; + } + else { + $p_header['comment_len'] = 0; + $p_header['comment'] = ''; + } + + // ----- Look for pre-add callback + if (isset($p_options[PCLZIP_CB_PRE_ADD])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_header, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_ADD].'(PCLZIP_CB_PRE_ADD, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_ADD](PCLZIP_CB_PRE_ADD, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_header['status'] = "skipped"; + $v_result = 1; + } + + // ----- Update the informations + // Only some fields can be modified + if ($p_header['stored_filename'] != $v_local_header['stored_filename']) { + $p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']); + } + } + + // ----- Look for empty stored filename + if ($p_header['stored_filename'] == "") { + $p_header['status'] = "filtered"; + } + + // ----- Check the path length + if (strlen($p_header['stored_filename']) > 0xFF) { + $p_header['status'] = 'filename_too_long'; + } + + // ----- Look if no error, or file not skipped + if ($p_header['status'] == 'ok') { + + // ----- Look for a file + if ($p_filedescr['type'] == 'file') { + // ----- Look for using temporary file to zip + if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) + && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) + || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) + && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])) ) ) { + $v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options); + if ($v_result < PCLZIP_ERR_NO_ERROR) { + return $v_result; + } + } + + // ----- Use "in memory" zip algo + else { + + // ----- Open the source file + if (($v_file = @fopen($p_filename, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); + return PclZip::errorCode(); + } + + // ----- Read the file content + $v_content = @fread($v_file, $p_header['size']); + + // ----- Close the file + @fclose($v_file); + + // ----- Calculate the CRC + $p_header['crc'] = @crc32($v_content); + + // ----- Look for no compression + if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { + // ----- Set header parameters + $p_header['compressed_size'] = $p_header['size']; + $p_header['compression'] = 0; + } + + // ----- Look for normal compression + else { + // ----- Compress the content + $v_content = @gzdeflate($v_content); + + // ----- Set header parameters + $p_header['compressed_size'] = strlen($v_content); + $p_header['compression'] = 8; + } + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + @fclose($v_file); + return $v_result; + } + + // ----- Write the compressed (or not) content + @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); + + } + + } + + // ----- Look for a virtual file (a file from string) + else if ($p_filedescr['type'] == 'virtual_file') { + + $v_content = $p_filedescr['content']; + + // ----- Calculate the CRC + $p_header['crc'] = @crc32($v_content); + + // ----- Look for no compression + if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { + // ----- Set header parameters + $p_header['compressed_size'] = $p_header['size']; + $p_header['compression'] = 0; + } + + // ----- Look for normal compression + else { + // ----- Compress the content + $v_content = @gzdeflate($v_content); + + // ----- Set header parameters + $p_header['compressed_size'] = strlen($v_content); + $p_header['compression'] = 8; + } + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + @fclose($v_file); + return $v_result; + } + + // ----- Write the compressed (or not) content + @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); + } + + // ----- Look for a directory + else if ($p_filedescr['type'] == 'folder') { + // ----- Look for directory last '/' + if (@substr($p_header['stored_filename'], -1) != '/') { + $p_header['stored_filename'] .= '/'; + } + + // ----- Set the file properties + $p_header['size'] = 0; + //$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked + $p_header['external'] = 0x00000010; // Value for a folder : to be checked + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) + { + return $v_result; + } + } + } + + // ----- Look for post-add callback + if (isset($p_options[PCLZIP_CB_POST_ADD])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_header, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_POST_ADD].'(PCLZIP_CB_POST_ADD, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_ADD](PCLZIP_CB_POST_ADD, $v_local_header); + if ($v_result == 0) { + // ----- Ignored + $v_result = 1; + } + + // ----- Update the informations + // Nothing can be modified + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFileUsingTempFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options) + { + $v_result=PCLZIP_ERR_NO_ERROR; + + // ----- Working variable + $p_filename = $p_filedescr['filename']; + + + // ----- Open the source file + if (($v_file = @fopen($p_filename, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); + return PclZip::errorCode(); + } + + // ----- Creates a compressed temporary file + $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; + if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) { + fclose($v_file); + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); + return PclZip::errorCode(); + } + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = filesize($p_filename); + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($v_file, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @gzputs($v_file_compressed, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Close the file + @fclose($v_file); + @gzclose($v_file_compressed); + + // ----- Check the minimum file size + if (filesize($v_gzip_temp_name) < 18) { + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \''.$v_gzip_temp_name.'\' has invalid filesize - should be minimum 18 bytes'); + return PclZip::errorCode(); + } + + // ----- Extract the compressed attributes + if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); + return PclZip::errorCode(); + } + + // ----- Read the gzip file header + $v_binary_data = @fread($v_file_compressed, 10); + $v_data_header = unpack('a1id1/a1id2/a1cm/a1flag/Vmtime/a1xfl/a1os', $v_binary_data); + + // ----- Check some parameters + $v_data_header['os'] = bin2hex($v_data_header['os']); + + // ----- Read the gzip file footer + @fseek($v_file_compressed, filesize($v_gzip_temp_name)-8); + $v_binary_data = @fread($v_file_compressed, 8); + $v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data); + + // ----- Set the attributes + $p_header['compression'] = ord($v_data_header['cm']); + //$p_header['mtime'] = $v_data_header['mtime']; + $p_header['crc'] = $v_data_footer['crc']; + $p_header['compressed_size'] = filesize($v_gzip_temp_name)-18; + + // ----- Close the file + @fclose($v_file_compressed); + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + return $v_result; + } + + // ----- Add the compressed data + if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) + { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); + return PclZip::errorCode(); + } + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + fseek($v_file_compressed, 10); + $v_size = $p_header['compressed_size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($v_file_compressed, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Close the file + @fclose($v_file_compressed); + + // ----- Unlink the temporary file + @unlink($v_gzip_temp_name); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCalculateStoredFilename() + // Description : + // Based on file descriptor properties and global options, this method + // calculate the filename that will be stored in the archive. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privCalculateStoredFilename(&$p_filedescr, &$p_options) + { + $v_result=1; + + // ----- Working variables + $p_filename = $p_filedescr['filename']; + if (isset($p_options[PCLZIP_OPT_ADD_PATH])) { + $p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH]; + } + else { + $p_add_dir = ''; + } + if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) { + $p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH]; + } + else { + $p_remove_dir = ''; + } + if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + else { + $p_remove_all_dir = 0; + } + + + // ----- Look for full name change + if (isset($p_filedescr['new_full_name'])) { + // ----- Remove drive letter if any + $v_stored_filename = PclZipUtilTranslateWinPath($p_filedescr['new_full_name']); + } + + // ----- Look for path and/or short name change + else { + + // ----- Look for short name change + // Its when we cahnge just the filename but not the path + if (isset($p_filedescr['new_short_name'])) { + $v_path_info = pathinfo($p_filename); + $v_dir = ''; + if ($v_path_info['dirname'] != '') { + $v_dir = $v_path_info['dirname'].'/'; + } + $v_stored_filename = $v_dir.$p_filedescr['new_short_name']; + } + else { + // ----- Calculate the stored filename + $v_stored_filename = $p_filename; + } + + // ----- Look for all path to remove + if ($p_remove_all_dir) { + $v_stored_filename = basename($p_filename); + } + // ----- Look for partial path remove + else if ($p_remove_dir != "") { + if (substr($p_remove_dir, -1) != '/') + $p_remove_dir .= "/"; + + if ( (substr($p_filename, 0, 2) == "./") + || (substr($p_remove_dir, 0, 2) == "./")) { + + if ( (substr($p_filename, 0, 2) == "./") + && (substr($p_remove_dir, 0, 2) != "./")) { + $p_remove_dir = "./".$p_remove_dir; + } + if ( (substr($p_filename, 0, 2) != "./") + && (substr($p_remove_dir, 0, 2) == "./")) { + $p_remove_dir = substr($p_remove_dir, 2); + } + } + + $v_compare = PclZipUtilPathInclusion($p_remove_dir, + $v_stored_filename); + if ($v_compare > 0) { + if ($v_compare == 2) { + $v_stored_filename = ""; + } + else { + $v_stored_filename = substr($v_stored_filename, + strlen($p_remove_dir)); + } + } + } + + // ----- Remove drive letter if any + $v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename); + + // ----- Look for path to add + if ($p_add_dir != "") { + if (substr($p_add_dir, -1) == "/") + $v_stored_filename = $p_add_dir.$v_stored_filename; + else + $v_stored_filename = $p_add_dir."/".$v_stored_filename; + } + } + + // ----- Filename (reduce the path of stored name) + $v_stored_filename = PclZipUtilPathReduction($v_stored_filename); + $p_filedescr['stored_filename'] = $v_stored_filename; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privWriteFileHeader(&$p_header) + { + $v_result=1; + + // ----- Store the offset position of the file + $p_header['offset'] = ftell($this->zip_fd); + + // ----- Transform UNIX mtime to DOS format mdate/mtime + $v_date = getdate($p_header['mtime']); + $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; + $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; + + // ----- Packed data + $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, + $p_header['version_extracted'], $p_header['flag'], + $p_header['compression'], $v_mtime, $v_mdate, + $p_header['crc'], $p_header['compressed_size'], + $p_header['size'], + strlen($p_header['stored_filename']), + $p_header['extra_len']); + + // ----- Write the first 148 bytes of the header in the archive + fputs($this->zip_fd, $v_binary_data, 30); + + // ----- Write the variable fields + if (strlen($p_header['stored_filename']) != 0) + { + fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); + } + if ($p_header['extra_len'] != 0) + { + fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteCentralFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privWriteCentralFileHeader(&$p_header) + { + $v_result=1; + + // TBC + //for(reset($p_header); $key = key($p_header); next($p_header)) { + //} + + // ----- Transform UNIX mtime to DOS format mdate/mtime + $v_date = getdate($p_header['mtime']); + $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; + $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; + + + // ----- Packed data + $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, + $p_header['version'], $p_header['version_extracted'], + $p_header['flag'], $p_header['compression'], + $v_mtime, $v_mdate, $p_header['crc'], + $p_header['compressed_size'], $p_header['size'], + strlen($p_header['stored_filename']), + $p_header['extra_len'], $p_header['comment_len'], + $p_header['disk'], $p_header['internal'], + $p_header['external'], $p_header['offset']); + + // ----- Write the 42 bytes of the header in the zip file + fputs($this->zip_fd, $v_binary_data, 46); + + // ----- Write the variable fields + if (strlen($p_header['stored_filename']) != 0) + { + fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); + } + if ($p_header['extra_len'] != 0) + { + fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); + } + if ($p_header['comment_len'] != 0) + { + fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteCentralHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment) + { + $v_result=1; + + // ----- Packed data + $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, + $p_nb_entries, $p_size, + $p_offset, strlen($p_comment)); + + // ----- Write the 22 bytes of the header in the zip file + fputs($this->zip_fd, $v_binary_data, 22); + + // ----- Write the variable fields + if (strlen($p_comment) != 0) + { + fputs($this->zip_fd, $p_comment, strlen($p_comment)); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privList() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privList(&$p_list) + { + $v_result=1; + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the zip file + if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) + { + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + // ----- Go to beginning of Central Dir + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_central_dir['offset'])) + { + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read each entry + for ($i=0; $i<$v_central_dir['entries']; $i++) + { + // ----- Read the file header + if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) + { + $this->privSwapBackMagicQuotes(); + return $v_result; + } + $v_header['index'] = $i; + + // ----- Get the only interesting attributes + $this->privConvertHeader2FileInfo($v_header, $p_list[$i]); + unset($v_header); + } + + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privConvertHeader2FileInfo() + // Description : + // This function takes the file informations from the central directory + // entries and extract the interesting parameters that will be given back. + // The resulting file infos are set in the array $p_info + // $p_info['filename'] : Filename with full path. Given by user (add), + // extracted in the filesystem (extract). + // $p_info['stored_filename'] : Stored filename in the archive. + // $p_info['size'] = Size of the file. + // $p_info['compressed_size'] = Compressed size of the file. + // $p_info['mtime'] = Last modification date of the file. + // $p_info['comment'] = Comment associated with the file. + // $p_info['folder'] = true/false : indicates if the entry is a folder or not. + // $p_info['status'] = status of the action on the file. + // $p_info['crc'] = CRC of the file content. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privConvertHeader2FileInfo($p_header, &$p_info) + { + $v_result=1; + + // ----- Get the interesting attributes + $v_temp_path = PclZipUtilPathReduction($p_header['filename']); + $p_info['filename'] = $v_temp_path; + $v_temp_path = PclZipUtilPathReduction($p_header['stored_filename']); + $p_info['stored_filename'] = $v_temp_path; + $p_info['size'] = $p_header['size']; + $p_info['compressed_size'] = $p_header['compressed_size']; + $p_info['mtime'] = $p_header['mtime']; + $p_info['comment'] = $p_header['comment']; + $p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010); + $p_info['index'] = $p_header['index']; + $p_info['status'] = $p_header['status']; + $p_info['crc'] = $p_header['crc']; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractByRule() + // Description : + // Extract a file or directory depending of rules (by index, by name, ...) + // Parameters : + // $p_file_list : An array where will be placed the properties of each + // extracted file + // $p_path : Path to add while writing the extracted files + // $p_remove_path : Path to remove (from the file memorized path) while writing the + // extracted files. If the path does not match the file path, + // the file is extracted with its memorized path. + // $p_remove_path does not apply to 'list' mode. + // $p_path and $p_remove_path are commulative. + // Return Values : + // 1 on success,0 or less on error (see error code list) + // -------------------------------------------------------------------------------- + function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) + { + $v_result=1; + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Check the path + if ( ($p_path == "") + || ( (substr($p_path, 0, 1) != "/") + && (substr($p_path, 0, 3) != "../") + && (substr($p_path,1,2)!=":/"))) + $p_path = "./".$p_path; + + // ----- Reduce the path last (and duplicated) '/' + if (($p_path != "./") && ($p_path != "/")) + { + // ----- Look for the path end '/' + while (substr($p_path, -1) == "/") + { + $p_path = substr($p_path, 0, strlen($p_path)-1); + } + } + + // ----- Look for path to remove format (should end by /) + if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) + { + $p_remove_path .= '/'; + } + $p_remove_path_size = strlen($p_remove_path); + + // ----- Open the zip file + if (($v_result = $this->privOpenFd('rb')) != 1) + { + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Start at beginning of Central Dir + $v_pos_entry = $v_central_dir['offset']; + + // ----- Read each entry + $j_start = 0; + for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) + { + + // ----- Read next Central dir entry + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_pos_entry)) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the file header + $v_header = array(); + if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Store the index + $v_header['index'] = $i; + + // ----- Store the file position + $v_pos_entry = ftell($this->zip_fd); + + // ----- Look for the specific extract rules + $v_extract = false; + + // ----- Look for extract by name rule + if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) + && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { + + // ----- Look if the filename is in the list + for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) + && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_extract = true; + } + } + // ----- Look for a filename + elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { + $v_extract = true; + } + } + } + + // ----- Look for extract by ereg rule + // ereg() is deprecated with PHP 5.3 + /* + else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) + && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { + + if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) { + $v_extract = true; + } + } + */ + + // ----- Look for extract by preg rule + else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) + && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { + + if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) { + $v_extract = true; + } + } + + // ----- Look for extract by index rule + else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) + && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { + + // ----- Look if the index is in the list + for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + $v_extract = true; + } + if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + $j_start = $j+1; + } + + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { + break; + } + } + } + + // ----- Look for no rule, which means extract all the archive + else { + $v_extract = true; + } + + // ----- Check compression method + if ( ($v_extract) + && ( ($v_header['compression'] != 8) + && ($v_header['compression'] != 0))) { + $v_header['status'] = 'unsupported_compression'; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, + "Filename '".$v_header['stored_filename']."' is " + ."compressed by an unsupported compression " + ."method (".$v_header['compression'].") "); + + return PclZip::errorCode(); + } + } + + // ----- Check encrypted files + if (($v_extract) && (($v_header['flag'] & 1) == 1)) { + $v_header['status'] = 'unsupported_encryption'; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, + "Unsupported encryption for " + ." filename '".$v_header['stored_filename'] + ."'"); + + return PclZip::errorCode(); + } + } + + // ----- Look for real extraction + if (($v_extract) && ($v_header['status'] != 'ok')) { + $v_result = $this->privConvertHeader2FileInfo($v_header, + $p_file_list[$v_nb_extracted++]); + if ($v_result != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + $v_extract = false; + } + + // ----- Look for real extraction + if ($v_extract) + { + + // ----- Go to the file position + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_header['offset'])) + { + // ----- Close the zip file + $this->privCloseFd(); + + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for extraction as string + if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) { + + $v_string = ''; + + // ----- Extracting the file + $v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Set the file content + $p_file_list[$v_nb_extracted]['content'] = $v_string; + + // ----- Next extracted file + $v_nb_extracted++; + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + // ----- Look for extraction in standard output + elseif ( (isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) + && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) { + // ----- Extracting the file in standard output + $v_result1 = $this->privExtractFileInOutput($v_header, $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + // ----- Look for normal extraction + else { + // ----- Extracting the file + $v_result1 = $this->privExtractFile($v_header, + $p_path, $p_remove_path, + $p_remove_all_path, + $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + } + } + + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFile() + // Description : + // Parameters : + // Return Values : + // + // 1 : ... ? + // PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback + // -------------------------------------------------------------------------------- + function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) + { + $v_result=1; + + // ----- Read the file header + if (($v_result = $this->privReadFileHeader($v_header)) != 1) + { + // ----- Return + return $v_result; + } + + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + // ----- Look for all path to remove + if ($p_remove_all_path == true) { + // ----- Look for folder entry that not need to be extracted + if (($p_entry['external']&0x00000010)==0x00000010) { + + $p_entry['status'] = "filtered"; + + return $v_result; + } + + // ----- Get the basename of the path + $p_entry['filename'] = basename($p_entry['filename']); + } + + // ----- Look for path to remove + else if ($p_remove_path != "") + { + if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) + { + + // ----- Change the file status + $p_entry['status'] = "filtered"; + + // ----- Return + return $v_result; + } + + $p_remove_path_size = strlen($p_remove_path); + if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) + { + + // ----- Remove the path + $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size); + + } + } + + // ----- Add the path + if ($p_path != '') { + $p_entry['filename'] = $p_path."/".$p_entry['filename']; + } + + // ----- Check a base_dir_restriction + if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) { + $v_inclusion + = PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION], + $p_entry['filename']); + if ($v_inclusion == 0) { + + PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION, + "Filename '".$p_entry['filename']."' is " + ."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION"); + + return PclZip::errorCode(); + } + } + + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + } + + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Look for specific actions while the file exist + if (file_exists($p_entry['filename'])) + { + + // ----- Look if file is a directory + if (is_dir($p_entry['filename'])) + { + + // ----- Change the file status + $p_entry['status'] = "already_a_directory"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY, + "Filename '".$p_entry['filename']."' is " + ."already used by an existing directory"); + + return PclZip::errorCode(); + } + } + // ----- Look if file is write protected + else if (!is_writeable($p_entry['filename'])) + { + + // ----- Change the file status + $p_entry['status'] = "write_protected"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, + "Filename '".$p_entry['filename']."' exists " + ."and is write protected"); + + return PclZip::errorCode(); + } + } + + // ----- Look if the extracted file is older + else if (filemtime($p_entry['filename']) > $p_entry['mtime']) + { + // ----- Change the file status + if ( (isset($p_options[PCLZIP_OPT_REPLACE_NEWER])) + && ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) { + } + else { + $p_entry['status'] = "newer_exist"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, + "Newer version of '".$p_entry['filename']."' exists " + ."and option PCLZIP_OPT_REPLACE_NEWER is not selected"); + + return PclZip::errorCode(); + } + } + } + else { + } + } + + // ----- Check the directory availability and create it if necessary + else { + if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) + $v_dir_to_check = $p_entry['filename']; + else if (!strstr($p_entry['filename'], "/")) + $v_dir_to_check = ""; + else + $v_dir_to_check = dirname($p_entry['filename']); + + if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) { + + // ----- Change the file status + $p_entry['status'] = "path_creation_fail"; + + // ----- Return + //return $v_result; + $v_result = 1; + } + } + } + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) + { + // ----- Look for not compressed file + if ($p_entry['compression'] == 0) { + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) + { + + // ----- Change the file status + $p_entry['status'] = "write_error"; + + // ----- Return + return $v_result; + } + + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['compressed_size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + /* Try to speed up the code + $v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_binary_data, $v_read_size); + */ + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Closing the destination file + fclose($v_dest_file); + + // ----- Change the file mtime + touch($p_entry['filename'], $p_entry['mtime']); + + + } + else { + // ----- TBC + // Need to be finished + if (($p_entry['flag'] & 1) == 1) { + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.'); + return PclZip::errorCode(); + } + + + // ----- Look for using temporary file to unzip + if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) + && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) + || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) + && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])) ) ) { + $v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options); + if ($v_result < PCLZIP_ERR_NO_ERROR) { + return $v_result; + } + } + + // ----- Look for extract in memory + else { + + + // ----- Read the compressed file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + $v_file_content = @gzinflate($v_buffer); + unset($v_buffer); + if ($v_file_content === FALSE) { + + // ----- Change the file status + // TBC + $p_entry['status'] = "error"; + + return $v_result; + } + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { + + // ----- Change the file status + $p_entry['status'] = "write_error"; + + return $v_result; + } + + // ----- Write the uncompressed data + @fwrite($v_dest_file, $v_file_content, $p_entry['size']); + unset($v_file_content); + + // ----- Closing the destination file + @fclose($v_dest_file); + + } + + // ----- Change the file mtime + @touch($p_entry['filename'], $p_entry['mtime']); + } + + // ----- Look for chmod option + if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) { + + // ----- Change the mode of the file + @chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]); + } + + } + } + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } + + // ----- Look for post-extract callback + elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFileUsingTempFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privExtractFileUsingTempFile(&$p_entry, &$p_options) + { + $v_result=1; + + // ----- Creates a temporary file + $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; + if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) { + fclose($v_file); + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); + return PclZip::errorCode(); + } + + + // ----- Write gz file format header + $v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3)); + @fwrite($v_dest_file, $v_binary_data, 10); + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['compressed_size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Write gz file format footer + $v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']); + @fwrite($v_dest_file, $v_binary_data, 8); + + // ----- Close the temporary file + @fclose($v_dest_file); + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { + $p_entry['status'] = "write_error"; + return $v_result; + } + + // ----- Open the temporary gz file + if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) { + @fclose($v_dest_file); + $p_entry['status'] = "read_error"; + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); + return PclZip::errorCode(); + } + + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['size']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @gzread($v_src_file, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + @fclose($v_dest_file); + @gzclose($v_src_file); + + // ----- Delete the temporary file + @unlink($v_gzip_temp_name); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFileInOutput() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privExtractFileInOutput(&$p_entry, &$p_options) + { + $v_result=1; + + // ----- Read the file header + if (($v_result = $this->privReadFileHeader($v_header)) != 1) { + return $v_result; + } + + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + } + + // ----- Trace + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) { + // ----- Look for not compressed file + if ($p_entry['compressed_size'] == $p_entry['size']) { + + // ----- Read the file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Send the file to the output + echo $v_buffer; + unset($v_buffer); + } + else { + + // ----- Read the compressed file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + $v_file_content = gzinflate($v_buffer); + unset($v_buffer); + + // ----- Send the file to the output + echo $v_file_content; + unset($v_file_content); + } + } + } + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } + + // ----- Look for post-extract callback + elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } + + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFileAsString() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privExtractFileAsString(&$p_entry, &$p_string, &$p_options) + { + $v_result=1; + + // ----- Read the file header + $v_header = array(); + if (($v_result = $this->privReadFileHeader($v_header)) != 1) + { + // ----- Return + return $v_result; + } + + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + } + + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) { + // ----- Look for not compressed file + // if ($p_entry['compressed_size'] == $p_entry['size']) + if ($p_entry['compression'] == 0) { + + // ----- Reading the file + $p_string = @fread($this->zip_fd, $p_entry['compressed_size']); + } + else { + + // ----- Reading the file + $v_data = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + if (($p_string = @gzinflate($v_data)) === FALSE) { + // TBC + } + } + + // ----- Trace + } + else { + // TBC : error : can not extract a folder in a string + } + + } + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } + + // ----- Look for post-extract callback + elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Swap the content to header + $v_local_header['content'] = $p_string; + $p_string = ''; + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + + // ----- Swap back the content to header + $p_string = $v_local_header['content']; + unset($v_local_header['content']); + + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privReadFileHeader(&$p_header) + { + $v_result=1; + + // ----- Read the 4 bytes signature + $v_binary_data = @fread($this->zip_fd, 4); + $v_data = unpack('Vid', $v_binary_data); + + // ----- Check signature + if ($v_data['id'] != 0x04034b50) + { + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the first 42 bytes of the header + $v_binary_data = fread($this->zip_fd, 26); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 26) + { + $p_header['filename'] = ""; + $p_header['status'] = "invalid_header"; + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Extract the values + $v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data); + + // ----- Get filename + $p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']); + + // ----- Get extra_fields + if ($v_data['extra_len'] != 0) { + $p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']); + } + else { + $p_header['extra'] = ''; + } + + // ----- Extract properties + $p_header['version_extracted'] = $v_data['version']; + $p_header['compression'] = $v_data['compression']; + $p_header['size'] = $v_data['size']; + $p_header['compressed_size'] = $v_data['compressed_size']; + $p_header['crc'] = $v_data['crc']; + $p_header['flag'] = $v_data['flag']; + $p_header['filename_len'] = $v_data['filename_len']; + + // ----- Recuperate date in UNIX format + $p_header['mdate'] = $v_data['mdate']; + $p_header['mtime'] = $v_data['mtime']; + if ($p_header['mdate'] && $p_header['mtime']) + { + // ----- Extract time + $v_hour = ($p_header['mtime'] & 0xF800) >> 11; + $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; + $v_seconde = ($p_header['mtime'] & 0x001F)*2; + + // ----- Extract date + $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; + $v_month = ($p_header['mdate'] & 0x01E0) >> 5; + $v_day = $p_header['mdate'] & 0x001F; + + // ----- Get UNIX date format + $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); + + } + else + { + $p_header['mtime'] = time(); + } + + // TBC + //for(reset($v_data); $key = key($v_data); next($v_data)) { + //} + + // ----- Set the stored filename + $p_header['stored_filename'] = $p_header['filename']; + + // ----- Set the status field + $p_header['status'] = "ok"; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadCentralFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privReadCentralFileHeader(&$p_header) + { + $v_result=1; + + // ----- Read the 4 bytes signature + $v_binary_data = @fread($this->zip_fd, 4); + $v_data = unpack('Vid', $v_binary_data); + + // ----- Check signature + if ($v_data['id'] != 0x02014b50) + { + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the first 42 bytes of the header + $v_binary_data = fread($this->zip_fd, 42); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 42) + { + $p_header['filename'] = ""; + $p_header['status'] = "invalid_header"; + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Extract the values + $p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data); + + // ----- Get filename + if ($p_header['filename_len'] != 0) + $p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']); + else + $p_header['filename'] = ''; + + // ----- Get extra + if ($p_header['extra_len'] != 0) + $p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']); + else + $p_header['extra'] = ''; + + // ----- Get comment + if ($p_header['comment_len'] != 0) + $p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']); + else + $p_header['comment'] = ''; + + // ----- Extract properties + + // ----- Recuperate date in UNIX format + //if ($p_header['mdate'] && $p_header['mtime']) + // TBC : bug : this was ignoring time with 0/0/0 + if (1) + { + // ----- Extract time + $v_hour = ($p_header['mtime'] & 0xF800) >> 11; + $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; + $v_seconde = ($p_header['mtime'] & 0x001F)*2; + + // ----- Extract date + $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; + $v_month = ($p_header['mdate'] & 0x01E0) >> 5; + $v_day = $p_header['mdate'] & 0x001F; + + // ----- Get UNIX date format + $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); + + } + else + { + $p_header['mtime'] = time(); + } + + // ----- Set the stored filename + $p_header['stored_filename'] = $p_header['filename']; + + // ----- Set default status to ok + $p_header['status'] = 'ok'; + + // ----- Look if it is a directory + if (substr($p_header['filename'], -1) == '/') { + //$p_header['external'] = 0x41FF0010; + $p_header['external'] = 0x00000010; + } + + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCheckFileHeaders() + // Description : + // Parameters : + // Return Values : + // 1 on success, + // 0 on error; + // -------------------------------------------------------------------------------- + function privCheckFileHeaders(&$p_local_header, &$p_central_header) + { + $v_result=1; + + // ----- Check the static values + // TBC + if ($p_local_header['filename'] != $p_central_header['filename']) { + } + if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) { + } + if ($p_local_header['flag'] != $p_central_header['flag']) { + } + if ($p_local_header['compression'] != $p_central_header['compression']) { + } + if ($p_local_header['mtime'] != $p_central_header['mtime']) { + } + if ($p_local_header['filename_len'] != $p_central_header['filename_len']) { + } + + // ----- Look for flag bit 3 + if (($p_local_header['flag'] & 8) == 8) { + $p_local_header['size'] = $p_central_header['size']; + $p_local_header['compressed_size'] = $p_central_header['compressed_size']; + $p_local_header['crc'] = $p_central_header['crc']; + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadEndCentralDir() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privReadEndCentralDir(&$p_central_dir) + { + $v_result=1; + + // ----- Go to the end of the zip file + $v_size = filesize($this->zipname); + @fseek($this->zip_fd, $v_size); + if (@ftell($this->zip_fd) != $v_size) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\''); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- First try : look if this is an archive with no commentaries (most of the time) + // in this case the end of central dir is at 22 bytes of the file end + $v_found = 0; + if ($v_size > 26) { + @fseek($this->zip_fd, $v_size-22); + if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22)) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read for bytes + $v_binary_data = @fread($this->zip_fd, 4); + $v_data = @unpack('Vid', $v_binary_data); + + // ----- Check signature + if ($v_data['id'] == 0x06054b50) { + $v_found = 1; + } + + $v_pos = ftell($this->zip_fd); + } + + // ----- Go back to the maximum possible size of the Central Dir End Record + if (!$v_found) { + $v_maximum_size = 65557; // 0xFFFF + 22; + if ($v_maximum_size > $v_size) + $v_maximum_size = $v_size; + @fseek($this->zip_fd, $v_size-$v_maximum_size); + if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size)) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read byte per byte in order to find the signature + $v_pos = ftell($this->zip_fd); + $v_bytes = 0x00000000; + while ($v_pos < $v_size) + { + // ----- Read a byte + $v_byte = @fread($this->zip_fd, 1); + + // ----- Add the byte + //$v_bytes = ($v_bytes << 8) | Ord($v_byte); + // Note we mask the old value down such that once shifted we can never end up with more than a 32bit number + // Otherwise on systems where we have 64bit integers the check below for the magic number will fail. + $v_bytes = ( ($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte); + + // ----- Compare the bytes + if ($v_bytes == 0x504b0506) + { + $v_pos++; + break; + } + + $v_pos++; + } + + // ----- Look if not found end of central dir + if ($v_pos == $v_size) + { + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature"); + + // ----- Return + return PclZip::errorCode(); + } + } + + // ----- Read the first 18 bytes of the header + $v_binary_data = fread($this->zip_fd, 18); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 18) + { + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data)); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Extract the values + $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data); + + // ----- Check the global size + if (($v_pos + $v_data['comment_size'] + 18) != $v_size) { + + // ----- Removed in release 2.2 see readme file + // The check of the file size is a little too strict. + // Some bugs where found when a zip is encrypted/decrypted with 'crypt'. + // While decrypted, zip has training 0 bytes + if (0) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, + 'The central dir is not at the end of the archive.' + .' Some trailing bytes exists after the archive.'); + + // ----- Return + return PclZip::errorCode(); + } + } + + // ----- Get comment + if ($v_data['comment_size'] != 0) { + $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']); + } + else + $p_central_dir['comment'] = ''; + + $p_central_dir['entries'] = $v_data['entries']; + $p_central_dir['disk_entries'] = $v_data['disk_entries']; + $p_central_dir['offset'] = $v_data['offset']; + $p_central_dir['size'] = $v_data['size']; + $p_central_dir['disk'] = $v_data['disk']; + $p_central_dir['disk_start'] = $v_data['disk_start']; + + // TBC + //for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) { + //} + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDeleteByRule() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privDeleteByRule(&$p_result_list, &$p_options) + { + $v_result=1; + $v_list_detail = array(); + + // ----- Open the zip file + if (($v_result=$this->privOpenFd('rb')) != 1) + { + // ----- Return + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privCloseFd(); + return $v_result; + } + + // ----- Go to beginning of File + @rewind($this->zip_fd); + + // ----- Scan all the files + // ----- Start at beginning of Central Dir + $v_pos_entry = $v_central_dir['offset']; + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_pos_entry)) + { + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read each entry + $v_header_list = array(); + $j_start = 0; + for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) + { + + // ----- Read the file header + $v_header_list[$v_nb_extracted] = array(); + if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + + return $v_result; + } + + + // ----- Store the index + $v_header_list[$v_nb_extracted]['index'] = $i; + + // ----- Look for the specific extract rules + $v_found = false; + + // ----- Look for extract by name rule + if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) + && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { + + // ----- Look if the filename is in the list + for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) + && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_found = true; + } + elseif ( (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */ + && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_found = true; + } + } + // ----- Look for a filename + elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { + $v_found = true; + } + } + } + + // ----- Look for extract by ereg rule + // ereg() is deprecated with PHP 5.3 + /* + else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) + && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { + + if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { + $v_found = true; + } + } + */ + + // ----- Look for extract by preg rule + else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) + && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { + + if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { + $v_found = true; + } + } + + // ----- Look for extract by index rule + else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) + && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { + + // ----- Look if the index is in the list + for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + $v_found = true; + } + if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + $j_start = $j+1; + } + + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { + break; + } + } + } + else { + $v_found = true; + } + + // ----- Look for deletion + if ($v_found) + { + unset($v_header_list[$v_nb_extracted]); + } + else + { + $v_nb_extracted++; + } + } + + // ----- Look if something need to be deleted + if ($v_nb_extracted > 0) { + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Creates a temporary zip archive + $v_temp_zip = new PclZip($v_zip_temp_name); + + // ----- Open the temporary zip file in write mode + if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) { + $this->privCloseFd(); + + // ----- Return + return $v_result; + } + + // ----- Look which file need to be kept + for ($i=0; $izip_fd); + if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the file header + $v_local_header = array(); + if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Check that local file header is same as central file header + if ($this->privCheckFileHeaders($v_local_header, + $v_header_list[$i]) != 1) { + // TBC + } + unset($v_local_header); + + // ----- Write the file header + if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Read/write the data block + if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($v_temp_zip->zip_fd); + + // ----- Re-Create the Central Dir files header + for ($i=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Transform the header to a 'usable' info + $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + + // ----- Zip file comment + $v_comment = ''; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($v_temp_zip->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) { + // ----- Reset the file list + unset($v_header_list); + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Close + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Destroy the temporary archive + unset($v_temp_zip); + } + + // ----- Remove every files : reset the file + else if ($v_central_dir['entries'] != 0) { + $this->privCloseFd(); + + if (($v_result = $this->privOpenFd('wb')) != 1) { + return $v_result; + } + + if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) { + return $v_result; + } + + $this->privCloseFd(); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDirCheck() + // Description : + // Check if a directory exists, if not it creates it and all the parents directory + // which may be useful. + // Parameters : + // $p_dir : Directory path to check. + // Return Values : + // 1 : OK + // -1 : Unable to create directory + // -------------------------------------------------------------------------------- + function privDirCheck($p_dir, $p_is_dir=false) + { + $v_result = 1; + + + // ----- Remove the final '/' + if (($p_is_dir) && (substr($p_dir, -1)=='/')) + { + $p_dir = substr($p_dir, 0, strlen($p_dir)-1); + } + + // ----- Check the directory availability + if ((is_dir($p_dir)) || ($p_dir == "")) + { + return 1; + } + + // ----- Extract parent directory + $p_parent_dir = dirname($p_dir); + + // ----- Just a check + if ($p_parent_dir != $p_dir) + { + // ----- Look for parent directory + if ($p_parent_dir != "") + { + if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) + { + return $v_result; + } + } + } + + // ----- Create the directory + if (!@mkdir($p_dir, 0777)) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privMerge() + // Description : + // If $p_archive_to_add does not exist, the function exit with a success result. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privMerge(&$p_archive_to_add) + { + $v_result=1; + + // ----- Look if the archive_to_add exists + if (!is_file($p_archive_to_add->zipname)) + { + + // ----- Nothing to merge, so merge is a success + $v_result = 1; + + // ----- Return + return $v_result; + } + + // ----- Look if the archive exists + if (!is_file($this->zipname)) + { + + // ----- Do a duplicate + $v_result = $this->privDuplicate($p_archive_to_add->zipname); + + // ----- Return + return $v_result; + } + + // ----- Open the zip file + if (($v_result=$this->privOpenFd('rb')) != 1) + { + // ----- Return + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privCloseFd(); + return $v_result; + } + + // ----- Go to beginning of File + @rewind($this->zip_fd); + + // ----- Open the archive_to_add file + if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1) + { + $this->privCloseFd(); + + // ----- Return + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir_to_add = array(); + if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) + { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + return $v_result; + } + + // ----- Go to beginning of File + @rewind($p_archive_to_add->zip_fd); + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Open the temporary file in write mode + if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) + { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = $v_central_dir['offset']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Copy the files from the archive_to_add into the temporary file + $v_size = $v_central_dir_to_add['offset']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($v_zip_temp_fd); + + // ----- Copy the block of file headers from the old archive + $v_size = $v_central_dir['size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Copy the block of file headers from the archive_to_add + $v_size = $v_central_dir_to_add['size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Merge the file comments + $v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment']; + + // ----- Calculate the size of the (new) central header + $v_size = @ftell($v_zip_temp_fd)-$v_offset; + + // ----- Swap the file descriptor + // Here is a trick : I swap the temporary fd with the zip fd, in order to use + // the following methods on the temporary fil and not the real archive fd + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) + { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + @fclose($v_zip_temp_fd); + $this->zip_fd = null; + + // ----- Reset the file list + unset($v_header_list); + + // ----- Return + return $v_result; + } + + // ----- Swap back the file descriptor + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Close + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDuplicate() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privDuplicate($p_archive_filename) + { + $v_result=1; + + // ----- Look if the $p_archive_filename exists + if (!is_file($p_archive_filename)) + { + + // ----- Nothing to duplicate, so duplicate is a success. + $v_result = 1; + + // ----- Return + return $v_result; + } + + // ----- Open the zip file + if (($v_result=$this->privOpenFd('wb')) != 1) + { + // ----- Return + return $v_result; + } + + // ----- Open the temporary file in write mode + if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) + { + $this->privCloseFd(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = filesize($p_archive_filename); + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($v_zip_temp_fd, $v_read_size); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Close + $this->privCloseFd(); + + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privErrorLog() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privErrorLog($p_error_code=0, $p_error_string='') + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + PclError($p_error_code, $p_error_string); + } + else { + $this->error_code = $p_error_code; + $this->error_string = $p_error_string; + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privErrorReset() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privErrorReset() + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + PclErrorReset(); + } + else { + $this->error_code = 0; + $this->error_string = ''; + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDisableMagicQuotes() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privDisableMagicQuotes() + { + $v_result=1; + + // ----- Look if function exists + if ( (!function_exists("get_magic_quotes_runtime")) + || (!function_exists("set_magic_quotes_runtime"))) { + return $v_result; + } + + // ----- Look if already done + if ($this->magic_quotes_status != -1) { + return $v_result; + } + + // ----- Get and memorize the magic_quote value + $this->magic_quotes_status = @get_magic_quotes_runtime(); + + // ----- Disable magic_quotes + if ($this->magic_quotes_status == 1) { + @set_magic_quotes_runtime(0); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privSwapBackMagicQuotes() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privSwapBackMagicQuotes() + { + $v_result=1; + + // ----- Look if function exists + if ( (!function_exists("get_magic_quotes_runtime")) + || (!function_exists("set_magic_quotes_runtime"))) { + return $v_result; + } + + // ----- Look if something to do + if ($this->magic_quotes_status != -1) { + return $v_result; + } + + // ----- Swap back magic_quotes + if ($this->magic_quotes_status == 1) { + @set_magic_quotes_runtime($this->magic_quotes_status); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + } + // End of class + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilPathReduction() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function PclZipUtilPathReduction($p_dir) + { + $v_result = ""; + + // ----- Look for not empty path + if ($p_dir != "") { + // ----- Explode path by directory names + $v_list = explode("/", $p_dir); + + // ----- Study directories from last to first + $v_skip = 0; + for ($i=sizeof($v_list)-1; $i>=0; $i--) { + // ----- Look for current path + if ($v_list[$i] == ".") { + // ----- Ignore this directory + // Should be the first $i=0, but no check is done + } + else if ($v_list[$i] == "..") { + $v_skip++; + } + else if ($v_list[$i] == "") { + // ----- First '/' i.e. root slash + if ($i == 0) { + $v_result = "/".$v_result; + if ($v_skip > 0) { + // ----- It is an invalid path, so the path is not modified + // TBC + $v_result = $p_dir; + $v_skip = 0; + } + } + // ----- Last '/' i.e. indicates a directory + else if ($i == (sizeof($v_list)-1)) { + $v_result = $v_list[$i]; + } + // ----- Double '/' inside the path + else { + // ----- Ignore only the double '//' in path, + // but not the first and last '/' + } + } + else { + // ----- Look for item to skip + if ($v_skip > 0) { + $v_skip--; + } + else { + $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:""); + } + } + } + + // ----- Look for skip + if ($v_skip > 0) { + while ($v_skip > 0) { + $v_result = '../'.$v_result; + $v_skip--; + } + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilPathInclusion() + // Description : + // This function indicates if the path $p_path is under the $p_dir tree. Or, + // said in an other way, if the file or sub-dir $p_path is inside the dir + // $p_dir. + // The function indicates also if the path is exactly the same as the dir. + // This function supports path with duplicated '/' like '//', but does not + // support '.' or '..' statements. + // Parameters : + // Return Values : + // 0 if $p_path is not inside directory $p_dir + // 1 if $p_path is inside directory $p_dir + // 2 if $p_path is exactly the same as $p_dir + // -------------------------------------------------------------------------------- + function PclZipUtilPathInclusion($p_dir, $p_path) + { + $v_result = 1; + + // ----- Look for path beginning by ./ + if ( ($p_dir == '.') + || ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) { + $p_dir = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_dir, 1); + } + if ( ($p_path == '.') + || ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) { + $p_path = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_path, 1); + } + + // ----- Explode dir and path by directory separator + $v_list_dir = explode("/", $p_dir); + $v_list_dir_size = sizeof($v_list_dir); + $v_list_path = explode("/", $p_path); + $v_list_path_size = sizeof($v_list_path); + + // ----- Study directories paths + $i = 0; + $j = 0; + while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) { + + // ----- Look for empty dir (path reduction) + if ($v_list_dir[$i] == '') { + $i++; + continue; + } + if ($v_list_path[$j] == '') { + $j++; + continue; + } + + // ----- Compare the items + if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ( $v_list_path[$j] != '')) { + $v_result = 0; + } + + // ----- Next items + $i++; + $j++; + } + + // ----- Look if everything seems to be the same + if ($v_result) { + // ----- Skip all the empty items + while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++; + while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++; + + if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) { + // ----- There are exactly the same + $v_result = 2; + } + else if ($i < $v_list_dir_size) { + // ----- The path is shorter than the dir + $v_result = 0; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilCopyBlock() + // Description : + // Parameters : + // $p_mode : read/write compression mode + // 0 : src & dest normal + // 1 : src gzip, dest normal + // 2 : src normal, dest gzip + // 3 : src & dest gzip + // Return Values : + // -------------------------------------------------------------------------------- + function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode=0) + { + $v_result = 1; + + if ($p_mode==0) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_src, $v_read_size); + @fwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + else if ($p_mode==1) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @gzread($p_src, $v_read_size); + @fwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + else if ($p_mode==2) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_src, $v_read_size); + @gzwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + else if ($p_mode==3) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @gzread($p_src, $v_read_size); + @gzwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilRename() + // Description : + // This function tries to do a simple rename() function. If it fails, it + // tries to copy the $p_src file in a new $p_dest file and then unlink the + // first one. + // Parameters : + // $p_src : Old filename + // $p_dest : New filename + // Return Values : + // 1 on success, 0 on failure. + // -------------------------------------------------------------------------------- + function PclZipUtilRename($p_src, $p_dest) + { + $v_result = 1; + + // ----- Try to rename the files + if (!@rename($p_src, $p_dest)) { + + // ----- Try to copy & unlink the src + if (!@copy($p_src, $p_dest)) { + $v_result = 0; + } + else if (!@unlink($p_src)) { + $v_result = 0; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilOptionText() + // Description : + // Translate option value in text. Mainly for debug purpose. + // Parameters : + // $p_option : the option value. + // Return Values : + // The option text value. + // -------------------------------------------------------------------------------- + function PclZipUtilOptionText($p_option) + { + + $v_list = get_defined_constants(); + for (reset($v_list); $v_key = key($v_list); next($v_list)) { + $v_prefix = substr($v_key, 0, 10); + if (( ($v_prefix == 'PCLZIP_OPT') + || ($v_prefix == 'PCLZIP_CB_') + || ($v_prefix == 'PCLZIP_ATT')) + && ($v_list[$v_key] == $p_option)) { + return $v_key; + } + } + + $v_result = 'Unknown'; + + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilTranslateWinPath() + // Description : + // Translate windows path by replacing '\' by '/' and optionally removing + // drive letter. + // Parameters : + // $p_path : path to translate. + // $p_remove_disk_letter : true | false + // Return Values : + // The path translated. + // -------------------------------------------------------------------------------- + function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter=true) + { + if (stristr(php_uname(), 'windows')) { + // ----- Look for potential disk letter + if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) { + $p_path = substr($p_path, $v_position+1); + } + // ----- Change potential windows directory separator + if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) { + $p_path = strtr($p_path, '\\', '/'); + } + } + return $p_path; + } + // -------------------------------------------------------------------------------- + + +?> diff --git a/hesk/index.php b/hesk/index.php new file mode 100644 index 0000000..5b7f283 --- /dev/null +++ b/hesk/index.php @@ -0,0 +1,526 @@ + $messages)); + + return true; +} // END print_select_category() + + +function print_add_ticket() +{ + global $hesk_settings, $hesklang; + + // Connect to the database + hesk_load_database_functions(); + hesk_dbConnect(); + + // Load custom fields + require_once(HESK_PATH . 'inc/custom_fields.inc.php'); + + // Load calendar JS and CSS + define('CALENDAR',1); + + // Auto-focus first empty or error field + define('AUTOFOCUS', true); + + // Pre-populate fields + // Customer name + if ( isset($_REQUEST['name']) ) + { + $_SESSION['c_name'] = $_REQUEST['name']; + } + + // Customer email address + if ( isset($_REQUEST['email']) ) + { + $_SESSION['c_email'] = $_REQUEST['email']; + $_SESSION['c_email2'] = $_REQUEST['email']; + } + + // Priority + if ( isset($_REQUEST['priority']) ) + { + $_SESSION['c_priority'] = intval($_REQUEST['priority']); + } + + // Subject + if ( isset($_REQUEST['subject']) ) + { + $_SESSION['c_subject'] = $_REQUEST['subject']; + } + + // Message + if ( isset($_REQUEST['message']) ) + { + $_SESSION['c_message'] = $_REQUEST['message']; + } + + // Custom fields + foreach ($hesk_settings['custom_fields'] as $k=>$v) + { + if ($v['use']==1 && isset($_REQUEST[$k]) ) + { + $_SESSION['c_'.$k] = $_REQUEST[$k]; + } + } + + // Varibles for coloring the fields in case of errors + if ( ! isset($_SESSION['iserror'])) + { + $_SESSION['iserror'] = array(); + } + + if ( ! isset($_SESSION['isnotice'])) + { + $_SESSION['isnotice'] = array(); + } + + hesk_cleanSessionVars('already_submitted'); + + // Tell header to load reCaptcha API if needed + if ($hesk_settings['recaptcha_use']) + { + define('RECAPTCHA',1); + } + + // Get categories + $hesk_settings['categories'] = array(); + $res = hesk_dbQuery("SELECT `id`, `name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE `type`='0' ORDER BY `cat_order` ASC"); + while ($row=hesk_dbFetchAssoc($res)) + { + $hesk_settings['categories'][$row['id']] = $row['name']; + } + + $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); + } + } + + // Print header + $hesk_settings['tmp_title'] = $hesk_settings['hesk_title'] . ' - ' . $hesklang['submit_ticket']; + + $messages = hesk_get_messages(); + + $visible_custom_fields_before_message = array(); + $visible_custom_fields_after_message = array(); + $custom_fields_before_message = array(); + $custom_fields_after_message = array(); + foreach ($hesk_settings['custom_fields'] as $k=>$v) { + if ($v['use'] == 1 && hesk_is_custom_field_in_category($k, $category)) { + if ($v['type'] == 'checkbox') { + $k_value = array(); + if (isset($_SESSION["c_$k"]) && is_array($_SESSION["c_$k"])) { + foreach ($_SESSION["c_$k"] as $myCB) { + $k_value[] = stripslashes(hesk_input($myCB)); + } + } + } elseif (isset($_SESSION["c_$k"])) { + $k_value = stripslashes(hesk_input($_SESSION["c_$k"])); + } else { + $k_value = ''; + } + + switch ($v['type']) { + /* Radio box */ + case 'radio': + $v['iserror'] = in_array($k, $_SESSION['iserror']); + $v['name'] = $k; + + $v['value']['options'] = array(); + foreach ($v['value']['radio_options'] as $option) { + if (strlen($k_value) == 0) { + $k_value = $option; + $checked = empty($v['value']['no_default']); + } elseif ($k_value == $option) { + $k_value = $option; + $checked = true; + } else { + $checked = false; + } + + $v['value']['options'][] = array( + 'value' => $option, + 'selected' => $checked + ); + } + + if ($v['place'] == 0) { + $visible_custom_fields_before_message[] = $v; + $custom_fields_before_message[] = $v; + } else { + $visible_custom_fields_after_message[] = $v; + $custom_fields_after_message[] = $v; + } + break; + + /* Select drop-down box */ + case 'select': + $v['iserror'] = in_array($k, $_SESSION['iserror']); + $v['name'] = $k; + + $v['value']['options'] = array(); + foreach ($v['value']['select_options'] as $option) { + if ($k_value == $option) { + $k_value = $option; + $selected = true; + } else { + $selected = false; + } + + $v['value']['options'][] = array( + 'value' => $option, + 'selected' => $selected + ); + } + + if ($v['place'] == 0) { + $visible_custom_fields_before_message[] = $v; + $custom_fields_before_message[] = $v; + } else { + $visible_custom_fields_after_message[] = $v; + $custom_fields_after_message[] = $v; + } + break; + + /* Checkbox */ + case 'checkbox': + $v['iserror'] = in_array($k, $_SESSION['iserror']); + $v['name'] = $k; + + $v['value']['options'] = array(); + foreach ($v['value']['checkbox_options'] as $option) { + if (in_array($option, $k_value)) { + $checked = 'checked'; + } else { + $checked = ''; + } + + $v['value']['options'][] = array( + 'value' => $option, + 'selected' => $checked + ); + } + + if ($v['place'] == 0) { + $visible_custom_fields_before_message[] = $v; + $custom_fields_before_message[] = $v; + } else { + $visible_custom_fields_after_message[] = $v; + $custom_fields_after_message[] = $v; + } + break; + + /* Large text box */ + // Date + case 'textarea': + case 'date': + case 'email': + $v['original_value'] = $k_value; + $v['iserror'] = in_array($k, $_SESSION['iserror']); + $v['name'] = $k; + + if ($v['place'] == 0) { + $visible_custom_fields_before_message[] = $v; + $custom_fields_before_message[] = $v; + } else { + $visible_custom_fields_after_message[] = $v; + $custom_fields_after_message[] = $v; + } + break; + + // Hidden + case 'hidden': + if (strlen($k_value) != 0 || isset($_SESSION["c_$k"])) { + $v['value']['default_value'] = $k_value; + } + + $v['name'] = $k; + + if ($v['place'] == 0) { + $custom_fields_before_message[] = $v; + } else { + $custom_fields_after_message[] = $v; + } + break; + + /* Default text input */ + default: + if (strlen($k_value) != 0 || isset($_SESSION["c_$k"])) { + $v['value']['default_value'] = $k_value; + } + + $v['iserror'] = in_array($k, $_SESSION['iserror']); + $v['name'] = $k; + + if ($v['place'] == 0) { + $visible_custom_fields_before_message[] = $v; + $custom_fields_before_message[] = $v; + } else { + $visible_custom_fields_after_message[] = $v; + $custom_fields_after_message[] = $v; + } + } + } + } + + $hesk_settings['render_template'](TEMPLATE_PATH . 'customer/create-ticket/create-ticket.php', array( + 'categoryId' => $category, + 'categoryName' => $hesk_settings['categories'][$category], + 'messages' => $messages, + 'visibleCustomFieldsBeforeMessage' => $visible_custom_fields_before_message, + 'visibleCustomFieldsAfterMessage' => $visible_custom_fields_after_message, + 'customFieldsBeforeMessage' => $custom_fields_before_message, + 'customFieldsAfterMessage' => $custom_fields_after_message + )); + + hesk_cleanSessionVars('iserror'); + hesk_cleanSessionVars('isnotice'); + + return true; +} // End print_add_ticket() + + +function print_start() +{ + global $hesk_settings, $hesklang; + + // Connect to database + hesk_load_database_functions(); + hesk_dbConnect(); + + // Include KB functionality only if we have any public articles + + $top_articles = array(); + $latest_articles = array(); + has_public_kb(); + if ($hesk_settings['kb_enable']) + { + require(HESK_PATH . 'inc/knowledgebase_functions.inc.php'); + + /* Get list of top articles */ + $top_articles = hesk_kbTopArticles($hesk_settings['kb_index_popart']); + + /* Get list of latest articles */ + $latest_articles = hesk_kbLatestArticles($hesk_settings['kb_index_latest']); + } + + // Service Messages + $res = hesk_dbQuery('SELECT `title`, `message`, `style` FROM `'.hesk_dbEscape($hesk_settings['db_pfix'])."service_messages` WHERE `type`='0' AND (`language` IS NULL OR `language` LIKE '".hesk_dbEscape($hesk_settings['language'])."') ORDER BY `order` ASC"); + $service_messages = array(); + while ($sm=hesk_dbFetchAssoc($res)) + { + $service_messages[] = $sm; + } + + $hesk_settings['render_template'](TEMPLATE_PATH . '/customer/index.php', array( + 'top_articles' => $top_articles, + 'latest_articles' => $latest_articles, + 'service_messages' => $service_messages + )); +} // End print_start() + + +function forgot_tid() +{ + global $hesk_settings, $hesklang; + + require(HESK_PATH . 'inc/email_functions.inc.php'); + + $email = hesk_emailCleanup( hesk_validateEmail( hesk_POST('email'), 'ERR' ,0) ) or hesk_process_messages($hesklang['enter_valid_email'],'ticket.php?remind=1'); + + if ( isset($_POST['open_only']) ) + { + $hesk_settings['open_only'] = $_POST['open_only'] == 1 ? 1 : 0; + } + + /* Get ticket(s) from database */ + hesk_load_database_functions(); + hesk_dbConnect(); + + // Get tickets from the database + $res = hesk_dbQuery('SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'tickets` FORCE KEY (`statuses`) WHERE ' . ($hesk_settings['open_only'] ? "`status` IN ('0','1','2','4','5') AND " : '') . ' ' . hesk_dbFormatEmail($email) . ' ORDER BY `status` ASC, `lastchange` DESC '); + + $num = hesk_dbNumRows($res); + if ($num < 1) + { + if ($hesk_settings['open_only']) + { + hesk_process_messages($hesklang['noopen'],'ticket.php?remind=1&e='.rawurlencode($email)); + } + else + { + hesk_process_messages($hesklang['tid_not_found'],'ticket.php?remind=1&e='.rawurlencode($email)); + } + } + + $tid_list = ''; + $name = ''; + + $email_param = $hesk_settings['email_view_ticket'] ? '&e='.rawurlencode($email) : ''; + + while ($my_ticket=hesk_dbFetchAssoc($res)) + { + $name = $name ? $name : hesk_msgToPlain($my_ticket['name'], 1, 0); +$tid_list .= " +$hesklang[trackID]: " . $my_ticket['trackid'] . " +$hesklang[subject]: " . hesk_msgToPlain($my_ticket['subject'], 1, 0) . " +$hesklang[status]: " . hesk_get_status_name($my_ticket['status']) . " +$hesk_settings[hesk_url]/ticket.php?track={$my_ticket['trackid']}{$email_param} +"; + } + + /* Get e-mail message for customer */ + $msg = hesk_getEmailMessage('forgot_ticket_id','',0,0,1); + $msg = str_replace('%%NAME%%', $name, $msg); + $msg = str_replace('%%NUM%%', $num, $msg); + $msg = str_replace('%%LIST_TICKETS%%', $tid_list, $msg); + $msg = str_replace('%%SITE_TITLE%%', hesk_msgToPlain($hesk_settings['site_title'], 1), $msg); + $msg = str_replace('%%SITE_URL%%', $hesk_settings['site_url'], $msg); + + $subject = hesk_getEmailSubject('forgot_ticket_id'); + + /* Send e-mail */ + hesk_mail($email, $subject, $msg); + + /* Show success message */ + $tmp = ''.$hesklang['tid_sent'].'!'; + $tmp .= '
     
    '.$hesklang['tid_sent2'].'.'; + $tmp .= '
     
    '.$hesklang['check_spambox']; + hesk_process_messages($tmp,'ticket.php?e='.$email,'SUCCESS'); + exit(); + +} // End forgot_tid() + + +function has_public_kb($use_cache=1) +{ + global $hesk_settings; + + // Return if KB is disabled + if ( ! $hesk_settings['kb_enable']) + { + return 0; + } + + // Do we have a cached version available + $cache_dir = $hesk_settings['cache_dir'].'/'; + $cache_file = $cache_dir . 'kb.cache.php'; + + if ($use_cache && file_exists($cache_file)) + { + require($cache_file); + return $hesk_settings['kb_enable']; + } + + // Make sure we have database connection + hesk_load_database_functions(); + hesk_dbConnect(); + + // Do we have any public articles at all? + $res = hesk_dbQuery("SELECT `t1`.`id` 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`='0' AND `t2`.`type`='0' LIMIT 1"); + + // If no public articles, disable the KB functionality + if (hesk_dbNumRows($res) < 1) + { + $hesk_settings['kb_enable'] = 0; + } + + // Try to cache results + if ($use_cache && (is_dir($cache_dir) || ( @mkdir($cache_dir, 0777) && is_writable($cache_dir) ) ) ) + { + // Is there an index.htm file? + if ( ! file_exists($cache_dir.'index.htm')) + { + @file_put_contents($cache_dir.'index.htm', ''); + } + + // Write data + @file_put_contents($cache_file, '{}[]"; + + var combinations = 0; + + if (hesk_contains(password, numbers) > 0) { + combinations += 10; + } + + if (hesk_contains(password, lowercase) > 0) { + combinations += 26; + } + + if (hesk_contains(password, uppercase) > 0) { + combinations += 26; + } + + if (hesk_contains(password, punctuation) > 0) { + combinations += punctuation.length; + } + + var totalCombinations = Math.pow(combinations, password.length); + var timeInSeconds = (totalCombinations / 200) / 2; + var timeInDays = timeInSeconds / 86400 + var lifetime = 365000; + var percentage = timeInDays / lifetime; + + var friendlyPercentage = hesk_cap(Math.round(percentage * 100), 98); + + if (friendlyPercentage < (password.length * 5)) { + friendlyPercentage += password.length * 5; + } + + var friendlyPercentage = hesk_cap(friendlyPercentage, 98); + + var progressBar = document.getElementById("progressBar"); + progressBar.style.width = friendlyPercentage + "%"; + + if (percentage > 1) { + // strong password + progressBar.style.backgroundColor = "#3bce08"; + return; + } + + if (percentage > 0.5) { + // reasonable password + progressBar.style.backgroundColor = "#ffd801"; + return; + } + + if (percentage > 0.10) { + // weak password + progressBar.style.backgroundColor = "orange"; + return; + } + + if (percentage <= 0.10) { + // very weak password + progressBar.style.backgroundColor = "red"; + return; + } + +} + +function hesk_cap(number, max) { + if (number > max) { + return max; + } else { + return number; + } +} + +function hesk_contains(password, validChars) { + + count = 0; + + for (i = 0; i < password.length; i++) { + var char = password.charAt(i); + if (validChars.indexOf(char) > -1) { + count++; + } + } + + return count; +} + +function setCookie(name, value, expires, path, domain, secure) +{ + document.cookie= name + "=" + escape(value) + + ((expires) ? "; expires=" + expires.toGMTString() : "") + + ((path) ? "; path=" + path : "") + + ((domain) ? "; domain=" + domain : "") + + ((secure) ? "; secure" : ""); +} + +function getCookie(name) +{ + var dc = document.cookie; + var prefix = name + "="; + var begin = dc.indexOf("; " + prefix); + if (begin == -1) { + begin = dc.indexOf(prefix); + if (begin != 0) return null; + } else { + begin += 2; + } + var end = document.cookie.indexOf(";", begin); + if (end == -1) { + end = dc.length; + } + return unescape(dc.substring(begin + prefix.length, end)); +} + +function deleteCookie(name, path, domain) +{ + if (getCookie(name)) { + document.cookie = name + "=" + + ((path) ? "; path=" + path : "") + + ((domain) ? "; domain=" + domain : "") + + "; expires=Thu, 01-Jan-70 00:00:01 GMT"; + } +} \ No newline at end of file diff --git a/hesk/install/hesk_style.css b/hesk/install/hesk_style.css new file mode 100644 index 0000000..a02fcbf --- /dev/null +++ b/hesk/install/hesk_style.css @@ -0,0 +1,961 @@ +body { + background-color: #f3fef4; + color: black; + font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 12px; + margin-left:0; + margin-right:0; + margin-top:0; + margin-bottom:0; +} + +table.enclosing { + background-color:#FFFFFF; + color : #4a5571; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 12px; + width: 960px; +} + +td { + color : #4a5571; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 12px; + text-align: left; +} + +a img { + vertical-align: bottom; + border : none; +} + +td.white { + background-color: #FFFFFF; + color : #4a5571; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 12px; +} + +td.admin_white { + background-color: #FFFFFF; + color : #4a5571; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 11px; + border: #d1dceb 1px solid; + padding: 1px; +} + +td.admin_gray { + background-color: #f5fffa; + color : #4a5571; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 11px; + border: #d1dceb 1px solid; + padding: 1px; +} + +td.notes { + background-color: #fffbf2; + color : #4a5571; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 12px; + border: #ffe6b8 1px solid; +} + +th.tDetailsHead { + background-color: #F7F7F7; + color : #4a5571; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 12px; + font-weight: normal; + text-align: center; +} + +td.tDetailsBody { + background-color: #FFFFFF; + color : #4a5571; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 12px; + border: #F7F7F7 1px solid; + text-align: center; +} + +.small { + font-size: 11px; +} + +.smaller { + font-size: 10px; +} + +a { + color : Blue; + text-decoration : underline; +} + +a:hover { + color : Red; + text-decoration : none; +} + +a.smaller { + font-size: 10px; + color : Blue; + text-decoration : underline; +} + +a.smaller:hover { + font-size: 10px; + color : Red; + text-decoration : none; +} + +table.white { + background-color: #ffffff ; + color : #23559C; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 12px; + border-collapse: collapse; +} + +table.white th { + background-color: #ffffff; + color : #23559C; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 11px; + border: #b2babd 1px solid; + border-collapse: collapse; + background-image: url(img/tableheader.jpg); + background-repeat: no-repeat; + background-position: left top; +} + +table.white th a { + color : #23559C; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 11px; +} + +table.white td { + height: 25px; + padding-left: 5px; +} + +.noborder { +border: none; +} + +h3 { + color : #74804e; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 13px; + font-weight: bold; + margin: 0px; +} + +.important { + color: Red; +} + +.medium { + color: #FF9900; +} + +input { + font-size: 12px; + font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; + color:#000000; +} + +input.button { + font-size: 12px; + font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; + color:#000000; + background-color:#FFFFFF; +} + +select { + font-size: 12px; + height: 20px; +} + +header a img {border: none; text-decoration: none !important;} + +.open {color : #FF0000;} +.waitingreply {color : #FF9933;} +.replied {color : #0000FF;} +.resolved {color : #008000;} +.allbutresolved {color : #000000;} + +.success {color : #008000;} +.error {color : #FF0000;} +.notice {color : #FF9900} + +#ok { + border: 1px solid #679800; +} + +#error { + border: 1px solid #ba3225; +} + +.rate { + color: #666666; + text-align: right; + font-style: italic; +} + +a.article { + color : Black; + text-decoration: none; + font-size: 11px; +} + +a.article:hover { + color : Red; + text-decoration : none; +} + +.article_list { + font-size: 11px; +} + +fieldset { + margin-bottom: 6px; + border: 1px SOLID #267DDC; + padding: 4px; + background-color:white; + position:relative; + display:block; + padding: 15px 10px 10px 10px; + margin:20px 0px 20px 0px; +} + +legend { + background-image: url(img/bluebtn.png); + background-repeat: no-repeat; + color: #172901; + border: 1px solid #267DDC; + height: 10px; + font-size: 10px; + font-weight:bold; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + background-position: left top; + display:block; + width: auto; + padding:5px 5px; + position:relative; + width:130px; +} + +/*newly introduced styles (version 2.0)*/ + +.header { + width: 100%; + background-color: #74a62b; + color : #ffffff; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 11px; + text-align: center; + background-image: url(img/header.png); + background-repeat: repeat-x; + height: 57px; + padding: 0px; + margin: 0px; +} + +.header td { +text-align: center; +vertical-align: middle; +color:#FFFFFF; +} +.header a, .header a:link, .header a:active, .header a:visited { + color : #ffffff; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 11px; + text-align: center; +} +.header a:hover {} + +.headersm { + width: 100%; + background-color: #669933; + color : #ffffff; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 12px; + text-align: left; + background-image: url(img/headerbgsm.jpg); + background-repeat: repeat-x; + height: 25px; + padding: 0px; + margin: 0px; + font-weight:bold; + padding-left: 20px; +} + +hr { + border: none; + border-bottom: 1px dotted #adbac3; + width: 100%; + padding-top: 10px; + margin-bottom: 10px; + height: 1px; +} + +.greenbutton { + background-image: url(img/greenbtn.jpg); + background-repeat: no-repeat; + text-align: center; + color: #FFFFFF; + border: 1px solid #527234; + font-size: 10px; + font-weight:bold; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + background-position: left top; + height: 19px; + padding-left: 6px; + padding-right: 6px; + margin-left: 2px; + margin-right: 2px +} + +.greenbuttonover { + background-image: url(img/greenbtnover.gif); + background-repeat: no-repeat; + text-align: center; + color: #FFFFFF; + border: 1px solid #527234; + font-size: 10px; + font-weight:bold; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + background-position: left top; + height: 19px; + padding-left: 6px; + padding-right: 6px; + margin-left: 2px; + margin-right: 2px +} + +.orangebutton { + background-image: url(img/orangebtn.jpg); + background-repeat: no-repeat; + text-align: center; + color: #660000; + border: 1px solid #bf6628; + height: 20px; + font-size: 10px; + font-weight:bold; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + background-position: left top; + padding-left: 6px; + padding-right: 6px; + margin-left: 2px; + margin-right: 2px; + text-decoration: none; + margin-top: 0px; +} + +.orangebuttonover { + background-image: url(img/orangebtnover.gif); + background-repeat: no-repeat; + text-align: center; + color: #660000; + border: 1px solid #bf6628; + height: 20px; + font-size: 10px; + font-weight:bold; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + background-position: left top; + padding-left: 6px; + padding-right: 6px; + margin-left: 2px; + margin-right: 2px; + text-decoration: none; + margin-top: 0px; +} + +.bluebutton { + background-image: url(img/bluebtn.png); + background-repeat: no-repeat; + text-align: center; + color: #660000; + border: 1px solid #5b79a3; + height: 20px; + font-size: 10px; + font-weight:bold; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + background-position: left top; + padding-left: 6px; + padding-right: 6px; + margin-left: 2px; + text-decoration: none; + margin-right: 2px; + padding-top: 2px; +} + + +/*styles for roundcorners tables*/ + +.roundcornersleft { + width: 7px; + background-image: url(img/roundcornerslm.jpg); + background-repeat: repeat-y; + background-position: left; +} +.roundcornersright { + width: 7px; + background-image: url(img/roundcornersrm.jpg); + background-repeat: repeat-y; + background-position: right; +} +.roundcornerstop { + height: 7px; + background-image: url(img/roundcornerst.jpg); + background-repeat: repeat-x; + background-position: top; +} +.roundcornersbottom { + height: 7px; + background-image: url(img/roundcornersb.jpg); + background-repeat: repeat-x; + background-position: bottom; +} +.ticketrow { + background-color: #f5fffa; + color : #4a5571; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 12px; + border: #748aaf 1px dotted; + padding: 6px; +} +.ticketalt { + background-color: #ffffff; + color : #4a5571; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 12px; + padding: 6px; +} + +.tickettd { + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 12px; +} + +.subheaderrow { + background-color: #ffffff; + color : #23559C; + border: #23559C solid 1px; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 11px; + border-collapse: collapse; + background-image: url(img/tableheader.jpg); + background-repeat: no-repeat; + background-position: left top; + height: 25px; + padding-left: 20px; + padding-right: 20px; + padding-top: 5px; + } + +.homepageh3, .section { + color: #74804e; + font-weight: bold; +} + +/*newly introduced styles (version 2.2)*/ + +.large { + font-size:14px; +} + +.largebold { + font-size:14px; + font-weight:bold; +} + +.assignedyou { + color: red; +} + +.assignedother { + color: green; +} + +div.error { + border: 1px solid #cd0a0a; + background: #fef1ec; + color: #cd0a0a; + padding: 10px; +} + +div.success { + border: 1px solid #18760f; + background: #e9ffdb; + color: #363636; + padding: 10px; +} + +div.notice { + border: 1px solid #fcefa1; + background: #fff9de; + color: #363636; + padding: 10px; + vertical-align: middle; +} + +.admin_green { + background-color: #e3ffd0; + font-weight: bold; +} + +.admin_red { + background-color: #fef1ec; + font-weight: bold; +} + +.borderBottom { + border-bottom: silver 1px dashed; +} + +.borderTop { + border-top: silver 1px dashed; +} + +.alignTop { + vertical-align: top; +} + +.alignMiddle { + vertical-align: middle; +} + +.alignBottom { + vertical-align: bottom; +} + +hr.dashed { + border: none 0; + border-top: 1px dashed silver; + height: 1px; +} + +/* newly introduced styles (version 2.3) */ + +h1 { + color : #74804e; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 13px; + font-weight: bold; + margin: 0px; +} + +.critical { + color: #9400d3; + font-weight: bold; +} + +td.admin_critical { + background-color: #fff0ff; + color : #000000; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 11px; + border: 1px solid #ff66ff; + padding: 1px; +} + +.isError { + color: black; + background-color: #fff9f7; + border: 1px solid red; +} + +.isNotice { + color: black; + border: 1px solid orange; + background: #fbf9ee; +} + +.optionWhiteON{ + padding:2px; + border:1px dotted silver; + background-color: #b0e0e6; +} + +.optionWhiteOFF { + padding:2px; + border:1px dotted silver; + background-color: white; +} + +.optionBlueON { + padding:2px; + border:1px dotted gray; + background-color: #b0e0e6; +} + +.optionBlueOFF { + padding:2px; + border:1px dotted gray; + background-color: #f5fffa; +} + +.optionWhiteNbON{ + border: none; + background-color: #b0e0e6; + vertical-align: text-bottom; +} + +.optionWhiteNbOFF { + border: none; + background-color: white; + vertical-align: text-bottom; +} + +.kbCatListON { + background-color: #fcefa1; +} + +.kbCatListOFF { + background-color: white; +} + +div.progress-container { + border: 1px solid #ccc; + width: 100px; + margin: 2px 5px 2px 0; + padding: 1px; + float: left; + background: white; +} + +div.progress-container > div { + background-color: #ACE97C; + height: 12px +} + +.black {color: black;} +.inprogress {color : #006400;} +.onhold {color : #000000;} + +div.online { + border: 1px solid #e5e8ff; + background: #ffffff; + color: #000000; + padding: 0px; + vertical-align: middle; +} + +span.online { + font-size: 10px; + white-space:nowrap; +} + +/* newly introduced styles (version 2.4) */ + +.orangebuttonsec { + background-image: url(img/orangebtnsec.jpg); + background-repeat: no-repeat; + text-align: center; + color: #660000; + border: 1px solid #bf6628; + height: 20px; + font-size: 10px; + font-weight:normal; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + background-position: left top; + padding-left: 6px; + padding-right: 6px; + margin-left: 2px; + margin-right: 2px; + text-decoration: none; + margin-top: 0px; +} + +.orangebuttonsecover { + background-image: url(img/orangebtnover.gif); + background-repeat: no-repeat; + text-align: center; + color: #660000; + border: 1px solid #bf6628; + height: 20px; + font-size: 10px; + font-weight:normal; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + background-position: left top; + padding-left: 6px; + padding-right: 6px; + margin-left: 2px; + margin-right: 2px; + text-decoration: none; + margin-top: 0px; +} + +td.admin_yellow { + background-color: #ffffe0; + color : #4a5571; + font-family : Verdana, Geneva, Arial, Helvetica, sans-serif; + font-size: 11px; + border: #d1dceb 1px solid; + padding: 1px; +} + +/* New styles in HESK version 2.5 */ + +.kb_published { + color: #009900; +} + +.kb_private { + color: #4a5571; +} + +.kb_draft { + color: #cc9933; +} + +.searchbutton { + cursor:pointer; + width:70px; + height:27px; + text-indent:-999px; + text-transform: capitalize; + color: transparent; + background: url(img/ico-search.png) no-repeat #4d90fe center; + border: 1px solid #3079ED; + -moz-border-radius: 2px; + -webkit-border-radius: 2px; +} + +.searchbutton:hover { + background: url(img/ico-search.png) no-repeat center #357AE8; + border: 1px solid #2F5BB7; +} + +.searchfield { + width:400px; + height:21px; + font-size:14px; + text-indent:2px; + vertical-align: bottom; +} + +.sbsmall { + width:50px; + height:22px; + margin-top:2px; +} + +.sfsmall { + width:200px; + height:16px; + font-size:12px; + margin-top:2px; +} + +/* New styles in HESK version 2.6 */ + +div.info { + border: 1px solid #9acfea; + background: #d9edf7; + color: #363636; + padding: 10px; + vertical-align: middle; +} + +div.none { + color: #363636; + padding: 10px; + vertical-align: middle; +} + +/* New styles in HESK version 2.7 */ + +div.select_category +{ + min-width: 50%; + min-height: 300px; + display: inline-block; + text-align:left; + margin-top: 10px; +} + +#select_category { + border: 1px solid #111; + background: transparent; + width: 100%; + padding: 5px 35px 5px 5px; + font-size: 14px; + border: 1px solid #ccc; + height: 34px; +} + +#ul_category { + list-style-type: none; + margin: 0; + padding: 0; +} + +#ul_category li { + border: 1px solid #d1d5d7; + border-top: none; + border-radius: 2px; +} + +#ul_category li:first-child { + border-top: 1px solid #d1d5d7; +} + +#ul_category li a { + display: block; + font-size: 14px; + padding: 0.75em 0.75em; + text-decoration: none; + transition: all 0.12s ease; + word-wrap: break-word; +} + +#ul_category li a:hover { + color: black; + background-color: #e9ffdb; +} + +select.multiple { + font-size: 12px; + height: auto; +} + +/* New styles in HESK version 2.8 */ + +#hesk_nav{ + list-style:none; + float:right; + /* Bring the nav above everything else--uncomment if needed. + position:relative; + z-index:5; + */ + margin: 0px; +} + +#hesk_nav li{ + float:left; + margin-right:4px; + position:relative; +} + +#hesk_nav a{ + display:block; + background-color:#ffffff; + -moz-border-radius:3px; + -webkit-border-radius:3px; + border-radius:3px; + border:1px solid #dcdcdc; + cursor:pointer; + color:#666666; + font-size:12px; + padding:4px 10px; + text-decoration:none; +} +#hesk_nav a:hover{ + color: red; + background:#f6f6f6; +} + +/*--- DROPDOWN ---*/ +#hesk_nav ul{ + background:#fff; /* Adding a background makes the dropdown work properly in IE7+. Make this as close to your page's background as possible (i.e. white page == white background). */ + background:rgba(255,255,255,0); /* But! Let's make the background fully transparent where we can, we don't actually want to see it if we can help it... */ + list-style:none; + position:absolute; + left:-9999px; /* Hide off-screen when not needed (this is more accessible than display:none;) */ + z-index:5; + padding-left: 0px; + padding-top: 2px; +} +#hesk_nav ul li{ + padding-top:1px; /* Introducing a padding between the li and the a give the illusion spaced items */ + float:none; +} +#hesk_nav ul a{ + white-space:nowrap; /* Stop text wrapping and creating multi-line dropdown items */ + padding:8px 14px; +} +#hesk_nav li:hover ul{ /* Display the dropdown on hover */ + left:auto; /* Bring back on-screen when needed */ + text-align:left; + right:0; + margin-right:-10px; +} +#hesk_nav li:hover a{ /* These create persistent hover states, meaning the top-most link stays 'hovered' even when your cursor has moved down the list. */ + background:#f6f6f6; + text-decoration:none; +} + +#hesk_nav li:hover ul a{ + background:#ffffff; + text-decoration:none; +} + +#hesk_nav li:hover ul a{ /* The persistent hover state does however create a global style for links even before they're hovered. Here we undo these effects. */ + text-decoration:none; +} +#hesk_nav li:hover ul li a:hover{ /* Here we define the most explicit hover states--what happens when you hover each individual link. */ + background:#f6f6f6; +} + +.notification { + background-color: #fff; + box-shadow: 0 4px 8px 0 rgba(0, 41, 89, 0.1); + padding: 20px 28px 20px 28px; + position: relative; + display: block; + margin-bottom: 24px; +} + +.notification::before { + content: ""; + width: 8px; + height: 100%; + position: absolute; + top: 0; + left: 0; +} + +.notification.red { + background-color: #fff5f5; +} + +.notification.red::before { + background-color: #e64342; +} + +.notification.orange { + background-color: #ffffcc; +} + +.notification.orange::before { + background-color: #eeb707; +} + +.notification.green { + background-color: #f0fff4; +} + +.notification.green::before { + background-color: #38bc7d; +} + +.notification.blue { + background-color: #ebf8ff; +} + +.notification.blue::before { + background-color: #002d73; +} + +.notification b { + font-weight: bold; +} + +.notification i { + font-style: italic; +} \ No newline at end of file diff --git a/hesk/install/img/error.png b/hesk/install/img/error.png new file mode 100644 index 0000000..c5f97b4 Binary files /dev/null and b/hesk/install/img/error.png differ diff --git a/hesk/install/img/headerbgsm.jpg b/hesk/install/img/headerbgsm.jpg new file mode 100644 index 0000000..f92a768 Binary files /dev/null and b/hesk/install/img/headerbgsm.jpg differ diff --git a/hesk/install/img/headerleftsm.jpg b/hesk/install/img/headerleftsm.jpg new file mode 100644 index 0000000..eaae334 Binary files /dev/null and b/hesk/install/img/headerleftsm.jpg differ diff --git a/hesk/install/img/headerrightsm.jpg b/hesk/install/img/headerrightsm.jpg new file mode 100644 index 0000000..69c4ff0 Binary files /dev/null and b/hesk/install/img/headerrightsm.jpg differ diff --git a/hesk/install/img/orangebtn.jpg b/hesk/install/img/orangebtn.jpg new file mode 100644 index 0000000..3aa48f0 Binary files /dev/null and b/hesk/install/img/orangebtn.jpg differ diff --git a/hesk/install/img/orangebtnover.gif b/hesk/install/img/orangebtnover.gif new file mode 100644 index 0000000..e75c306 Binary files /dev/null and b/hesk/install/img/orangebtnover.gif differ diff --git a/hesk/install/img/orangebtnsec.jpg b/hesk/install/img/orangebtnsec.jpg new file mode 100644 index 0000000..1206a88 Binary files /dev/null and b/hesk/install/img/orangebtnsec.jpg differ diff --git a/hesk/install/img/roundcornersb.jpg b/hesk/install/img/roundcornersb.jpg new file mode 100644 index 0000000..e8d69a1 Binary files /dev/null and b/hesk/install/img/roundcornersb.jpg differ diff --git a/hesk/install/img/roundcornerslb.jpg b/hesk/install/img/roundcornerslb.jpg new file mode 100644 index 0000000..b6ab537 Binary files /dev/null and b/hesk/install/img/roundcornerslb.jpg differ diff --git a/hesk/install/img/roundcornerslm.jpg b/hesk/install/img/roundcornerslm.jpg new file mode 100644 index 0000000..ad55cf9 Binary files /dev/null and b/hesk/install/img/roundcornerslm.jpg differ diff --git a/hesk/install/img/roundcornerslt.jpg b/hesk/install/img/roundcornerslt.jpg new file mode 100644 index 0000000..0d70b75 Binary files /dev/null and b/hesk/install/img/roundcornerslt.jpg differ diff --git a/hesk/install/img/roundcornersrb.jpg b/hesk/install/img/roundcornersrb.jpg new file mode 100644 index 0000000..46ef2c5 Binary files /dev/null and b/hesk/install/img/roundcornersrb.jpg differ diff --git a/hesk/install/img/roundcornersrm.jpg b/hesk/install/img/roundcornersrm.jpg new file mode 100644 index 0000000..75b1d03 Binary files /dev/null and b/hesk/install/img/roundcornersrm.jpg differ diff --git a/hesk/install/img/roundcornersrt.jpg b/hesk/install/img/roundcornersrt.jpg new file mode 100644 index 0000000..32c8ab2 Binary files /dev/null and b/hesk/install/img/roundcornersrt.jpg differ diff --git a/hesk/install/img/roundcornerst.jpg b/hesk/install/img/roundcornerst.jpg new file mode 100644 index 0000000..6c49bcd Binary files /dev/null and b/hesk/install/img/roundcornerst.jpg differ diff --git a/hesk/install/index.php b/hesk/install/index.php new file mode 100644 index 0000000..26f73d6 --- /dev/null +++ b/hesk/install/index.php @@ -0,0 +1,49 @@ + + +
    +
    + + +
    +
    + +
    + + +
    +
    +
    + + + + +
    Visit HESK.com

    Thank you for downloading HESK. Please choose an option below:

    + +
    + +
    +

    +

    Install a new copy of HESK

    +
    + +
    + +
    +

    +

    Update existing HESK to version

    +
    + + diff --git a/hesk/install/install.php b/hesk/install/install.php new file mode 100644 index 0000000..b4d7e41 --- /dev/null +++ b/hesk/install/install.php @@ -0,0 +1,744 @@ + + +
    + + +

    Next steps:

    + +
      + +
    1. Delete the /install folder from your server!
       
    2. + +
    3. Remember your login details:
      + +
      +Username: 
      +Password: 
      +
      + +
        + +
    4. + + + + + + + +
      +
      + + + + + + +
      +
      - or - +
      + + + + + + +
      +
      + +
    + +

     

    + + Attachments +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."attachments` ( + `att_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `ticket_id` varchar(13) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `saved_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `real_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `size` int(10) unsigned NOT NULL DEFAULT '0', + `type` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + PRIMARY KEY (`att_id`), + KEY `ticket_id` (`ticket_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +// -> Banned emails +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."banned_emails` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `email` varchar(255) NOT NULL, + `banned_by` smallint(5) unsigned NOT NULL, + `dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + KEY `email` (`email`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 +"); + +// -> Banned IPs +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."banned_ips` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `ip_from` int(10) unsigned NOT NULL DEFAULT '0', + `ip_to` int(10) unsigned NOT NULL DEFAULT '0', + `ip_display` varchar(100) NOT NULL, + `banned_by` smallint(5) unsigned NOT NULL, + `dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 +"); + +// -> Categories +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(60) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `cat_order` smallint(5) unsigned NOT NULL DEFAULT '0', + `autoassign` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1', + `type` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + `priority` enum('0','1','2','3') COLLATE utf8_unicode_ci NOT NULL DEFAULT '3', + PRIMARY KEY (`id`), + KEY `type` (`type`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +// ---> Insert default category +hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` (`id`, `name`, `cat_order`) VALUES (1, 'General', 10)"); + +// -> Custom fields +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_fields` ( + `id` tinyint(3) UNSIGNED NOT NULL, + `use` enum('0','1','2') NOT NULL DEFAULT '0', + `place` enum('0','1') NOT NULL DEFAULT '0', + `type` varchar(20) NOT NULL DEFAULT 'text', + `req` enum('0','1','2') NOT NULL DEFAULT '0', + `category` text, + `name` text, + `value` text, + `order` smallint(5) UNSIGNED NOT NULL DEFAULT '10', + PRIMARY KEY (`id`), + KEY `useType` (`use`,`type`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +// ---> Insert empty custom fields +hesk_dbQuery(" +INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_fields` (`id`, `use`, `place`, `type`, `req`, `category`, `name`, `value`, `order`) VALUES +(1, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(2, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(3, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(4, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(5, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(6, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(7, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(8, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(9, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(10, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(11, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(12, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(13, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(14, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(15, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(16, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(17, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(18, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(19, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(20, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(21, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(22, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(23, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(24, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(25, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(26, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(27, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(28, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(29, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(30, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(31, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(32, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(33, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(34, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(35, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(36, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(37, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(38, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(39, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(40, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(41, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(42, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(43, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(44, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(45, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(46, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(47, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(48, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(49, '0', '0', 'text', '0', NULL, '', NULL, 1000), +(50, '0', '0', 'text', '0', NULL, '', NULL, 1000) +"); + +// -> Custom statuses +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_statuses` ( + `id` tinyint(3) UNSIGNED NOT NULL, + `name` text NOT NULL, + `color` varchar(6) NOT NULL, + `can_customers_change` enum('0','1') NOT NULL DEFAULT '1', + `order` smallint(5) UNSIGNED NOT NULL DEFAULT '10', + PRIMARY KEY (`id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +// -> KB Articles +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `catid` smallint(5) unsigned NOT NULL, + `dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `author` smallint(5) unsigned NOT NULL, + `subject` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `content` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `keywords` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `rating` float NOT NULL DEFAULT '0', + `votes` mediumint(8) unsigned NOT NULL DEFAULT '0', + `views` mediumint(8) unsigned NOT NULL DEFAULT '0', + `type` enum('0','1','2') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + `html` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + `sticky` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + `art_order` smallint(5) unsigned NOT NULL DEFAULT '0', + `history` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `attachments` mediumtext COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + KEY `catid` (`catid`), + KEY `sticky` (`sticky`), + KEY `type` (`type`), + FULLTEXT KEY `subject` (`subject`,`content`,`keywords`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +// -> KB Attachments +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_attachments` ( + `att_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `saved_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `real_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `size` int(10) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`att_id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +// -> KB Categories +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `parent` smallint(5) unsigned NOT NULL, + `articles` smallint(5) unsigned NOT NULL DEFAULT '0', + `articles_private` smallint(5) unsigned NOT NULL DEFAULT '0', + `articles_draft` smallint(5) unsigned NOT NULL DEFAULT '0', + `cat_order` smallint(5) unsigned NOT NULL, + `type` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `type` (`type`), + KEY `parent` (`parent`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +// ---> Insert default KB category +hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` (`id`, `name`, `parent`, `cat_order`, `type`) VALUES (1, 'Knowledgebase', 0, 10, '0')"); + +// -> Login attempts +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."logins` ( + `ip` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `number` tinyint(3) unsigned NOT NULL DEFAULT '1', + `last_attempt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNIQUE KEY `ip` (`ip`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +// -> Private messages +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."mail` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `from` smallint(5) unsigned NOT NULL, + `to` smallint(5) unsigned NOT NULL, + `subject` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `message` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `read` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + `deletedby` smallint(5) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `from` (`from`), + KEY `to` (`to`,`read`,`deletedby`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +// ---> Insert welcome email +hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."mail` (`id`, `from`, `to`, `subject`, `message`, `dt`, `read`, `deletedby`) VALUES (NULL, 9999, 1, 'HESK quick start guide', '".hesk_dbEscape("

    \r\n\r\n

     
    Welcome to HESK! You'll find it is a great tool for improving your customer support.

    \r\n\r\n

    Here is a short guide to get you started.
     

    \r\n\r\n
    \r\nSTEP #1: setup your profile\r\n
    \r\n
      \r\n
    1. go to Profile,
    2. \r\n
    3. set your name and email address.
    4. \r\n
    \r\n\r\n \r\n\r\n
    \r\nSTEP #2: configure HESK\r\n
    \r\n
      \r\n
    1. go to Settings,
    2. \r\n
    3. for a quick start, just modify these on the \"General\" tab:

      \r\nWebsite title
      \r\nWebsite URL
      \r\nWebmaster email
       \r\n
    4. \r\n
    5. you can come back to the settings page later and explore all the options. To view details about a setting, click the [?]
    6. \r\n
    \r\n\r\n \r\n\r\n
    \r\nSTEP #3: add ticket categories\r\n
    \r\n

    Go to Categories to add ticket categories.

    \r\n

    You cannot delete the default category, but you can rename it.

    \r\n\r\n

     

    \r\n\r\n
    \r\nSTEP #4: add staff accounts\r\n
    \r\n

    Go to Users to create new staff accounts.

    \r\n

    You can use two user types in HESK:

    \r\n
      \r\n
    • Administrators, who have full access to all HESK features
    • \r\n
    • Staff, who have access to limited privileges and categories
    • \r\n
    \r\n\r\n \r\n\r\n
    \r\nSTEP #5: useful tools\r\n
    \r\n

    You can do a lot on the Tools page, for example:

    \r\n
      \r\n
    • create custom ticket statuses,
    • \r\n
    • add custom input fields to the \"Submit a ticket\" form,
    • \r\n
    • modify email templates,
    • \r\n
    • and more.
    • \r\n
    \r\n\r\n \r\n\r\n
    \r\nSTEP #6: create a knowledgebase\r\n
    \r\n

    A clear and comprehensive knowledgebase can drastically reduce the number of support tickets you receive, thereby saving you significant time and effort in the long run.

    \r\n

    Go to Knowledgebase to create categories and write articles for your knowledgebase.

    \r\n\r\n \r\n\r\n
    \r\nSTEP #7: don't repeat yourself\r\n
    \r\n

    Sometimes several support tickets are addressing the same issues - allowing you to use pre-written ("canned") responses.

    \r\n

    To compose canned responses go to Canned page.

    \r\n\r\n \r\n\r\n
    \r\nSTEP #8: secure your help desk\r\n
    \r\n

    Make sure your help desk is as secure as possible by going through HESK security check list

    \r\n\r\n \r\n\r\n
    \r\nSTEP #9: stay updated\r\n
    \r\n

    HESK regularly receives improvements and bug fixes, make sure you know about them!

    \r\n\r\n\r\n \r\n\r\n
    \r\nSTEP #10: look professional\r\n
    \r\n

    To look more professional and not advertise the tools you use, remove "Powered by" links from your help desk.

    \r\n\r\n

     

    \r\n\r\n

    Again, welcome to HESK and enjoy using it!

    \r\n\r\n

    Klemen Stirn
    \r\nAuthor and owner

    \r\n\r\n

    ")."', NOW(), '0', 9999)"); + +// -> Notes +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."notes` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `ticket` mediumint(8) unsigned NOT NULL, + `who` smallint(5) unsigned NOT NULL, + `dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `message` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `attachments` mediumtext COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + KEY `ticketid` (`ticket`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +// -> Online +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."online` ( + `user_id` smallint(5) unsigned NOT NULL, + `dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `tmp` int(11) unsigned NOT NULL DEFAULT '0', + UNIQUE KEY `user_id` (`user_id`), + KEY `dt` (`dt`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +// -> Pipe loops +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."pipe_loops` ( + `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `hits` smallint(1) unsigned NOT NULL DEFAULT '0', + `message_hash` char(32) COLLATE utf8_unicode_ci NOT NULL, + `dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + KEY `email` (`email`,`hits`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +// -> Replies +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `replyto` mediumint(8) unsigned NOT NULL DEFAULT '0', + `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `message` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `attachments` mediumtext COLLATE utf8_unicode_ci, + `staffid` smallint(5) unsigned NOT NULL DEFAULT '0', + `rating` enum('1','5') COLLATE utf8_unicode_ci DEFAULT NULL, + `read` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `replyto` (`replyto`), + KEY `dt` (`dt`), + KEY `staffid` (`staffid`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +// -> Reply drafts +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."reply_drafts` ( + `owner` smallint(5) unsigned NOT NULL, + `ticket` mediumint(8) unsigned NOT NULL, + `message` mediumtext CHARACTER SET utf8 NOT NULL, + `dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + KEY `owner` (`owner`), + KEY `ticket` (`ticket`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +// -> Reset password +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."reset_password` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `user` smallint(5) unsigned NOT NULL, + `hash` char(40) NOT NULL, + `ip` varchar(45) NOT NULL, + `dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + KEY `user` (`user`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; +"); + +// -> Service messages +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."service_messages` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `author` smallint(5) unsigned NOT NULL, + `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `message` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `language` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `style` enum('0','1','2','3','4') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + `type` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + `order` smallint(5) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `type` (`type`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +"); + +// -> Canned Responses +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."std_replies` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `title` varchar(100) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `message` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `reply_order` smallint(5) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +// -> Tickets +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `trackid` varchar(13) COLLATE utf8_unicode_ci NOT NULL, + `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `email` varchar(1000) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `category` smallint(5) unsigned NOT NULL DEFAULT '1', + `priority` enum('0','1','2','3') COLLATE utf8_unicode_ci NOT NULL DEFAULT '3', + `subject` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `message` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `dt` timestamp NOT NULL DEFAULT '2000-01-01 00:00:00', + `lastchange` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `firstreply` timestamp NULL DEFAULT NULL, + `closedat` timestamp NULL DEFAULT NULL, + `articles` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `ip` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `language` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `status` tinyint(3) unsigned NOT NULL DEFAULT '0', + `openedby` mediumint(8) DEFAULT '0', + `firstreplyby` smallint(5) unsigned DEFAULT NULL, + `closedby` mediumint(8) NULL DEFAULT NULL, + `replies` smallint(5) unsigned NOT NULL DEFAULT '0', + `staffreplies` smallint(5) unsigned NOT NULL DEFAULT '0', + `owner` smallint(5) unsigned NOT NULL DEFAULT '0', + `assignedby` mediumint(8) NULL DEFAULT NULL, + `time_worked` time NOT NULL DEFAULT '00:00:00', + `lastreplier` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + `replierid` smallint(5) unsigned DEFAULT NULL, + `archive` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + `locked` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + `attachments` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `merged` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `history` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom1` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom2` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom3` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom4` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom5` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom6` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom7` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom8` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom9` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom10` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom11` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom12` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom13` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom14` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom15` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom16` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom17` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom18` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom19` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom20` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom21` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom22` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom23` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom24` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom25` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom26` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom27` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom28` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom29` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom30` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom31` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom32` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom33` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom34` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom35` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom36` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom37` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom38` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom39` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom40` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom41` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom42` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom43` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom44` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom45` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom46` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom47` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom48` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom49` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `custom50` mediumtext COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + KEY `trackid` (`trackid`), + KEY `archive` (`archive`), + KEY `categories` (`category`), + KEY `statuses` (`status`), + KEY `owner` (`owner`), + KEY `openedby` (`openedby`,`firstreplyby`,`closedby`), + KEY `dt` (`dt`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +// -> Ticket templates +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_templates` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `title` varchar(100) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `message` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `tpl_order` smallint(5) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +// -> Users +hesk_dbQuery(" +CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."users` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `user` varchar(20) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `pass` char(40) COLLATE utf8_unicode_ci NOT NULL, + `isadmin` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `signature` varchar(1000) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `language` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `categories` varchar(500) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `afterreply` enum('0','1','2') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + `autostart` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1', + `autoreload` smallint(5) unsigned NOT NULL DEFAULT '0', + `notify_customer_new` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1', + `notify_customer_reply` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1', + `show_suggested` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1', + `notify_new_unassigned` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1', + `notify_new_my` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1', + `notify_reply_unassigned` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1', + `notify_reply_my` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1', + `notify_assigned` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1', + `notify_pm` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1', + `notify_note` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1', + `default_list` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `autoassign` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1', + `heskprivileges` varchar(1000) COLLATE utf8_unicode_ci DEFAULT NULL, + `ratingneg` mediumint(8) unsigned NOT NULL DEFAULT '0', + `ratingpos` mediumint(8) unsigned NOT NULL DEFAULT '0', + `rating` float NOT NULL DEFAULT '0', + `replies` mediumint(8) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `autoassign` (`autoassign`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci +"); + +hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."users` (`id`, `user`, `pass`, `isadmin`, `name`, `email`, `heskprivileges`) VALUES (1, '".hesk_dbEscape($_SESSION['admin_user'])."', '".hesk_dbEscape($_SESSION['admin_hash'])."', '1', 'Your name', 'you@example.com', '')"); + + return true; + +} // End hesk_iTables() + + +function hesk_iSaveSettings() +{ + global $hesk_settings, $hesklang; + + $spam_question = hesk_generate_SPAM_question(); + + $hesk_settings['secimg_use'] = empty($_SESSION['set_captcha']) ? 0 : 1; + $hesk_settings['use_spamq'] = empty($_SESSION['use_spamq']) ? 0 : 1; + $hesk_settings['question_ask'] = $spam_question[0]; + $hesk_settings['question_ans'] = $spam_question[1]; + $hesk_settings['set_attachments'] = empty($_SESSION['set_attachments']) ? 0 : 1; + $hesk_settings['hesk_version'] = HESK_NEW_VERSION; + + if (isset($_SERVER['HTTP_HOST'])) + { + $protocol = HESK_SSL? 'https://' : 'http://'; + $hesk_settings['site_url']=$protocol . $_SERVER['HTTP_HOST']; + + if (isset($_SERVER['REQUEST_URI'])) + { + $hesk_settings['hesk_url']=$protocol . $_SERVER['HTTP_HOST'] . str_replace('/install/install.php','',$_SERVER['REQUEST_URI']); + } + } + + /* Encode and escape characters */ + $set = $hesk_settings; + foreach ($hesk_settings as $k=> $v) + { + if (is_array($v) || is_object($v)) + { + continue; + } + $set[$k] = addslashes($v); + } + $set['debug_mode'] = 0; + + $set['email_providers'] = count($set['email_providers']) ? "'" . implode("','", $set['email_providers']) . "'" : ''; + $set['notify_spam_tags'] = count($set['notify_spam_tags']) ? "'" . implode("','", $set['notify_spam_tags']) . "'" : ''; + + // Check if PHP version is 5.2.3+ + $set['db_vrsn'] = (version_compare(PHP_VERSION, '5.2.3') >= 0) ? 1 : 0; + + // If SSL is enabled, let's force it by default + $set['force_ssl'] = HESK_SSL ? 1 : 0; + + hesk_iSaveSettingsFile($set); + + return true; +} // End hesk_iSaveSettings() +?> diff --git a/hesk/install/install_functions.inc.php b/hesk/install/install_functions.inc.php new file mode 100644 index 0000000..b9a2ac5 --- /dev/null +++ b/hesk/install/install_functions.inc.php @@ -0,0 +1,1191 @@ + array('folder'=>'en','hr'=>'------ Reply above this line ------')); + +if (!isset($hesk_settings['x_frame_opt'])) +{ + $hesk_settings['x_frame_opt'] = 1; +} + +if (!isset($hesk_settings['force_ssl'])) +{ + $hesk_settings['force_ssl'] = 0; +} + +error_reporting(E_ALL); + +// Database upgrades from old versions can take quite some time, remove time limit +if ( function_exists('set_time_limit') ) +{ + set_time_limit(0); +} + +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(); + +// Start the session +hesk_session_start(); + + +// ******* FUNCTIONS ******* // + + +function hesk_iTestDatabaseConnection($use_existing_settings = false) +{ + global $hesk_db_link, $hesk_settings, $hesklang; + + $db_success = 1; + + // Get MySQL settings, except for successful updates + if ( ! $use_existing_settings) + { + $hesk_settings['db_host'] = hesk_input( hesk_POST('host') ); + $hesk_settings['db_name'] = hesk_input( hesk_POST('name') ); + $hesk_settings['db_user'] = hesk_input( hesk_POST('user') ); + $hesk_settings['db_pass'] = str_replace('&', '&', hesk_input( hesk_POST('pass') ) ); + + if (INSTALL_PAGE == 'install.php') + { + // Get table prefix, don't allow any special chars + $hesk_settings['db_pfix'] = preg_replace('/[^0-9a-zA-Z_]/', '', hesk_POST('pfix', 'hesk_') ); + } + } + + // Use MySQLi extension to connect? + $use_mysqli = function_exists('mysqli_connect') ? true : false; + + // Start output buffering + ob_start(); + + // Connect to database + if ($use_mysqli) + { + // Do we need a special port? Check and connect to the database + if ( strpos($hesk_settings['db_host'], ':') ) + { + list($hesk_settings['db_host_no_port'], $hesk_settings['db_port']) = explode(':', $hesk_settings['db_host']); + $hesk_db_link = mysqli_connect($hesk_settings['db_host_no_port'], $hesk_settings['db_user'], $hesk_settings['db_pass'], $hesk_settings['db_name'], intval($hesk_settings['db_port']) ) or $db_success=0; + } + else + { + $hesk_db_link = mysqli_connect($hesk_settings['db_host'], $hesk_settings['db_user'], $hesk_settings['db_pass'], $hesk_settings['db_name']) or $db_success=0; + } + } + else + { + $hesk_db_link = mysql_connect($hesk_settings['db_host'],$hesk_settings['db_user'], $hesk_settings['db_pass']) or $db_success=0; + + // Select database works OK? + if ($db_success == 1 && ! mysql_select_db($hesk_settings['db_name'], $hesk_db_link) ) + { + // No, try to create the database + if (function_exists('mysql_create_db') && mysql_create_db($hesk_settings['db_name'], $hesk_db_link)) + { + if (mysql_select_db($hesk_settings['db_name'], $hesk_db_link)) + { + $db_success = 1; + } + else + { + $db_success = 0; + } + } + else + { + $db_success = 0; + } + } + } + + ob_end_clean(); + + // Test DB permissions + if ($db_success) + { + $sql[0] = "DROP TABLE IF EXISTS `".hesk_dbEscape($hesk_settings['db_pfix'])."mysql_test`"; + $sql[1] = "CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."mysql_test` (`id` smallint(1) unsigned NOT NULL DEFAULT '0') ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; + $sql[2] = "INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."mysql_test` (`id`) VALUES ('0')"; + $sql[3] = "SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."mysql_test` WHERE `id`='0' LIMIT 1"; + $sql[4] = "UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."mysql_test` SET `id`='1' WHERE `id`='0'"; + $sql[5] = "DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."mysql_test` WHERE `id`='0'"; + $sql[6] = "ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."mysql_test` ADD `name` CHAR(1) NULL DEFAULT NULL AFTER `id`"; + $sql[7] = "CREATE INDEX `name` ON `".hesk_dbEscape($hesk_settings['db_pfix'])."mysql_test`(`name`) "; + $sql[8] = "DROP TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."mysql_test`"; + + if ($use_mysqli) + { + for ($i=0; $i<=8; $i++) + { + if (! $res = mysqli_query($hesk_db_link, $sql[$i])) + { + global $mysql_log; + $mysql_log = mysqli_error($hesk_db_link); + hesk_iDatabase(1); + } + } + } + else + { + for ($i=0; $i<=8; $i++) + { + if (! $res = mysql_query($sql[$i], $hesk_db_link)) + { + global $mysql_log; + $mysql_log = mysql_error(); + hesk_iDatabase(1); + } + } + } + } + + // Any errors? + if ( ! $db_success) + { + global $mysql_log; + $mysql_log = $use_mysqli ? mysqli_connect_error() : mysql_error(); + + hesk_iDatabase(1); + } + + // Check MySQL version + define('MYSQL_VERSION', hesk_dbResult( hesk_dbQuery('SELECT VERSION() AS version') ) ); + if ( version_compare(MYSQL_VERSION,REQUIRE_MYSQL_VERSION,'<') ) + { + hesk_iDatabase(5); + } + + return $hesk_db_link; + +} // END hesk_iTestDatabaseConnection() + + +function hesk_iSaveSettingsFile($set) +{ + global $hesk_settings, $hesklang; + + // Make sure OPcache is reset when modifying settings + if ( function_exists('opcache_reset') ) + { + opcache_reset(); + } + + $settings_file_content=' GENERAL + +// --> General settings +$hesk_settings[\'site_title\']=\'' . $set['site_title'] . '\'; +$hesk_settings[\'site_url\']=\'' . $set['site_url'] . '\'; +$hesk_settings[\'hesk_title\']=\'' . $set['hesk_title'] . '\'; +$hesk_settings[\'hesk_url\']=\'' . $set['hesk_url'] . '\'; +$hesk_settings[\'webmaster_mail\']=\'' . $set['webmaster_mail'] . '\'; +$hesk_settings[\'noreply_mail\']=\'' . $set['noreply_mail'] . '\'; +$hesk_settings[\'noreply_name\']=\'' . $set['noreply_name'] . '\'; +$hesk_settings[\'site_theme\']=\'' . $set['site_theme'] . '\'; + +// --> Language settings +$hesk_settings[\'can_sel_lang\']=' . $set['can_sel_lang'] . '; +$hesk_settings[\'language\']=\'' . $set['language'] . '\'; +$hesk_settings[\'languages\']=array( +\'English\' => array(\'folder\'=>\'en\',\'hr\'=>\'------ Reply above this line ------\'), +); + +// --> Database settings +$hesk_settings[\'db_host\']=\'' . $set['db_host'] . '\'; +$hesk_settings[\'db_name\']=\'' . $set['db_name'] . '\'; +$hesk_settings[\'db_user\']=\'' . $set['db_user'] . '\'; +$hesk_settings[\'db_pass\']=\'' . $set['db_pass'] . '\'; +$hesk_settings[\'db_pfix\']=\'' . $set['db_pfix'] . '\'; +$hesk_settings[\'db_vrsn\']=' . $set['db_vrsn'] . '; + + +// ==> HELP DESK + +// --> Help desk settings +$hesk_settings[\'admin_dir\']=\'' . $set['admin_dir'] . '\'; +$hesk_settings[\'attach_dir\']=\'' . $set['attach_dir'] . '\'; +$hesk_settings[\'cache_dir\']=\'' . $set['cache_dir'] . '\'; +$hesk_settings[\'max_listings\']=' . $set['max_listings'] . '; +$hesk_settings[\'print_font_size\']=' . $set['print_font_size'] . '; +$hesk_settings[\'autoclose\']=' . $set['autoclose'] . '; +$hesk_settings[\'max_open\']=' . $set['max_open'] . '; +$hesk_settings[\'new_top\']=' . $set['new_top'] . '; +$hesk_settings[\'reply_top\']=' . $set['reply_top'] . '; + +// --> Features +$hesk_settings[\'autologin\']=' . $set['autologin'] . '; +$hesk_settings[\'autoassign\']=' . $set['autoassign'] . '; +$hesk_settings[\'require_email\']=' . $set['require_email'] . '; +$hesk_settings[\'require_owner\']=' . $set['require_owner'] . '; +$hesk_settings[\'require_subject\']=' . $set['require_subject'] . '; +$hesk_settings[\'require_message\']=' . $set['require_message'] . '; +$hesk_settings[\'custclose\']=' . $set['custclose'] . '; +$hesk_settings[\'custopen\']=' . $set['custopen'] . '; +$hesk_settings[\'rating\']=' . $set['rating'] . '; +$hesk_settings[\'cust_urgency\']=' . $set['cust_urgency'] . '; +$hesk_settings[\'sequential\']=' . $set['sequential'] . '; +$hesk_settings[\'time_worked\']=' . $set['time_worked'] . '; +$hesk_settings[\'spam_notice\']=' . $set['spam_notice'] . '; +$hesk_settings[\'list_users\']=' . $set['list_users'] . '; +$hesk_settings[\'debug_mode\']=' . $set['debug_mode'] . '; +$hesk_settings[\'short_link\']=' . $set['short_link'] . '; +$hesk_settings[\'select_cat\']=' . $set['select_cat'] . '; +$hesk_settings[\'select_pri\']=' . $set['select_pri'] . '; +$hesk_settings[\'cat_show_select\']=' . $set['cat_show_select'] . '; + +// --> SPAM Prevention +$hesk_settings[\'secimg_use\']=' . $set['secimg_use'] . '; +$hesk_settings[\'secimg_sum\']=\'' . $set['secimg_sum'] . '\'; +$hesk_settings[\'recaptcha_use\']=' . $set['recaptcha_use'] . '; +$hesk_settings[\'recaptcha_public_key\']=\'' . $set['recaptcha_public_key'] . '\'; +$hesk_settings[\'recaptcha_private_key\']=\'' . $set['recaptcha_private_key'] . '\'; +$hesk_settings[\'question_use\']=' . $set['question_use'] . '; +$hesk_settings[\'question_ask\']=\'' . $set['question_ask'] . '\'; +$hesk_settings[\'question_ans\']=\'' . $set['question_ans'] . '\'; + +// --> Security +$hesk_settings[\'attempt_limit\']=' . $set['attempt_limit'] . '; +$hesk_settings[\'attempt_banmin\']=' . $set['attempt_banmin'] . '; +$hesk_settings[\'reset_pass\']=' . $set['reset_pass'] . '; +$hesk_settings[\'email_view_ticket\']=' . $set['email_view_ticket'] . '; +$hesk_settings[\'x_frame_opt\']=' . $set['x_frame_opt'] . '; +$hesk_settings[\'force_ssl\']=' . $set['force_ssl'] . '; + +// --> Attachments +$hesk_settings[\'attachments\']=array ( +\'use\' => ' . $set['attachments']['use'] . ', +\'max_number\' => ' . $set['attachments']['max_number'] . ', +\'max_size\' => ' . $set['attachments']['max_size'] . ', +\'allowed_types\' => array(\'' . implode('\',\'',$set['attachments']['allowed_types']) . '\') +); + + +// ==> KNOWLEDGEBASE + +// --> Knowledgebase settings +$hesk_settings[\'kb_enable\']=' . $set['kb_enable'] . '; +$hesk_settings[\'kb_wysiwyg\']=' . $set['kb_wysiwyg'] . '; +$hesk_settings[\'kb_search\']=' . $set['kb_search'] . '; +$hesk_settings[\'kb_search_limit\']=' . $set['kb_search_limit'] . '; +$hesk_settings[\'kb_views\']=' . $set['kb_views'] . '; +$hesk_settings[\'kb_date\']=' . $set['kb_date'] . '; +$hesk_settings[\'kb_recommendanswers\']=' . $set['kb_recommendanswers'] . '; +$hesk_settings[\'kb_rating\']=' . $set['kb_rating'] . '; +$hesk_settings[\'kb_substrart\']=' . $set['kb_substrart'] . '; +$hesk_settings[\'kb_cols\']=' . $set['kb_cols'] . '; +$hesk_settings[\'kb_numshow\']=' . $set['kb_numshow'] . '; +$hesk_settings[\'kb_popart\']=' . $set['kb_popart'] . '; +$hesk_settings[\'kb_latest\']=' . $set['kb_latest'] . '; +$hesk_settings[\'kb_index_popart\']=' . $set['kb_index_popart'] . '; +$hesk_settings[\'kb_index_latest\']=' . $set['kb_index_latest'] . '; +$hesk_settings[\'kb_related\']=' . $set['kb_related'] . '; + + +// ==> EMAIL + +// --> Email sending +$hesk_settings[\'smtp\']=' . $set['smtp'] . '; +$hesk_settings[\'smtp_host_name\']=\'' . $set['smtp_host_name'] . '\'; +$hesk_settings[\'smtp_host_port\']=' . $set['smtp_host_port'] . '; +$hesk_settings[\'smtp_timeout\']=' . $set['smtp_timeout'] . '; +$hesk_settings[\'smtp_ssl\']=' . $set['smtp_ssl'] . '; +$hesk_settings[\'smtp_tls\']=' . $set['smtp_tls'] . '; +$hesk_settings[\'smtp_user\']=\'' . $set['smtp_user'] . '\'; +$hesk_settings[\'smtp_password\']=\'' . $set['smtp_password'] . '\'; + +// --> Email piping +$hesk_settings[\'email_piping\']=' . $set['email_piping'] . '; + +// --> POP3 Fetching +$hesk_settings[\'pop3\']=' . $set['pop3'] . '; +$hesk_settings[\'pop3_job_wait\']=' . $set['pop3_job_wait'] . '; +$hesk_settings[\'pop3_host_name\']=\'' . $set['pop3_host_name'] . '\'; +$hesk_settings[\'pop3_host_port\']=' . $set['pop3_host_port'] . '; +$hesk_settings[\'pop3_tls\']=' . $set['pop3_tls'] . '; +$hesk_settings[\'pop3_keep\']=' . $set['pop3_keep'] . '; +$hesk_settings[\'pop3_user\']=\'' . $set['pop3_user'] . '\'; +$hesk_settings[\'pop3_password\']=\'' . $set['pop3_password'] . '\'; + +// --> IMAP Fetching +$hesk_settings[\'imap\']=' . $set['imap'] . '; +$hesk_settings[\'imap_job_wait\']=' . $set['imap_job_wait'] . '; +$hesk_settings[\'imap_host_name\']=\'' . $set['imap_host_name'] . '\'; +$hesk_settings[\'imap_host_port\']=' . $set['imap_host_port'] . '; +$hesk_settings[\'imap_enc\']=\'' . $set['imap_enc'] . '\'; +$hesk_settings[\'imap_keep\']=' . $set['imap_keep'] . '; +$hesk_settings[\'imap_user\']=\'' . $set['imap_user'] . '\'; +$hesk_settings[\'imap_password\']=\'' . $set['imap_password'] . '\'; + +// --> Email loops +$hesk_settings[\'loop_hits\']=' . $set['loop_hits'] . '; +$hesk_settings[\'loop_time\']=' . $set['loop_time'] . '; + +// --> Detect email typos +$hesk_settings[\'detect_typos\']=' . $set['detect_typos'] . '; +$hesk_settings[\'email_providers\']=array(' . $set['email_providers'] . '); + +// --> Notify customer when +$hesk_settings[\'notify_new\']=' . $set['notify_new'] . '; +$hesk_settings[\'notify_skip_spam\']=' . $set['notify_skip_spam'] . '; +$hesk_settings[\'notify_spam_tags\']=array(' . $set['notify_spam_tags'] . '); +$hesk_settings[\'notify_closed\']=' . $set['notify_closed'] . '; + +// --> Other +$hesk_settings[\'strip_quoted\']=' . $set['strip_quoted'] . '; +$hesk_settings[\'eml_req_msg\']=' . $set['eml_req_msg'] . '; +$hesk_settings[\'save_embedded\']=' . $set['save_embedded'] . '; +$hesk_settings[\'multi_eml\']=' . $set['multi_eml'] . '; +$hesk_settings[\'confirm_email\']=' . $set['confirm_email'] . '; +$hesk_settings[\'open_only\']=' . $set['open_only'] . '; + + +// ==> TICKET LIST + +$hesk_settings[\'ticket_list\']=array(\'' . implode('\',\'',$set['ticket_list']) . '\'); + +// --> Other +$hesk_settings[\'submittedformat\']=' . $set['submittedformat'] . '; +$hesk_settings[\'updatedformat\']=' . $set['updatedformat'] . '; + + +// ==> MISC + +// --> Date & Time +$hesk_settings[\'timezone\']=\'' . $set['timezone'] . '\'; +$hesk_settings[\'timeformat\']=\'' . $set['timeformat'] . '\'; + +// --> Other +$hesk_settings[\'ip_whois\']=\'' . $set['ip_whois'] . '\'; +$hesk_settings[\'maintenance_mode\']=' . $set['maintenance_mode'] . '; +$hesk_settings[\'alink\']=' . $set['alink'] . '; +$hesk_settings[\'submit_notice\']=' . $set['submit_notice'] . '; +$hesk_settings[\'online\']=' . $set['online'] . '; +$hesk_settings[\'online_min\']=' . $set['online_min'] . '; +$hesk_settings[\'check_updates\']=' . $set['check_updates'] . '; + + +############################# +# 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) ) + { + hesk_error($hesklang['err_openset']); + } + + return true; +} // END hesk_iSaveSettingsFile() + + +function hesk_iDatabase($problem=0) +{ + global $hesk_settings, $hesk_db_link, $mysql_log; + + hesk_iHeader(); + ?> + +

    Database settings

    + +
    + +
    Double-check all the information below. Contact your hosting company for the correct information to use!

    MySQL said: '.$mysql_log.'

    ', 'Database connection failed'); + } + elseif ($problem == 2) + { + hesk_show_error('Database tables already exist!

    + HESK database tables with '.$hesk_settings['db_pfix'].' prefix already exist in this database!

    + To upgrade an existing HESK installation select Update existing install instead.

    + To install a new copy of HESK in the same database use a unique table prefix.'); + } + elseif ($problem == 3) + { + hesk_show_error('Old database tables not found!

    + HESK database tables have not been found in this database!

    + To install HESK use the New install option instead.'); + } + elseif ($problem == 4) + { + hesk_show_error('Version '.HESK_NEW_VERSION.' tables already exist!

    + Your database seems to be compatible with HESK version '.HESK_NEW_VERSION.'

    + To install a new copy of HESK use the New install option instead.'); + } + elseif ($problem == 5) + { + hesk_show_error('MySQL version '.REQUIRE_MYSQL_VERSION.'+ required, you are using: ' . MYSQL_VERSION . '

    + You are using and old and insecure MySQL version with known bugs, security issues and outdated functionality.

    + Ask your hosting company to update your MySQL version.'); + } + elseif ($problem == 6) + { + hesk_show_notice('Please select your help desk timezone'); + } + else + { + hesk_show_notice('Contact your host for help with correct database settings', 'Tip'); + } + ?> + +
    + + +
    + +
    + + + + + + + + + + + + + + + + + + + + + + + +
    Database Host:
    Database Name:
    Database User (login):
    User Password:
    Table prefix:
    + +
    + + + +

    HESK login details

    + +

    Username and password you will use to login into HESK administration.

    + + + + + + + + + + + + + + +
    Choose a Username:
    Choose a Password:
     Generate a random password
    + + +
    + + +
    + +

    Other info

    + + + + + + +
    Help desk timezone: + + +
    + +

     

    + +

    + + + + + +
    + + '.REQUIRE_PHP_VERSION.'+
    required, you are using: ' . PHP_VERSION . '

    + You are using and old and insecure PHP version with known bugs, security issues and outdated functionality.

    + Ask your hosting company to update your PHP version. + '; + } + + // 2. File hesk_settings.inc.php must be writable + if ( ! is__writable(HESK_PATH . 'hesk_settings.inc.php') ) + { + // -> try to CHMOD it + if ( function_exists('chmod') ) + { + @chmod(HESK_PATH . 'hesk_settings.inc.php', 0666); + } + + // -> test again + if ( ! is__writable(HESK_PATH . 'hesk_settings.inc.php') ) + { + $correct_these[] = ' + File hesk_settings.inc.php is not writable by PHP.

    + Make sure PHP has permission to write to file hesk_settings.inc.php

    + » on Linux servers CHMOD this file to 666 (rw-rw-rw-)
    + » on Windows servers allow Internet Guest Account to modify the file
    + » contact your hosting company for help with setting up file permissions. + '; + } + } + + // 3. Folder attachments must exist + $hesk_settings['attach_dir_name'] = isset($hesk_settings['attach_dir']) ? $hesk_settings['attach_dir'] : 'attachments'; + $hesk_settings['attach_dir'] = HESK_PATH . $hesk_settings['attach_dir_name']; + + // -> Try to create it + if ( ! file_exists($hesk_settings['attach_dir']) ) + { + @mkdir($hesk_settings['attach_dir'], 0755); + } + + // -> Is the folder now there? + if ( is_dir($hesk_settings['attach_dir']) ) + { + + // -> Is it writable? + if ( ! is__writable($hesk_settings['attach_dir']) ) + { + // -> try to CHMOD it + @chmod($hesk_settings['attach_dir'], 0777); + + // -> test again + if ( ! is__writable($hesk_settings['attach_dir']) ) + { + $correct_these[] = ' + Folder ' . $hesk_settings['attach_dir_name'] . ' is not writable by PHP.

    + Make sure PHP has permission to write to folder ' . $hesk_settings['attach_dir_name'] . '

    + » on Linux servers CHMOD this folder to 777 (rwxrwxrwx)
    + » on Windows servers allow Internet Guest Account to modify the folder
    + » contact your hosting company for help with setting up folder permissions. + '; + } + } + } + else + { + $correct_these[] = ' + Folder ' . $hesk_settings['attach_dir_name'] . ' is missing.

    + Create a folder called ' . $hesk_settings['attach_dir_name'] . ' inside your main HESK folder.

    + '; + } + + // 3.2 Folder cache must exist + $hesk_settings['cache_dir_name'] = isset($hesk_settings['cache_dir']) ? $hesk_settings['cache_dir'] : 'cache'; + $hesk_settings['cache_dir'] = HESK_PATH . $hesk_settings['cache_dir_name']; + + // -> Try to create it + if ( ! file_exists($hesk_settings['cache_dir']) ) + { + @mkdir($hesk_settings['cache_dir'], 0755); + } + + // -> Is the folder now there? + if ( is_dir($hesk_settings['cache_dir']) ) + { + + // -> Is it writable? + if ( ! is__writable($hesk_settings['cache_dir']) ) + { + // -> try to CHMOD it + @chmod($hesk_settings['cache_dir'], 0777); + + // -> test again + if ( ! is__writable($hesk_settings['cache_dir']) ) + { + $correct_these[] = ' + Folder ' . $hesk_settings['cache_dir_name'] . ' is not writable by PHP.

    + Make sure PHP has permission to write to folder ' . $hesk_settings['cache_dir_name'] . '

    + » on Linux servers CHMOD this folder to 777 (rwxrwxrwx)
    + » on Windows servers allow Internet Guest Account to modify the folder
    + » contact your hosting company for help with setting up folder permissions. + '; + } + } + } + else + { + $correct_these[] = ' + Folder ' . $hesk_settings['cache_dir_name'] . ' is missing.

    + Create a folder called ' . $hesk_settings['cache_dir_name'] . ' inside your main HESK folder.

    + '; + } + + // 4. MySQL must be available + if ( ! function_exists('mysql_connect') && ! function_exists('mysqli_connect') ) + { + $correct_these[] = ' + MySQL is disabled.

    + HESK requires MySQL to be installed and enabled.

    + Ask your hosting company to enable MySQL for PHP. + '; + } + + // 5. Can we use GD library? + $GD_LIB = ( extension_loaded('gd') && function_exists('gd_info') ) ? true : false; + + // 6. Make sure old files are deleted + $hesk_settings['admin_dir'] = isset($hesk_settings['admin_dir']) ? $hesk_settings['admin_dir'] : 'admin'; + $old_files = array( + + // pre-0.93 *.inc files + 'hesk_settings.inc','hesk.sql','inc/common.inc','inc/database.inc','inc/footer.inc','inc/header.inc', + 'inc/print_tickets.inc','inc/show_admin_nav.inc','inc/show_search_form.inc','install.php','update.php', + + // pre-2.0 files + 'admin.php','admin_change_status.php','admin_main.php','admin_move_category','admin_reply_ticket.php', + 'admin_settings.php','admin_settings_save.php','admin_ticket.php','archive.php', + 'delete_tickets.php','find_tickets.php','manage_canned.php','manage_categories.php', + 'manage_users.php','profile.php','show_tickets.php', + + // pre-2.1 files + 'emails/','language/english.php', + + // pre-2.3 files + 'secimg.inc.php', + + // pre-2.4 files + 'hesk_style_v23.css','help_files/','TreeMenu.js', + + // malicious files that were found on some websites illegally redistributing HESK + 'inc/tiny_mce/utils/r00t10.php', 'language/en/help_files/r00t10.php', + + // pre-2.5 files + 'hesk_style_v24.css', 'hesk_javascript_v24.js', + + // pre-2.6 files + 'hesk_style_v25.css', 'hesk_javascript_v25.js', + + // pre-2.7 files, + $hesk_settings['admin_dir'].'/options.php', + + // pre-3.0 files, + $hesk_settings['admin_dir'].'/admin_settings.php', + 'img/add_article.png', + 'img/add_category.png', + 'img/anonymize.png', + 'img/article_text.png', + 'img/autoassign_off.png', + 'img/autoassign_on.png', + 'img/ban.png', + 'img/banned.png', + 'img/blank.gif', + 'img/bluebtn.png', + 'img/clip.png', + 'img/code.png', + 'img/code_off.png', + 'img/delete.png', + 'img/delete_off.png', + 'img/delete_ticket.png', + 'img/edit.png', + 'img/email.png', + 'img/error.png', + 'img/existingticket.png', + 'img/export.png', + 'img/flag_critical.png', + 'img/flag_high.png', + 'img/flag_low.png', + 'img/flag_low2.png', + 'img/flag_medium.png', + 'img/folder-expanded.gif', + 'img/folder.gif', + 'img/greenbtn.jpg', + 'img/greenbtnover.gif', + 'img/header.png', + 'img/headerbgsm.jpg', + 'img/headerleftsm.jpg', + 'img/headerrightsm.jpg', + 'img/header_bottom.png', + 'img/header_bottom_left.png', + 'img/header_bottom_right.png', + 'img/header_left.png', + 'img/header_right.png', + 'img/header_top.png', + 'img/header_up_left.png', + 'img/header_up_right.png', + 'img/ico-search.png', + 'img/ico_canned.gif', + 'img/ico_categories.gif', + 'img/ico_home.gif', + 'img/ico_kb.gif', + 'img/ico_logout.gif', + 'img/ico_mail.gif', + 'img/ico_profile.gif', + 'img/ico_reports.gif', + 'img/ico_settings.gif', + 'img/ico_tools.png', + 'img/ico_users.gif', + 'img/import_kb.png', + 'img/import_kb1.png', + 'img/inbox.png', + 'img/info.png', + 'img/link.png', + 'img/lock.png', + 'img/login.png', + 'img/mail.png', + 'img/manage.png', + 'img/menu.png', + 'img/move_down.png', + 'img/move_down1.png', + 'img/move_down2.png', + 'img/move_down3.png', + 'img/move_down4.png', + 'img/move_down5.png', + 'img/move_down6.png', + 'img/move_down7.png', + 'img/move_down8.png', + 'img/move_down9.png', + 'img/move_up.png', + 'img/move_up1.png', + 'img/move_up2.png', + 'img/move_up3.png', + 'img/move_up4.png', + 'img/move_up5.png', + 'img/move_up6.png', + 'img/move_up7.png', + 'img/move_up8.png', + 'img/move_up9.png', + 'img/newticket.png', + 'img/new_mail.png', + 'img/notice.png', + 'img/online_off.png', + 'img/online_on.png', + 'img/orangebtn.jpg', + 'img/orangebtnover.gif', + 'img/orangebtnsec.jpg', + 'img/outbox.png', + 'img/print.png', + 'img/private.png', + 'img/public.png', + 'img/refresh.png', + 'img/reload.png', + 'img/roundcornersb.jpg', + 'img/roundcornerslb.jpg', + 'img/roundcornerslm.jpg', + 'img/roundcornerslt.jpg', + 'img/roundcornersrb.jpg', + 'img/roundcornersrm.jpg', + 'img/roundcornersrt.jpg', + 'img/roundcornerst.jpg', + 'img/sort_priority_asc.png', + 'img/sort_priority_desc.png', + 'img/star_0.png', + 'img/star_10.png', + 'img/star_15.png', + 'img/star_20.png', + 'img/star_25.png', + 'img/star_30.png', + 'img/star_35.png', + 'img/star_40.png', + 'img/star_45.png', + 'img/star_50.png', + 'img/sticky.png', + 'img/sticky_off.png', + 'img/success.png', + 'img/tableheader.jpg', + 'img/tag.png', + 'img/tag_off.png', + 'img/unlock.png', + 'img/vertical.jpg', + 'img/view.png', + 'inc/calendar/' + ); + + sort($old_files); + + $still_exist = array(); + + foreach ($old_files as $f) + { + if (file_exists(HESK_PATH . $f)) + { + //Try to remove the file + @unlink(HESK_PATH . $f); + + // If not successful, ask the user to delete those files + if (file_exists(HESK_PATH . $f)) + { + $still_exist[] = $f; + } + } + } + + if ( count($still_exist) ) + { + $correct_these[] = ' + Outdated files and folders

    + For security reasons please delete these legacy files and folders:
    +
    • '.implode('
    • ',$still_exist).'
    + '; + } + + // Do we have any errors? + if ( count($correct_these) ) + { + hesk_iHeader(); + ?> + +   + + + +
    +

    +
    +

     

    + +

    HESK Software End User License Agreement

    +

    Read the HESK End-User License Agreement here

    +
    +

     

    +

     

    + '; + + echo file_exists('../docs/license.html') ? '' : $eula_alt; + ?> + +

     

    + +
    +
    + + + + +
    + +

    Do you accept the HESK Software End-User License Agreement?
     

    + +

    + + +   + +

    + +

     

    + +
    +
    +
    + + '1. License agreement', + 2 => '2. Check setup', + 3 => '3. Setup Database', + 4 => '4. Finishing touches' + ); + + ?> + + + + HESK setup script: <?php echo HESK_NEW_VERSION; ?> + + + + + + +
    + + + + + + + +
    + + + + + + +
    HESK setup script:
    +
    + + + + + + + +
    + $description) + { + if ($number == $_SESSION['step']) + { + $steps[$number] = '' . $steps[$number] . ''; + } + elseif ($number < $_SESSION['step']) + { + $steps[$number] = '' . $steps[$number] . ''; + } + } + + echo implode(' » ', $steps); + ?> +
    + +
    + Read installation guide before using this setup script!', 'Important'); + } + ?> + +
    + + + + + + + + + + + + + + + + +
      + +  
    +
    + +

     
    Powered by Help Desk Software HESK, in partnership with SysAid Technologies

    +
    +
    + + + + +
    +
    + + Error: PHP sessions not working!

    Note that this is a server configuration issue, not a HESK issue.

    Please contact your hosting company and ask them to verify why PHP sessions aren't working on your server! +
    +
    + +
    +

    +
    + + $sub_v) + { + $v[$k] = hesk_compareVariable($sub_k,$sub_v); + } + } + + if (isset($hesk_settings[$k])) + { + return $hesk_settings[$k]; + } + else + { + return $v; + } +} // END hesk_compareVariable() + + +function is__writable($path) +{ +//will work in despite of Windows ACLs bug +//NOTE: use a trailing slash for folders!!! +//see http://bugs.php.net/bug.php?id=27609 +//see http://bugs.php.net/bug.php?id=30931 + + if ($path[strlen($path)-1]=='/') // recursively return a temporary file path + return is__writable($path.uniqid(mt_rand()).'.tmp'); + else if (is_dir($path)) + return is__writable($path.'/'.uniqid(mt_rand()).'.tmp'); + // check tmp file for read/write capabilities + $rm = file_exists($path); + $f = @fopen($path, 'a'); + if ($f===false) + return false; + fclose($f); + if (!$rm) + unlink($path); + return true; +} // END is__writable() diff --git a/hesk/install/update.php b/hesk/install/update.php new file mode 100644 index 0000000..3b1b838 --- /dev/null +++ b/hesk/install/update.php @@ -0,0 +1,1634 @@ + + +

    Update database tables

    + +
    + + +
    Please enable a different anti-SPAM measure in HESK settings.'); + } + ?> + +

    Things to do next:

    + +
      + +
    1. Delete the /install folder from your server!
       
    2. + +
    3. Login to HESK administration panel and make sure everything works fine.

      + +
      +

      +
      + +
    4. + +
    + +

     

    + + $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}'"); + + // Force order articles + $res = hesk_dbQuery("SELECT `id`, `sticky` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` WHERE `catid`='{$catid}' ORDER BY `sticky` DESC, `art_order` ASC"); + + $i = 10; + $previous_sticky = 1; + + while ( $article = hesk_dbFetchAssoc($res) ) + { + 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; + } + } + + // Force order categories + $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; + } + + $update_all_next = 1; + } // END version 2.4.0 to 2.5.0 + + // 2.5.1 no changes + // 2.5.2 no changes + // 2.5.3 no changes + // 2.5.4 no changes + // 2.5.5 no changes + + // Upgrade version 2.5.x to 2.6.0 + if ($update_all_next || $hesk_settings['update_from'] == '2.5') + { + // -> Banned emails + hesk_dbQuery(" + CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."banned_emails` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `email` varchar(255) NOT NULL, + `banned_by` smallint(5) unsigned NOT NULL, + `dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + KEY `email` (`email`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8 + "); + + // -> Banned IPs + hesk_dbQuery(" + CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."banned_ips` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `ip_from` int(10) unsigned NOT NULL DEFAULT '0', + `ip_to` int(10) unsigned NOT NULL DEFAULT '0', + `ip_display` varchar(100) NOT NULL, + `banned_by` smallint(5) unsigned NOT NULL, + `dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8 + "); + + // -> Reply drafts + hesk_dbQuery(" + CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."reply_drafts` ( + `owner` smallint(5) unsigned NOT NULL, + `ticket` mediumint(8) unsigned NOT NULL, + `message` mediumtext CHARACTER SET utf8 NOT NULL, + `dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + KEY `owner` (`owner`), + KEY `ticket` (`ticket`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci + "); + + // -> Reset password + hesk_dbQuery(" + CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."reset_password` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `user` smallint(5) unsigned NOT NULL, + `hash` char(40) NOT NULL, + `ip` varchar(45) NOT NULL, + `dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + KEY `user` (`user`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8; + "); + + // -> Service messages + hesk_dbQuery(" + CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."service_messages` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `author` smallint(5) unsigned NOT NULL, + `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `message` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `style` enum('0','1','2','3','4') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + `type` enum('0','1') COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + `order` smallint(5) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `type` (`type`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + "); + + // -> Ticket templates + hesk_dbQuery(" + CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."ticket_templates` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `title` varchar(100) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `message` mediumtext COLLATE utf8_unicode_ci NOT NULL, + `tpl_order` smallint(5) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci + "); + + // 2.6.0 table changes + $sql = array(); + + $sql[] = "ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."mail` CHANGE `dt` `dt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP"; + $sql[] = "ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."notes` CHANGE `dt` `dt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP"; + $sql[] = "ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` CHANGE `dt` `dt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP"; + + $sql[] = "ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."attachments` ADD `type` ENUM( '0', '1' ) NOT NULL DEFAULT '0'"; + + $sql[] = "ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` ADD `priority` ENUM( '0', '1', '2', '3' ) NOT NULL DEFAULT '3'"; + + $sql[] = "ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` CHANGE `type` `type` ENUM('0','1') CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '0'"; + + $sql[] = "ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."logins` CHANGE `ip` `ip` VARCHAR(45) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL"; + + $sql[] = "ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."notes` ADD `attachments` MEDIUMTEXT NOT NULL"; + + $sql[] = "ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."pipe_loops` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci"; + + $sql[] = "ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` CHANGE `rating` `rating` ENUM('1','5') CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL, ADD INDEX(`dt`), ADD INDEX(`staffid`)"; + + $sql[] = "ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` + CHANGE `email` `email` VARCHAR( 1000 ) NOT NULL DEFAULT '', + CHANGE `ip` `ip` VARCHAR(45) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + ADD `firstreply` TIMESTAMP NULL DEFAULT NULL AFTER `lastchange`, + ADD `closedat` TIMESTAMP NULL DEFAULT NULL AFTER `firstreply`, + ADD `articles` VARCHAR(255) NULL DEFAULT NULL AFTER `closedat`, + ADD `openedby` MEDIUMINT(8) DEFAULT '0' AFTER `status`, + ADD `firstreplyby` SMALLINT(5) UNSIGNED NULL DEFAULT NULL AFTER `openedby`, + ADD `closedby` MEDIUMINT(8) NULL DEFAULT NULL AFTER `firstreplyby`, + ADD `replies` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0' AFTER `closedby`, + ADD `staffreplies` SMALLINT( 5 ) UNSIGNED NOT NULL DEFAULT '0' AFTER `replies`, + ADD INDEX ( `openedby` , `firstreplyby` , `closedby` ), + ADD INDEX(`dt`)"; + + $sql[] = "ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."users` + CHANGE `signature` `signature` VARCHAR( 1000 ) NOT NULL DEFAULT '', + CHANGE `heskprivileges` `heskprivileges` VARCHAR(1000) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL, + CHANGE `categories` `categories` VARCHAR(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + ADD `notify_customer_new` ENUM('0','1') NOT NULL DEFAULT '1' AFTER `autostart`, + ADD `notify_customer_reply` ENUM('0','1') NOT NULL DEFAULT '1' AFTER `notify_customer_new`, + ADD `show_suggested` ENUM('0','1') NOT NULL DEFAULT '1' AFTER `notify_customer_reply`"; + + foreach ($sql as $s) + { + hesk_dbQuery($s); + } + + // ==> Populate new fields where available + + // Get list of valid ticket categories + $cat = array(); + $res = hesk_dbQuery("SELECT `id` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories`"); + while ($row=hesk_dbFetchAssoc($res)) + { + $cat[]=$row['id']; + } + + + // Update tickets + $res = hesk_dbQuery("SELECT `id`, `category` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets`"); + while ($ticket = hesk_dbFetchAssoc($res) ) + { + $sql = array(); + + // Verify that the category is valid + if ( ! in_array($ticket['category'], $cat) ) + { + $sql[] = " `category`=1 "; + } + + + // Update number of staff replies + $res2 = hesk_dbQuery("SELECT COUNT(*) as `cnt`, (CASE WHEN `staffid` = 0 THEN 0 ELSE 1 END) AS `staffcnt` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` WHERE `replyto`=".intval($ticket['id'])." GROUP BY `staffcnt`"); + + $total = 0; + $staffreplies = 0; + + while ( $row = hesk_dbFetchAssoc($res2) ) + { + $total += $row['cnt']; + $staffreplies += ($row['staffcnt'] ? $row['cnt'] : 0); + } + + if ( $total > 0 ) + { + $sql[] = " `replies`={$total}, `staffreplies`={$staffreplies} "; + } + + // If we have staff replies, find the first one + if ( $staffreplies > 0 ) + { + $res2 = hesk_dbQuery("SELECT `dt`, `staffid` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` WHERE `replyto`={$ticket['id']} AND `staffid`>0 ORDER BY `id` ASC LIMIT 1"); + + if ( hesk_dbNumRows($res2) == 1) + { + $reply = hesk_dbFetchAssoc($res2); + $sql[] = " `firstreply`='".hesk_dbEscape($reply['dt'])."', `firstreplyby`={$reply['staffid']} "; + } + } + + // Do we need to update the ticket? + if ( count($sql) ) + { + hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET " . implode(',', $sql) . ", `lastchange`=`lastchange` WHERE `id`={$ticket['id']}"); + } + } + + $update_all_next = 1; + } // END version 2.5.x to 2.6.0 + + // 2.6.1 no changes + + // 2.6.2 change `closedby` type for all 2.6.x to be sure + if ($hesk_settings['update_from'] == '2.6') + { + hesk_dbQuery("ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` CHANGE `closedby` `closedby` MEDIUMINT(8) NULL DEFAULT NULL"); + } + + // 2.6.3 no changes + // 2.6.4 no changes + // 2.6.5 no changes + // 2.6.6 no changes + // 2.6.7 no changes + + // Updating version 2.6 to 2.7 + if ($update_all_next || $hesk_settings['update_from'] == '2.6') + { + // Delete old export folder + $export_dir = HESK_PATH.$hesk_settings['attach_dir'].'/export/'; + if (is_dir($export_dir)) + { + $files = glob($export_dir.'*', GLOB_NOSORT); + if (is_array($files)) + { + array_walk($files, 'hesk_unlink_callable'); + } + @rmdir($export_dir); + } + + // Delete old __latest.txt file + hesk_unlink(HESK_PATH.$hesk_settings['attach_dir'].'/__latest.txt'); + + // Delete HTMLPurifier cache + if (is_dir(HESK_PATH.'inc/htmlpurifier/standalone/HTMLPurifier/DefinitionCache/Serializer')) + { + hesk_rrmdir(HESK_PATH.'inc/htmlpurifier/standalone/HTMLPurifier/DefinitionCache/Serializer', true); + } + + $sql = array(); + + $sql[] = "ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."users` ADD `autoreload` SMALLINT UNSIGNED NOT NULL DEFAULT '0' AFTER `autostart`"; + + foreach ($sql as $s) + { + hesk_dbQuery($s); + } + + // Add new custom field columns and make sure all are set to mediumtext + $sql = array(); + $table = array(); + + // Is the status column an enum type? (HESK < 2.7.0) If no, don't subtract 1 later on + $res = hesk_dbQuery("SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '".hesk_dbEscape($hesk_settings['db_name'])."' AND TABLE_NAME = '".hesk_dbEscape($hesk_settings['db_pfix'])."tickets' AND COLUMN_NAME = 'status'"); + $adjust_status_column = false; + if (hesk_dbResult($res) == 'enum') { + $adjust_status_column = true; + } + // Change the type regardless + $sql[] = "CHANGE `status` `status` TINYINT UNSIGNED NOT NULL DEFAULT '0'"; + + $res = hesk_dbQuery("DESCRIBE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets`"); + while($row = hesk_dbFetchAssoc($res)) + { + $table[$row['Field']] = $row['Type']; + } + + for ($i=1; $i<=50; $i++) + { + if (isset($table['custom'.$i])) + { + if (strtolower($table['custom'.$i]) != 'mediumtext') + { + $sql[] = 'CHANGE `custom'.$i.'` `custom'.$i.'` MEDIUMTEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL'; + } + } + else + { + $sql[] = 'ADD `custom'.$i.'` MEDIUMTEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL'; + } + } + + hesk_dbQuery("ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` " . implode(',', $sql)); + + // A tweak to fix converting enum to int + if ($adjust_status_column) { + hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `status`=`status`-1, `lastchange`=`lastchange`"); + } + + // -> Custom fields + hesk_dbQuery(" + CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_fields` ( + `id` tinyint(3) UNSIGNED NOT NULL, + `use` enum('0','1','2') NOT NULL DEFAULT '0', + `place` enum('0','1') NOT NULL DEFAULT '0', + `type` varchar(20) NOT NULL DEFAULT 'text', + `req` enum('0','1','2') NOT NULL DEFAULT '0', + `category` text, + `name` text, + `value` text, + `order` smallint(5) UNSIGNED NOT NULL DEFAULT '10', + PRIMARY KEY (`id`), + KEY `useType` (`use`,`type`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci + "); + + // ---> Insert empty custom fields + hesk_dbQuery(" + INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_fields` (`id`, `use`, `place`, `type`, `req`, `category`, `name`, `value`, `order`) VALUES + (1, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (2, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (3, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (4, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (5, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (6, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (7, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (8, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (9, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (10, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (11, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (12, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (13, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (14, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (15, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (16, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (17, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (18, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (19, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (20, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (21, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (22, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (23, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (24, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (25, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (26, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (27, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (28, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (29, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (30, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (31, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (32, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (33, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (34, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (35, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (36, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (37, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (38, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (39, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (40, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (41, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (42, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (43, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (44, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (45, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (46, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (47, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (48, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (49, '0', '0', 'text', '0', NULL, '', NULL, 1000), + (50, '0', '0', 'text', '0', NULL, '', NULL, 1000) + "); + + // ---> Update custom fields with current values + if (isset($hesk_settings['custom_fields'])) + { + foreach ($hesk_settings['custom_fields'] as $k => $v) + { + if ( ! $v['use']) + { + continue; + } + + $cf = array(); + + // ID + $id = intval(str_replace('custom', '', $k)); + + // Name + $cf['names'][$hesk_settings['language']] = $v['name']; + $cf['names'] = addslashes(json_encode($cf['names'])); + + // Type and value + $cf['type'] = $v['type']; + switch ($cf['type']) + { + case 'textarea': + $size = explode('#',$v['value']); + $cf['rows'] = empty($size[0]) ? 5 : intval($size[0]); + $cf['cols'] = empty($size[1]) ? 30 : intval($size[1]); + $cf['value'] = array('rows' => $cf['rows'], 'cols' => $cf['cols']); + break; + + case 'radio': + $options = explode('#HESK#',$v['value']); + $cf['value'] = array('radio_options' => $options); + break; + + case 'select': + $v['value'] = str_replace('{HESK_SELECT}', '', $v['value'], $num); + $options = explode('#HESK#',$v['value']); + $cf['value'] = array('show_select' => ($num ? 1 : 0), 'select_options' => $options); + break; + + case 'checkbox': + $options = explode('#HESK#',$v['value']); + $cf['value'] = array('checkbox_options' => $options); + break; + + default: + $cf['type'] = 'text'; + $cf['max_length'] = intval($v['maxlen']); + $cf['default_value'] = $v['value']; + $cf['value'] = array('max_length' => $cf['max_length'], 'default_value' => $cf['default_value']); + } + + $cf['value'] = addslashes(json_encode($cf['value'])); + + // Update custom_fields table with this field settings + hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_fields` SET + `use` = '1', + `place` = '".($v['place'] ? '1' : '0')."', + `type` = '{$cf['type']}', + `req` = '".($v['req'] ? '1' : '0')."', + `name` = '".hesk_dbEscape($cf['names'])."', + `value` = ".(strlen($cf['value']) ? "'".hesk_dbEscape($cf['value'])."'" : 'NULL')." + WHERE `id`={$id}"); + } + } + + // -> Custom statuses + hesk_dbQuery(" + CREATE TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."custom_statuses` ( + `id` tinyint(3) UNSIGNED NOT NULL, + `name` text NOT NULL, + `color` varchar(6) NOT NULL, + `can_customers_change` enum('0','1') NOT NULL DEFAULT '1', + `order` smallint(5) UNSIGNED NOT NULL DEFAULT '10', + PRIMARY KEY (`id`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci + "); + + // Update staff with new permissions (allowed by default) + hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."users` SET `heskprivileges`=CONCAT(`heskprivileges`,',can_resolve,can_submit_any_cat') WHERE `isadmin` = '0' AND `heskprivileges` LIKE '%can_reply_tickets%' "); + + $update_all_next = 1; + } // END version 2.6 to 2.7 + + // Updating version 2.7 to 2.8 + if ($update_all_next || $hesk_settings['update_from'] == '2.7') + { + // Modify tickets table + hesk_dbQuery("ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` ADD `assignedby` MEDIUMINT NULL DEFAULT NULL AFTER `owner`, ADD INDEX (`assignedby`)"); + + $update_all_next = 1; + } // END version 2.7 to 2.8 + + // Updating 2.8 to 2.8.2 + if ($update_all_next || $hesk_settings['update_from'] == '2.8') + { + // Modify service_messages table + hesk_dbQuery("ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."service_messages` ADD `language` VARCHAR(50) NULL DEFAULT NULL AFTER `message`"); + + $update_all_next = 1; + } // END version 2.8 to 2.8.2 + + // Updating 2.8.2 to 2.8.3 + if ($update_all_next || $hesk_settings['update_from'] == '2.8.2') + { + // Modify tickets table + hesk_dbQuery("ALTER TABLE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` CHANGE `name` `name` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '', CHANGE `subject` `subject` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT ''"); + + $update_all_next = 1; + } // END version 2.8.2 to 2.8.3 + + // 2.8.4 no changes + // 2.8.5 no changes + // 3.0.0 no changes + + // Insert the "HESK updated to latest version" mail for the administrator + if ( file_exists(HESK_PATH.'hesk_license.php') ) + { + hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."mail` (`id`, `from`, `to`, `subject`, `message`, `dt`, `read`, `deletedby`) VALUES (NULL, 9999, 1, 'HESK updated to version ".HESK_NEW_VERSION."', '".hesk_dbEscape("

    \r\n\r\n

     
    Congratulations, your HESK has been successfully updated.

    \r\n\r\n

    Before you go, let me invite you to:
     

    \r\n\r\n
    \r\n#1: help us improve\r\n
    \r\n

    You can suggest what features should be added to HESK by posting them here.

    \r\n\r\n \r\n\r\n
    \r\n#2: stay updated\r\n
    \r\n

    HESK regularly receives improvements and bug fixes, make sure you know about them!

    \r\n\r\n\r\n

     

    \r\n\r\n

    Best regards,

    \r\n\r\n

    Klemen Stirn
    \r\nAuthor and owner

    \r\n\r\n

    ")."', NOW(), '0', 9999)"); + } + else + { + hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."mail` (`id`, `from`, `to`, `subject`, `message`, `dt`, `read`, `deletedby`) VALUES (NULL, 9999, 1, 'HESK updated to version ".HESK_NEW_VERSION."', '".hesk_dbEscape("

    \r\n\r\n

     
    Congratulations, your HESK has been successfully updated.

    \r\n\r\n

    Before you go, let me invite you to:
     

    \r\n\r\n
    \r\n#1: help us improve\r\n
    \r\n

    You can suggest what features should be added to HESK by posting them here.

    \r\n\r\n \r\n\r\n
    \r\n#2: stay updated\r\n
    \r\n

    HESK regularly receives improvements and bug fixes, make sure you know about them!

    \r\n\r\n\r\n \r\n\r\n
    \r\n#3: look professional\r\n
    \r\n

    To look more professional and not advertise the tools you use, remove "Powered by" links from your help desk.

    \r\n\r\n

     

    \r\n\r\n

    Best regards,

    \r\n\r\n

    Klemen Stirn
    \r\nAuthor and owner

    \r\n\r\n

    ")."', NOW(), '0', 9999)"); + } + + return true; + +} // End hesk_iUpdateTables() + + +function hesk_iSaveSettings() +{ + global $hesk_settings, $hesklang; + + // Get default settings + $hesk_default = hesk_defaultSettings(); + + // Set a new version number + $hesk_settings['hesk_version'] = HESK_NEW_VERSION; + + // Correct typos in variable names before 2.4 + if ( isset($hesk_settings['stmp_host_port']) ) + { + $hesk_settings['smtp_host_port'] = isset($hesk_settings['stmp_host_port']) ? $hesk_settings['stmp_host_port'] : 25; + $hesk_settings['smtp_timeout'] = isset($hesk_settings['stmp_timeout']) ? $hesk_settings['stmp_timeout'] : 10; + $hesk_settings['smtp_user'] = isset($hesk_settings['stmp_user']) ? $hesk_settings['stmp_user'] : ''; + $hesk_settings['smtp_password'] = isset($hesk_settings['stmp_password']) ? $hesk_settings['stmp_password'] : ''; + } + + // Assign all required values + foreach ($hesk_default as $k => $v) + { + if (is_array($v)) + { + // Arrays will be processed separately + continue; + } + if ( ! isset($hesk_settings[$k])) + { + $hesk_settings[$k] = $v; + } + } + + // Arrays need special care + $hesk_settings['attachments'] = isset($hesk_settings['attachments']) ? $hesk_settings['attachments'] : $hesk_default['attachments']; + $hesk_settings['email_providers'] = isset($hesk_settings['email_providers']) ? array_unique(array_merge($hesk_settings['email_providers'], $hesk_default['email_providers'])) : $hesk_default['email_providers']; + $hesk_settings['notify_spam_tags'] = isset($hesk_settings['notify_spam_tags']) ? $hesk_settings['notify_spam_tags'] : $hesk_default['notify_spam_tags']; + $hesk_settings['ticket_list'] = isset($hesk_settings['ticket_list']) ? $hesk_settings['ticket_list'] : $hesk_default['ticket_list']; + + // Attachments max size must be multiplied by 1024 since version 2.4 + if ($hesk_settings['attachments']['max_size'] < 102400) + { + $hesk_settings['attachments']['max_size'] = $hesk_settings['attachments']['max_size'] * 1024; + } + + // Encode and escape characters + $set = $hesk_settings; + foreach ($hesk_settings as $k=> $v) + { + if (is_array($v) || is_object($v)) + { + continue; + } + $set[$k] = addslashes($v); + } + $set['debug_mode'] = 0; + + $set['email_providers'] = count($hesk_settings['email_providers']) ? "'" . implode("','", $hesk_settings['email_providers']) . "'" : ''; + $set['notify_spam_tags'] = count($hesk_settings['notify_spam_tags']) ? "'" . implode("','", $hesk_settings['notify_spam_tags']) . "'" : ''; + $set['ip_whois'] = str_replace('http://whois.domaintools.com', 'https://whois.domaintools.com', $set['ip_whois']); + + // Check if PHP version is 5.2.3+ and MySQL is 5.0.7+ + $set['db_vrsn'] = (version_compare(PHP_VERSION, '5.2.3') >= 0) ? 1 : 0; + + // reCaptcha v1 has been removed in 2.8, disable it + if ($set['recaptcha_use'] == 1 && version_compare($hesk_settings['update_from'], '2.8', '<')) + { + $set['recaptcha_use'] = 0; + define('RECAPTCHA_V1', true); + } + + hesk_iSaveSettingsFile($set); + + return true; + +} // End hesk_iSaveSettings() + + +function hesk_defaultSettings() +{ + $spam_question = hesk_generate_SPAM_question(); + + $secimg_sum = ''; + for ($i=1;$i<=10;$i++) + { + $secimg_sum .= substr('AEUYBDGHJLMNPQRSTVWXZ123456789', rand(0,29), 1); + } + + // --> General settings + $hesk_settings['site_title']='Website'; + $hesk_settings['site_url']='http://www.example.com'; + $hesk_settings['webmaster_mail']='support@example.com'; + $hesk_settings['noreply_mail']='noreply@example.com'; + $hesk_settings['noreply_name']='Help Desk'; + $hesk_settings['site_theme']='hesk3'; + + // --> Language settings + $hesk_settings['can_sel_lang']=0; + $hesk_settings['language']='English'; + $hesk_settings['languages']=array( + 'English' => array('folder'=>'en','hr'=>'------ Reply above this line ------'), + ); + + // --> Database settings + $hesk_settings['db_host']='localhost'; + $hesk_settings['db_name']='hesk'; + $hesk_settings['db_user']='test'; + $hesk_settings['db_pass']='test'; + $hesk_settings['db_pfix']='hesk_'; + $hesk_settings['db_vrsn']=0; + + + // ==> HELP DESK + + // --> Help desk settings + $hesk_settings['hesk_title']='Help Desk'; + $hesk_settings['hesk_url']='http://www.example.com/helpdesk'; + $hesk_settings['admin_dir']='admin'; + $hesk_settings['attach_dir']='attachments'; + $hesk_settings['cache_dir']='cache'; + $hesk_settings['max_listings']=20; + $hesk_settings['print_font_size']=12; + $hesk_settings['autoclose']=0; + $hesk_settings['max_open']=0; + $hesk_settings['new_top']=0; + $hesk_settings['reply_top']=0; + + // --> Features + $hesk_settings['autologin']=1; + $hesk_settings['autoassign']=1; + $hesk_settings['require_email']=1; + $hesk_settings['require_owner']=0; + $hesk_settings['require_subject']=1; + $hesk_settings['require_message']=1; + $hesk_settings['custclose']=1; + $hesk_settings['custopen']=1; + $hesk_settings['rating']=1; + $hesk_settings['cust_urgency']=1; + $hesk_settings['sequential']=1; + $hesk_settings['time_worked']=1; + $hesk_settings['spam_notice']=1; + $hesk_settings['list_users']=0; + $hesk_settings['debug_mode']=0; + $hesk_settings['short_link']=0; + $hesk_settings['select_cat']=0; + $hesk_settings['select_pri']=0; + $hesk_settings['cat_show_select']=15; + + // --> SPAM Prevention + $hesk_settings['secimg_use']=1; + $hesk_settings['secimg_sum']=$secimg_sum; + $hesk_settings['recaptcha_use']=0; + $hesk_settings['recaptcha_public_key']=''; + $hesk_settings['recaptcha_private_key']=''; + $hesk_settings['question_use']=0; + $hesk_settings['question_ask']=$spam_question[0]; + $hesk_settings['question_ans']=$spam_question[1]; + + // --> Security + $hesk_settings['attempt_limit']=6; + $hesk_settings['attempt_banmin']=60; + $hesk_settings['reset_pass']=1; + $hesk_settings['email_view_ticket']=1; + $hesk_settings['x_frame_opt']=1; + $hesk_settings['force_ssl']=0; + + // --> Attachments + $hesk_settings['attachments']=array ( + 'use' => 1, + 'max_number' => 2, + 'max_size' => 2097152, + 'allowed_types' => array('.gif','.jpg','.png','.zip','.rar','.csv','.doc','.docx','.xls','.xlsx','.txt','.pdf') + ); + + + // ==> KNOWLEDGEBASE + + // --> Knowledgebase settings + $hesk_settings['kb_enable']=1; + $hesk_settings['kb_wysiwyg']=1; + $hesk_settings['kb_search']=2; + $hesk_settings['kb_search_limit']=10; + $hesk_settings['kb_views']=0; + $hesk_settings['kb_date']=0; + $hesk_settings['kb_recommendanswers']=1; + $hesk_settings['kb_rating']=1; + $hesk_settings['kb_substrart']=200; + $hesk_settings['kb_cols']=2; + $hesk_settings['kb_numshow']=3; + $hesk_settings['kb_popart']=6; + $hesk_settings['kb_latest']=6; + $hesk_settings['kb_index_popart']=6; + $hesk_settings['kb_index_latest']=0; + $hesk_settings['kb_related']=5; + + + // ==> EMAIL + + // --> Email sending + $hesk_settings['smtp']=0; + $hesk_settings['smtp_host_name']='mail.example.com'; + $hesk_settings['smtp_host_port']=25; + $hesk_settings['smtp_timeout']=10; + $hesk_settings['smtp_ssl']=0; + $hesk_settings['smtp_tls']=0; + $hesk_settings['smtp_user']=''; + $hesk_settings['smtp_password']=''; + + // --> Email piping + $hesk_settings['email_piping']=0; + + // --> POP3 Fetching + $hesk_settings['pop3']=0; + $hesk_settings['pop3_job_wait']=15; + $hesk_settings['pop3_host_name']='mail.example.com'; + $hesk_settings['pop3_host_port']=110; + $hesk_settings['pop3_tls']=0; + $hesk_settings['pop3_keep']=0; + $hesk_settings['pop3_user']=''; + $hesk_settings['pop3_password']=''; + + // --> IMAP Fetching + $hesk_settings['imap']=0; + $hesk_settings['imap_job_wait']=15; + $hesk_settings['imap_host_name']='mail.example.com'; + $hesk_settings['imap_host_port']=993; + $hesk_settings['imap_enc']='ssl'; + $hesk_settings['imap_keep']=0; + $hesk_settings['imap_user']=''; + $hesk_settings['imap_password']=''; + + // --> Email loops + $hesk_settings['loop_hits']=6; + $hesk_settings['loop_time']=300; + + // --> Detect email typos + $hesk_settings['detect_typos']=1; + $hesk_settings['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'); + + // --> Notify customer when + $hesk_settings['notify_new']=1; + $hesk_settings['notify_skip_spam']=1; + $hesk_settings['notify_spam_tags']=array('Spam?}','***SPAM***','[SPAM]','SPAM-LOW:','SPAM-MED:'); + $hesk_settings['notify_closed']=1; + + // --> Other + $hesk_settings['strip_quoted']=1; + $hesk_settings['eml_req_msg']=0; + $hesk_settings['save_embedded']=1; + $hesk_settings['multi_eml']=0; + $hesk_settings['confirm_email']=0; + $hesk_settings['open_only']=1; + + // ==> TICKET LIST + + $hesk_settings['ticket_list']=array('trackid','lastchange','name','subject','status','lastreplier'); + + // --> Other + $hesk_settings['submittedformat']=2; + $hesk_settings['updatedformat']=2; + + + // ==> MISC + + // --> Date & Time + $hesk_settings['timezone']=date_default_timezone_get(); + $hesk_settings['timeformat']='Y-m-d H:i:s'; + + // --> Other + $hesk_settings['ip_whois']='https://whois.domaintools.com/{IP}'; + $hesk_settings['maintenance_mode']=0; + $hesk_settings['alink']=1; + $hesk_settings['submit_notice']=0; + $hesk_settings['online']=0; + $hesk_settings['online_min']=10; + $hesk_settings['check_updates']=1; + + return $hesk_settings; +} // END hesk_defaultSettings() + + +function hesk_iDetectVersion() +{ + global $hesk_settings, $hesklang; + + // Version 2.8.3 tables installed? + $res = hesk_dbQuery("SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '".hesk_dbEscape($hesk_settings['db_pfix'])."tickets' AND table_schema = '".hesk_dbEscape($hesk_settings['db_name'])."' AND column_name = 'name' LIMIT 0, 1"); + $row = hesk_dbFetchRow($res); + if ($row[0] == 255) + { + return '2.8.3'; + } + + // Version 2.8.2 tables installed? + $res = hesk_dbQuery("SHOW TABLES FROM `".hesk_dbEscape($hesk_settings['db_name'])."` LIKE '".hesk_dbEscape($hesk_settings['db_pfix'])."service_messages'"); + if (hesk_dbNumRows($res)) + { + $res = hesk_dbQuery("SHOW COLUMNS FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."service_messages` LIKE 'language'"); + if (hesk_dbNumRows($res)) + { + return '2.8.2'; + } + } + + // Version 2.8 tables installed? + $res = hesk_dbQuery("SHOW COLUMNS FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` LIKE 'assignedby'"); + if (hesk_dbNumRows($res)) + { + return '2.8'; + } + + // Get a list of tables from the database + $tables = array(); + $res = hesk_dbQuery('SHOW TABLES FROM `'.hesk_dbEscape($hesk_settings['db_name']).'`'); + + while ($row = hesk_dbFetchRow($res)) + { + $tables[] = $row[0]; + } + + // Version 2.7 tables installed? + if ( + in_array($hesk_settings['db_pfix'].'custom_fields', $tables) || + in_array($hesk_settings['db_pfix'].'custom_statuses', $tables) + ) + { + return '2.7'; + } + + // Version 2.6 tables installed? + if ( + in_array($hesk_settings['db_pfix'].'banned_emails', $tables) || + in_array($hesk_settings['db_pfix'].'banned_ips', $tables) || + in_array($hesk_settings['db_pfix'].'reply_drafts', $tables) || + in_array($hesk_settings['db_pfix'].'reset_password', $tables) || + in_array($hesk_settings['db_pfix'].'service_messages', $tables) || + in_array($hesk_settings['db_pfix'].'ticket_templates', $tables) + ) + { + return '2.6'; + } + + // Version 2.4/2.5 tables installed? + elseif (in_array($hesk_settings['db_pfix'].'pipe_loops', $tables)) + { + // Version 2.4 didn't have articles_private in kb_categories + $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_categories` WHERE `id`=1 LIMIT 1"); + $row = hesk_dbFetchAssoc($res); + if (isset($row['articles_private'])) + { + // This is one of the 2.5.x version + // Database is 100% compatible, so let's be safe and return 2.5 + return '2.5'; + } + else + { + return '2.4'; + } + } + + // Version 2.3 tables installed? + elseif (in_array($hesk_settings['db_pfix'].'online', $tables) || in_array($hesk_settings['db_pfix'].'logins', $tables)) + { + return '2.3'; + } + + // Version 2.2 tables installed? + elseif (in_array($hesk_settings['db_pfix'].'mail', $tables)) + { + return '2.2'; + } + + // Version 2.1 tables installed? + elseif (in_array($hesk_settings['db_pfix'].'kb_attachments', $tables)) + { + return '2.1'; + } + + // Version 2.0 tables installed? + elseif (in_array($hesk_settings['db_pfix'].'kb_articles', $tables)) + { + return '2.0'; + } + + // Version 0.94.1 tables installed? + elseif (in_array('hesk_attachments', $tables)) + { + return '0.94.1'; + } + + // Version 0.94 tables installed? + elseif (in_array('hesk_std_replies', $tables)) + { + return '0.94'; + } + + // It's a version older than 0.94 or no tables found + else + { + // If we don't have four basic tables this is not a valid HESK install + if ( ! in_array('hesk_categories', $tables) || ! in_array('hesk_replies', $tables) || ! in_array('hesk_tickets', $tables) || ! in_array('hesk_users', $tables) ) + { + hesk_iDatabase(3); + } + + // Version 0.90 didn't have the notify column in users table + $res = hesk_dbQuery("SELECT * FROM `hesk_users` WHERE `id`=1 LIMIT 1"); + $row = hesk_dbFetchAssoc($res); + if (isset($row['notify'])) + { + return '0.91-0.93.1'; + } + else + { + // Wow, we found someone using the very first HESK version :-) + return '0.90'; + } + } + +} // END hesk_iDetectVersion() +?> + diff --git a/hesk/ip_whois.php b/hesk/ip_whois.php new file mode 100644 index 0000000..b5578fe --- /dev/null +++ b/hesk/ip_whois.php @@ -0,0 +1,56 @@ +this link'; // %s will be replaced with URL + +// Don't bother validating IP address format, just sure no invalid chars are sent +if ( isset($_GET['ip']) && preg_match('/^[0-9A-Fa-f\:\.]+$/', $_GET['ip']) ) +{ + // Create redirect URL + $url = str_replace('{IP}', str_replace(':', '%3A', $_GET['ip']), $hesk_settings['ip_whois']); + + // Redirect to the IP whois + ?> + + + + + + + <?php echo $hesklang['1']; ?> + + + + + + '); + var cleanUp, debounce, i, len, ripple, rippleContainer, ripples, showRipple, outClose; + + debounce = function (func, delay) { + var inDebounce; + inDebounce = undefined; + return function () { + var args, context; + context = this; + args = arguments; + clearTimeout(inDebounce); + return inDebounce = setTimeout(function () { + return func.apply(context, args); + }, delay); + }; + }; + + + showRipple = function (e) { + var pos, ripple, rippler, size, style, x, y; + ripple = this; + rippler = document.createElement('span'); + size = ripple.offsetWidth; + pos = ripple.getBoundingClientRect(); + x = e.offsetX - (size / 2); + y = e.offsetY - (size / 2); + style = 'top:' + y + 'px; left: ' + x + 'px; height: ' + size + 'px; width: ' + size + 'px;'; + ripple.rippleContainer.appendChild(rippler); + return rippler.setAttribute('style', style); + }; + + cleanUp = function () { + while (this.rippleContainer.firstChild) { + this.rippleContainer.removeChild(this.rippleContainer.firstChild); + } + }; + + outClose = function (time) { + time = time ? time : 150; + // header notification + $('.profile__item--notification').removeClass('active').find('.notification-list').slideUp(time); + + // profile menu + $('.profile__user').removeClass('active').find('.profile__menu').slideUp(time); + + $('.dropdown, .dropdown-select').removeClass('active'); + $('.dropdown-list').slideUp(time, function () { + $(this).find('.assign--buttons').show(); + $(this).find('.assign--list').hide(); + }); + $('.form__search_type').slideUp(150); + $('.form__search_results').slideUp(150); + } + + dropdownSelectRender = function (el) { + var select = $(el).find('select'); + var options = []; + var value; + select.find('option').each(function (i, el) { + options.push({ + val: $(el).val(), + text: $(el).text(), + selected: $(el).is(':selected') + }); + if ($(el).is(':selected')) { + value = $(el).text(); + } + }); + var heskPath = $('input[type="hidden"][name="HESK_PATH"]').val(); + var template = '

    ' + value + '
    '; + $(el).append(template); + } + + ripples = document.querySelectorAll('[ripple]'); + + for (i = 0, len = ripples.length; i < len; i++) { + ripple = ripples[i]; + rippleContainer = document.createElement('div'); + rippleContainer.className = 'ripple--container'; + ripple.addEventListener('mousedown', showRipple); + ripple.addEventListener('mouseup', debounce(cleanUp, 10000)); + ripple.rippleContainer = rippleContainer; + ripple.appendChild(rippleContainer); + } + + // show/hide password + $('.input-group-append--icon').on('click', function (e) { + var $passwordField = $(this).closest('.form-group').find('input'); + var $iconUrl = $(this).find('use').attr('xlink:href'); + if ($passwordField.attr('type') == 'text') { + $passwordField.attr('type', 'password'); + $(this).find('svg').removeClass('icon-eye-open').addClass('icon-eye-close'); + $iconUrl = $iconUrl.replace('eye-open', 'eye-close'); + $(this).find('use').attr('xlink:href', $iconUrl); + } else if ($passwordField.attr('type') == 'password') { + $passwordField.attr('type', 'text'); + $(this).toggleClass('passwordIsHidden'); + $iconUrl = $iconUrl.replace('eye-close', 'eye-open'); + $(this).find('use').attr('xlink:href', $iconUrl); + $(this).find('svg').removeClass('icon-eye-close').addClass('icon-eye-open'); + } + }); + // end show/hide password + + // toggle submenu + $(".listitem.submenu").click( + function (e) { + if (!$(this).hasClass('submenu-is-opened')) { + $('.submenu.submenu-is-opened .submenu__list').slideUp(400, function () { + $(this).closest('.submenu-is-opened').removeClass('submenu-is-opened'); + }); + } + if (!$(e.target).closest('.submenu__list').length) { + e.preventDefault(); + console.log($(this).hasClass('submenu-is-opened')); + $(this).find(".submenu__list").stop(true, true).slideToggle(150); + $(this).toggleClass("submenu-is-opened"); + + } else { + location.href = $(e.target).find('a').attr('href'); + } + } + ); + // $(".is-toggled .listitem").hover( + // function () { + // var $lengthToTop = $(this).closest(".listitem").offset(); + // $(this).find(".listitem__menu").css("top", $lengthToTop.top) + // }); + // end toggle submenu + + // toggle Main menu + $("#navbarToggler").click(function () { + console.log() + if(!$(this).closest(".main-menu").hasClass("is-toggled")){ + localStorage.setItem('main_menu', 'close'); + $(this).closest(".main-menu").addClass("is-toggled"); + }else{ + localStorage.setItem('main_menu', 'open'); + $(this).closest(".main-menu").removeClass("is-toggled"); + } + + }) + // end toggle Main menu + if ($(".table").length > 0) { + $(".table__td-id .checkbox-custom label").click(function () { + $(this).closest("tr").toggleClass("is-checked"); + }) + } + + $('.checkbox-custom input[type="checkbox"]').change(function (e) { + if ($(e.target).is(':checked')) { + $(e.target).closest('.checkbox-custom').addClass('checked'); + } else { + $(e.target).closest('.checkbox-custom').removeClass('checked'); + } + }); + + // Custom select + var x, i, j, selElmnt, a, b, c; + /*look for any elements with the class "select-custom":*/ + x = document.getElementsByClassName('select-custom'); + for (i = 0; i < x.length; i++) { + selElmnt = x[i].getElementsByTagName('select')[0]; + /*for each element, create a new DIV that will act as the selected item:*/ + a = document.createElement('DIV'); + a.setAttribute('class', 'select-selected'); + a.dataset.value = selElmnt[0].value; + a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML; + x[i].insertBefore(a, selElmnt); + // x[i].insertBefore(a, x[i].firstChild); + + /*for each element, create a new DIV that will contain the option list:*/ + b = document.createElement('DIV'); + b.setAttribute('class', 'select-items select-hide'); + for (j = 1; j < selElmnt.length; j++) { + /*for each option in the original select element, + create a new DIV that will act as an option item:*/ + c = document.createElement('DIV'); + c.innerHTML = selElmnt.options[j].innerHTML; + c.addEventListener('click', function (e) { + /*when an item is clicked, update the original select box, + and the selected item:*/ + var y, i, k, s, h; + s = this.parentNode.parentNode.getElementsByTagName('select')[0]; + h = this.parentNode.previousSibling; + for (i = 0; i < s.length; i++) { + if (s.options[i].innerHTML == this.innerHTML) { + s.selectedIndex = i; + h.innerHTML = this.innerHTML; + y = this.parentNode.getElementsByClassName('same-as-selected'); + for (k = 0; k < y.length; k++) { + y[k].removeAttribute('class'); + } + this.setAttribute('class', 'same-as-selected'); + h.dataset.value = s.options[i].getAttribute('value'); + break; + } + } + h.click(); + }); + b.appendChild(c); + } + x[i].insertBefore(b, selElmnt); + a.addEventListener('click', function (e) { + /*when the select box is clicked, close any other select boxes, + and open/close the current select box:*/ + e.stopPropagation(); + closeAllSelect(this); + this.nextSibling.classList.toggle('select-hide'); + this.classList.toggle('select-arrow-active'); + }); + } + + function closeAllSelect(elmnt) { + /*a function that will close all select boxes in the document, + except the current select box:*/ + var x, y, i, arrNo = []; + x = document.getElementsByClassName('select-items'); + y = document.getElementsByClassName('select-selected'); + for (i = 0; i < y.length; i++) { + if (elmnt == y[i]) { + arrNo.push(i); + } else { + y[i].classList.remove('select-arrow-active'); + } + } + for (i = 0; i < x.length; i++) { + if (arrNo.indexOf(i)) { + x[i].classList.add('select-hide'); + } + } + + + if (!$(elmnt.target).closest('.out-close').length) outClose(); + if ($(elmnt.target).closest('.dropdown').length) return; + + + event.stopPropagation(); + } + + + /*if the user clicks anywhere outside the select box, + + + then close all select boxes:*/ + var documentClick = true; + $(document).click(closeAllSelect); + $(document).on('touchend', 'body', function (e) { + if (documentClick) { + $(document).unbind('click'); + documentClick = false; + } + closeAllSelect(e); + }); + // $('body').on('click', '.selectize-dropdown', function(e){ + // console.log(e); + // }); + + // Toggle table filters + if ($(".filters").length > 0) { + var filtersListing = $("#filtersListing"); + var filtersBtnToggle = $("#btnToggleFilters"); + var filtersAction = $("#filtersAction"); + function toggleFilters() { + filtersBtnToggle.find(".toggler-value").text(filtersListing.find(".filter-item").length); + if (filtersListing.hasClass("is-collapsed")) { + filtersListing.removeClass("is-collapsed"); + filtersListing.find(".overflowed").unwrap().removeClass("overflowed"); + filtersBtnToggle.find(".toggler-text").text("Hide"); + } else { + filtersBtnToggle.find(".toggler-text").text("Show all"); + var btnWidth = filtersBtnToggle.width() + parseInt(filtersBtnToggle.css("marginLeft")); + var temporaryWidth = filtersListing.width() - btnWidth - filtersAction.width() + 200; + var filtersListingRowWidth = btnWidth + filtersAction.width(); + filtersListing.children('.filter-item').each(function (index, value) { + var tempWidth = filtersListingRowWidth + $(this).width() + parseInt($(this).css('marginLeft'), 10); + if (temporaryWidth > tempWidth) { + filtersListingRowWidth = tempWidth; + } else { + $(this).addClass('overflowed'); + } + }) + filtersBtnToggle.removeClass("overflowed"); + filtersListing.find(".overflowed").wrapAll("
    "); + filtersListing.addClass('is-collapsed'); + } + } + toggleFilters() + filtersBtnToggle.click(function () { + toggleFilters() + }) + } + + $('.filters-mobile [data-action="mobile-filters-more"]').click(function () { + $('.filters-mobile').toggleClass('open'); + }); + $('.filters-mobile [data-action="mobile-filters-hide"]').click(function () { + $('.filters-mobile').toggleClass('open'); + }); + + // end Toggle table filters + + $('[data-action="go-back"]').click(function (e) { + window.history.go(-1); + e.preventDefault(); + }); + + /* =========================================================== + FORM VALIDATION + ============================================================*/ + $('#login-form').submit(function (e) { + var login = $.trim($('#regInputUsername').val()).length; + var pass = $('#regInputPassword').val().length; + if (!login) { + $('#regInputUsername').closest('.form-group').addClass('error'); + e.preventDefault(); + } + if (!pass) { + $('#regInputPassword').closest('.form-group').addClass('error'); + e.preventDefault(); + } + if (login && pass) { + // For example + $(e.target).addClass('invalid'); + e.preventDefault(); + } + }); + + $('#login-form input').keyup(function (e) { + if ($(e.target).val()) { + $(e.target).closest('.form-group').removeClass('error'); + } + }); + $('#delInputPassword').keyup(function (e) { + // For example + if ($(e.target).val().length) { + $('#delete-form .btn-full').removeAttr('disabled'); + } else { + $('#delete-form .btn-full').attr('disabled', 'disabled'); + } + }); + $('#header-search').focus(function (e) { + $('.form__search').addClass('focus'); + if(!$('.form__search').hasClass('type')){ + $('.form__search_type').slideDown(150); + } + }); + $('#header-search').blur(function (e) { + $('.form__search').removeClass('focus'); + }); + $('#header-search').keyup(function (e) { + var val = $.trim($(this).val()); + if (val.length) { + $('.form__search').addClass('value'); + } else { + $('.form__search').removeClass('value'); + } + }); + $('.form__search .search--type').click(function(e){ + $('.form__search_results').slideUp(150); + $('.form__search_type').slideDown(150); + }); + $('.form__search_type .type--list [data-type]').click(function(e){ + var type = $(this).attr('data-type'); + $('.form__search').addClass('type value').find('input').attr('placeholder', '').prop('readonly', false).focus(); + $('.form__search .search-clear').show(); + $('.form__search .search--type').html(type+':').show(); + $('.form__search_type').slideUp(150); + }); + $('.form__search .search-clear').click(function (e) { + $('#header-search').val('').attr('placeholder', 'Search for tickets, templates, articles, team members').prop('readonly', true); + $('.form__search').removeClass(['value', 'type']); + $('#header-search').focus(); + $('.form__search .search--type').hide().html(''); + $('.form__search_results').slideUp(150); + }); + + $('.topmenu__list .topmenu__item').mouseenter(function (e) { + if (!$(this).find('.topmenu__dropdown').length) return; + var w = $(this).find('.topmenu__dropdown').width(); + var left = $(this).offset().left - ((w / 2) - ($(this).width() / 2)) < 0; + var right = ($(this).offset().left + $(this).width()) + ((w / 2) - ($(this).width() / 2)) > $(document).width(); + if (left) { + $(this).find('.topmenu__dropdown').css('left', 0); + } else if (right) { + $(this).find('.topmenu__dropdown').css({ + 'left': 'auto', + 'right': 0 + }); + } else { + $(this).find('.topmenu__dropdown').removeAttr('style'); + } + }); + + $('[data-action="advanced-search"]').click(function(e){ + $('.right-bar.advanced-search').fadeIn(150); + }); + + /* =========================================================== + Textarea autosize + ============================================================*/ + $('.textarea-scrollbar').scrollbar(); + + if ($('.ticket .block--message textarea').length && $('.ticket .block--message textarea').val().length) $('.ticket .block--message .placeholder').hide(); + $('.ticket .block--message textarea').focus(function (e) { + $(e.target).closest('.block--message').find('.placeholder').fadeOut(150); + }); + $('.ticket .block--message textarea').blur(function (e) { + if ($(e.target).val().length == 0) $(e.target).closest('.block--message').find('.placeholder').fadeIn(150); + }); + $('.ticket .block--message .placeholder').click(function (e) { + $(e.currentTarget).fadeOut(150); + $(e.currentTarget).closest('.block--message').find('textarea').focus(); + }) + // END Textarea autosize + + /* =========================================================== + Dropdown & dropdown selects + ============================================================*/ + + $('.dropdown-select').each(function (i, el) { + dropdownSelectRender(el); + }); + + + + $('body').on('click', '.dropdown > label', function (e) { + if ($(e.currentTarget).closest('.dropdown').hasClass('active')) { + $(e.currentTarget).closest('.dropdown').removeClass('active').find('.dropdown-list').slideUp(150); + } else { + $('.dropdown').removeClass('active'); + $('.dropdown-list').slideUp(150); + $(e.currentTarget).closest('.dropdown').addClass('active').find('.dropdown-list').slideDown(150); + } + }); + $('body').on('click', '.dropdown-list > li', function (e) { + if ($(e.currentTarget).hasClass('noclose')) return; + $(e.currentTarget).closest('.dropdown').removeClass('active').find('.dropdown-list').slideUp(150); + }); + $('body').on('click', '.dropdown-select .label', function (e) { + if ($(e.currentTarget).closest('.dropdown-select').hasClass('active')) { + $(e.currentTarget).closest('.dropdown-select').removeClass('active').find('.dropdown-list').slideUp(150); + } else { + $('.dropdown-select').removeClass('active'); + $('.dropdown-list').slideUp(150); + $(e.currentTarget).closest('.dropdown-select').addClass('active').find('.dropdown-list').slideDown(150); + } + }); + $('body').on('click', '.dropdown-list > li', function (e) { + if ($(e.currentTarget).hasClass('noclose')) return; + $(e.currentTarget).closest('.dropdown').removeClass('active').find('.dropdown-list').slideUp(150); + }); + $('body').on('click', '.dropdown-select .dropdown-list li', function (e) { + var text, value; + value = $(e.currentTarget).attr('data-option'); + if ($(e.currentTarget).closest('.dropdown-select').hasClass('submit-us')) { + text = value.length ? 'Submit as ' + $(e.currentTarget).text() : $(e.currentTarget).text(); + text = text.toLowerCase().charAt(0).toUpperCase() + text.toLowerCase().substr(1); + } else { + text = $(e.currentTarget).text(); + } + $(e.currentTarget).closest('.dropdown-list').find('li').removeClass('selected'); + $(e.currentTarget).addClass('selected'); + $(e.currentTarget).closest('.dropdown-select').attr('data-value', value).find('.label span').text(text);; + $(e.currentTarget).closest('.dropdown-select').removeClass('active'); + $(e.currentTarget).closest('.dropdown-list').slideUp(150); + $(e.currentTarget).closest('.dropdown-select').find('select option[value="' + value + '"]').prop('selected', true); + $(e.currentTarget).closest('.dropdown-select').find('select').trigger('change'); + }); + + // End Dropdown & dropdown selects + + + /* =========================================================== + Ticket details + ============================================================*/ + $('.ticket__replies_link').click(function (e) { + if ($(e.currentTarget).hasClass('visible')) { + $(e.currentTarget).removeClass('visible'); + $('.ticket__replies_list').slideUp(150); + } else { + $('.ticket__replies_list').slideDown(150); + $(e.currentTarget).addClass('visible'); + } + }); + + // Ticket upload file + var ticketFiles = []; + $('.block--attach input[type="file"]').change(function (e) { + for (i = 0; i < e.target.files.length; i++) { + ticketFiles.push(e.target.files[i]); + var extension = '.' + e.target.files[i].name.split('.')[e.target.files[i].name.split('.').length - 1]; + var name = ''; + for (n = 0; n < e.target.files[i].name.split('.').length; n++) { + if (n < (e.target.files[i].name.split('.').length - 1)) { + name += e.target.files[i].name.split('.')[n]; + } + } + if (name.length > 16) name = name.slice(0, 10) + '...' + name.slice((name.length - 8), name.length); + var label = '
    ' + name + extension + '
    '; + $('.block--attach-list').append(label); + $('.block--attach-list div').each(function (i, el) { + $(el).attr('data-i', i); + }); + } + }); + $('body').on('click', '.block--attach-list div i', function (e) { + var i = Number($(e.target).closest('div').attr('data-i')); + ticketFiles.splice(i, 1); + $(e.currentTarget).closest('div').slideUp(150, function () { + $(e.currentTarget).closest('div').remove(); + $('.block--attach-list div').each(function (i, el) { + $(el).attr('data-i', i); + }) + }); + console.log(ticketFiles); + }); + + $('.accordion-title').click(function (e) { + if ($(e.currentTarget).closest('.accordion').hasClass('visible')) { + $(e.currentTarget).closest('.accordion').find('.accordion-body').slideUp(150); + $(e.currentTarget).closest('.accordion').removeClass('visible'); + } else { + $(e.currentTarget).closest('.accordion').find('.accordion-body').slideDown(150); + $(e.currentTarget).closest('.accordion').addClass('visible'); + } + }); + + $('.filter-item .close').click(function(e){ + e.preventDefault(); + e.stopPropagation(); + $(this).closest('.filter-item').remove(); + $('#btnToggleFilters .toggler-value').text($('.filters .filters__listing .filter-item').length); + }); + $('.filter-item.group input[type="checkbox"]').change(function(e){ + e.preventDefault(); + e.stopPropagation(); + $('.filter-item.group input[type="checkbox"]:checked').prop('checked', false); + $(this).prop('checked', true); + }); + + /* =========================================================== + Templates + ============================================================*/ + + // Template Create/Edit + var openCreateTemplate = function (e) { + $('.right-bar.template-create').fadeIn(150, function () { + $(this).find('.right-bar__body').css('transform', 'translateX(0%)'); + }); + }; + var closeRightBar = function (e) { + var link = $('.right-bar__body h3 a')[0]; + if (link && link.href !== '' && link.href !== 'javascript:') { + window.location.href = link.href; + } + + $('.right-bar').fadeOut(150); + $('body').removeClass('noscroll'); + }; + $('body').on('click', '[data-action="create-template"], [data-action="edit-template"]', function (e) { + openCreateTemplate(e); + e.preventDefault(); + }); + $('.right-bar').click(function (e) { + if ($(e.target).closest('.right-bar__body').length) return; + closeRightBar(e); + }); + $('.right-bar__body h3 a').click(function (e) { + closeRightBar(e); + + if (e.currentTarget.href === '' || e.currentTarget.href === 'javascript:') { + e.preventDefault(); + } + }); + $('[data-action="delete-template"]').click(function (e) { + openCreateTemplate(e); + e.preventDefault(); + }); + + + // Template Delete + var lastDeletedTemplate = {}; + $('body').on('click', '[data-action="delete"]', function (e) { + var name = $(e.target).closest('li').find('h3').text(); + var type = $(e.target).closest('ul').attr('class') == 'response__list' ? 'response' : 'ticket'; + $(this).closest('li').addClass('pre-delete'); + $('.modal.templates .modal__description').html(name); + $('.modal.templates h3 span').html(type); + openModal(e, $('.modal.templates')); + e.preventDefault(); + }); + $('.modal').click(function (e) { + if ($(e.target).hasClass('modal')) closeModal(e); + //if($(e.target).attr('data-action') == 'modal-close' || $(e.target).closest('[data-action="modal-close"]').length || $(e.target).closest('.modal__body').length == 0)closeModal(e); + }); + $('[data-action="template-delete-confirm"]').click(function (e) { + var type = $('.pre-delete').closest('ul').attr('class') == 'response__list' ? 'response' : 'ticket'; + var name = $('.pre-delete h3').text(); + $('.pre-delete').slideUp(150, function (e) { + $(this).addClass('deleted'); + $(this).closest('ul').find('li').each(function (i, el) { + if ($(this).hasClass('deleted')) { + lastDeletedTemplate = { + type: type, + position: i, + el: el + } + } + }); + $(this).remove(); + console.log(lastDeletedTemplate); + }); + closeModal(); + $('[data-type="template-delete"] .notification--title').text('You deleted the ' + type); + $('[data-type="template-delete"] .notification--text').text(name); + $('[data-type="template-delete"]').fadeIn(150); + }); + $('[data-action="template-delete-cancel"]').click(function (e) { + var type = lastDeletedTemplate.type == 'response' ? '.response__list' : '.ticket__list'; + if (lastDeletedTemplate.position == 0) { + $(type).prepend(lastDeletedTemplate.el); + } else { + $(type + ' li:nth-child(' + lastDeletedTemplate.position + ')').after(lastDeletedTemplate.el); + } + $('.deleted').slideDown(150, function () { + $(this).removeClass('deleted'); + }); + $(this).closest('.notification-flash').fadeOut(150); + }); + + + + /* =========================================================== + Header + ============================================================*/ + // Header events + $('[data-action="show-notification"]').click(function (e) { + if ($(this).closest('.profile__item').hasClass('active')) { + $(this).closest('.profile__item').removeClass('active').find('.notification-list').slideUp(150); + } else { + outClose(); + $(this).closest('.profile__item').addClass('active').find('.notification-list').slideDown(150); + } + }); + $('[data-action="show-profile"]').click(function (e) { + if ($('.profile__user').hasClass('active')) { + $('.profile__user').removeClass('active').find('.profile__menu').slideUp(150); + } else { + outClose(); + $('.profile__user').addClass('active').find('.profile__menu').slideDown(150); + } + }); + + + + /* =========================================================== + Modals + ============================================================*/ + var openModal = function (e, el) { + //$('body').addClass('noscroll'); + el.fadeIn(150); + }; + $('[data-modal]').click(function() { + $this = $(this); + if ($this.attr('data-callback') !== undefined) { + window[$this.attr('data-callback')]($this); + } + openModal(undefined, $('.modal' + $this.attr('data-modal'))); + }); + + var closeModal = function (e) { + if ($('.right-bar').is(':hidden') || !$('.right-bar').length) { + $('body').removeClass('noscroll'); + } + $('.modal').fadeOut(150); + $('.pre-delete').removeClass('pre-delete'); + }; + + $('.notification-flash .close').click(function (e) { + $(this).closest('.notification-flash').fadeOut(150); + }); + $('.notification-bar .close').click(function (e) { + $(this).closest('.notification-bar').fadeOut(150); + }); + + + + + + /* =========================================================== + Tickets list + ============================================================*/ + // Tickets Filters + $('.scrollbar-inner').scrollbar(); + $('[data-action="filter--search"]').keyup(function (e) { + if ($(e.target).val().length) { + $(this).closest('.form-group').find('.search-clear').css('opacity', 1); + } else { + $(this).closest('.form-group').find('.search-clear').css('opacity', 0); + } + $('.search--list .checkbox-custom').filter(function () { + $(this).toggle($(this).find('label').text().toLowerCase().indexOf($(e.target).val()) > -1); + }); + }); + $('.right-bar.filter-list .filter--search .search-clear').click(function (e) { + $('.search--list .checkbox-custom').filter(function () { + $(this).toggle($(this).find('label').text().toLowerCase().indexOf('') > -1); + }); + $(this).closest('.form-group').find('[data-action="filter--search"]').val(''); + $(this).css('opacity', 0); + }); + $('.filter-list .section--title a').click(function (e) { + if ($(this).hasClass('all-selected')) { + $(this).removeClass('all-selected').text('Select all').closest('.filter-list__section').find('input[type="checkbox"]').prop('checked', false).change(); + } else { + $(this).addClass('all-selected').text('Deselect all').closest('.filter-list__section').find('input[type="checkbox"]').prop('checked', true).change(); + } + e.preventDefault(); + }); + $('.filter-list__section input[type="checkbox"]').change(function (e) { + var all = $(this).closest('.filter-list__section').find('input[type="checkbox"]').length; + var checked = $(this).closest('.filter-list__section').find('input[type="checkbox"]:checked').length; + if (all == checked) { + $(this).closest('.filter-list__section').find('.section--title a').addClass('all-selected').text('Deselect all') + } else { + if ($(this).closest('.filter-list__section').find('.section--title a').hasClass('all-selected')) { + $(this).closest('.filter-list__section').find('.section--title a').removeClass('all-selected').text('Select all') + } + } + }); + $('table thead [data-action="select-all"]').change(function (e) { + var checked = $(this).is(':checked'); + $(this).closest('table').find('tbody .table__first_td input[type="checkbox"]').prop('checked', checked); + if (checked) { + $('.topmenu, .botmenu').addClass('active'); + } else { + $('.topmenu, .botmenu').removeClass('active'); + } + }); + $('.right-bar__body.filter-list__body input[type="checkbox"]').change(function (e) { + if ($('.right-bar__body.filter-list__body input[type="checkbox"]:checked').length) { + $('.right-bar__body.filter-list__body [data-action="filters-save-group"]').prop('disabled', false); + } else { + $('.right-bar__body.filter-list__body [data-action="filters-save-group"]').prop('disabled', true); + } + }); + + // $('.right-bar__body li').filter(function(){ + // $(this).toggle($(this).text().toLowerCase().indexOf('at') > -1) + // }); + + + + // Tickets + if ($('.assign--list select').length) { + $('.assign--list select').selectize(); + } + if ($('.bulk-actions select').length) { + $('.bulk-actions select').selectize(); + } + if ($('.search-options select').length) { + $('.search-options select').selectize(); + } + + $('[data-action="add-filters"], [data-action="ticket-mobile-filters"]').click(function (e) { + $('body').toggleClass('noscroll'); + $('.filter-list').fadeIn(150); + }); + + $('.dropdown.assignment .assign__body > li > a').click(function (e) { + var type = $(e.currentTarget).closest('li').attr('data-type') + console.log(type); + if (type == 'to-my') { + $(e.currentTarget).closest('.assign__wrapper').removeClass('unassigned').removeClass('assign').addClass('to-my'); + $(e.currentTarget).closest('.assign__wrapper').find('.assign__head .assign__head_name b').text('To my'); + $(e.currentTarget).closest('.assign__wrapper').find('.assign__head .assign__head_name span').text('Assigned to me'); + $(e.currentTarget).closest('.dropdown').find('label span').text('To my'); + outClose(10); + } else if (type == 'unassigned') { + $(e.currentTarget).closest('.assign__wrapper').removeClass('to-my').removeClass('assign').addClass('unassigned'); + $(e.currentTarget).closest('.assign__wrapper').find('.assign__head .assign__head_name b').text('Unassigned'); + $(e.currentTarget).closest('.assign__wrapper').find('.assign__head .assign__head_name span').text('This ticket is not assigned to anyone'); + $(e.currentTarget).closest('.dropdown').find('label span').text('Unassigned'); + outClose(10); + } else if (type == 'assign') { + + var $select = $(e.currentTarget).closest('.dropdown').find('select').selectize(); + var selectize = $select[0].selectize; // This stores the selectize object to a variable (with name 'selectize') + selectize.clear(); + $(e.currentTarget).closest('.dropdown').find('.assign--buttons').hide(); + $(e.currentTarget).closest('.dropdown').find('.assign--list').show(); + + } + e.preventDefault(); + }); + $('.dropdown.assignment .assign--list [data-action="close"]').click(function (e) { + $(e.currentTarget).closest('.dropdown').find('.assign--buttons').show(); + $(e.currentTarget).closest('.dropdown').find('.assign--list').hide(); + }); + $('.dropdown.assignment .assign--list [data-action="save"]').click(function (e) { + var val = $(e.currentTarget).closest('.assign--list').find('select').val(); + if ($.trim(val).length) { + $(e.currentTarget).closest('.dropdown').find('.assign__wrapper').removeClass('unassigned').removeClass('to-my').addClass('assign'); + $(e.currentTarget).closest('.dropdown').find('.assign__head .assign__head_name b').text(val); + $(e.currentTarget).closest('.dropdown').find('.assign__head .assign__head_name span').text('Assigned to ' + val); + $(e.currentTarget).closest('.dropdown').find('label span').text(val); + outClose(10); + } + }); + $('#default-table .table__first_td input[type="checkbox"]').change(function (e) { + if ($(this).is(':checked')) { + $(this).closest('tr').addClass('selected'); + } else { + $(this).closest('tr').removeClass('selected'); + } + var checked = $('#default-table .table__first_td input[type="checkbox"]:checked').length; + $('.topmenu > p').text(checked + ' tasks selected') + if (checked > 0) { + $('.topmenu, .botmenu').addClass('active'); + } else { + $('.topmenu, .botmenu').removeClass('active'); + } + }); + $('.tickets__mobile_head [data-action="ticket-mobile-actions"]').click(function (e) { + $('.main__content.tickets').toggleClass('actions'); + }); + $('[data-action="tickets-select-dismiss"]').click(function (e) { + $('.topmenu, .botmenu').removeClass('active'); + $('#default-table .table__first_th input[type="checkbox"]:checked, #default-table .table__first_td input[type="checkbox"]:checked').prop('checked', false); + }) + + + /* =========================================================== + Clipboard + ============================================================*/ + function coptToClipboard(text) { + var textArea = document.createElement("textarea"); + textArea.style.position = 'absolute'; + textArea.style.top = '-10000px'; + textArea.style.left = '-10000px'; + textArea.value = text; + document.body.appendChild(textArea); + textArea.focus(); + textArea.select(); + try { + var successful = document.execCommand("copy"); + var msg = successful ? "successful" : "unsuccessful"; + console.log("Fallback: Copying text command was " + msg); + } catch (err) { + console.error("Fallback: Oops, unable to copy", err); + } + + document.body.removeChild(textArea); + } + function copyTextToClipboard(text) { + if (!navigator.clipboard) { + fallbackCopyTextToClipboard(text); + return; + } + navigator.clipboard.writeText(text).then( + function () { + console.log("Async: Copying to clipboard was successful!"); + }, + function (err) { + console.error("Async: Could not copy text: ", err); + } + ); + } + + + /* =========================================================== + Categories + ============================================================*/ + $(document).on('click', '[data-action="generate-link"]', function (e) { + coptToClipboard($(this).data('link')); + $('[data-type="link-generate-message"]').fadeIn(150, function () { + var notification = $(this); + setTimeout(function () { + notification.fadeOut(150); + }, 3000); + }); + e.preventDefault(); + }); + $('[data-action="category-create"]').click(function (e) { + $('.right-bar.category-create').fadeIn(150); + $('body').addClass('noscroll'); + e.preventDefault(); + }); + + + /* =========================================================== + Team + ============================================================*/ + $('[data-action="team-create"]').click(function (e) { + $('.right-bar.team-create').fadeIn(150); + $('body').addClass('noscroll'); + e.preventDefault(); + }); + $('.right-bar.team-create [data-action="next"]').click(function (e) { + var step = Number($('.right-bar.team-create .right-bar__body').attr('data-step')) + 1; + $('.right-bar.team-create .right-bar__body').attr('data-step', step); + }); + $('.right-bar.team-create [data-action="back"]').click(function (e) { + var step = Number($('.right-bar.team-create .right-bar__body').attr('data-step')) - 1; + $('.right-bar.team-create .right-bar__body').attr('data-step', step); + }); + $('.right-bar.team-create [data-action="save"]').click(function (e) { + // FOR EXEMPLES + var rand = 0 - 0.5 + Math.random() * (7 - 0 + 1) + rand = Math.round(rand); + var newTeam = '' + $($('.table tbody tr')[rand]).html() + ''; + $('.team .table tbody').prepend(newTeam); + $('.right-bar.team-create').fadeOut(150).find('.right-bar__body').attr('data-step', 1); + $('.notification-flash[data-type="team-created-confirm"]').fadeIn(150, function () { + var notification = $(this); + setTimeout(function () { + notification.fadeOut(150); + }, 3000); + }); + }); + $('.modal.team-delete [data-action="cancel"]').click(function () { + $('.modal.team-delete').fadeOut(150); + }); + $('.modal.team-delete [data-action="close"]').click(function (e) { + $('.team-create').fadeOut(150, closeModal).find('.right-bar__body').attr('data-step', 1); + + }); + + + + /* =========================================================== + Create ticket + ============================================================*/ + $('.datepicker').datepicker({ + language: 'en', + position: 'right top', + autoClose: true, + onSelect: function (formattedDate, date, inst) { + if (formattedDate.length) { + inst.$el + .parent() + .parent() + .find('.calendar--value').fadeIn(150).find('span').text(formattedDate); + } + }, + onHide: function (inst, animationCompleted) { + $('.param.calendar button').removeClass('active'); + } + }); + $('.param.calendar button').click(function (e) { + $(this).addClass('active'); + $(this).parent() + .find('.datepicker') + .data("datepicker") + .show(); + }); + $('.param.calendar .close').click(function (e) { + $(this).parent().parent() + .find('.calendar--button') + .find('.datepicker') + .data("datepicker") + .clear(); + $('.param.calendar .calendar--value').fadeOut(150, function () { + $(this).find('span').text(''); + }) + }); + $('.right-bar.ticket-create .step-1 .cayrgory-list li').click(function (e) { + $('.right-bar.ticket-create .right-bar__body').attr('data-step', 2); + }); + $('.right-bar.ticket-create [data-action="next"]').click(function (e) { + var step = Number($('.right-bar.ticket-create .right-bar__body').attr('data-step')) + 1; + $('.right-bar.ticket-create .right-bar__body').attr('data-step', step); + }); + $('.right-bar.ticket-create [data-action="back"]').click(function (e) { + var step = Number($('.right-bar.ticket-create .right-bar__body').attr('data-step')) - 1; + $('.right-bar.ticket-create .right-bar__body').attr('data-step', step); + }); + $('.right-bar.ticket-create [data-action="save"]').click(function (e) { + // FOR EXEMPLES + var rand = 0 - 0.5 + Math.random() * (7 - 0 + 1) + rand = Math.round(rand); + var newTeam = '' + $($('.table tbody tr')[rand]).html() + ''; + $('.table.ticket-list tbody').prepend(newTeam); + $('.right-bar.ticket-create').fadeOut(150).find('.right-bar__body').attr('data-step', 1); + $('.notification-flash[data-type="ticket-created-confirm"]').fadeIn(150, function () { + var notification = $(this); + setTimeout(function () { + notification.fadeOut(150); + }, 3000); + }); + $('body').removeClass('noscroll'); + }); + + + + + + /* =========================================================== + Profile + ============================================================*/ + + $('.right-bar .step-bar li').click(function (e) { + var step = Number($(this).attr('data-link')); + var current = Number($(this).closest('.right-bar__body').attr('data-step')); + if (step != current) { + $(this).closest('.right-bar__body').attr('data-step', step); + } + }); + $('.main__content.profile [data-action="profile-edit"]').click(function (e) { + $('.right-bar.profile-edit').fadeIn(150); + $('body').addClass('noscroll'); + }); + $('.main__content.profile [data-action="profile-delete"]').click(function (e) { + $('.modal.profile-delete').fadeIn(150); + e.preventDefault(); + }); + $('.modal [data-action="cancel"]').click(function (e) { + e.preventDefault(); + closeModal(); + }); + $('[data-action="profile-log-out"]').click(function (e) { + $('.modal.log-out').fadeIn(150); + e.preventDefault(); + }); + $('.right-bar.profile-edit [data-action="save"]').click(function (e) { + $(this).closest('.right-bar').fadeOut(150); + $('body').removeClass('noscroll'); + $('.notification-bar[data-type="profile-saved"]').fadeIn(150); + }); + $('#profile-photo-upload').change(function (e) { + var reader = new FileReader(); + var img = $(this).closest('.profile__photo').find('.profile__photo_wrapper img'); + if (this.files && this.files[0]) { + reader.onload = function (e) { + img.attr('src', e.target.result); + //el.html(img); + } + + reader.readAsDataURL(this.files[0]); + $(this).closest('.edit-modal__photo').find('.edit-modal__photo_delete').show(); + } + }); + + /* =========================================================== + Emails + ============================================================*/ + /*$('.email__list_aside .list--item').click(function (e) { + $('.email__list_aside .list--item').removeClass('current'); + $(this).addClass('current'); + if ($(this).hasClass('new')) $(this).removeClass('new'); + }); + $('.emails__head_tabs li').click(function (e) { + var target = $(this).attr('data-link'); + $('.emails__head_tabs li').removeClass('current'); + $(this).addClass('current'); + $('.email__tabs').attr('class', 'email__tabs') + $('.email__tabs').attr('data-current', target); + }); + + $('.main__content.emails [data-action="new-email"]').click(function (e) { + $('.right-bar.email-create').fadeIn(150); + $('body').addClass('noscroll'); + e.preventDefault(); + });*/ + if ($('#email-create-destination').length) { + $('#email-create-destination').selectize(); + }; + if ($('#email-batch-process').length) { + $('#email-batch-process').selectize(); + }; + + + /* =========================================================== + Tools + ============================================================*/ + $('[data-action="create-service-message"]').click(function (e) { + console.log(e); + $('body').addClass('noscroll'); + $('.right-bar.service-message-create').fadeIn(150); + }); + $('.right-bar.service-message-create [data-action="back"]').click(function (e) { + $('.right-bar.service-message-create .right-bar__body').attr('data-step', 1); + }); + $('.right-bar.service-message-create [data-action="next"]').click(function (e) { + $('.right-bar.service-message-create .right-bar__body').attr('data-step', 2); + }); + $('.right-bar.service-message-create [data-action="save"]').click(function (e) { + // To do something + $('.right-bar.service-message-create').fadeOut(150); + $('body').removeClass('noscroll'); + }); + + $('[data-action="edit-tools-email-template"]').click(function (e) { + $('.right-bar.tools-email-template-edit').fadeIn(150); + $('body').addClass('noscroll'); + e.preventDefault(); + }); + $('.right-bar.tools-email-template-edit [data-action="save-changes"]').click(function (e) { + // To do something + $('.right-bar.tools-email-template-edit').fadeOut(150); + $('body').removeClass('noscroll'); + }); + + $('[data-action="create-custom-field"]').click(function (e) { + $('.right-bar.create-custom-field').fadeIn(150); + $('body').addClass('noscroll'); + }); + $('.right-bar.create-custom-field [data-action="save"]').click(function (e) { + // To do something + $('.right-bar.create-custom-field').fadeOut(150); + $('body').removeClass('noscroll'); + }); + + $('[data-action="create-custom-status"]').click(function (e) { + $('.right-bar.create-status').fadeIn(150); + $('body').addClass('noscroll'); + }); + $('.right-bar.create-status [data-action="save"]').click(function (e) { + // To do something + $('.right-bar.create-status').fadeOut(150); + $('body').removeClass('noscroll'); + }); + $('.right-bar.create-status [data-action="status-color"]').change(function (e) { + var isOk = /^#[0-9A-F]{6}$/i.test($(this).val()); + if (isOk) { + $(this).css('color', $(this).val()); + $(this).closest('.form-group').find('span').css('color', $(this).val()); + } else { + $(this).css('color', '#26282a').val(''); + $(this).closest('.form-group').find('span').css('color', '#26282a'); + } + }); + + + + + + + + /* =========================================================== + Tooltyps + ============================================================*/ + $('body').on('mouseenter', '.tooltype', function (e) { + //$(this).find('.tooltype__content').fadeIn(150); + }); + $('body').on('mouseleave', '.tooltype', function (e) { + //$(this).find('.tooltype__content').fadeOut(150); + }); + + + /* =========================================================== + Settings + ============================================================*/ + $('.input-tags').selectize({ + persist: false, + createOnBlur: true, + create: true + }); + if ($('#timezone-select').length) { + $('#timezone-select').selectize(); + + }; + + + /* =========================================================== + Knowledge base + ============================================================*/ + $('.knowledge__head_tabs li').click(function (e) { + var target = $(this).attr('data-link'); + $('.knowledge__head_tabs li').removeClass('current'); + $(this).addClass('current'); + $('.knowledge__tabs').attr('data-current', target); + }); + $('.main__content.knowledge.category .category__list_head .toogle, .main__content.knowledge.category .category__list_head .show').click(function (e) { + if ($(this).closest('.category__list').hasClass('visible')) { + $(this).closest('.category__list').removeClass('visible').find('.category__list_table').slideUp(150); + } else { + $(this).closest('.category__list').addClass('visible').find('.category__list_table').slideDown(150); + } + e.preventDefault(); + }); + + $('#knowledge-article-edit-keywords').selectize({ + plugins: ['remove_button'], + delimiter: ',', + persist: false, + create: function (input) { + return { + value: input, + text: input + } + } + }); + $('.knowledge [data-action="knowledge-category-create"]').click(function (e) { + $('.right-bar.knowledge-category-create').fadeIn(150); + $('body').addClass('noscroll'); + e.preventDefault(); + }); + $('.knowledge [data-action="knowledge-sub-category-create"]').click(function (e) { + $('.right-bar.knowledge-sub-category-create').fadeIn(150); + $('body').addClass('noscroll'); + e.preventDefault(); + }); + $('.knowledge [data-action="knowledge-category-edit"]').click(function (e) { + $('.right-bar.knowledge-category-edit').fadeIn(150); + $('body').addClass('noscroll'); + e.preventDefault(); + }); + $('.knowledge [data-action="knowledge-category-edit"]').click(function (e) { + $('.right-bar.knowledge-category-edit').fadeIn(150); + $('body').addClass('noscroll'); + e.preventDefault(); + }); + $('.knowledge [data-action="knowledge-sub-category-edit"]').click(function (e) { + $('.right-bar.knowledge-sub-category-edit').fadeIn(150); + $('body').addClass('noscroll'); + e.preventDefault(); + }); + $('.knowledge').on('click', '[data-action="generate-link"]', function (e) { + var generateLink = 'https://some-generate-link.html' + coptToClipboard(generateLink); + $('[data-type="link-generate-message"]').fadeIn(150, function () { + var notification = $(this); + setTimeout(function () { + notification.fadeOut(150); + }, 3000); + }); + e.preventDefault(); + }); + + + + $('#search-datepicker').datepicker({ + language: 'en', + position: 'left top', + autoClose: true, + range: true, + multipleDatesSeparator: ' - ', + toggleSelected: false, + onSelect: function (formattedDate, date, inst) { + if (formattedDate.length) { + //$('.ticket-create .param.calendar .calendar--value').fadeIn(150).find('span').text(formattedDate); + } + }, + onHide: function (inst, animationCompleted) { + //$('.ticket-create .param.calendar button').removeClass('active'); + } + }); + + + + + /* =========================================================== + MOBILE LOGIC + ============================================================*/ + $('.header__mobile [data-action="toggle-menu"]').click(function (e) { + $('body').removeClass('show-search'); + $('body').toggleClass('show-menu'); + }); + $('.header__mobile [data-action="toggle-search"]').click(function (e) { + $('body').toggleClass('show-search'); + }); + + // Never allow typing in dropdowns + $('.selectize-input input').prop('readonly', true); +}); + +// Show mail description +$('.email__list_aside .list--item').click(function (e) { + var title = $(this).find('.head h5').text(); + $('.email__list_descr .head h3').text(title); + $('.email__list_article').fadeIn(150).animate({ right: 0 }, 300); +}); +$(".btn-hide-article").click(function () { + $(this).closest('.email__list_article').animate({ right: "-100vw" }, 300); +}); + + +// Search autocomplete +$('#header-search').keyup(function (e) { + var val = $.trim($(this).val()); + if (val.length) { + $('.form__search_results').slideDown(150); + } else { + $('.form__search_results').slideUp(150); + } +}); + +// $('.right-bar__body li').filter(function(){ +// $(this).toggle($(this).text().toLowerCase().indexOf('at') > -1) +// }); + + +/* +window.onload = function(){ + $('#loader').fadeOut(150); +};*/ diff --git a/hesk/js/app.min.js b/hesk/js/app.min.js new file mode 100644 index 0000000..a3b327e --- /dev/null +++ b/hesk/js/app.min.js @@ -0,0 +1,50 @@ +$(document).ready(function(){var toggleMenu=localStorage.getItem('main_menu')?localStorage.getItem('main_menu'):'open';if($(document).width()<1200){$(".main-menu").addClass("is-toggled")}else{if(toggleMenu=='close'){console.log(toggleMenu=='close');$(".main-menu").addClass("is-toggled")}else if(toggleMenu=='open'){$(".main-menu").removeClass("is-toggled")}} +$(window).resize(function(e){if($(document).width()<1200){$(".main-menu").addClass("is-toggled")}else{$(".main-menu").removeClass("is-toggled")}});svg4everybody();var cleanUp,debounce,i,len,ripple,rippleContainer,ripples,showRipple,outClose;debounce=function(func,delay){var inDebounce;inDebounce=undefined;return function(){var args,context;context=this;args=arguments;clearTimeout(inDebounce);return inDebounce=setTimeout(function(){return func.apply(context,args)},delay)}};showRipple=function(e){var pos,ripple,rippler,size,style,x,y;ripple=this;rippler=document.createElement('span');size=ripple.offsetWidth;pos=ripple.getBoundingClientRect();x=e.offsetX-(size/2);y=e.offsetY-(size/2);style='top:'+y+'px; left: '+x+'px; height: '+size+'px; width: '+size+'px;';ripple.rippleContainer.appendChild(rippler);return rippler.setAttribute('style',style)};cleanUp=function(){while(this.rippleContainer.firstChild){this.rippleContainer.removeChild(this.rippleContainer.firstChild)}};outClose=function(time){time=time?time:150;$('.profile__item--notification').removeClass('active').find('.notification-list').slideUp(time);$('.profile__user').removeClass('active').find('.profile__menu').slideUp(time);$('.dropdown, .dropdown-select').removeClass('active');$('.dropdown-list').slideUp(time,function(){$(this).find('.assign--buttons').show();$(this).find('.assign--list').hide()});$('.form__search_type').slideUp(150);$('.form__search_results').slideUp(150)} +dropdownSelectRender=function(el){var select=$(el).find('select');var options=[];var value;select.find('option').each(function(i,el){options.push({val:$(el).val(),text:$(el).text(),selected:$(el).is(':selected')});if($(el).is(':selected')){value=$(el).text()}});var heskPath=$('input[type="hidden"][name="HESK_PATH"]').val();var template='
    '+value+'
    ';$(el).append(template)} +ripples=document.querySelectorAll('[ripple]');for(i=0,len=ripples.length;i0){$(".table__td-id .checkbox-custom label").click(function(){$(this).closest("tr").toggleClass("is-checked")})} +$('.checkbox-custom input[type="checkbox"]').change(function(e){if($(e.target).is(':checked')){$(e.target).closest('.checkbox-custom').addClass('checked')}else{$(e.target).closest('.checkbox-custom').removeClass('checked')}});var x,i,j,selElmnt,a,b,c;x=document.getElementsByClassName('select-custom');for(i=0;i0){var filtersListing=$("#filtersListing");var filtersBtnToggle=$("#btnToggleFilters");var filtersAction=$("#filtersAction");function toggleFilters(){filtersBtnToggle.find(".toggler-value").text(filtersListing.find(".filter-item").length);if(filtersListing.hasClass("is-collapsed")){filtersListing.removeClass("is-collapsed");filtersListing.find(".overflowed").unwrap().removeClass("overflowed");filtersBtnToggle.find(".toggler-text").text("Hide")}else{filtersBtnToggle.find(".toggler-text").text("Show all");var btnWidth=filtersBtnToggle.width()+parseInt(filtersBtnToggle.css("marginLeft"));var temporaryWidth=filtersListing.width()-btnWidth-filtersAction.width()+200;var filtersListingRowWidth=btnWidth+filtersAction.width();filtersListing.children('.filter-item').each(function(index,value){var tempWidth=filtersListingRowWidth+$(this).width()+parseInt($(this).css('marginLeft'),10);if(temporaryWidth>tempWidth){filtersListingRowWidth=tempWidth}else{$(this).addClass('overflowed')}}) +filtersBtnToggle.removeClass("overflowed");filtersListing.find(".overflowed").wrapAll("
    ");filtersListing.addClass('is-collapsed')}} +toggleFilters() +filtersBtnToggle.click(function(){toggleFilters()})} +$('.filters-mobile [data-action="mobile-filters-more"]').click(function(){$('.filters-mobile').toggleClass('open')});$('.filters-mobile [data-action="mobile-filters-hide"]').click(function(){$('.filters-mobile').toggleClass('open')});$('[data-action="go-back"]').click(function(e){window.history.go(-1);e.preventDefault()});$('#login-form').submit(function(e){var login=$.trim($('#regInputUsername').val()).length;var pass=$('#regInputPassword').val().length;if(!login){$('#regInputUsername').closest('.form-group').addClass('error');e.preventDefault()} +if(!pass){$('#regInputPassword').closest('.form-group').addClass('error');e.preventDefault()} +if(login&&pass){$(e.target).addClass('invalid');e.preventDefault()}});$('#login-form input').keyup(function(e){if($(e.target).val()){$(e.target).closest('.form-group').removeClass('error')}});$('#delInputPassword').keyup(function(e){if($(e.target).val().length){$('#delete-form .btn-full').removeAttr('disabled')}else{$('#delete-form .btn-full').attr('disabled','disabled')}});$('#header-search').focus(function(e){$('.form__search').addClass('focus');if(!$('.form__search').hasClass('type')){$('.form__search_type').slideDown(150)}});$('#header-search').blur(function(e){$('.form__search').removeClass('focus')});$('#header-search').keyup(function(e){var val=$.trim($(this).val());if(val.length){$('.form__search').addClass('value')}else{$('.form__search').removeClass('value')}});$('.form__search .search--type').click(function(e){$('.form__search_results').slideUp(150);$('.form__search_type').slideDown(150)});$('.form__search_type .type--list [data-type]').click(function(e){var type=$(this).attr('data-type');$('.form__search').addClass('type value').find('input').attr('placeholder','').prop('readonly',!1).focus();$('.form__search .search-clear').show();$('.form__search .search--type').html(type+':').show();$('.form__search_type').slideUp(150)});$('.form__search .search-clear').click(function(e){$('#header-search').val('').attr('placeholder','Search for tickets, templates, articles, team members').prop('readonly',!0);$('.form__search').removeClass(['value','type']);$('#header-search').focus();$('.form__search .search--type').hide().html('');$('.form__search_results').slideUp(150)});$('.topmenu__list .topmenu__item').mouseenter(function(e){if(!$(this).find('.topmenu__dropdown').length)return;var w=$(this).find('.topmenu__dropdown').width();var left=$(this).offset().left-((w/2)-($(this).width()/2))<0;var right=($(this).offset().left+$(this).width())+((w/2)-($(this).width()/2))>$(document).width();if(left){$(this).find('.topmenu__dropdown').css('left',0)}else if(right){$(this).find('.topmenu__dropdown').css({'left':'auto','right':0})}else{$(this).find('.topmenu__dropdown').removeAttr('style')}});$('[data-action="advanced-search"]').click(function(e){$('.right-bar.advanced-search').fadeIn(150)});$('.textarea-scrollbar').scrollbar();if($('.ticket .block--message textarea').length&&$('.ticket .block--message textarea').val().length)$('.ticket .block--message .placeholder').hide();$('.ticket .block--message textarea').focus(function(e){$(e.target).closest('.block--message').find('.placeholder').fadeOut(150)});$('.ticket .block--message textarea').blur(function(e){if($(e.target).val().length==0)$(e.target).closest('.block--message').find('.placeholder').fadeIn(150)});$('.ticket .block--message .placeholder').click(function(e){$(e.currentTarget).fadeOut(150);$(e.currentTarget).closest('.block--message').find('textarea').focus()}) +$('.dropdown-select').each(function(i,el){dropdownSelectRender(el)});$('body').on('click','.dropdown > label',function(e){if($(e.currentTarget).closest('.dropdown').hasClass('active')){$(e.currentTarget).closest('.dropdown').removeClass('active').find('.dropdown-list').slideUp(150)}else{$('.dropdown').removeClass('active');$('.dropdown-list').slideUp(150);$(e.currentTarget).closest('.dropdown').addClass('active').find('.dropdown-list').slideDown(150)}});$('body').on('click','.dropdown-list > li',function(e){if($(e.currentTarget).hasClass('noclose'))return;$(e.currentTarget).closest('.dropdown').removeClass('active').find('.dropdown-list').slideUp(150)});$('body').on('click','.dropdown-select .label',function(e){if($(e.currentTarget).closest('.dropdown-select').hasClass('active')){$(e.currentTarget).closest('.dropdown-select').removeClass('active').find('.dropdown-list').slideUp(150)}else{$('.dropdown-select').removeClass('active');$('.dropdown-list').slideUp(150);$(e.currentTarget).closest('.dropdown-select').addClass('active').find('.dropdown-list').slideDown(150)}});$('body').on('click','.dropdown-list > li',function(e){if($(e.currentTarget).hasClass('noclose'))return;$(e.currentTarget).closest('.dropdown').removeClass('active').find('.dropdown-list').slideUp(150)});$('body').on('click','.dropdown-select .dropdown-list li',function(e){var text,value;value=$(e.currentTarget).attr('data-option');if($(e.currentTarget).closest('.dropdown-select').hasClass('submit-us')){text=value.length?'Submit as '+$(e.currentTarget).text():$(e.currentTarget).text();text=text.toLowerCase().charAt(0).toUpperCase()+text.toLowerCase().substr(1)}else{text=$(e.currentTarget).text()} +$(e.currentTarget).closest('.dropdown-list').find('li').removeClass('selected');$(e.currentTarget).addClass('selected');$(e.currentTarget).closest('.dropdown-select').attr('data-value',value).find('.label span').text(text);$(e.currentTarget).closest('.dropdown-select').removeClass('active');$(e.currentTarget).closest('.dropdown-list').slideUp(150);$(e.currentTarget).closest('.dropdown-select').find('select option[value="'+value+'"]').prop('selected',!0);$(e.currentTarget).closest('.dropdown-select').find('select').trigger('change')});$('.ticket__replies_link').click(function(e){if($(e.currentTarget).hasClass('visible')){$(e.currentTarget).removeClass('visible');$('.ticket__replies_list').slideUp(150)}else{$('.ticket__replies_list').slideDown(150);$(e.currentTarget).addClass('visible')}});var ticketFiles=[];$('.block--attach input[type="file"]').change(function(e){for(i=0;i16)name=name.slice(0,10)+'...'+name.slice((name.length-8),name.length);var label='
    '+name+extension+'
    ';$('.block--attach-list').append(label);$('.block--attach-list div').each(function(i,el){$(el).attr('data-i',i)})}});$('body').on('click','.block--attach-list div i',function(e){var i=Number($(e.target).closest('div').attr('data-i'));ticketFiles.splice(i,1);$(e.currentTarget).closest('div').slideUp(150,function(){$(e.currentTarget).closest('div').remove();$('.block--attach-list div').each(function(i,el){$(el).attr('data-i',i)})});console.log(ticketFiles)});$('.accordion-title').click(function(e){if($(e.currentTarget).closest('.accordion').hasClass('visible')){$(e.currentTarget).closest('.accordion').find('.accordion-body').slideUp(150);$(e.currentTarget).closest('.accordion').removeClass('visible')}else{$(e.currentTarget).closest('.accordion').find('.accordion-body').slideDown(150);$(e.currentTarget).closest('.accordion').addClass('visible')}});$('.filter-item .close').click(function(e){e.preventDefault();e.stopPropagation();$(this).closest('.filter-item').remove();$('#btnToggleFilters .toggler-value').text($('.filters .filters__listing .filter-item').length)});$('.filter-item.group input[type="checkbox"]').change(function(e){e.preventDefault();e.stopPropagation();$('.filter-item.group input[type="checkbox"]:checked').prop('checked',!1);$(this).prop('checked',!0)});var openCreateTemplate=function(e){$('.right-bar.template-create').fadeIn(150,function(){$(this).find('.right-bar__body').css('transform','translateX(0%)')})};var closeRightBar=function(e){var link=$('.right-bar__body h3 a')[0];if(link&&link.href!==''&&link.href!=='javascript:'){window.location.href=link.href} +$('.right-bar').fadeOut(150);$('body').removeClass('noscroll')};$('body').on('click','[data-action="create-template"], [data-action="edit-template"]',function(e){openCreateTemplate(e);e.preventDefault()});$('.right-bar').click(function(e){if($(e.target).closest('.right-bar__body').length)return;closeRightBar(e)});$('.right-bar__body h3 a').click(function(e){closeRightBar(e);if(e.currentTarget.href===''||e.currentTarget.href==='javascript:'){e.preventDefault()}});$('[data-action="delete-template"]').click(function(e){openCreateTemplate(e);e.preventDefault()});var lastDeletedTemplate={};$('body').on('click','[data-action="delete"]',function(e){var name=$(e.target).closest('li').find('h3').text();var type=$(e.target).closest('ul').attr('class')=='response__list'?'response':'ticket';$(this).closest('li').addClass('pre-delete');$('.modal.templates .modal__description').html(name);$('.modal.templates h3 span').html(type);openModal(e,$('.modal.templates'));e.preventDefault()});$('.modal').click(function(e){if($(e.target).hasClass('modal'))closeModal(e)});$('[data-action="template-delete-confirm"]').click(function(e){var type=$('.pre-delete').closest('ul').attr('class')=='response__list'?'response':'ticket';var name=$('.pre-delete h3').text();$('.pre-delete').slideUp(150,function(e){$(this).addClass('deleted');$(this).closest('ul').find('li').each(function(i,el){if($(this).hasClass('deleted')){lastDeletedTemplate={type:type,position:i,el:el}}});$(this).remove();console.log(lastDeletedTemplate)});closeModal();$('[data-type="template-delete"] .notification--title').text('You deleted the '+type);$('[data-type="template-delete"] .notification--text').text(name);$('[data-type="template-delete"]').fadeIn(150)});$('[data-action="template-delete-cancel"]').click(function(e){var type=lastDeletedTemplate.type=='response'?'.response__list':'.ticket__list';if(lastDeletedTemplate.position==0){$(type).prepend(lastDeletedTemplate.el)}else{$(type+' li:nth-child('+lastDeletedTemplate.position+')').after(lastDeletedTemplate.el)} +$('.deleted').slideDown(150,function(){$(this).removeClass('deleted')});$(this).closest('.notification-flash').fadeOut(150)});$('[data-action="show-notification"]').click(function(e){if($(this).closest('.profile__item').hasClass('active')){$(this).closest('.profile__item').removeClass('active').find('.notification-list').slideUp(150)}else{outClose();$(this).closest('.profile__item').addClass('active').find('.notification-list').slideDown(150)}});$('[data-action="show-profile"]').click(function(e){if($('.profile__user').hasClass('active')){$('.profile__user').removeClass('active').find('.profile__menu').slideUp(150)}else{outClose();$('.profile__user').addClass('active').find('.profile__menu').slideDown(150)}});var openModal=function(e,el){el.fadeIn(150)};$('[data-modal]').click(function(){$this=$(this);if($this.attr('data-callback')!==undefined){window[$this.attr('data-callback')]($this)} +openModal(undefined,$('.modal'+$this.attr('data-modal')))});var closeModal=function(e){if($('.right-bar').is(':hidden')||!$('.right-bar').length){$('body').removeClass('noscroll')} +$('.modal').fadeOut(150);$('.pre-delete').removeClass('pre-delete')};$('.notification-flash .close').click(function(e){$(this).closest('.notification-flash').fadeOut(150)});$('.notification-bar .close').click(function(e){$(this).closest('.notification-bar').fadeOut(150)});$('.scrollbar-inner').scrollbar();$('[data-action="filter--search"]').keyup(function(e){if($(e.target).val().length){$(this).closest('.form-group').find('.search-clear').css('opacity',1)}else{$(this).closest('.form-group').find('.search-clear').css('opacity',0)} +$('.search--list .checkbox-custom').filter(function(){$(this).toggle($(this).find('label').text().toLowerCase().indexOf($(e.target).val())>-1)})});$('.right-bar.filter-list .filter--search .search-clear').click(function(e){$('.search--list .checkbox-custom').filter(function(){$(this).toggle($(this).find('label').text().toLowerCase().indexOf('')>-1)});$(this).closest('.form-group').find('[data-action="filter--search"]').val('');$(this).css('opacity',0)});$('.filter-list .section--title a').click(function(e){if($(this).hasClass('all-selected')){$(this).removeClass('all-selected').text('Select all').closest('.filter-list__section').find('input[type="checkbox"]').prop('checked',!1).change()}else{$(this).addClass('all-selected').text('Deselect all').closest('.filter-list__section').find('input[type="checkbox"]').prop('checked',!0).change()} +e.preventDefault()});$('.filter-list__section input[type="checkbox"]').change(function(e){var all=$(this).closest('.filter-list__section').find('input[type="checkbox"]').length;var checked=$(this).closest('.filter-list__section').find('input[type="checkbox"]:checked').length;if(all==checked){$(this).closest('.filter-list__section').find('.section--title a').addClass('all-selected').text('Deselect all')}else{if($(this).closest('.filter-list__section').find('.section--title a').hasClass('all-selected')){$(this).closest('.filter-list__section').find('.section--title a').removeClass('all-selected').text('Select all')}}});$('table thead [data-action="select-all"]').change(function(e){var checked=$(this).is(':checked');$(this).closest('table').find('tbody .table__first_td input[type="checkbox"]').prop('checked',checked);if(checked){$('.topmenu, .botmenu').addClass('active')}else{$('.topmenu, .botmenu').removeClass('active')}});$('.right-bar__body.filter-list__body input[type="checkbox"]').change(function(e){if($('.right-bar__body.filter-list__body input[type="checkbox"]:checked').length){$('.right-bar__body.filter-list__body [data-action="filters-save-group"]').prop('disabled',!1)}else{$('.right-bar__body.filter-list__body [data-action="filters-save-group"]').prop('disabled',!0)}});if($('.assign--list select').length){$('.assign--list select').selectize()} +if($('.bulk-actions select').length){$('.bulk-actions select').selectize()} +if($('.search-options select').length){$('.search-options select').selectize()} +$('[data-action="add-filters"], [data-action="ticket-mobile-filters"]').click(function(e){$('body').toggleClass('noscroll');$('.filter-list').fadeIn(150)});$('.dropdown.assignment .assign__body > li > a').click(function(e){var type=$(e.currentTarget).closest('li').attr('data-type') +console.log(type);if(type=='to-my'){$(e.currentTarget).closest('.assign__wrapper').removeClass('unassigned').removeClass('assign').addClass('to-my');$(e.currentTarget).closest('.assign__wrapper').find('.assign__head .assign__head_name b').text('To my');$(e.currentTarget).closest('.assign__wrapper').find('.assign__head .assign__head_name span').text('Assigned to me');$(e.currentTarget).closest('.dropdown').find('label span').text('To my');outClose(10)}else if(type=='unassigned'){$(e.currentTarget).closest('.assign__wrapper').removeClass('to-my').removeClass('assign').addClass('unassigned');$(e.currentTarget).closest('.assign__wrapper').find('.assign__head .assign__head_name b').text('Unassigned');$(e.currentTarget).closest('.assign__wrapper').find('.assign__head .assign__head_name span').text('This ticket is not assigned to anyone');$(e.currentTarget).closest('.dropdown').find('label span').text('Unassigned');outClose(10)}else if(type=='assign'){var $select=$(e.currentTarget).closest('.dropdown').find('select').selectize();var selectize=$select[0].selectize;selectize.clear();$(e.currentTarget).closest('.dropdown').find('.assign--buttons').hide();$(e.currentTarget).closest('.dropdown').find('.assign--list').show()} +e.preventDefault()});$('.dropdown.assignment .assign--list [data-action="close"]').click(function(e){$(e.currentTarget).closest('.dropdown').find('.assign--buttons').show();$(e.currentTarget).closest('.dropdown').find('.assign--list').hide()});$('.dropdown.assignment .assign--list [data-action="save"]').click(function(e){var val=$(e.currentTarget).closest('.assign--list').find('select').val();if($.trim(val).length){$(e.currentTarget).closest('.dropdown').find('.assign__wrapper').removeClass('unassigned').removeClass('to-my').addClass('assign');$(e.currentTarget).closest('.dropdown').find('.assign__head .assign__head_name b').text(val);$(e.currentTarget).closest('.dropdown').find('.assign__head .assign__head_name span').text('Assigned to '+val);$(e.currentTarget).closest('.dropdown').find('label span').text(val);outClose(10)}});$('#default-table .table__first_td input[type="checkbox"]').change(function(e){if($(this).is(':checked')){$(this).closest('tr').addClass('selected')}else{$(this).closest('tr').removeClass('selected')} +var checked=$('#default-table .table__first_td input[type="checkbox"]:checked').length;$('.topmenu > p').text(checked+' tasks selected') +if(checked>0){$('.topmenu, .botmenu').addClass('active')}else{$('.topmenu, .botmenu').removeClass('active')}});$('.tickets__mobile_head [data-action="ticket-mobile-actions"]').click(function(e){$('.main__content.tickets').toggleClass('actions')});$('[data-action="tickets-select-dismiss"]').click(function(e){$('.topmenu, .botmenu').removeClass('active');$('#default-table .table__first_th input[type="checkbox"]:checked, #default-table .table__first_td input[type="checkbox"]:checked').prop('checked',!1)}) +function coptToClipboard(text){var textArea=document.createElement("textarea");textArea.style.position='absolute';textArea.style.top='-10000px';textArea.style.left='-10000px';textArea.value=text;document.body.appendChild(textArea);textArea.focus();textArea.select();try{var successful=document.execCommand("copy");var msg=successful?"successful":"unsuccessful";console.log("Fallback: Copying text command was "+msg)}catch(err){console.error("Fallback: Oops, unable to copy",err)} +document.body.removeChild(textArea)} +function copyTextToClipboard(text){if(!navigator.clipboard){fallbackCopyTextToClipboard(text);return} +navigator.clipboard.writeText(text).then(function(){console.log("Async: Copying to clipboard was successful!")},function(err){console.error("Async: Could not copy text: ",err)})} +$(document).on('click','[data-action="generate-link"]',function(e){coptToClipboard($(this).data('link'));$('[data-type="link-generate-message"]').fadeIn(150,function(){var notification=$(this);setTimeout(function(){notification.fadeOut(150)},3000)});e.preventDefault()});$('[data-action="category-create"]').click(function(e){$('.right-bar.category-create').fadeIn(150);$('body').addClass('noscroll');e.preventDefault()});$('[data-action="team-create"]').click(function(e){$('.right-bar.team-create').fadeIn(150);$('body').addClass('noscroll');e.preventDefault()});$('.right-bar.team-create [data-action="next"]').click(function(e){var step=Number($('.right-bar.team-create .right-bar__body').attr('data-step'))+1;$('.right-bar.team-create .right-bar__body').attr('data-step',step)});$('.right-bar.team-create [data-action="back"]').click(function(e){var step=Number($('.right-bar.team-create .right-bar__body').attr('data-step'))-1;$('.right-bar.team-create .right-bar__body').attr('data-step',step)});$('.right-bar.team-create [data-action="save"]').click(function(e){var rand=0-0.5+Math.random()*(7-0+1) +rand=Math.round(rand);var newTeam=''+$($('.table tbody tr')[rand]).html()+'';$('.team .table tbody').prepend(newTeam);$('.right-bar.team-create').fadeOut(150).find('.right-bar__body').attr('data-step',1);$('.notification-flash[data-type="team-created-confirm"]').fadeIn(150,function(){var notification=$(this);setTimeout(function(){notification.fadeOut(150)},3000)})});$('.modal.team-delete [data-action="cancel"]').click(function(){$('.modal.team-delete').fadeOut(150)});$('.modal.team-delete [data-action="close"]').click(function(e){$('.team-create').fadeOut(150,closeModal).find('.right-bar__body').attr('data-step',1)});$('.datepicker').datepicker({language:'en',position:'right top',autoClose:!0,onSelect:function(formattedDate,date,inst){if(formattedDate.length){inst.$el.parent().parent().find('.calendar--value').fadeIn(150).find('span').text(formattedDate)}},onHide:function(inst,animationCompleted){$('.param.calendar button').removeClass('active')}});$('.param.calendar button').click(function(e){$(this).addClass('active');$(this).parent().find('.datepicker').data("datepicker").show()});$('.param.calendar .close').click(function(e){$(this).parent().parent().find('.calendar--button').find('.datepicker').data("datepicker").clear();$('.param.calendar .calendar--value').fadeOut(150,function(){$(this).find('span').text('')})});$('.right-bar.ticket-create .step-1 .cayrgory-list li').click(function(e){$('.right-bar.ticket-create .right-bar__body').attr('data-step',2)});$('.right-bar.ticket-create [data-action="next"]').click(function(e){var step=Number($('.right-bar.ticket-create .right-bar__body').attr('data-step'))+1;$('.right-bar.ticket-create .right-bar__body').attr('data-step',step)});$('.right-bar.ticket-create [data-action="back"]').click(function(e){var step=Number($('.right-bar.ticket-create .right-bar__body').attr('data-step'))-1;$('.right-bar.ticket-create .right-bar__body').attr('data-step',step)});$('.right-bar.ticket-create [data-action="save"]').click(function(e){var rand=0-0.5+Math.random()*(7-0+1) +rand=Math.round(rand);var newTeam=''+$($('.table tbody tr')[rand]).html()+'';$('.table.ticket-list tbody').prepend(newTeam);$('.right-bar.ticket-create').fadeOut(150).find('.right-bar__body').attr('data-step',1);$('.notification-flash[data-type="ticket-created-confirm"]').fadeIn(150,function(){var notification=$(this);setTimeout(function(){notification.fadeOut(150)},3000)});$('body').removeClass('noscroll')});$('.right-bar .step-bar li').click(function(e){var step=Number($(this).attr('data-link'));var current=Number($(this).closest('.right-bar__body').attr('data-step'));if(step!=current){$(this).closest('.right-bar__body').attr('data-step',step)}});$('.main__content.profile [data-action="profile-edit"]').click(function(e){$('.right-bar.profile-edit').fadeIn(150);$('body').addClass('noscroll')});$('.main__content.profile [data-action="profile-delete"]').click(function(e){$('.modal.profile-delete').fadeIn(150);e.preventDefault()});$('.modal [data-action="cancel"]').click(function(e){e.preventDefault();closeModal()});$('[data-action="profile-log-out"]').click(function(e){$('.modal.log-out').fadeIn(150);e.preventDefault()});$('.right-bar.profile-edit [data-action="save"]').click(function(e){$(this).closest('.right-bar').fadeOut(150);$('body').removeClass('noscroll');$('.notification-bar[data-type="profile-saved"]').fadeIn(150)});$('#profile-photo-upload').change(function(e){var reader=new FileReader();var img=$(this).closest('.profile__photo').find('.profile__photo_wrapper img');if(this.files&&this.files[0]){reader.onload=function(e){img.attr('src',e.target.result)} +reader.readAsDataURL(this.files[0]);$(this).closest('.edit-modal__photo').find('.edit-modal__photo_delete').show()}});if($('#email-create-destination').length){$('#email-create-destination').selectize()};if($('#email-batch-process').length){$('#email-batch-process').selectize()};$('[data-action="create-service-message"]').click(function(e){console.log(e);$('body').addClass('noscroll');$('.right-bar.service-message-create').fadeIn(150)});$('.right-bar.service-message-create [data-action="back"]').click(function(e){$('.right-bar.service-message-create .right-bar__body').attr('data-step',1)});$('.right-bar.service-message-create [data-action="next"]').click(function(e){$('.right-bar.service-message-create .right-bar__body').attr('data-step',2)});$('.right-bar.service-message-create [data-action="save"]').click(function(e){$('.right-bar.service-message-create').fadeOut(150);$('body').removeClass('noscroll')});$('[data-action="edit-tools-email-template"]').click(function(e){$('.right-bar.tools-email-template-edit').fadeIn(150);$('body').addClass('noscroll');e.preventDefault()});$('.right-bar.tools-email-template-edit [data-action="save-changes"]').click(function(e){$('.right-bar.tools-email-template-edit').fadeOut(150);$('body').removeClass('noscroll')});$('[data-action="create-custom-field"]').click(function(e){$('.right-bar.create-custom-field').fadeIn(150);$('body').addClass('noscroll')});$('.right-bar.create-custom-field [data-action="save"]').click(function(e){$('.right-bar.create-custom-field').fadeOut(150);$('body').removeClass('noscroll')});$('[data-action="create-custom-status"]').click(function(e){$('.right-bar.create-status').fadeIn(150);$('body').addClass('noscroll')});$('.right-bar.create-status [data-action="save"]').click(function(e){$('.right-bar.create-status').fadeOut(150);$('body').removeClass('noscroll')});$('.right-bar.create-status [data-action="status-color"]').change(function(e){var isOk=/^#[0-9A-F]{6}$/i.test($(this).val());if(isOk){$(this).css('color',$(this).val());$(this).closest('.form-group').find('span').css('color',$(this).val())}else{$(this).css('color','#26282a').val('');$(this).closest('.form-group').find('span').css('color','#26282a')}});$('body').on('mouseenter','.tooltype',function(e){});$('body').on('mouseleave','.tooltype',function(e){});$('.input-tags').selectize({persist:!1,createOnBlur:!0,create:!0});if($('#timezone-select').length){$('#timezone-select').selectize()};$('.knowledge__head_tabs li').click(function(e){var target=$(this).attr('data-link');$('.knowledge__head_tabs li').removeClass('current');$(this).addClass('current');$('.knowledge__tabs').attr('data-current',target)});$('.main__content.knowledge.category .category__list_head .toogle, .main__content.knowledge.category .category__list_head .show').click(function(e){if($(this).closest('.category__list').hasClass('visible')){$(this).closest('.category__list').removeClass('visible').find('.category__list_table').slideUp(150)}else{$(this).closest('.category__list').addClass('visible').find('.category__list_table').slideDown(150)} +e.preventDefault()});$('#knowledge-article-edit-keywords').selectize({plugins:['remove_button'],delimiter:',',persist:!1,create:function(input){return{value:input,text:input}}});$('.knowledge [data-action="knowledge-category-create"]').click(function(e){$('.right-bar.knowledge-category-create').fadeIn(150);$('body').addClass('noscroll');e.preventDefault()});$('.knowledge [data-action="knowledge-sub-category-create"]').click(function(e){$('.right-bar.knowledge-sub-category-create').fadeIn(150);$('body').addClass('noscroll');e.preventDefault()});$('.knowledge [data-action="knowledge-category-edit"]').click(function(e){$('.right-bar.knowledge-category-edit').fadeIn(150);$('body').addClass('noscroll');e.preventDefault()});$('.knowledge [data-action="knowledge-category-edit"]').click(function(e){$('.right-bar.knowledge-category-edit').fadeIn(150);$('body').addClass('noscroll');e.preventDefault()});$('.knowledge [data-action="knowledge-sub-category-edit"]').click(function(e){$('.right-bar.knowledge-sub-category-edit').fadeIn(150);$('body').addClass('noscroll');e.preventDefault()});$('.knowledge').on('click','[data-action="generate-link"]',function(e){var generateLink='https://some-generate-link.html' +coptToClipboard(generateLink);$('[data-type="link-generate-message"]').fadeIn(150,function(){var notification=$(this);setTimeout(function(){notification.fadeOut(150)},3000)});e.preventDefault()});$('#search-datepicker').datepicker({language:'en',position:'left top',autoClose:!0,range:!0,multipleDatesSeparator:' - ',toggleSelected:!1,onSelect:function(formattedDate,date,inst){if(formattedDate.length){}},onHide:function(inst,animationCompleted){}});$('.header__mobile [data-action="toggle-menu"]').click(function(e){$('body').removeClass('show-search');$('body').toggleClass('show-menu')});$('.header__mobile [data-action="toggle-search"]').click(function(e){$('body').toggleClass('show-search')});$('.selectize-input input').prop('readonly',!0)});$('.email__list_aside .list--item').click(function(e){var title=$(this).find('.head h5').text();$('.email__list_descr .head h3').text(title);$('.email__list_article').fadeIn(150).animate({right:0},300)});$(".btn-hide-article").click(function(){$(this).closest('.email__list_article').animate({right:"-100vw"},300)});$('#header-search').keyup(function(e){var val=$.trim($(this).val());if(val.length){$('.form__search_results').slideDown(150)}else{$('.form__search_results').slideUp(150)}}) \ No newline at end of file diff --git a/hesk/js/datepicker.en.js b/hesk/js/datepicker.en.js new file mode 100644 index 0000000..6097edd --- /dev/null +++ b/hesk/js/datepicker.en.js @@ -0,0 +1,13 @@ +;(function ($) { $.fn.datepicker.language['en'] = { + days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + daysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], + daysMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + months: ['January','February','March','April','May','June', 'July','August','September','October','November','December'], + monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + today: 'Today', + clear: 'Clear', + dateFormat: 'mm/dd/yyyy', + timeFormat: 'hh:ii aa', + firstDay: 1 +}; })(jQuery); +//# sourceMappingURL=datepicker.en.js.map diff --git a/hesk/js/datepicker.min.js b/hesk/js/datepicker.min.js new file mode 100644 index 0000000..53df79a --- /dev/null +++ b/hesk/js/datepicker.min.js @@ -0,0 +1,3 @@ +!function(t,e,i){!function(){var s,a,n,h="2.2.3",o="datepicker",r=".datepicker-here",c=!1,d='
    ',l={classes:"",inline:!1,language:"ru",startDate:new Date,firstDay:"",weekends:[6,0],dateFormat:"",altField:"",altFieldDateFormat:"@",toggleSelected:!0,keyboardNav:!0,position:"bottom left",offset:12,view:"days",minView:"days",showOtherMonths:!0,selectOtherMonths:!0,moveToOtherMonthsOnSelect:!0,showOtherYears:!0,selectOtherYears:!0,moveToOtherYearsOnSelect:!0,minDate:"",maxDate:"",disableNavWhenOutOfRange:!0,multipleDates:!1,multipleDatesSeparator:",",range:!1,todayButton:!1,clearButton:!1,showEvent:"focus",autoClose:!1,monthsField:"monthsShort",prevHtml:'',nextHtml:'',navTitles:{days:"MM, yyyy",months:"yyyy",years:"yyyy1 - yyyy2"},timepicker:!1,onlyTimepicker:!1,dateTimeSeparator:" ",timeFormat:"",minHours:0,maxHours:24,minMinutes:0,maxMinutes:59,hoursStep:1,minutesStep:1,onSelect:"",onShow:"",onHide:"",onChangeMonth:"",onChangeYear:"",onChangeDecade:"",onChangeView:"",onRenderCell:""},u={ctrlRight:[17,39],ctrlUp:[17,38],ctrlLeft:[17,37],ctrlDown:[17,40],shiftRight:[16,39],shiftUp:[16,38],shiftLeft:[16,37],shiftDown:[16,40],altUp:[18,38],altRight:[18,39],altLeft:[18,37],altDown:[18,40],ctrlShiftUp:[16,17,38]},m=function(t,a){this.el=t,this.$el=e(t),this.opts=e.extend(!0,{},l,a,this.$el.data()),s==i&&(s=e("body")),this.opts.startDate||(this.opts.startDate=new Date),"INPUT"==this.el.nodeName&&(this.elIsInput=!0),this.opts.altField&&(this.$altField="string"==typeof this.opts.altField?e(this.opts.altField):this.opts.altField),this.inited=!1,this.visible=!1,this.silent=!1,this.currentDate=this.opts.startDate,this.currentView=this.opts.view,this._createShortCuts(),this.selectedDates=[],this.views={},this.keys=[],this.minRange="",this.maxRange="",this._prevOnSelectValue="",this.init()};n=m,n.prototype={VERSION:h,viewIndexes:["days","months","years"],init:function(){c||this.opts.inline||!this.elIsInput||this._buildDatepickersContainer(),this._buildBaseHtml(),this._defineLocale(this.opts.language),this._syncWithMinMaxDates(),this.elIsInput&&(this.opts.inline||(this._setPositionClasses(this.opts.position),this._bindEvents()),this.opts.keyboardNav&&!this.opts.onlyTimepicker&&this._bindKeyboardEvents(),this.$datepicker.on("mousedown",this._onMouseDownDatepicker.bind(this)),this.$datepicker.on("mouseup",this._onMouseUpDatepicker.bind(this))),this.opts.classes&&this.$datepicker.addClass(this.opts.classes),this.opts.timepicker&&(this.timepicker=new e.fn.datepicker.Timepicker(this,this.opts),this._bindTimepickerEvents()),this.opts.onlyTimepicker&&this.$datepicker.addClass("-only-timepicker-"),this.views[this.currentView]=new e.fn.datepicker.Body(this,this.currentView,this.opts),this.views[this.currentView].show(),this.nav=new e.fn.datepicker.Navigation(this,this.opts),this.view=this.currentView,this.$el.on("clickCell.adp",this._onClickCell.bind(this)),this.$datepicker.on("mouseenter",".datepicker--cell",this._onMouseEnterCell.bind(this)),this.$datepicker.on("mouseleave",".datepicker--cell",this._onMouseLeaveCell.bind(this)),this.inited=!0},_createShortCuts:function(){this.minDate=this.opts.minDate?this.opts.minDate:new Date(-86399999136e5),this.maxDate=this.opts.maxDate?this.opts.maxDate:new Date(86399999136e5)},_bindEvents:function(){this.$el.on(this.opts.showEvent+".adp",this._onShowEvent.bind(this)),this.$el.on("mouseup.adp",this._onMouseUpEl.bind(this)),this.$el.on("blur.adp",this._onBlur.bind(this)),this.$el.on("keyup.adp",this._onKeyUpGeneral.bind(this)),e(t).on("resize.adp",this._onResize.bind(this)),e("body").on("mouseup.adp",this._onMouseUpBody.bind(this))},_bindKeyboardEvents:function(){this.$el.on("keydown.adp",this._onKeyDown.bind(this)),this.$el.on("keyup.adp",this._onKeyUp.bind(this)),this.$el.on("hotKey.adp",this._onHotKey.bind(this))},_bindTimepickerEvents:function(){this.$el.on("timeChange.adp",this._onTimeChange.bind(this))},isWeekend:function(t){return-1!==this.opts.weekends.indexOf(t)},_defineLocale:function(t){"string"==typeof t?(this.loc=e.fn.datepicker.language[t],this.loc||(console.warn("Can't find language \""+t+'" in Datepicker.language, will use "ru" instead'),this.loc=e.extend(!0,{},e.fn.datepicker.language.ru)),this.loc=e.extend(!0,{},e.fn.datepicker.language.ru,e.fn.datepicker.language[t])):this.loc=e.extend(!0,{},e.fn.datepicker.language.ru,t),this.opts.dateFormat&&(this.loc.dateFormat=this.opts.dateFormat),this.opts.timeFormat&&(this.loc.timeFormat=this.opts.timeFormat),""!==this.opts.firstDay&&(this.loc.firstDay=this.opts.firstDay),this.opts.timepicker&&(this.loc.dateFormat=[this.loc.dateFormat,this.loc.timeFormat].join(this.opts.dateTimeSeparator)),this.opts.onlyTimepicker&&(this.loc.dateFormat=this.loc.timeFormat);var i=this._getWordBoundaryRegExp;(this.loc.timeFormat.match(i("aa"))||this.loc.timeFormat.match(i("AA")))&&(this.ampm=!0)},_buildDatepickersContainer:function(){c=!0,s.append('
    '),a=e("#datepickers-container")},_buildBaseHtml:function(){var t,i=e('
    ');t="INPUT"==this.el.nodeName?this.opts.inline?i.insertAfter(this.$el):a:i.appendTo(this.$el),this.$datepicker=e(d).appendTo(t),this.$content=e(".datepicker--content",this.$datepicker),this.$nav=e(".datepicker--nav",this.$datepicker)},_triggerOnChange:function(){if(!this.selectedDates.length){if(""===this._prevOnSelectValue)return;return this._prevOnSelectValue="",this.opts.onSelect("","",this)}var t,e=this.selectedDates,i=n.getParsedDate(e[0]),s=this,a=new Date(i.year,i.month,i.date,i.hours,i.minutes);t=e.map(function(t){return s.formatDate(s.loc.dateFormat,t)}).join(this.opts.multipleDatesSeparator),(this.opts.multipleDates||this.opts.range)&&(a=e.map(function(t){var e=n.getParsedDate(t);return new Date(e.year,e.month,e.date,e.hours,e.minutes)})),this._prevOnSelectValue=t,this.opts.onSelect(t,a,this)},next:function(){var t=this.parsedDate,e=this.opts;switch(this.view){case"days":this.date=new Date(t.year,t.month+1,1),e.onChangeMonth&&e.onChangeMonth(this.parsedDate.month,this.parsedDate.year);break;case"months":this.date=new Date(t.year+1,t.month,1),e.onChangeYear&&e.onChangeYear(this.parsedDate.year);break;case"years":this.date=new Date(t.year+10,0,1),e.onChangeDecade&&e.onChangeDecade(this.curDecade)}},prev:function(){var t=this.parsedDate,e=this.opts;switch(this.view){case"days":this.date=new Date(t.year,t.month-1,1),e.onChangeMonth&&e.onChangeMonth(this.parsedDate.month,this.parsedDate.year);break;case"months":this.date=new Date(t.year-1,t.month,1),e.onChangeYear&&e.onChangeYear(this.parsedDate.year);break;case"years":this.date=new Date(t.year-10,0,1),e.onChangeDecade&&e.onChangeDecade(this.curDecade)}},formatDate:function(t,e){e=e||this.date;var i,s=t,a=this._getWordBoundaryRegExp,h=this.loc,o=n.getLeadingZeroNum,r=n.getDecade(e),c=n.getParsedDate(e),d=c.fullHours,l=c.hours,u=t.match(a("aa"))||t.match(a("AA")),m="am",p=this._replacer;switch(this.opts.timepicker&&this.timepicker&&u&&(i=this.timepicker._getValidHoursFromDate(e,u),d=o(i.hours),l=i.hours,m=i.dayPeriod),!0){case/@/.test(s):s=s.replace(/@/,e.getTime());case/aa/.test(s):s=p(s,a("aa"),m);case/AA/.test(s):s=p(s,a("AA"),m.toUpperCase());case/dd/.test(s):s=p(s,a("dd"),c.fullDate);case/d/.test(s):s=p(s,a("d"),c.date);case/DD/.test(s):s=p(s,a("DD"),h.days[c.day]);case/D/.test(s):s=p(s,a("D"),h.daysShort[c.day]);case/mm/.test(s):s=p(s,a("mm"),c.fullMonth);case/m/.test(s):s=p(s,a("m"),c.month+1);case/MM/.test(s):s=p(s,a("MM"),this.loc.months[c.month]);case/M/.test(s):s=p(s,a("M"),h.monthsShort[c.month]);case/ii/.test(s):s=p(s,a("ii"),c.fullMinutes);case/i/.test(s):s=p(s,a("i"),c.minutes);case/hh/.test(s):s=p(s,a("hh"),d);case/h/.test(s):s=p(s,a("h"),l);case/yyyy/.test(s):s=p(s,a("yyyy"),c.year);case/yyyy1/.test(s):s=p(s,a("yyyy1"),r[0]);case/yyyy2/.test(s):s=p(s,a("yyyy2"),r[1]);case/yy/.test(s):s=p(s,a("yy"),c.year.toString().slice(-2))}return s},_replacer:function(t,e,i){return t.replace(e,function(t,e,s,a){return e+i+a})},_getWordBoundaryRegExp:function(t){var e="\\s|\\.|-|/|\\\\|,|\\$|\\!|\\?|:|;";return new RegExp("(^|>|"+e+")("+t+")($|<|"+e+")","g")},selectDate:function(t){var e=this,i=e.opts,s=e.parsedDate,a=e.selectedDates,h=a.length,o="";if(Array.isArray(t))return void t.forEach(function(t){e.selectDate(t)});if(t instanceof Date){if(this.lastSelectedDate=t,this.timepicker&&this.timepicker._setTime(t),e._trigger("selectDate",t),this.timepicker&&(t.setHours(this.timepicker.hours),t.setMinutes(this.timepicker.minutes)),"days"==e.view&&t.getMonth()!=s.month&&i.moveToOtherMonthsOnSelect&&(o=new Date(t.getFullYear(),t.getMonth(),1)),"years"==e.view&&t.getFullYear()!=s.year&&i.moveToOtherYearsOnSelect&&(o=new Date(t.getFullYear(),0,1)),o&&(e.silent=!0,e.date=o,e.silent=!1,e.nav._render()),i.multipleDates&&!i.range){if(h===i.multipleDates)return;e._isSelected(t)||e.selectedDates.push(t)}else i.range?2==h?(e.selectedDates=[t],e.minRange=t,e.maxRange=""):1==h?(e.selectedDates.push(t),e.maxRange?e.minRange=t:e.maxRange=t,n.bigger(e.maxRange,e.minRange)&&(e.maxRange=e.minRange,e.minRange=t),e.selectedDates=[e.minRange,e.maxRange]):(e.selectedDates=[t],e.minRange=t):e.selectedDates=[t];e._setInputValue(),i.onSelect&&e._triggerOnChange(),i.autoClose&&!this.timepickerIsActive&&(i.multipleDates||i.range?i.range&&2==e.selectedDates.length&&e.hide():e.hide()),e.views[this.currentView]._render()}},removeDate:function(t){var e=this.selectedDates,i=this;if(t instanceof Date)return e.some(function(s,a){return n.isSame(s,t)?(e.splice(a,1),i.selectedDates.length?i.lastSelectedDate=i.selectedDates[i.selectedDates.length-1]:(i.minRange="",i.maxRange="",i.lastSelectedDate=""),i.views[i.currentView]._render(),i._setInputValue(),i.opts.onSelect&&i._triggerOnChange(),!0):void 0})},today:function(){this.silent=!0,this.view=this.opts.minView,this.silent=!1,this.date=new Date,this.opts.todayButton instanceof Date&&this.selectDate(this.opts.todayButton)},clear:function(){this.selectedDates=[],this.minRange="",this.maxRange="",this.views[this.currentView]._render(),this._setInputValue(),this.opts.onSelect&&this._triggerOnChange()},update:function(t,i){var s=arguments.length,a=this.lastSelectedDate;return 2==s?this.opts[t]=i:1==s&&"object"==typeof t&&(this.opts=e.extend(!0,this.opts,t)),this._createShortCuts(),this._syncWithMinMaxDates(),this._defineLocale(this.opts.language),this.nav._addButtonsIfNeed(),this.opts.onlyTimepicker||this.nav._render(),this.views[this.currentView]._render(),this.elIsInput&&!this.opts.inline&&(this._setPositionClasses(this.opts.position),this.visible&&this.setPosition(this.opts.position)),this.opts.classes&&this.$datepicker.addClass(this.opts.classes),this.opts.onlyTimepicker&&this.$datepicker.addClass("-only-timepicker-"),this.opts.timepicker&&(a&&this.timepicker._handleDate(a),this.timepicker._updateRanges(),this.timepicker._updateCurrentTime(),a&&(a.setHours(this.timepicker.hours),a.setMinutes(this.timepicker.minutes))),this._setInputValue(),this},_syncWithMinMaxDates:function(){var t=this.date.getTime();this.silent=!0,this.minTime>t&&(this.date=this.minDate),this.maxTime=this.minTime&&i<=this.maxTime,month:o>=this.minTime&&r<=this.maxTime,year:s.year>=a.year&&s.year<=h.year};return e?c[e]:c.day},_getDimensions:function(t){var e=t.offset();return{width:t.outerWidth(),height:t.outerHeight(),left:e.left,top:e.top}},_getDateFromCell:function(t){var e=this.parsedDate,s=t.data("year")||e.year,a=t.data("month")==i?e.month:t.data("month"),n=t.data("date")||1;return new Date(s,a,n)},_setPositionClasses:function(t){t=t.split(" ");var e=t[0],i=t[1],s="datepicker -"+e+"-"+i+"- -from-"+e+"-";this.visible&&(s+=" active"),this.$datepicker.removeAttr("class").addClass(s)},setPosition:function(t){t=t||this.opts.position;var e,i,s=this._getDimensions(this.$el),a=this._getDimensions(this.$datepicker),n=t.split(" "),h=this.opts.offset,o=n[0],r=n[1];switch(o){case"top":e=s.top-a.height-h;break;case"right":i=s.left+s.width+h;break;case"bottom":e=s.top+s.height+h;break;case"left":i=s.left-a.width-h}switch(r){case"top":e=s.top;break;case"right":i=s.left+s.width-a.width;break;case"bottom":e=s.top+s.height-a.height;break;case"left":i=s.left;break;case"center":/left|right/.test(o)?e=s.top+s.height/2-a.height/2:i=s.left+s.width/2-a.width/2}this.$datepicker.css({left:i,top:e})},show:function(){var t=this.opts.onShow;this.setPosition(this.opts.position),this.$datepicker.addClass("active"),this.visible=!0,t&&this._bindVisionEvents(t)},hide:function(){var t=this.opts.onHide;this.$datepicker.removeClass("active").css({left:"-100000px"}),this.focused="",this.keys=[],this.inFocus=!1,this.visible=!1,this.$el.blur(),t&&this._bindVisionEvents(t)},down:function(t){this._changeView(t,"down")},up:function(t){this._changeView(t,"up")},_bindVisionEvents:function(t){this.$datepicker.off("transitionend.dp"),t(this,!1),this.$datepicker.one("transitionend.dp",t.bind(this,this,!0))},_changeView:function(t,e){t=t||this.focused||this.date;var i="up"==e?this.viewIndex+1:this.viewIndex-1;i>2&&(i=2),0>i&&(i=0),this.silent=!0,this.date=new Date(t.getFullYear(),t.getMonth(),1),this.silent=!1,this.view=this.viewIndexes[i]},_handleHotKey:function(t){var e,i,s,a=n.getParsedDate(this._getFocusedDate()),h=this.opts,o=!1,r=!1,c=!1,d=a.year,l=a.month,u=a.date;switch(t){case"ctrlRight":case"ctrlUp":l+=1,o=!0;break;case"ctrlLeft":case"ctrlDown":l-=1,o=!0;break;case"shiftRight":case"shiftUp":r=!0,d+=1;break;case"shiftLeft":case"shiftDown":r=!0,d-=1;break;case"altRight":case"altUp":c=!0,d+=10;break;case"altLeft":case"altDown":c=!0,d-=10;break;case"ctrlShiftUp":this.up()}s=n.getDaysCount(new Date(d,l)),i=new Date(d,l,u),u>s&&(u=s),i.getTime()this.maxTime&&(i=this.maxDate),this.focused=i,e=n.getParsedDate(i),o&&h.onChangeMonth&&h.onChangeMonth(e.month,e.year),r&&h.onChangeYear&&h.onChangeYear(e.year),c&&h.onChangeDecade&&h.onChangeDecade(this.curDecade)},_registerKey:function(t){var e=this.keys.some(function(e){return e==t});e||this.keys.push(t)},_unRegisterKey:function(t){var e=this.keys.indexOf(t);this.keys.splice(e,1)},_isHotKeyPressed:function(){var t,e=!1,i=this,s=this.keys.sort();for(var a in u)t=u[a],s.length==t.length&&t.every(function(t,e){return t==s[e]})&&(i._trigger("hotKey",a),e=!0);return e},_trigger:function(t,e){this.$el.trigger(t,e)},_focusNextCell:function(t,e){e=e||this.cellType;var i=n.getParsedDate(this._getFocusedDate()),s=i.year,a=i.month,h=i.date;if(!this._isHotKeyPressed()){switch(t){case 37:"day"==e?h-=1:"","month"==e?a-=1:"","year"==e?s-=1:"";break;case 38:"day"==e?h-=7:"","month"==e?a-=3:"","year"==e?s-=4:"";break;case 39:"day"==e?h+=1:"","month"==e?a+=1:"","year"==e?s+=1:"";break;case 40:"day"==e?h+=7:"","month"==e?a+=3:"","year"==e?s+=4:""}var o=new Date(s,a,h);o.getTime()this.maxTime&&(o=this.maxDate),this.focused=o}},_getFocusedDate:function(){var t=this.focused||this.selectedDates[this.selectedDates.length-1],e=this.parsedDate;if(!t)switch(this.view){case"days":t=new Date(e.year,e.month,(new Date).getDate());break;case"months":t=new Date(e.year,e.month,1);break;case"years":t=new Date(e.year,0,1)}return t},_getCell:function(t,i){i=i||this.cellType;var s,a=n.getParsedDate(t),h='.datepicker--cell[data-year="'+a.year+'"]';switch(i){case"month":h='[data-month="'+a.month+'"]';break;case"day":h+='[data-month="'+a.month+'"][data-date="'+a.date+'"]'}return s=this.views[this.currentView].$el.find(h),s.length?s:e("")},destroy:function(){var t=this;t.$el.off(".adp").data("datepicker",""),t.selectedDates=[],t.focused="",t.views={},t.keys=[],t.minRange="",t.maxRange="",t.opts.inline||!t.elIsInput?t.$datepicker.closest(".datepicker-inline").remove():t.$datepicker.remove()},_handleAlreadySelectedDates:function(t,e){this.opts.range?this.opts.toggleSelected?this.removeDate(e):2!=this.selectedDates.length&&this._trigger("clickCell",e):this.opts.toggleSelected&&this.removeDate(e),this.opts.toggleSelected||(this.lastSelectedDate=t,this.opts.timepicker&&(this.timepicker._setTime(t),this.timepicker.update()))},_onShowEvent:function(t){this.visible||this.show()},_onBlur:function(){!this.inFocus&&this.visible&&this.hide()},_onMouseDownDatepicker:function(t){this.inFocus=!0},_onMouseUpDatepicker:function(t){this.inFocus=!1,t.originalEvent.inFocus=!0,t.originalEvent.timepickerFocus||this.$el.focus()},_onKeyUpGeneral:function(t){var e=this.$el.val();e||this.clear()},_onResize:function(){this.visible&&this.setPosition()},_onMouseUpBody:function(t){t.originalEvent.inFocus||this.visible&&!this.inFocus&&this.hide()},_onMouseUpEl:function(t){t.originalEvent.inFocus=!0,setTimeout(this._onKeyUpGeneral.bind(this),4)},_onKeyDown:function(t){var e=t.which;if(this._registerKey(e),e>=37&&40>=e&&(t.preventDefault(),this._focusNextCell(e)),13==e&&this.focused){if(this._getCell(this.focused).hasClass("-disabled-"))return;if(this.view!=this.opts.minView)this.down();else{var i=this._isSelected(this.focused,this.cellType);if(!i)return this.timepicker&&(this.focused.setHours(this.timepicker.hours),this.focused.setMinutes(this.timepicker.minutes)),void this.selectDate(this.focused);this._handleAlreadySelectedDates(i,this.focused)}}27==e&&this.hide()},_onKeyUp:function(t){var e=t.which;this._unRegisterKey(e)},_onHotKey:function(t,e){this._handleHotKey(e)},_onMouseEnterCell:function(t){var i=e(t.target).closest(".datepicker--cell"),s=this._getDateFromCell(i);this.silent=!0,this.focused&&(this.focused=""),i.addClass("-focus-"),this.focused=s,this.silent=!1,this.opts.range&&1==this.selectedDates.length&&(this.minRange=this.selectedDates[0],this.maxRange="",n.less(this.minRange,this.focused)&&(this.maxRange=this.minRange,this.minRange=""),this.views[this.currentView]._update())},_onMouseLeaveCell:function(t){var i=e(t.target).closest(".datepicker--cell");i.removeClass("-focus-"),this.silent=!0,this.focused="",this.silent=!1},_onTimeChange:function(t,e,i){var s=new Date,a=this.selectedDates,n=!1;a.length&&(n=!0,s=this.lastSelectedDate),s.setHours(e),s.setMinutes(i),n||this._getCell(s).hasClass("-disabled-")?(this._setInputValue(),this.opts.onSelect&&this._triggerOnChange()):this.selectDate(s)},_onClickCell:function(t,e){this.timepicker&&(e.setHours(this.timepicker.hours),e.setMinutes(this.timepicker.minutes)),this.selectDate(e)},set focused(t){if(!t&&this.focused){var e=this._getCell(this.focused);e.length&&e.removeClass("-focus-")}this._focused=t,this.opts.range&&1==this.selectedDates.length&&(this.minRange=this.selectedDates[0],this.maxRange="",n.less(this.minRange,this._focused)&&(this.maxRange=this.minRange,this.minRange="")),this.silent||(this.date=t)},get focused(){return this._focused},get parsedDate(){return n.getParsedDate(this.date)},set date(t){return t instanceof Date?(this.currentDate=t,this.inited&&!this.silent&&(this.views[this.view]._render(),this.nav._render(),this.visible&&this.elIsInput&&this.setPosition()),t):void 0},get date(){return this.currentDate},set view(t){return this.viewIndex=this.viewIndexes.indexOf(t),this.viewIndex<0?void 0:(this.prevView=this.currentView,this.currentView=t,this.inited&&(this.views[t]?this.views[t]._render():this.views[t]=new e.fn.datepicker.Body(this,t,this.opts),this.views[this.prevView].hide(),this.views[t].show(),this.nav._render(),this.opts.onChangeView&&this.opts.onChangeView(t),this.elIsInput&&this.visible&&this.setPosition()),t)},get view(){return this.currentView},get cellType(){return this.view.substring(0,this.view.length-1)},get minTime(){var t=n.getParsedDate(this.minDate);return new Date(t.year,t.month,t.date).getTime()},get maxTime(){var t=n.getParsedDate(this.maxDate);return new Date(t.year,t.month,t.date).getTime()},get curDecade(){return n.getDecade(this.date)}},n.getDaysCount=function(t){return new Date(t.getFullYear(),t.getMonth()+1,0).getDate()},n.getParsedDate=function(t){return{year:t.getFullYear(),month:t.getMonth(),fullMonth:t.getMonth()+1<10?"0"+(t.getMonth()+1):t.getMonth()+1,date:t.getDate(),fullDate:t.getDate()<10?"0"+t.getDate():t.getDate(),day:t.getDay(),hours:t.getHours(),fullHours:t.getHours()<10?"0"+t.getHours():t.getHours(),minutes:t.getMinutes(),fullMinutes:t.getMinutes()<10?"0"+t.getMinutes():t.getMinutes()}},n.getDecade=function(t){var e=10*Math.floor(t.getFullYear()/10);return[e,e+9]},n.template=function(t,e){return t.replace(/#\{([\w]+)\}/g,function(t,i){return e[i]||0===e[i]?e[i]:void 0})},n.isSame=function(t,e,i){if(!t||!e)return!1;var s=n.getParsedDate(t),a=n.getParsedDate(e),h=i?i:"day",o={day:s.date==a.date&&s.month==a.month&&s.year==a.year,month:s.month==a.month&&s.year==a.year,year:s.year==a.year};return o[h]},n.less=function(t,e,i){return t&&e?e.getTime()t.getTime():!1},n.getLeadingZeroNum=function(t){return parseInt(t)<10?"0"+t:t},n.resetTime=function(t){return"object"==typeof t?(t=n.getParsedDate(t),new Date(t.year,t.month,t.date)):void 0},e.fn.datepicker=function(t){return this.each(function(){if(e.data(this,o)){var i=e.data(this,o);i.opts=e.extend(!0,i.opts,t),i.update()}else e.data(this,o,new m(this,t))})},e.fn.datepicker.Constructor=m,e.fn.datepicker.language={ru:{days:["ВоÑкреÑенье","Понедельник","Вторник","Среда","Четверг","ПÑтница","Суббота"],daysShort:["ВоÑ","Пон","Вто","Сре","Чет","ПÑÑ‚","Суб"],daysMin:["Ð’Ñ","Пн","Ð’Ñ‚","Ср","Чт","Пт","Сб"],months:["Январь","Февраль","Март","Ðпрель","Май","Июнь","Июль","ÐвгуÑÑ‚","СентÑбрь","ОктÑбрь","ÐоÑбрь","Декабрь"],monthsShort:["Янв","Фев","Мар","Ðпр","Май","Июн","Июл","Ðвг","Сен","Окт","ÐоÑ","Дек"],today:"СегоднÑ",clear:"ОчиÑтить",dateFormat:"dd.mm.yyyy",timeFormat:"hh:ii",firstDay:1}},e(function(){e(r).datepicker()})}(),function(){var t={days:'
    ',months:'
    ',years:'
    '},s=e.fn.datepicker,a=s.Constructor;s.Body=function(t,i,s){this.d=t,this.type=i,this.opts=s,this.$el=e(""),this.opts.onlyTimepicker||this.init()},s.Body.prototype={init:function(){this._buildBaseHtml(),this._render(),this._bindEvents()},_bindEvents:function(){this.$el.on("click",".datepicker--cell",e.proxy(this._onClickCell,this))},_buildBaseHtml:function(){this.$el=e(t[this.type]).appendTo(this.d.$content),this.$names=e(".datepicker--days-names",this.$el),this.$cells=e(".datepicker--cells",this.$el)},_getDayNamesHtml:function(t,e,s,a){return e=e!=i?e:t,s=s?s:"",a=a!=i?a:0,a>7?s:7==e?this._getDayNamesHtml(t,0,s,++a):(s+='
    '+this.d.loc.daysMin[e]+"
    ",this._getDayNamesHtml(t,++e,s,++a))},_getCellContents:function(t,e){var i="datepicker--cell datepicker--cell-"+e,s=new Date,n=this.d,h=a.resetTime(n.minRange),o=a.resetTime(n.maxRange),r=n.opts,c=a.getParsedDate(t),d={},l=c.date;switch(e){case"day":n.isWeekend(c.day)&&(i+=" -weekend-"),c.month!=this.d.parsedDate.month&&(i+=" -other-month-",r.selectOtherMonths||(i+=" -disabled-"),r.showOtherMonths||(l=""));break;case"month":l=n.loc[n.opts.monthsField][c.month];break;case"year":var u=n.curDecade;l=c.year,(c.yearu[1])&&(i+=" -other-decade-",r.selectOtherYears||(i+=" -disabled-"),r.showOtherYears||(l=""))}return r.onRenderCell&&(d=r.onRenderCell(t,e)||{},l=d.html?d.html:l,i+=d.classes?" "+d.classes:""),r.range&&(a.isSame(h,t,e)&&(i+=" -range-from-"),a.isSame(o,t,e)&&(i+=" -range-to-"),1==n.selectedDates.length&&n.focused?((a.bigger(h,t)&&a.less(n.focused,t)||a.less(o,t)&&a.bigger(n.focused,t))&&(i+=" -in-range-"),a.less(o,t)&&a.isSame(n.focused,t)&&(i+=" -range-from-"),a.bigger(h,t)&&a.isSame(n.focused,t)&&(i+=" -range-to-")):2==n.selectedDates.length&&a.bigger(h,t)&&a.less(o,t)&&(i+=" -in-range-")),a.isSame(s,t,e)&&(i+=" -current-"),n.focused&&a.isSame(t,n.focused,e)&&(i+=" -focus-"),n._isSelected(t,e)&&(i+=" -selected-"),(!n._isInRange(t,e)||d.disabled)&&(i+=" -disabled-"),{html:l,classes:i}},_getDaysHtml:function(t){var e=a.getDaysCount(t),i=new Date(t.getFullYear(),t.getMonth(),1).getDay(),s=new Date(t.getFullYear(),t.getMonth(),e).getDay(),n=i-this.d.loc.firstDay,h=6-s+this.d.loc.firstDay;n=0>n?n+7:n,h=h>6?h-7:h;for(var o,r,c=-n+1,d="",l=c,u=e+h;u>=l;l++)r=t.getFullYear(),o=t.getMonth(),d+=this._getDayHtml(new Date(r,o,l));return d},_getDayHtml:function(t){var e=this._getCellContents(t,"day");return'
    '+e.html+"
    "},_getMonthsHtml:function(t){for(var e="",i=a.getParsedDate(t),s=0;12>s;)e+=this._getMonthHtml(new Date(i.year,s)),s++;return e},_getMonthHtml:function(t){var e=this._getCellContents(t,"month");return'
    '+e.html+"
    "},_getYearsHtml:function(t){var e=(a.getParsedDate(t),a.getDecade(t)),i=e[0]-1,s="",n=i;for(n;n<=e[1]+1;n++)s+=this._getYearHtml(new Date(n,0));return s},_getYearHtml:function(t){var e=this._getCellContents(t,"year");return'
    '+e.html+"
    "},_renderTypes:{days:function(){var t=this._getDayNamesHtml(this.d.loc.firstDay),e=this._getDaysHtml(this.d.currentDate);this.$cells.html(e),this.$names.html(t)},months:function(){var t=this._getMonthsHtml(this.d.currentDate);this.$cells.html(t)},years:function(){var t=this._getYearsHtml(this.d.currentDate);this.$cells.html(t)}},_render:function(){this.opts.onlyTimepicker||this._renderTypes[this.type].bind(this)()},_update:function(){var t,i,s,a=e(".datepicker--cell",this.$cells),n=this;a.each(function(a,h){i=e(this),s=n.d._getDateFromCell(e(this)),t=n._getCellContents(s,n.d.cellType),i.attr("class",t.classes)})},show:function(){this.opts.onlyTimepicker||(this.$el.addClass("active"),this.acitve=!0)},hide:function(){this.$el.removeClass("active"),this.active=!1},_handleClick:function(t){var e=t.data("date")||1,i=t.data("month")||0,s=t.data("year")||this.d.parsedDate.year,a=this.d;if(a.view!=this.opts.minView)return void a.down(new Date(s,i,e));var n=new Date(s,i,e),h=this.d._isSelected(n,this.d.cellType);return h?void a._handleAlreadySelectedDates.bind(a,h,n)():void a._trigger("clickCell",n)},_onClickCell:function(t){var i=e(t.target).closest(".datepicker--cell");i.hasClass("-disabled-")||this._handleClick.bind(this)(i)}}}(),function(){var t='
    #{prevHtml}
    #{title}
    #{nextHtml}
    ',i='
    ',s='#{label}',a=e.fn.datepicker,n=a.Constructor;a.Navigation=function(t,e){this.d=t,this.opts=e,this.$buttonsContainer="",this.init()},a.Navigation.prototype={init:function(){this._buildBaseHtml(),this._bindEvents()},_bindEvents:function(){this.d.$nav.on("click",".datepicker--nav-action",e.proxy(this._onClickNavButton,this)),this.d.$nav.on("click",".datepicker--nav-title",e.proxy(this._onClickNavTitle,this)),this.d.$datepicker.on("click",".datepicker--button",e.proxy(this._onClickNavButton,this))},_buildBaseHtml:function(){this.opts.onlyTimepicker||this._render(),this._addButtonsIfNeed()},_addButtonsIfNeed:function(){this.opts.todayButton&&this._addButton("today"),this.opts.clearButton&&this._addButton("clear")},_render:function(){var i=this._getTitle(this.d.currentDate),s=n.template(t,e.extend({title:i},this.opts));this.d.$nav.html(s),"years"==this.d.view&&e(".datepicker--nav-title",this.d.$nav).addClass("-disabled-"),this.setNavStatus()},_getTitle:function(t){return this.d.formatDate(this.opts.navTitles[this.d.view],t)},_addButton:function(t){this.$buttonsContainer.length||this._addButtonsContainer();var i={action:t,label:this.d.loc[t]},a=n.template(s,i);e("[data-action="+t+"]",this.$buttonsContainer).length||this.$buttonsContainer.append(a)},_addButtonsContainer:function(){this.d.$datepicker.append(i),this.$buttonsContainer=e(".datepicker--buttons",this.d.$datepicker)},setNavStatus:function(){if((this.opts.minDate||this.opts.maxDate)&&this.opts.disableNavWhenOutOfRange){var t=this.d.parsedDate,e=t.month,i=t.year,s=t.date;switch(this.d.view){case"days":this.d._isInRange(new Date(i,e-1,1),"month")||this._disableNav("prev"),this.d._isInRange(new Date(i,e+1,1),"month")||this._disableNav("next");break;case"months":this.d._isInRange(new Date(i-1,e,s),"year")||this._disableNav("prev"),this.d._isInRange(new Date(i+1,e,s),"year")||this._disableNav("next");break;case"years":var a=n.getDecade(this.d.date);this.d._isInRange(new Date(a[0]-1,0,1),"year")||this._disableNav("prev"),this.d._isInRange(new Date(a[1]+1,0,1),"year")||this._disableNav("next")}}},_disableNav:function(t){e('[data-action="'+t+'"]',this.d.$nav).addClass("-disabled-")},_activateNav:function(t){e('[data-action="'+t+'"]',this.d.$nav).removeClass("-disabled-")},_onClickNavButton:function(t){var i=e(t.target).closest("[data-action]"),s=i.data("action");this.d[s]()},_onClickNavTitle:function(t){return e(t.target).hasClass("-disabled-")?void 0:"days"==this.d.view?this.d.view="months":void(this.d.view="years")}}}(),function(){var t='
    #{hourVisible} : #{minValue}
    ',i=e.fn.datepicker,s=i.Constructor;i.Timepicker=function(t,e){this.d=t,this.opts=e,this.init()},i.Timepicker.prototype={init:function(){var t="input";this._setTime(this.d.date),this._buildHTML(),navigator.userAgent.match(/trident/gi)&&(t="change"),this.d.$el.on("selectDate",this._onSelectDate.bind(this)),this.$ranges.on(t,this._onChangeRange.bind(this)),this.$ranges.on("mouseup",this._onMouseUpRange.bind(this)),this.$ranges.on("mousemove focus ",this._onMouseEnterRange.bind(this)),this.$ranges.on("mouseout blur",this._onMouseOutRange.bind(this))},_setTime:function(t){var e=s.getParsedDate(t);this._handleDate(t),this.hours=e.hourst.getHours()&&(this.minMinutes=this.opts.minMinutes)},_setMaxTimeFromDate:function(t){ +this.maxHours=t.getHours(),this.maxMinutes=t.getMinutes(),this.d.lastSelectedDate&&this.d.lastSelectedDate.getHours()t?0:i.minHours,this.minMinutes=i.minMinutes<0||i.minMinutes>e?0:i.minMinutes,this.maxHours=i.maxHours<0||i.maxHours>t?t:i.maxHours,this.maxMinutes=i.maxMinutes<0||i.maxMinutes>e?e:i.maxMinutes},_validateHoursMinutes:function(t){this.hoursthis.maxHours&&(this.hours=this.maxHours),this.minutesthis.maxMinutes&&(this.minutes=this.maxMinutes)},_buildHTML:function(){var i=s.getLeadingZeroNum,a={hourMin:this.minHours,hourMax:i(this.maxHours),hourStep:this.opts.hoursStep,hourValue:this.hours,hourVisible:i(this.displayHours),minMin:this.minMinutes,minMax:i(this.maxMinutes),minStep:this.opts.minutesStep,minValue:i(this.minutes)},n=s.template(t,a);this.$timepicker=e(n).appendTo(this.d.$datepicker),this.$ranges=e('[type="range"]',this.$timepicker),this.$hours=e('[name="hours"]',this.$timepicker),this.$minutes=e('[name="minutes"]',this.$timepicker),this.$hoursText=e(".datepicker--time-current-hours",this.$timepicker),this.$minutesText=e(".datepicker--time-current-minutes",this.$timepicker),this.d.ampm&&(this.$ampm=e('').appendTo(e(".datepicker--time-current",this.$timepicker)).html(this.dayPeriod),this.$timepicker.addClass("-am-pm-"))},_updateCurrentTime:function(){var t=s.getLeadingZeroNum(this.displayHours),e=s.getLeadingZeroNum(this.minutes);this.$hoursText.html(t),this.$minutesText.html(e),this.d.ampm&&this.$ampm.html(this.dayPeriod)},_updateRanges:function(){this.$hours.attr({min:this.minHours,max:this.maxHours}).val(this.hours),this.$minutes.attr({min:this.minMinutes,max:this.maxMinutes}).val(this.minutes)},_handleDate:function(t){this._setDefaultMinMaxTime(),t&&(s.isSame(t,this.d.opts.minDate)?this._setMinTimeFromDate(this.d.opts.minDate):s.isSame(t,this.d.opts.maxDate)&&this._setMaxTimeFromDate(this.d.opts.maxDate)),this._validateHoursMinutes(t)},update:function(){this._updateRanges(),this._updateCurrentTime()},_getValidHoursFromDate:function(t,e){var i=t,a=t;t instanceof Date&&(i=s.getParsedDate(t),a=i.hours);var n=e||this.d.ampm,h="am";if(n)switch(!0){case 0==a:a=12;break;case 12==a:h="pm";break;case a>11:a-=12,h="pm"}return{hours:a,dayPeriod:h}},set hours(t){this._hours=t;var e=this._getValidHoursFromDate(t);this.displayHours=e.hours,this.dayPeriod=e.dayPeriod},get hours(){return this._hours},_onChangeRange:function(t){var i=e(t.target),s=i.attr("name");this.d.timepickerIsActive=!0,this[s]=i.val(),this._updateCurrentTime(),this.d._trigger("timeChange",[this.hours,this.minutes]),this._handleDate(this.d.lastSelectedDate),this.update()},_onSelectDate:function(t,e){this._handleDate(e),this.update()},_onMouseEnterRange:function(t){var i=e(t.target).attr("name");e(".datepicker--time-current-"+i,this.$timepicker).addClass("-focus-")},_onMouseOutRange:function(t){var i=e(t.target).attr("name");this.d.inFocus||e(".datepicker--time-current-"+i,this.$timepicker).removeClass("-focus-")},_onMouseUpRange:function(t){this.d.timepickerIsActive=!1}}}()}(window,jQuery); +//# sourceMappingURL=datepicker.min.js.map diff --git a/hesk/js/hesk_javascript.js b/hesk/js/hesk_javascript.js new file mode 100644 index 0000000..ad0c646 --- /dev/null +++ b/hesk/js/hesk_javascript.js @@ -0,0 +1,466 @@ +/** + * + * 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 + * + */ + +function hesk_insertTag(tag) { +var text_to_insert = '%%'+tag+'%%'; +hesk_insertAtCursor(document.form1.msg, text_to_insert); +document.form1.message.focus(); +} + +function hesk_insertAtCursor(myField, myValue) { +if (document.selection) { +myField.focus(); +sel = document.selection.createRange(); +sel.text = myValue; +} +else if (myField.selectionStart || myField.selectionStart == '0') { +var startPos = myField.selectionStart; +var endPos = myField.selectionEnd; +myField.value = myField.value.substring(0, startPos) ++ myValue ++ myField.value.substring(endPos, myField.value.length); +} else { +myField.value += myValue; +} +} + +function hesk_changeAll(myID) { + var d = document.form1; + var setTo = myID.checked ? true : false; + + for (var i = 0; i < d.elements.length; i++) + { + if(d.elements[i].type == 'checkbox' && d.elements[i].name != 'checkall') + { + d.elements[i].checked = setTo; + } + } +} + +function hesk_attach_disable(ids) { + for($i=0;$i' + + '
    {1}
    ' + + '
    ' + + '' + + '{4}' + + ' | ' + + '' + + '{5}' + + '' + + '
    ' + + '
    '; + var response = JSON.parse(xmlHttp.responseText); + for (var i = 0; i < response.length; i++) { + var suggestion = response[i]; + element.innerHTML += suggestFormat.replace(/\{0}/g, suggestion.id) + .replace(/\{1}/g, suggestion.suggestText) + .replace(/\{2}/g, suggestion.originalAddress) + .replace(/\{3}/g, suggestion.formattedSuggestedEmail) + .replace(/\{4}/g, suggestion.yesResponseText) + .replace(/\{5}/g, suggestion.noResponseText); + console.log(response[i]); + } + element.style.display = 'block'; + } + } + + xmlHttp.send(params); + } +} + +function hesk_applyEmailSuggestion(emailTypoId, emailField, originalEmail, formattedSuggestedEmail) { + var eml = document.getElementById(emailField).value; + var regex = new RegExp(originalEmail, "gi"); + document.getElementById(emailField).value = eml.replace(regex, formattedSuggestedEmail); + document.getElementById(emailTypoId).style.display = 'none'; +} + +function hesk_btn(Elem, myClass) +{ + Elem.className = myClass; +} + +function hesk_checkPassword(password) +{ + + var numbers = "0123456789"; + var lowercase = "abcdefghijklmnopqrstuvwxyz"; + var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + var punctuation = "!.@$#*()%~<>{}[]"; + + var combinations = 0; + + if (hesk_contains(password, numbers) > 0) { + combinations += 10; + } + + if (hesk_contains(password, lowercase) > 0) { + combinations += 26; + } + + if (hesk_contains(password, uppercase) > 0) { + combinations += 26; + } + + if (hesk_contains(password, punctuation) > 0) { + combinations += punctuation.length; + } + + var totalCombinations = Math.pow(combinations, password.length); + var timeInSeconds = (totalCombinations / 200) / 2; + var timeInDays = timeInSeconds / 86400 + var lifetime = 365000; + var percentage = timeInDays / lifetime; + + var friendlyPercentage = hesk_cap(Math.round(percentage * 100), 98); + + if (friendlyPercentage < (password.length * 5)) { + friendlyPercentage += password.length * 5; + } + + var friendlyPercentage = hesk_cap(friendlyPercentage, 98); + + var progressBar = document.getElementById("progressBar"); + progressBar.style.width = friendlyPercentage + "%"; + + if (percentage > 1) { + // strong password + progressBar.style.backgroundColor = "#3bce08"; + return; + } + + if (percentage > 0.5) { + // reasonable password + progressBar.style.backgroundColor = "#ffd801"; + return; + } + + if (percentage > 0.10) { + // weak password + progressBar.style.backgroundColor = "orange"; + return; + } + + if (percentage <= 0.10) { + // very weak password + progressBar.style.backgroundColor = "red"; + return; + } + +} + +function hesk_cap(number, max) { + if (number > max) { + return max; + } else { + return number; + } +} + +function hesk_contains(password, validChars) { + + count = 0; + + for (i = 0; i < password.length; i++) { + var char = password.charAt(i); + if (validChars.indexOf(char) > -1) { + count++; + } + } + + return count; +} + +function setCookie(name, value, expires, path, domain, secure) +{ + document.cookie= name + "=" + escape(value) + + ((expires) ? "; expires=" + expires.toGMTString() : "") + + ((path) ? "; path=" + path : "") + + ((domain) ? "; domain=" + domain : "") + + ((secure) ? "; secure" : ""); +} + +function getCookie(name) +{ + var dc = document.cookie; + var prefix = name + "="; + var begin = dc.indexOf("; " + prefix); + if (begin == -1) { + begin = dc.indexOf(prefix); + if (begin != 0) return null; + } else { + begin += 2; + } + var end = document.cookie.indexOf(";", begin); + if (end == -1) { + end = dc.length; + } + return unescape(dc.substring(begin + prefix.length, end)); +} + +function deleteCookie(name, path, domain) +{ + if (getCookie(name)) { + document.cookie = name + "=" + + ((path) ? "; path=" + path : "") + + ((domain) ? "; domain=" + domain : "") + + "; expires=Thu, 01-Jan-70 00:00:01 GMT"; + } +} \ No newline at end of file diff --git a/hesk/js/hesk_javascript.min.js b/hesk/js/hesk_javascript.min.js new file mode 100644 index 0000000..a60013e --- /dev/null +++ b/hesk/js/hesk_javascript.min.js @@ -0,0 +1,104 @@ +function hesk_insertTag(tag){var text_to_insert='%%'+tag+'%%';hesk_insertAtCursor(document.form1.msg,text_to_insert);document.form1.message.focus()} +function hesk_insertAtCursor(myField,myValue){if(document.selection){myField.focus();sel=document.selection.createRange();sel.text=myValue} +else if(myField.selectionStart||myField.selectionStart=='0'){var startPos=myField.selectionStart;var endPos=myField.selectionEnd;myField.value=myField.value.substring(0,startPos)+myValue+myField.value.substring(endPos,myField.value.length)}else{myField.value+=myValue}} +function hesk_changeAll(myID){var d=document.form1;var setTo=myID.checked?!0:!1;for(var i=0;i'+'
    {1}
    '+'
    '+''+'{4}'+' | '+''+'{5}'+''+'
    '+'
    ';var response=JSON.parse(xmlHttp.responseText);for(var i=0;i0){combinations+=10} +if(hesk_contains(password,lowercase)>0){combinations+=26} +if(hesk_contains(password,uppercase)>0){combinations+=26} +if(hesk_contains(password,punctuation)>0){combinations+=punctuation.length} +var totalCombinations=Math.pow(combinations,password.length);var timeInSeconds=(totalCombinations/200)/2;var timeInDays=timeInSeconds/86400 +var lifetime=365000;var percentage=timeInDays/lifetime;var friendlyPercentage=hesk_cap(Math.round(percentage*100),98);if(friendlyPercentage<(password.length*5)){friendlyPercentage+=password.length*5} +var friendlyPercentage=hesk_cap(friendlyPercentage,98);var progressBar=document.getElementById("progressBar");progressBar.style.width=friendlyPercentage+"%";if(percentage>1){progressBar.style.backgroundColor="#3bce08";return} +if(percentage>0.5){progressBar.style.backgroundColor="#ffd801";return} +if(percentage>0.10){progressBar.style.backgroundColor="orange";return} +if(percentage<=0.10){progressBar.style.backgroundColor="red";return}} +function hesk_cap(number,max){if(number>max){return max}else{return number}} +function hesk_contains(password,validChars){count=0;for(i=0;i-1){count++}} +return count} +function setCookie(name,value,expires,path,domain,secure) +{document.cookie=name+"="+escape(value)+((expires)?"; expires="+expires.toGMTString():"")+((path)?"; path="+path:"")+((domain)?"; domain="+domain:"")+((secure)?"; secure":"")} +function getCookie(name) +{var dc=document.cookie;var prefix=name+"=";var begin=dc.indexOf("; "+prefix);if(begin==-1){begin=dc.indexOf(prefix);if(begin!=0)return null}else{begin+=2} +var end=document.cookie.indexOf(";",begin);if(end==-1){end=dc.length} +return unescape(dc.substring(begin+prefix.length,end))} +function deleteCookie(name,path,domain) +{if(getCookie(name)){document.cookie=name+"="+((path)?"; path="+path:"")+((domain)?"; domain="+domain:"")+"; expires=Thu, 01-Jan-70 00:00:01 GMT"}} \ No newline at end of file diff --git a/hesk/js/jquery-3.4.1.min.js b/hesk/js/jquery-3.4.1.min.js new file mode 100644 index 0000000..42a1299 --- /dev/null +++ b/hesk/js/jquery-3.4.1.min.js @@ -0,0 +1,4 @@ +/*! jQuery v3.4.1 | (c) JS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],E=C.document,r=Object.getPrototypeOf,s=t.slice,g=t.concat,u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.4.1",k=function(e,t){return new k.fn.init(e,t)},p=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;function d(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp($),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+$),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ne=function(e,t,n){var r="0x"+t-65536;return r!=r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(m.childNodes),m.childNodes),t[m.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&((e?e.ownerDocument||e:m)!==C&&T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!A[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&U.test(t)){(s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=k),o=(l=h(t)).length;while(o--)l[o]="#"+s+" "+xe(l[o]);c=l.join(","),f=ee.test(t)&&ye(e.parentNode)||e}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){A(t,!0)}finally{s===k&&e.removeAttribute("id")}}}return g(t.replace(B,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[k]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:m;return r!==C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),m!==C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=k,!C.getElementsByName||!C.getElementsByName(k).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+k+"-]").length||v.push("~="),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+k+"+*").length||v.push(".#.+[+~]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",$)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e===C||e.ownerDocument===m&&y(m,e)?-1:t===C||t.ownerDocument===m&&y(m,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===C?-1:t===C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]===m?-1:s[r]===m?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if((e.ownerDocument||e)!==C&&T(e),d.matchesSelector&&E&&!A[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){A(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=p[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&p(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?k.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?k.grep(e,function(e){return e===n!==r}):"string"!=typeof n?k.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(k.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:L.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof k?t[0]:t,k.merge(this,k.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),D.test(r[1])&&k.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(k):k.makeArray(e,this)}).prototype=k.fn,q=k(E);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}k.fn.extend({has:function(e){var t=k(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,""],thead:[1,"","
    "],col:[2,"","
    "],tr:[2,"","
    "],td:[3,"","
    "],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?k.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;nx",y.noCloneChecked=!!me.cloneNode(!0).lastChild.defaultValue;var Te=/^key/,Ce=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ee=/^([^.]*)(?:\.(.+)|)/;function ke(){return!0}function Se(){return!1}function Ne(e,t){return e===function(){try{return E.activeElement}catch(e){}}()==("focus"===t)}function Ae(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)Ae(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Se;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return k().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=k.guid++)),e.each(function(){k.event.add(this,t,i,r,n)})}function De(e,i,o){o?(Q.set(e,i,!1),k.event.add(e,i,{namespace:!1,handler:function(e){var t,n,r=Q.get(this,i);if(1&e.isTrigger&&this[i]){if(r.length)(k.event.special[i]||{}).delegateType&&e.stopPropagation();else if(r=s.call(arguments),Q.set(this,i,r),t=o(this,i),this[i](),r!==(n=Q.get(this,i))||t?Q.set(this,i,!1):n={},r!==n)return e.stopImmediatePropagation(),e.preventDefault(),n.value}else r.length&&(Q.set(this,i,{value:k.event.trigger(k.extend(r[0],k.Event.prototype),r.slice(1),this)}),e.stopImmediatePropagation())}})):void 0===Q.get(e,i)&&k.event.add(e,i,ke)}k.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.get(t);if(v){n.handler&&(n=(o=n).handler,i=o.selector),i&&k.find.matchesSelector(ie,i),n.guid||(n.guid=k.guid++),(u=v.events)||(u=v.events={}),(a=v.handle)||(a=v.handle=function(e){return"undefined"!=typeof k&&k.event.triggered!==e.type?k.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(R)||[""]).length;while(l--)d=g=(s=Ee.exec(e[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=k.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=k.event.special[d]||{},c=k.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&k.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(d,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),k.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.hasData(e)&&Q.get(e);if(v&&(u=v.events)){l=(t=(t||"").match(R)||[""]).length;while(l--)if(d=g=(s=Ee.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d){f=k.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,v.handle)||k.removeEvent(e,d,v.handle),delete u[d])}else for(d in u)k.event.remove(e,d+t[l],n,r,!0);k.isEmptyObject(u)&&Q.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=k.event.fix(e),u=new Array(arguments.length),l=(Q.get(this,"events")||{})[s.type]||[],c=k.event.special[s.type]||{};for(u[0]=s,t=1;t\x20\t\r\n\f]*)[^>]*)\/>/gi,qe=/\s*$/g;function Oe(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&k(e).children("tbody")[0]||e}function Pe(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Re(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Me(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(Q.hasData(e)&&(o=Q.access(e),a=Q.set(t,o),l=o.events))for(i in delete a.handle,a.events={},l)for(n=0,r=l[i].length;n")},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=oe(e);if(!(y.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||k.isXMLDoc(e)))for(a=ve(c),r=0,i=(o=ve(e)).length;r").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Vt,Gt=[],Yt=/(=)\?(?=&|$)|\?\?/;k.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Gt.pop()||k.expando+"_"+kt++;return this[e]=!0,e}}),k.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Yt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Yt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Yt,"$1"+r):!1!==e.jsonp&&(e.url+=(St.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||k.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?k(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Gt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Vt=E.implementation.createHTMLDocument("").body).innerHTML="
    ",2===Vt.childNodes.length),k.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=D.exec(e))?[t.createElement(i[1])]:(i=we([e],t,o),o&&o.length&&k(o).remove(),k.merge([],i.childNodes)));var r,i,o},k.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(k.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},k.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){k.fn[t]=function(e){return this.on(t,e)}}),k.expr.pseudos.animated=function(t){return k.grep(k.timers,function(e){return t===e.elem}).length},k.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=k.css(e,"position"),c=k(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=k.css(e,"top"),u=k.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,k.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},k.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){k.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===k.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===k.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=k(e).offset()).top+=k.css(e,"borderTopWidth",!0),i.left+=k.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-k.css(r,"marginTop",!0),left:t.left-i.left-k.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===k.css(e,"position"))e=e.offsetParent;return e||ie})}}),k.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;k.fn[t]=function(e){return _(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),k.each(["top","left"],function(e,n){k.cssHooks[n]=ze(y.pixelPosition,function(e,t){if(t)return t=_e(e,n),$e.test(t)?k(e).position()[n]+"px":t})}),k.each({Height:"height",Width:"width"},function(a,s){k.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){k.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return _(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?k.css(e,t,i):k.style(e,t,n,i)},s,n?e:void 0,n)}})}),k.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){k.fn[n]=function(e,t){return 0 + */ +(function ($) { + 'use strict'; + var ARROWLEFT = 37, + ARROWRIGHT = 39, + ARROWUP = 38, + ARROWDOWN = 40, + TAB = 9, + CTRLKEY = 17, + SHIFTKEY = 16, + DEL = 46, + ENTER = 13, + ESC = 27, + BACKSPACE = 8, + AKEY = 65, + CKEY = 67, + VKEY = 86, + ZKEY = 90, + YKEY = 89, + defaultSetting = {}, + //currentInput = false, + ctrlDown = false, + shiftDown = false, + publics = {}, + accent_map = { + 'ẚ':'a','Ã':'a','á':'a','À':'a','à':'a','Ä‚':'a','ă':'a','Ắ':'a','ắ':'a','Ằ':'a','ằ':'a','Ẵ':'a','ẵ':'a','Ẳ':'a', + 'Ẫ':'a','ẫ':'a','Ẩ':'a','ẩ':'a','Ç':'a','ÇŽ':'a','Ã…':'a','Ã¥':'a','Ǻ':'a','Ç»':'a','Ä':'a','ä':'a','Çž':'a','ÇŸ':'a', + 'Ã':'a','ã':'a','Ȧ':'a','ȧ':'a','Ç ':'a','Ç¡':'a','Ä„':'a','Ä…':'a','Ä€':'a','Ä':'a','Ả':'a','ả':'a','È€':'a','È':'a', + 'È‚':'a','ȃ':'a','Ạ':'a','ạ':'a','Ặ':'a','ặ':'a','Ậ':'a','ậ':'a','Ḁ':'a','á¸':'a','Ⱥ':'a','â±¥':'a','Ǽ':'a','ǽ':'a', + 'Ç¢':'a','Ç£':'a','Ḃ':'b','ḃ':'b','Ḅ':'b','ḅ':'b','Ḇ':'b','ḇ':'b','Ƀ':'b','Æ€':'b','ᵬ':'b','Æ':'b','É“':'b','Æ‚':'b', + 'ƃ':'b','Ć':'c','ć':'c','Ĉ':'c','ĉ':'c','ÄŒ':'c','Ä':'c','ÄŠ':'c','Ä‹':'c','Ç':'c','ç':'c','Ḉ':'c','ḉ':'c','È»':'c', + 'ȼ':'c','Ƈ':'c','ƈ':'c','É•':'c','ÄŽ':'d','Ä':'d','Ḋ':'d','ḋ':'d','á¸':'d','ḑ':'d','Ḍ':'d','á¸':'d','Ḓ':'d','ḓ':'d', + 'Ḏ':'d','á¸':'d','Ä':'d','Ä‘':'d','áµ­':'d','Ɖ':'d','É–':'d','ÆŠ':'d','É—':'d','Æ‹':'d','ÆŒ':'d','È¡':'d','ð':'d','É':'e', + 'Æ':'e','ÆŽ':'e','Ç':'e','é':'e','È':'e','è':'e','Ä”':'e','Ä•':'e','Ê':'e','ê':'e','Ế':'e','ế':'e','Ề':'e','á»':'e', + 'Ễ':'e','á»…':'e','Ể':'e','ể':'e','Äš':'e','Ä›':'e','Ë':'e','ë':'e','Ẽ':'e','ẽ':'e','Ä–':'e','Ä—':'e','Ȩ':'e','È©':'e', + 'Ḝ':'e','á¸':'e','Ę':'e','Ä™':'e','Ä’':'e','Ä“':'e','Ḗ':'e','ḗ':'e','Ḕ':'e','ḕ':'e','Ẻ':'e','ẻ':'e','È„':'e','È…':'e', + 'Ȇ':'e','ȇ':'e','Ẹ':'e','ẹ':'e','Ệ':'e','ệ':'e','Ḙ':'e','ḙ':'e','Ḛ':'e','ḛ':'e','Ɇ':'e','ɇ':'e','Éš':'e','É':'e', + 'Ḟ':'f','ḟ':'f','áµ®':'f','Æ‘':'f','Æ’':'f','Ç´':'g','ǵ':'g','Äž':'g','ÄŸ':'g','Äœ':'g','Ä':'g','Ǧ':'g','ǧ':'g','Ä ':'g', + 'Ä¡':'g','Ä¢':'g','Ä£':'g','Ḡ':'g','ḡ':'g','Ǥ':'g','Ç¥':'g','Æ“':'g','É ':'g','Ĥ':'h','Ä¥':'h','Èž':'h','ÈŸ':'h','Ḧ':'h', + 'ḧ':'h','Ḣ':'h','ḣ':'h','Ḩ':'h','ḩ':'h','Ḥ':'h','ḥ':'h','Ḫ':'h','ḫ':'h','H':'h','̱':'h','ẖ':'h','Ħ':'h','ħ':'h', + 'â±§':'h','ⱨ':'h','Ã':'i','í':'i','ÃŒ':'i','ì':'i','Ĭ':'i','Ä­':'i','ÃŽ':'i','î':'i','Ç':'i','Ç':'i','Ã':'i','ï':'i', + 'Ḯ':'i','ḯ':'i','Ĩ':'i','Ä©':'i','İ':'i','i':'i','Ä®':'i','į':'i','Ī':'i','Ä«':'i','Ỉ':'i','ỉ':'i','Ȉ':'i','ȉ':'i', + 'ÈŠ':'i','È‹':'i','Ị':'i','ị':'i','Ḭ':'i','ḭ':'i','I':'i','ı':'i','Æ—':'i','ɨ':'i','Ä´':'j','ĵ':'j','J':'j','ÌŒ':'j', + 'ǰ':'j','È·':'j','Ɉ':'j','ɉ':'j','Ê':'j','ÉŸ':'j','Ê„':'j','Ḱ':'k','ḱ':'k','Ǩ':'k','Ç©':'k','Ķ':'k','Ä·':'k','Ḳ':'k', + 'ḳ':'k','Ḵ':'k','ḵ':'k','Ƙ':'k','Æ™':'k','Ⱪ':'k','ⱪ':'k','Ĺ':'a','ĺ':'l','Ľ':'l','ľ':'l','Ä»':'l','ļ':'l','Ḷ':'l', + 'ḷ':'l','Ḹ':'l','ḹ':'l','Ḽ':'l','ḽ':'l','Ḻ':'l','ḻ':'l','Å':'l','Å‚':'l','Ì£':'l','Ä¿':'l', + 'Å€':'l','Ƚ':'l','Æš':'l','â± ':'l','ⱡ':'l','â±¢':'l','É«':'l','ɬ':'l','É­':'l','È´':'l','Ḿ':'m','ḿ':'m','á¹€':'m','á¹':'m', + 'Ṃ':'m','ṃ':'m','ɱ':'m','Ń':'n','Å„':'n','Ǹ':'n','ǹ':'n','Ň':'n','ň':'n','Ñ':'n','ñ':'n','Ṅ':'n','á¹…':'n','Å…':'n', + 'ņ':'n','Ṇ':'n','ṇ':'n','Ṋ':'n','ṋ':'n','Ṉ':'n','ṉ':'n','Æ':'n','ɲ':'n','È ':'n','Æž':'n','ɳ':'n','ȵ':'n','N':'n', + '̈':'n','n':'n','Ó':'o','ó':'o','Ã’':'o','ò':'o','ÅŽ':'o','Å':'o','Ô':'o','ô':'o','á»':'o','ố':'o','á»’':'o', + 'ồ':'o','á»–':'o','á»—':'o','á»”':'o','ổ':'o','Ç‘':'o','Ç’':'o','Ö':'o','ö':'o','Ȫ':'o','È«':'o','Å':'o','Å‘':'o','Õ':'o', + 'õ':'o','Ṍ':'o','á¹':'o','Ṏ':'o','á¹':'o','Ȭ':'o','È­':'o','È®':'o','ȯ':'o','Ȱ':'o','ȱ':'o','Ø':'o','ø':'o','Ǿ':'o', + 'Ç¿':'o','Ǫ':'o','Ç«':'o','Ǭ':'o','Ç­':'o','ÅŒ':'o','Å':'o','á¹’':'o','ṓ':'o','á¹':'o','ṑ':'o','Ỏ':'o','á»':'o','ÈŒ':'o', + 'È':'o','ÈŽ':'o','È':'o','Æ ':'o','Æ¡':'o','Ớ':'o','á»›':'o','Ờ':'o','á»':'o','á» ':'o','ỡ':'o','Ở':'o','ở':'o','Ợ':'o', + 'ợ':'o','Ọ':'o','á»':'o','Ộ':'o','á»™':'o','ÆŸ':'o','ɵ':'o','á¹”':'p','ṕ':'p','á¹–':'p','á¹—':'p','â±£':'p','Ƥ':'p','Æ¥':'p', + 'P':'p','̃':'p','p':'p','Ê ':'q','ÉŠ':'q','É‹':'q','Å”':'r','Å•':'r','Ř':'r','Å™':'r','Ṙ':'r','á¹™':'r','Å–':'r', + 'Å—':'r','È':'r','È‘':'r','È’':'r','È“':'r','Ṛ':'r','á¹›':'r','Ṝ':'r','á¹':'r','Ṟ':'r','ṟ':'r','ÉŒ':'r','É':'r','áµ²':'r', + 'ɼ':'r','Ɽ':'r','ɽ':'r','ɾ':'r','áµ³':'r','ß':'s','Åš':'s','Å›':'s','Ṥ':'s','á¹¥':'s','Åœ':'s','Å':'s','Å ':'s','Å¡':'s', + 'Ṧ':'s','á¹§':'s','á¹ ':'s','ṡ':'s','ẛ':'s','Åž':'s','ÅŸ':'s','á¹¢':'s','á¹£':'s','Ṩ':'s','ṩ':'s','Ș':'s','È™':'s','Ê‚':'s', + 'S':'s','Ì©':'s','s':'s','Þ':'t','þ':'t','Ť':'t','Å¥':'t','T':'t','ẗ':'t','Ṫ':'t','ṫ':'t','Å¢':'t','Å£':'t','Ṭ':'t', + 'á¹­':'t','Èš':'t','È›':'t','á¹°':'t','á¹±':'t','á¹®':'t','ṯ':'t','Ŧ':'t','ŧ':'t','Ⱦ':'t','ⱦ':'t','áµµ':'t', + 'Æ«':'t','Ƭ':'t','Æ­':'t','Æ®':'t','ʈ':'t','ȶ':'t','Ú':'u','ú':'u','Ù':'u','ù':'u','Ŭ':'u','Å­':'u','Û':'u','û':'u', + 'Ç“':'u','Ç”':'u','Å®':'u','ů':'u','Ü':'u','ü':'u','Ç—':'u','ǘ':'u','Ç›':'u','Çœ':'u','Ç™':'u','Çš':'u','Ç•':'u','Ç–':'u', + 'Ű':'u','ű':'u','Ũ':'u','Å©':'u','Ṹ':'u','á¹¹':'u','Ų':'u','ų':'u','Ū':'u','Å«':'u','Ṻ':'u','á¹»':'u','Ủ':'u','á»§':'u', + 'È”':'u','È•':'u','È–':'u','È—':'u','Ư':'u','ư':'u','Ứ':'u','ứ':'u','Ừ':'u','ừ':'u','á»®':'u','ữ':'u','Ử':'u','á»­':'u', + 'á»°':'u','á»±':'u','Ụ':'u','ụ':'u','á¹²':'u','á¹³':'u','á¹¶':'u','á¹·':'u','á¹´':'u','á¹µ':'u','É„':'u','ʉ':'u','á¹¼':'v','á¹½':'v', + 'á¹¾':'v','ṿ':'v','Ʋ':'v','Ê‹':'v','Ẃ':'w','ẃ':'w','Ẁ':'w','áº':'w','Å´':'w','ŵ':'w','W':'w','ÌŠ':'w','ẘ':'w','Ẅ':'w', + 'ẅ':'w','Ẇ':'w','ẇ':'w','Ẉ':'w','ẉ':'w','Ẍ':'x','áº':'x','Ẋ':'x','ẋ':'x','Ã':'y','ý':'y','Ỳ':'y','ỳ':'y','Ŷ':'y', + 'Å·':'y','Y':'y','ẙ':'y','Ÿ':'y','ÿ':'y','Ỹ':'y','ỹ':'y','Ẏ':'y','áº':'y','Ȳ':'y','ȳ':'y','á»¶':'y','á»·':'y', + 'á»´':'y','ỵ':'y','Ê':'y','ÉŽ':'y','É':'y','Ƴ':'y','Æ´':'y','Ź':'z','ź':'z','áº':'z','ẑ':'z','Ž':'z','ž':'z','Å»':'z', + 'ż':'z','Ẓ':'z','ẓ':'z','Ẕ':'z','ẕ':'z','Ƶ':'z','ƶ':'z','Ȥ':'z','È¥':'z','Ê':'z','Ê‘':'z','Ⱬ':'z','ⱬ':'z','Ç®':'z', + 'ǯ':'z','ƺ':'z','ï¼’':'2','ï¼–':'6','ï¼¢':'B','F':'F','J':'J','ï¼®':'N','ï¼²':'R','ï¼¶':'V','Z':'Z','b':'b','f':'f','j':'j', + 'n':'n','ï½’':'r','ï½–':'v','z':'z','1':'1','5':'5','ï¼™':'9','A':'A','ï¼¥':'E','I':'I','ï¼­':'M','ï¼±':'Q','ï¼µ':'U','ï¼¹':'Y', + 'ï½':'a','ï½…':'e','i':'i','ï½':'m','q':'q','u':'u','ï½™':'y','ï¼':'0','ï¼”':'4','8':'8','D':'D','H':'H','L':'L','ï¼°':'P', + 'ï¼´':'T','X':'X','d':'d','h':'h','l':'l','ï½':'p','ï½”':'t','x':'x','3':'3','ï¼—':'7','ï¼£':'C','ï¼§':'G','K':'K','O':'O', + 'ï¼³':'S','ï¼·':'W','c':'c','g':'g','k':'k','ï½':'o','s':'s','ï½—':'w','ẳ':'a','Â':'a','â':'a','Ấ':'a','ấ':'a','Ầ':'a','ầ':'a' + }; + + if (window.getComputedStyle === undefined) { + window.getComputedStyle = (function () { + function getPixelSize(element, style, property, fontSize) { + var sizeWithSuffix = style[property], + size = parseFloat(sizeWithSuffix), + suffix = sizeWithSuffix.split(/\d/)[0], + rootSize; + + fontSize = fontSize !== null ? fontSize : /%|em/.test(suffix) && element.parentElement ? getPixelSize(element.parentElement, element.parentElement.currentStyle, 'fontSize', null) : 16; + rootSize = property === 'fontSize' ? fontSize : /width/i.test(property) ? element.clientWidth : element.clientHeight; + + return (suffix === 'em') ? size * fontSize : (suffix === 'in') ? size * 96 : (suffix === 'pt') ? size * 96 / 72 : (suffix === '%') ? size / 100 * rootSize : size; + } + + function setShortStyleProperty(style, property) { + var borderSuffix = property === 'border' ? 'Width' : '', + t = property + 'Top' + borderSuffix, + r = property + 'Right' + borderSuffix, + b = property + 'Bottom' + borderSuffix, + l = property + 'Left' + borderSuffix; + + style[property] = (style[t] === style[r] === style[b] === style[l] ? [style[t]] + : style[t] === style[b] && style[l] === style[r] ? [style[t], style[r]] + : style[l] === style[r] ? [style[t], style[r], style[b]] + : [style[t], style[r], style[b], style[l]]).join(' '); + } + + function CSSStyleDeclaration(element) { + var currentStyle = element.currentStyle, + style = this, + property, + fontSize = getPixelSize(element, currentStyle, 'fontSize', null); + + for (property in currentStyle) { + if (Object.prototype.hasOwnProperty.call(currentStyle, property)) { + if (/width|height|margin.|padding.|border.+W/.test(property) && style[property] !== 'auto') { + style[property] = getPixelSize(element, currentStyle, property, fontSize) + 'px'; + } else if (property === 'styleFloat') { + style.float = currentStyle[property]; + } else { + style[property] = currentStyle[property]; + } + } + } + + setShortStyleProperty(style, 'margin'); + setShortStyleProperty(style, 'padding'); + setShortStyleProperty(style, 'border'); + + style.fontSize = fontSize + 'px'; + + return style; + } + + CSSStyleDeclaration.prototype = { + constructor: CSSStyleDeclaration, + getPropertyPriority: function () {}, + getPropertyValue: function (prop) { + return this[prop] || ''; + }, + item: function () {}, + removeProperty: function () {}, + setProperty: function () {}, + getPropertyCSSValue: function () {} + }; + + function getComputedStyle(element) { + return new CSSStyleDeclaration(element); + } + + return getComputedStyle; + }(this)); + } + + + $(document) + .on('keydown.xdsoftctrl', function (e) { + if (e.keyCode === CTRLKEY) { + ctrlDown = true; + } + if (e.keyCode === SHIFTKEY) { + ctrlDown = true; + } + }) + .on('keyup.xdsoftctrl', function (e) { + if (e.keyCode === CTRLKEY) { + ctrlDown = false; + } + if (e.keyCode === SHIFTKEY) { + ctrlDown = false; + } + }); + + function accentReplace (s) { + if (!s) { return ''; } + var ret = '',i; + for (i=0; i < s.length; i+=1) { + ret += accent_map[s.charAt(i)] || s.charAt(i); + } + return ret; + } + + function escapeRegExp (str) { + return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); + } + + function getCaretPosition(input) { + if (!input) { + return; + } + if (input.selectionStart) { + return input.selectionStart; + } + if (document.selection) { + input.focus(); + var sel = document.selection.createRange(), + selLen = document.selection.createRange().text.length; + sel.moveStart('character', -input.value.length); + return sel.text.length - selLen; + } + } + + function setCaretPosition(input, pos) { + if (input.setSelectionRange) { + input.focus(); + input.setSelectionRange(pos, pos); + } else if (input.createTextRange) { + var range = input.createTextRange(); + range.collapse(true); + range.moveEnd('character', pos); + range.moveStart('character', pos); + range.select(); + } + } + + function isset(value) { + return value !== undefined; + } + + function safe_call(callback, args, callback2, defaultValue) { + if (isset(callback) && !$.isArray(callback)) { + return $.isFunction(callback) ? callback.apply(this,args):defaultValue; + } + if(isset(callback2)) { + return safe_call.call(this,callback2,args); + } + return defaultValue; + }; + + function __safe( callbackName,source,args,defaultValue ){ + var undefinedVar; + return safe_call.call( this, (isset(this.source[source])&& + Object.prototype.hasOwnProperty.call(this.source[source], callbackName)) ? this.source[source][callbackName] : undefinedVar, args, function(){ + return safe_call.call(this, + isset(this[callbackName][source])? + this[callbackName][source]:( + isset(this[callbackName][0])? + this[callbackName][0]:( + Object.prototype.hasOwnProperty.call(this, callbackName)? + this[callbackName]: + undefinedVar + ) + ), + args, + defaultSetting[callbackName][source]||defaultSetting[callbackName][0]||defaultSetting[callbackName], + defaultValue + ); + },defaultValue); + }; + + function __get( property,source ){ + if(!isset(source)) + source = 0; + + if( $.isArray(this.source) && isset(this.source[source]) && isset(this.source[source][property])) + return this.source[source][property]; + + if( isset(this[property]) ){ + if( $.isArray(this[property]) ){ + if( isset(this[property][source]) ) + return this[property][source]; + if( isset(this[property][0]) ) + return this[property][0]; + return null; + } + return this[property]; + } + + return null; + }; + + function loadRemote( url,sourceObject,done,debug ){ + if (sourceObject.xhr) { + sourceObject.xhr.abort(); + } + sourceObject.xhr = $.ajax($.extend(true,{ + url : url, + type : 'GET' , + async:true, + cache :false, + dataType : 'json' + },sourceObject.ajax)) + + .done(function( data ){ + done&&done.apply(this,$.makeArray(arguments)); + }) + + .fail(function( jqXHR, textStatus ){ + if( debug ) + console.log("Request failed: " + textStatus); + }); + } + + + function findRight( data,query ){ + var right = false,source; + + for (source = 0;source < data.length;source += 1) { + if( right = __safe.call(this,"findRight",source,[data[source],query,source]) ){ + return {right:right,source:source}; + } + } + + return false; + } + + function processData( data,query ){ + var source; + preparseData + .call( this,data,query ); + + for (source = 0;source < data.length;source += 1) { + data[source] = __safe.call(this, + 'filter', + source, + [data[source], query, source], + data[source] + ); + } + }; + + + function collectData( query,datasource,callback ){ + var options = this,source; + + if( $.isFunction(options.source) ){ + options.source.apply(options,[query,function(items){ + datasource = [items]; + safe_call.call(options,callback,[query]); + },datasource,0]); + }else{ + for (source = 0;source < options.source.length;source += 1) { + if ($.isArray(options.source[source])) { + datasource[source] = options.source[source]; + } else if ($.isFunction(options.source[source])) { + (function (source) { + options.source[source].apply(options,[query, function(items){ + if (!datasource[source]) { + datasource[source] = []; + } + + if (items && $.isArray(items)) { + switch (options.appendMethod) { + case 'replace': + datasource[source] = items; + break; + default: + datasource[source] = datasource[source].concat(items); + } + } + + safe_call.call(options,callback,[query]); + }, datasource,source]); + }(source)); + } else { + switch (options.source[source].type) { + case 'remote': + if (isset(options.source[source].url)) { + if (!isset(options.source[source].minLength) || query.length >= options.source[source].minLength){ + var url = __safe.call(options,'replace',source,[options.source[source].url,query],''); + if (!datasource[source]) { + datasource[source] = []; + } + (function (source) { + loadRemote(url,options.source[source], function(resp){ + datasource[source] = resp; + safe_call.call(options,callback,[query]); + },options.debug); + }(source)); + } + } + break; + default: + if( isset(options.source[source]['data']) ){ + datasource[source] = options.source[source]['data']; + }else{ + datasource[source] = options.source[source]; + } + } + } + } + } + safe_call.call(options,callback,[query]); + }; + + function preparseData( data,query ){ + for( var source=0;source=this.limit ) + break; + + $div = $(__safe.call(this, + 'render',source, + [data[source][i],source,i,query], + '' + )); + + $div.data('source',source); + $div.data('pid',i); + $div.data('item',data[source][i]); + + $divs.push($div); + } + } + + return $divs; + }; + + function getItem( $div,dataset ){ + if( isset($div.data('source')) && + isset($div.data('pid')) && + isset(dataset[$div.data('source')]) && + isset(dataset[$div.data('source')][$div.data('pid')]) + ){ + return dataset[$div.data('source')][$div.data('pid')]; + } + return false; + }; + + function getValue( $div,dataset ){ + var item = getItem($div,dataset); + + if( item ){ + return __safe.call(this, + 'getValue',$div.data('source'), + [item,$div.data('source')] + ); + }else{ + if( isset($div.data('value')) ){ + return decodeURIComponent($div.data('value')); + }else{ + return $div.html(); + } + } + }; + + defaultSetting = { + minLength: 0, + valueKey: 'value', + titleKey: 'title', + highlight: true, + + showHint: true, + + dropdownWidth: '100%', + dropdownStyle: {}, + itemStyle: {}, + hintStyle: false, + style: false, + + debug: true, + openOnFocus: false, + closeOnBlur: true, + + autoselect: false, + + accents: true, + replaceAccentsForRemote: true, + + limit: 20, + visibleLimit: 20, + visibleHeight: 0, + defaultHeightItem: 30, + + timeoutUpdate: 10, + + get: function (property, source) { + return __get.call(this,property,source); + }, + + replace: [ + function (url, query) { + if (this.replaceAccentsForRemote) { + query = accentReplace(query); + } + return url.replace('%QUERY%',encodeURIComponent(query)); + } + ], + + equal:function( value,query ){ + return query.toLowerCase()==value.substr(0,query.length).toLowerCase(); + }, + + findRight:[ + function(items,query,source){ + var results = [],value = '',i; + if (items) { + for (i = 0;i < items.length;i += 1) { + value = __safe.call(this,'getValue',source,[items[i],source]); + if (__safe.call(this, 'equal', source, [value,query,source], false)) { + return items[i]; + } + } + } + return false; + } + ], + + valid:[ + function (value, query) { + if (this.accents) { + value = accentReplace(value); + query = accentReplace(query); + } + return value.toLowerCase().indexOf(query.toLowerCase())!=-1; + + } + ], + + filter:[ + function (items, query, source) { + var results = [], value = '',i; + if (items) { + for (i = 0;i < items.length;i += 1) { + value = isset(items[i][this.get('valueKey', source)]) ? items[i][this.get('valueKey', source)] : items[i].toString(); + if (__safe.call(this, 'valid', source, [value, query])) { + results.push(items[i]); + } + } + } + return results; + } + ], + + preparse:function(items){ + return items; + }, + + getValue: [ + function (item, source) { + return isset(item[this.get('valueKey',source)])?item[this.get('valueKey',source)]:item.toString(); + } + ], + + getTitle: [ + function (item, source) { + return isset(item[this.get('titleKey',source)])?item[this.get('titleKey',source)]:item.toString(); + } + ], + + render: [ + function (item, source, pid, query) { + var value = __safe.call(this, "getValue", source, [item, source], defaultSetting.getValue[0].call(this, item, source)), + title = __safe.call(this, "getTitle", source, [item, source], defaultSetting.getTitle[0].call(this, item, source)), + _value = '', + _query = '', + _title = '', + hilite_hints = '', + highlighted = '', + c, h, i, + spos = 0; + + if (this.highlight) { + if (!this.accents) { + title = title.replace(new RegExp('('+escapeRegExp(query)+')','i'),'$1'); + }else{ + _title = accentReplace(title).toLowerCase().replace(/[<>]+/g, ''), + _query = accentReplace(query).toLowerCase().replace(/[<>]+/g, ''); + + hilite_hints = _title.replace(new RegExp(escapeRegExp(_query), 'g'), '<'+_query+'>'); + for (i=0;i < hilite_hints.length;i += 1) { + c = title.charAt(spos); + h = hilite_hints.charAt(i); + if (h === '<') { + highlighted += ''; + } else if (h === '>') { + highlighted += ''; + } else { + spos += 1; + highlighted += c; + } + } + title = highlighted; + } + } + + return '
    ' + +title+ + '
    '; + } + ], + appendMethod: 'concat', // supported merge and replace + source:[], + afterSelected: function() { + } + }; + function init( that,options ){ + if( $(that).hasClass('xdsoft_input') ) + return; + + var $box = $('
    '), + $dropdown = $('
    '), + $hint = $(''), + $input = $(that), + timer1 = 0, + intervalForVisibility, + dataset = [], + iOpen = false, + value = '', + currentValue = '', + currentSelect = '', + active = null, + pos = 0; + + //it can be used to access settings + $input.data('autocomplete_options', options); + + $dropdown + .on('mousedown', function(e) { + e.preventDefault(); + e.stopPropagation(); + }) + .on('updatescroll.xdsoft', function() { + var _act = $dropdown.find('.active'); + if (!_act.length) { + return; + } + + var top = _act.position().top, + actHght = _act.outerHeight(true), + scrlTop = $dropdown.scrollTop(), + hght = $dropdown.height(); + + if (top <0) { + $dropdown.scrollTop(scrlTop-Math.abs(top)); + } else if (top+actHght>hght) { + $dropdown.scrollTop(scrlTop+top+actHght-hght); + } + }); + + $box + .css({ + 'display':$input.css('display'), + 'width':$input.css('width') + }); + + if( options.style ) + $box.css(options.style); + + $input + .addClass('xdsoft_input') + .attr('autocomplete','off'); + + var xDown = null; + var yDown = null; + var isSwipe = false; + $dropdown + .on('mousemove','div',function(){ + if( $(this).hasClass('active') ) + return true; + $dropdown.find('div').removeClass('active'); + $(this).addClass('active'); + }) + .on('mousedown','div',function(e){ + $dropdown.find('div').removeClass('active'); + $(this).addClass('active'); + $input.trigger('pick.xdsoft'); + }) + .on('touchstart','div',function(e){ + xDown = e.originalEvent.touches[0].clientX; + yDown = e.originalEvent.touches[0].clientY; + }) + .on('touchend','div',function(e){ + if(isSwipe === false) { + $dropdown.find('div').removeClass('active'); + $(this).addClass('active'); + $input.trigger('pick.xdsoft'); + } + + isSwipe = false; + }) + .on('touchmove','div',function(e){ + if ( ! xDown || ! yDown ) { + return; + } + + var xUp = e.originalEvent.touches[0].clientX; + var yUp = e.originalEvent.touches[0].clientY; + + var xDiff = xDown - xUp; + var yDiff = yDown - yUp; + + if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) { + if ( xDiff > 0 ) { + isSwipe = 'left'; + } else { + isSwipe = 'right'; + } + } else { + if ( yDiff > 0 ) { + isSwipe = 'top'; + } else { + isSwipe = 'bottm'; + } + } + + xDown = null; + yDown = null; + }); + + function manageData(){ + if ($input.val()!=currentValue){ + currentValue = $input.val(); + } else { + return; + } + if (currentValue.length < options.minLength) { + $input.trigger('close.xdsoft'); + return; + } + collectData.call(options,currentValue,dataset,function( query ){ + if (query != currentValue) { + return; + } + var right; + processData.call(options, dataset,query); + + $input.trigger('updateContent.xdsoft'); + + if (options.showHint && currentValue.length && currentValue.length<=$input.prop('size') && (right = findRight.call(options,dataset,currentValue))) { + var title = __safe.call(options,'getTitle',right.source,[right.right,right.source]); + title = query + title.substr(query.length); + $hint.val(title); + } else { + $hint.val(''); + } + }); + + return; + } + + function manageKey (event) { + var key = event.keyCode, right; + + switch( key ){ + case AKEY: case CKEY: case VKEY: case ZKEY: case YKEY: + if (event.shiftKey || event.ctrlKey) { + return true; + } + break; + case SHIFTKEY: + case CTRLKEY: + return true; + break; + case ARROWRIGHT: + case ARROWLEFT: + if (ctrlDown || shiftDown || event.shiftKey || event.ctrlKey) { + return true; + } + value = $input.val(); + pos = getCaretPosition($input[0]); + if (key === ARROWRIGHT && pos === value.length) { + if (right = findRight.call(options, dataset, value)){ + $input.trigger('pick.xdsoft', [ + __safe.call(options, + 'getValue', right.source, + [right.right, right.source] + ) + ]); + } else { + $input.trigger('pick.xdsoft'); + } + event.preventDefault(); + return false; + } + return true; + case TAB: + return true; + case ENTER: + if (iOpen) { + if (options.autoselect) { + $input.trigger('pick.xdsoft'); + } else if (!options.autoselect && active) { + $input.trigger('pick.xdsoft'); + } else { + $input.trigger('close.xdsoft'); + return true; + } + event.preventDefault(); + return false; + } else { + return true; + } + break; + case ESC: + $input + .val(currentValue) + .trigger('close.xdsoft'); + event.preventDefault(); + return false; + case ARROWDOWN: + case ARROWUP: + if (!iOpen) { + $input.trigger('open.xdsoft'); + $input.trigger('updateContent.xdsoft'); + event.preventDefault(); + return false; + } + + active = $dropdown.find('div.active'); + + var next = key==ARROWDOWN?'next':'prev', timepick = true; + + if( active.length ){ + active.removeClass('active'); + if( active[next]().length ){ + active[next]().addClass('active'); + }else{ + $input.val(currentValue); + timepick = false; + } + }else{ + $dropdown.children().eq(key==ARROWDOWN?0:-1).addClass('active'); + } + + if( timepick ){ + $input.trigger('timepick.xdsoft'); + } + + $dropdown + .trigger('updatescroll.xdsoft'); + + event.preventDefault(); + return false; + } + return; + } + + $input + .data('xdsoft_autocomplete',dataset) + .after($box) + .on('pick.xdsoft', function( event,_value ){ + + $input.trigger('timepick.xdsoft',_value); + + currentSelect = currentValue = $input.val(); + + $input.trigger('close.xdsoft'); + + //currentInput = false; + + active = $dropdown.find('div.active').eq(0); + + if( !active.length ) + active = $dropdown.children().first(); + + $input.trigger('selected.xdsoft',[getItem(active,dataset)]); + + if (options.afterSelected) + options.afterSelected(); + }) + .on('timepick.xdsoft', function( event,_value ){ + active = $dropdown.find('div.active'); + + if( !active.length ) + active = $dropdown.children().first(); + + if( active.length ){ + if( !isset(_value) ){ + $input.val(getValue.call(options,active,dataset)); + }else{ + $input.val(_value); + } + $input.trigger('autocompleted.xdsoft',[getItem(active,dataset)]); + $hint.val(''); + setCaretPosition($input[0],$input.val().length); + } + }) + .on('keydown.xdsoft input.xdsoft cut.xdsoft paste.xdsoft', function( event ){ + var ret = manageKey(event); + + if (ret === false || ret === true) { + return ret; + } + + setTimeout(function(){ + manageData(); + },1); + + manageData(); + }) + .on('change.xdsoft', function( event ){ + currentValue = $input.val(); + }); + + currentValue = $input.val(); + + collectData.call(options, $input.val(),dataset,function( query ){ + processData.call(options,dataset,query); + }); + + if( options.openOnFocus ){ + $input.on('focusin.xdsoft',function(){ + $input.trigger('open.xdsoft'); + $input.trigger('updateContent.xdsoft'); + }); + } + + if( options.closeOnBlur ) + $input.on('focusout.xdsoft',function(){ + $input.trigger('close.xdsoft'); + }); + + $box + .append($input) + .append($dropdown); + + + var olderBackground = false, + timerUpdate = 0; + + $input + .on('updateHelperPosition.xdsoft',function(){ + clearTimeout(timerUpdate); + timerUpdate = setTimeout(function(){ + $box.css({ + 'display':$input.css('display'), + 'width':$input.css('width') + }); + $dropdown.css($.extend(true,{ + left:$input.position().left, + top:$input.position().top + parseInt($input.css('marginTop'))+parseInt($input[0].offsetHeight), + marginLeft:$input.css('marginLeft'), + marginRight:$input.css('marginRight'), + width:options.dropdownWidth=='100%'?$input[0].offsetWidth:options.dropdownWidth + },options.dropdownStyle)); + + if (options.showHint) { + var style = getComputedStyle($input[0], ""); + + $hint[0].style.cssText = style.cssText; + + $hint.css({ + 'box-sizing':style.boxSizing, + borderStyle:'solid', + borderCollapse:style.borderCollapse, + borderLeftWidth:style.borderLeftWidth, + borderRightWidth:style.borderRightWidth, + borderTopWidth:style.borderTopWidth, + borderBottomWidth:style.borderBottomWidth, + paddingBottom:style.paddingBottom, + marginBottom:style.marginBottom, + paddingTop:style.paddingTop, + marginTop:style.marginTop, + paddingLeft:style.paddingLeft, + marginLeft:style.marginLeft, + paddingRight:style.paddingRight, + marginRight:style.marginRight, + maxHeight:style.maxHeight, + minHeight:style.minHeight, + maxWidth:style.maxWidth, + minWidth:style.minWidth, + width:style.width, + letterSpacing:style.letterSpacing, + lineHeight:style.lineHeight, + outlineWidth:style.outlineWidth, + fontFamily:style.fontFamily, + fontVariant:style.fontVariant, + fontStyle:$input.css('fontStyle'), + fontSize:$input.css('fontSize'), + fontWeight:$input.css('fontWeight'), + flex:style.flex, + justifyContent:style.justifyContent, + borderRadius:style.borderRadius, + '-webkit-box-shadow':'none', + 'box-shadow':'none' + }); + + $input.css('font-size',$input.css('fontSize'))// fix bug with em font size + + $hint.innerHeight($input.innerHeight()); + + $hint.css($.extend(true,{ + position:'absolute', + zIndex:'1', + borderColor:'transparent', + outlineColor:'transparent', + left:$input.position().left, + top:$input.position().top, + background:$input.css('background') + },options.hintStyle)); + +// This code is not needed because we are already setting $hint in upper line +// if( olderBackground !== false ){ +// $hint.css('background',olderBackground); +// } else { +// olderBackground = $input.css('background'); +// } + + try{ + $input[0].style.setProperty('background', 'transparent', 'important'); + } catch(e) { + $input.css('background','transparent') + } + + $box + .append($hint); + } + }, options.timeoutUpdate||1); + }); + + if ($input.is(':visible')) { + $input + .trigger('updateHelperPosition.xdsoft'); + } else { + intervalForVisibility = setInterval(function () { + if ($input.is(':visible')) { + $input + .trigger('updateHelperPosition.xdsoft'); + clearInterval(intervalForVisibility); + } + },100); + } + + $(window).on('resize',function () { + $box.css({ + 'width':'auto' + }); + $input + .trigger('updateHelperPosition.xdsoft'); + }) + + $input + .on('close.xdsoft',function(){ + if (!iOpen) { + return; + } + + $dropdown + .hide(); + + $hint + .val(''); + + if (!options.autoselect) { + $input.val(currentValue); + } + + iOpen = false; + + //currentInput = false; + }) + + .on('updateContent.xdsoft',function(){ + var out = renderData.call(options,dataset,$input.val()), + hght = 10; + + if (out.length) { + $input.trigger('open.xdsoft'); + } else { + $input.trigger('close.xdsoft'); + return; + } + + $(out).each(function(){ + this.css($.extend(true,{ + paddingLeft:$input.css('paddingLeft'), + paddingRight:$input.css('paddingRight') + },options.itemStyle)); + }); + + $dropdown + .html(out); + + if (options.visibleHeight){ + hght = options.visibleHeight; + } else { + hght = options.visibleLimit * ((out[0] ? out[0].outerHeight(true) : 0) || options.defaultHeightItem) + 5; + } + + $dropdown + .css('maxHeight', hght+'px') + }) + + .on('open.xdsoft',function(){ + if( iOpen ) + return; + + $dropdown + .show(); + + iOpen = true; + + //currentInput = $input; + }) + .on('destroy.xdsoft',function(){ + $input.removeClass('xdsoft'); + $box.after($input); + $box.remove(); + clearTimeout(timer1); + clearTimeout(intervalForVisibility); + //currentInput = false; + $input.data('xdsoft_autocomplete',null); + $input + .off('.xdsoft') + }); + }; + + publics = { + destroy: function () { + return this.trigger('destroy.xdsoft'); + }, + update: function () { + return this.trigger('updateHelperPosition.xdsoft'); + }, + options: function (_options) { + if (this.data('autocomplete_options') && $.isPlainObject(_options)) { + this.data('autocomplete_options', $.extend(true, this.data('autocomplete_options'), _options)); + } + return this; + }, + setSource: function (_newsource, id) { + if(this.data('autocomplete_options') && ($.isPlainObject(_newsource) || $.isFunction(_newsource) || $.isArray(_newsource))) { + var options = this.data('autocomplete_options'), + dataset = this.data('xdsoft_autocomplete'), + source = options.source; + if (id!==undefined && !isNaN(id)) { + if ($.isPlainObject(_newsource) || $.isArray(_newsource)) { + source[id] = $.extend(true,$.isArray(_newsource) ? [] : {}, _newsource); + } else { + source[id] = _newsource; + } + } else { + if ($.isFunction(_newsource)) { + this.data('autocomplete_options').source = _newsource; + } else { + $.extend(true, source, _newsource); + } + } + + collectData.call(options, this.val(), dataset,function( query ){ + processData.call(options,dataset,query); + }); + } + return this; + }, + getSource: function (id) { + if (this.data('autocomplete_options')) { + var source = this.data('autocomplete_options').source; + if (id!==undefined && !isNaN(id) &&source[id]) { + return source[id]; + } else { + return source; + } + } + return null; + } + }; + + $.fn.autocomplete = function(_options, _second, _third){ + if ($.type(_options) === 'string' && publics[_options]) { + return publics[_options].call(this, _second, _third); + } + return this.each(function () { + var options = $.extend(true, {}, defaultSetting, _options); + init(this, options); + }); + }; +}(jQuery)); + +//# sourceMappingURL=jquery.autocomplete.js.map diff --git a/hesk/js/jquery.scrollbar.min.js b/hesk/js/jquery.scrollbar.min.js new file mode 100644 index 0000000..dec6477 --- /dev/null +++ b/hesk/js/jquery.scrollbar.min.js @@ -0,0 +1,17 @@ +/** + * jQuery CSS Customizable Scrollbar + * + * Copyright 2015, Yuriy Khabarov + * Dual licensed under the MIT or GPL Version 2 licenses. + * + * If you found bug, please contact me via email <13real008@gmail.com> + * + * Compressed by http://jscompress.com/ + * + * @author Yuriy Khabarov aka Gromo + * @version 0.2.11 + * @url https://github.com/gromo/jquery.scrollbar/ + * + */ +!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],b):b("undefined"!=typeof exports?require("jquery"):a.jQuery)}(this,function(a){"use strict";function h(b){if(c.webkit&&!b)return{height:0,width:0};if(!c.data.outer){var d={border:"none","box-sizing":"content-box",height:"200px",margin:"0",padding:"0",width:"200px"};c.data.inner=a("
    ").css(a.extend({},d)),c.data.outer=a("
    ").css(a.extend({left:"-1000px",overflow:"scroll",position:"absolute",top:"-1000px"},d)).append(c.data.inner).appendTo("body")}return c.data.outer.scrollLeft(1e3).scrollTop(1e3),{height:Math.ceil(c.data.outer.offset().top-c.data.inner.offset().top||0),width:Math.ceil(c.data.outer.offset().left-c.data.inner.offset().left||0)}}function i(){var a=h(!0);return!(a.height||a.width)}function j(a){var b=a.originalEvent;return(!b.axis||b.axis!==b.HORIZONTAL_AXIS)&&!b.wheelDeltaX}var b=!1,c={data:{index:0,name:"scrollbar"},firefox:/firefox/i.test(navigator.userAgent),macosx:/mac/i.test(navigator.platform),msedge:/edge\/\d+/i.test(navigator.userAgent),msie:/(msie|trident)/i.test(navigator.userAgent),mobile:/android|webos|iphone|ipad|ipod|blackberry/i.test(navigator.userAgent),overlay:null,scroll:null,scrolls:[],webkit:/webkit/i.test(navigator.userAgent)&&!/edge\/\d+/i.test(navigator.userAgent)};c.scrolls.add=function(a){this.remove(a).push(a)},c.scrolls.remove=function(b){for(;a.inArray(b,this)>=0;)this.splice(a.inArray(b,this),1);return this};var d={autoScrollSize:!0,autoUpdate:!0,debug:!1,disableBodyScroll:!1,duration:200,ignoreMobile:!1,ignoreOverlay:!1,isRtl:!1,scrollStep:30,showArrows:!1,stepScrolling:!0,scrollx:null,scrolly:null,onDestroy:null,onFallback:null,onInit:null,onScroll:null,onUpdate:null},e=function(b){c.scroll||(c.overlay=i(),c.scroll=h(),g(),a(window).resize(function(){var a=!1;if(c.scroll&&(c.scroll.height||c.scroll.width)){var b=h();b.height===c.scroll.height&&b.width===c.scroll.width||(c.scroll=b,a=!0)}g(a)})),this.container=b,this.namespace=".scrollbar_"+c.data.index++,this.options=a.extend({},d,window.jQueryScrollbarOptions||{}),this.scrollTo=null,this.scrollx={},this.scrolly={},b.data(c.data.name,this),c.scrolls.add(this)};e.prototype={destroy:function(){if(this.wrapper){this.container.removeData(c.data.name),c.scrolls.remove(this);var b=this.container.scrollLeft(),d=this.container.scrollTop();this.container.insertBefore(this.wrapper).css({height:"",margin:"","max-height":""}).removeClass("scroll-content scroll-scrollx_visible scroll-scrolly_visible").off(this.namespace).scrollLeft(b).scrollTop(d),this.scrollx.scroll.removeClass("scroll-scrollx_visible").find("div").addBack().off(this.namespace),this.scrolly.scroll.removeClass("scroll-scrolly_visible").find("div").addBack().off(this.namespace),this.wrapper.remove(),a(document).add("body").off(this.namespace),a.isFunction(this.options.onDestroy)&&this.options.onDestroy.apply(this,[this.container])}},init:function(b){var d=this,e=this.container,f=this.containerWrapper||e,g=this.namespace,h=a.extend(this.options,b||{}),i={x:this.scrollx,y:this.scrolly},k=this.wrapper,l={},m={scrollLeft:e.scrollLeft(),scrollTop:e.scrollTop()};if(c.mobile&&h.ignoreMobile||c.overlay&&h.ignoreOverlay||c.macosx&&!c.webkit)return a.isFunction(h.onFallback)&&h.onFallback.apply(this,[e]),!1;if(k)l={height:"auto","margin-bottom":c.scroll.height*-1+"px","max-height":""},l[h.isRtl?"margin-left":"margin-right"]=c.scroll.width*-1+"px",f.css(l);else{if(this.wrapper=k=a("
    ").addClass("scroll-wrapper").addClass(e.attr("class")).css("position","absolute"===e.css("position")?"absolute":"relative").insertBefore(e).append(e),h.isRtl&&k.addClass("scroll--rtl"),e.is("textarea")&&(this.containerWrapper=f=a("
    ").insertBefore(e).append(e),k.addClass("scroll-textarea")),l={height:"auto","margin-bottom":c.scroll.height*-1+"px","max-height":""},l[h.isRtl?"margin-left":"margin-right"]=c.scroll.width*-1+"px",f.addClass("scroll-content").css(l),e.on("scroll"+g,function(b){var f=e.scrollLeft(),g=e.scrollTop();if(h.isRtl)switch(!0){case c.firefox:f=Math.abs(f);case c.msedge||c.msie:f=e[0].scrollWidth-e[0].clientWidth-f}a.isFunction(h.onScroll)&&h.onScroll.call(d,{maxScroll:i.y.maxScrollOffset,scroll:g,size:i.y.size,visible:i.y.visible},{maxScroll:i.x.maxScrollOffset,scroll:f,size:i.x.size,visible:i.x.visible}),i.x.isVisible&&i.x.scroll.bar.css("left",f*i.x.kx+"px"),i.y.isVisible&&i.y.scroll.bar.css("top",g*i.y.kx+"px")}),k.on("scroll"+g,function(){k.scrollTop(0).scrollLeft(0)}),h.disableBodyScroll){var n=function(a){j(a)?i.y.isVisible&&i.y.mousewheel(a):i.x.isVisible&&i.x.mousewheel(a)};k.on("MozMousePixelScroll"+g,n),k.on("mousewheel"+g,n),c.mobile&&k.on("touchstart"+g,function(b){var c=b.originalEvent.touches&&b.originalEvent.touches[0]||b,d={pageX:c.pageX,pageY:c.pageY},f={left:e.scrollLeft(),top:e.scrollTop()};a(document).on("touchmove"+g,function(a){var b=a.originalEvent.targetTouches&&a.originalEvent.targetTouches[0]||a;e.scrollLeft(f.left+d.pageX-b.pageX),e.scrollTop(f.top+d.pageY-b.pageY),a.preventDefault()}),a(document).on("touchend"+g,function(){a(document).off(g)})})}a.isFunction(h.onInit)&&h.onInit.apply(this,[e])}a.each(i,function(b,f){var k=null,l=1,m="x"===b?"scrollLeft":"scrollTop",n=h.scrollStep,o=function(){var a=e[m]();e[m](a+n),1==l&&a+n>=p&&(a=e[m]()),l==-1&&a+n<=p&&(a=e[m]()),e[m]()==a&&k&&k()},p=0;f.scroll||(f.scroll=d._getScroll(h["scroll"+b]).addClass("scroll-"+b),h.showArrows&&f.scroll.addClass("scroll-element_arrows_visible"),f.mousewheel=function(a){if(!f.isVisible||"x"===b&&j(a))return!0;if("y"===b&&!j(a))return i.x.mousewheel(a),!0;var c=a.originalEvent.wheelDelta*-1||a.originalEvent.detail,g=f.size-f.visible-f.offset;return c||("x"===b&&a.originalEvent.deltaX?c=40*a.originalEvent.deltaX:"y"===b&&a.originalEvent.deltaY&&(c=40*a.originalEvent.deltaY)),(c>0&&p0)&&(p+=c,p<0&&(p=0),p>g&&(p=g),d.scrollTo=d.scrollTo||{},d.scrollTo[m]=p,setTimeout(function(){d.scrollTo&&(e.stop().animate(d.scrollTo,240,"linear",function(){p=e[m]()}),d.scrollTo=null)},1)),a.preventDefault(),!1},f.scroll.on("MozMousePixelScroll"+g,f.mousewheel).on("mousewheel"+g,f.mousewheel).on("mouseenter"+g,function(){p=e[m]()}),f.scroll.find(".scroll-arrow, .scroll-element_track").on("mousedown"+g,function(g){if(1!=g.which)return!0;l=1;var i={eventOffset:g["x"===b?"pageX":"pageY"],maxScrollValue:f.size-f.visible-f.offset,scrollbarOffset:f.scroll.bar.offset()["x"===b?"left":"top"],scrollbarSize:f.scroll.bar["x"===b?"outerWidth":"outerHeight"]()},j=0,q=0;if(a(this).hasClass("scroll-arrow")){if(l=a(this).hasClass("scroll-arrow_more")?1:-1,n=h.scrollStep*l,p=l>0?i.maxScrollValue:0,h.isRtl)switch(!0){case c.firefox:p=l>0?0:i.maxScrollValue*-1;break;case c.msie||c.msedge:}}else l=i.eventOffset>i.scrollbarOffset+i.scrollbarSize?1:i.eventOffset','
    ','
    ','
    ','
    ','
    ','
    ','
    ','
    ',"
    ","
    ",'
    ','
    ','
    ',"
    ",'
    ','
    ',"
    ","
    ","
    "].join(""),simple:['
    ','
    ','
    ','
    ','
    ',"
    ","
    "].join("")};return c[b]&&(b=c[b]),b||(b=c.simple),b="string"==typeof b?a(b).appendTo(this.wrapper):a(b),a.extend(b,{bar:b.find(".scroll-bar"),size:b.find(".scroll-element_size"),track:b.find(".scroll-element_track")}),b},_handleMouseDown:function(b,c){var d=this.namespace;return a(document).on("blur"+d,function(){a(document).add("body").off(d),b&&b()}),a(document).on("dragstart"+d,function(a){return a.preventDefault(),!1}),a(document).on("mouseup"+d,function(){a(document).add("body").off(d),b&&b()}),a("body").on("selectstart"+d,function(a){return a.preventDefault(),!1}),c&&c.preventDefault(),!1},_updateScroll:function(b,d){var e=this.container,f=this.containerWrapper||e,g="scroll-scroll"+b+"_visible",h="x"===b?this.scrolly:this.scrollx,i=parseInt(this.container.css("x"===b?"left":"top"),10)||0,j=this.wrapper,k=d.size,l=d.visible+i;d.isVisible=k-l>1,d.isVisible?(d.scroll.addClass(g),h.scroll.addClass(g),f.addClass(g)):(d.scroll.removeClass(g),h.scroll.removeClass(g),f.removeClass(g)),"y"===b&&(e.is("textarea")||k10?(window.console&&console.log("Scroll updates exceed 10"),g=function(){}):(clearTimeout(a),a=setTimeout(g,300))}}();window.angular&&!function(a){a.module("jQueryScrollbar",[]).provider("jQueryScrollbar",function(){var b=d;return{setOptions:function(c){a.extend(b,c)},$get:function(){return{options:a.copy(b)}}}}).directive("jqueryScrollbar",["jQueryScrollbar","$parse",function(a,b){return{restrict:"AC",link:function(c,d,e){var f=b(e.jqueryScrollbar),g=f(c);d.scrollbar(g||a.options).on("$destroy",function(){d.scrollbar("destroy")})}}}])}(window.angular)}); +//# sourceMappingURL=jquery.scrollbar.min.js.map diff --git a/hesk/js/selectize.js b/hesk/js/selectize.js new file mode 100644 index 0000000..b63fb7c --- /dev/null +++ b/hesk/js/selectize.js @@ -0,0 +1,3892 @@ +/** + * sifter.js + * Copyright (c) 2013 Brian Reavis & contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this + * file except in compliance with the License. You may obtain a copy of the License at: + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF + * ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + * + * @author Brian Reavis + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + define('sifter', factory); + } else if (typeof exports === 'object') { + module.exports = factory(); + } else { + root.Sifter = factory(); + } +}(this, function() { + + /** + * Textually searches arrays and hashes of objects + * by property (or multiple properties). Designed + * specifically for autocomplete. + * + * @constructor + * @param {array|object} items + * @param {object} items + */ + var Sifter = function(items, settings) { + this.items = items; + this.settings = settings || {diacritics: true}; + }; + + /** + * Splits a search string into an array of individual + * regexps to be used to match results. + * + * @param {string} query + * @returns {array} + */ + Sifter.prototype.tokenize = function(query) { + query = trim(String(query || '').toLowerCase()); + if (!query || !query.length) return []; + + var i, n, regex, letter; + var tokens = []; + var words = query.split(/ +/); + + for (i = 0, n = words.length; i < n; i++) { + regex = escape_regex(words[i]); + if (this.settings.diacritics) { + for (letter in DIACRITICS) { + if (DIACRITICS.hasOwnProperty(letter)) { + regex = regex.replace(new RegExp(letter, 'g'), DIACRITICS[letter]); + } + } + } + tokens.push({ + string : words[i], + regex : new RegExp(regex, 'i') + }); + } + + return tokens; + }; + + /** + * Iterates over arrays and hashes. + * + * ``` + * this.iterator(this.items, function(item, id) { + * // invoked for each item + * }); + * ``` + * + * @param {array|object} object + */ + Sifter.prototype.iterator = function(object, callback) { + var iterator; + if (is_array(object)) { + iterator = Array.prototype.forEach || function(callback) { + for (var i = 0, n = this.length; i < n; i++) { + callback(this[i], i, this); + } + }; + } else { + iterator = function(callback) { + for (var key in this) { + if (this.hasOwnProperty(key)) { + callback(this[key], key, this); + } + } + }; + } + + iterator.apply(object, [callback]); + }; + + /** + * Returns a function to be used to score individual results. + * + * Good matches will have a higher score than poor matches. + * If an item is not a match, 0 will be returned by the function. + * + * @param {object|string} search + * @param {object} options (optional) + * @returns {function} + */ + Sifter.prototype.getScoreFunction = function(search, options) { + var self, fields, tokens, token_count, nesting; + + self = this; + search = self.prepareSearch(search, options); + tokens = search.tokens; + fields = search.options.fields; + token_count = tokens.length; + nesting = search.options.nesting; + + /** + * Calculates how close of a match the + * given value is against a search token. + * + * @param {mixed} value + * @param {object} token + * @return {number} + */ + var scoreValue = function(value, token) { + var score, pos; + + if (!value) return 0; + value = String(value || ''); + pos = value.search(token.regex); + if (pos === -1) return 0; + score = token.string.length / value.length; + if (pos === 0) score += 0.5; + return score; + }; + + /** + * Calculates the score of an object + * against the search query. + * + * @param {object} token + * @param {object} data + * @return {number} + */ + var scoreObject = (function() { + var field_count = fields.length; + if (!field_count) { + return function() { return 0; }; + } + if (field_count === 1) { + return function(token, data) { + return scoreValue(getattr(data, fields[0], nesting), token); + }; + } + return function(token, data) { + for (var i = 0, sum = 0; i < field_count; i++) { + sum += scoreValue(getattr(data, fields[i], nesting), token); + } + return sum / field_count; + }; + })(); + + if (!token_count) { + return function() { return 0; }; + } + if (token_count === 1) { + return function(data) { + return scoreObject(tokens[0], data); + }; + } + + if (search.options.conjunction === 'and') { + return function(data) { + var score; + for (var i = 0, sum = 0; i < token_count; i++) { + score = scoreObject(tokens[i], data); + if (score <= 0) return 0; + sum += score; + } + return sum / token_count; + }; + } else { + return function(data) { + for (var i = 0, sum = 0; i < token_count; i++) { + sum += scoreObject(tokens[i], data); + } + return sum / token_count; + }; + } + }; + + /** + * Returns a function that can be used to compare two + * results, for sorting purposes. If no sorting should + * be performed, `null` will be returned. + * + * @param {string|object} search + * @param {object} options + * @return function(a,b) + */ + Sifter.prototype.getSortFunction = function(search, options) { + var i, n, self, field, fields, fields_count, multiplier, multipliers, get_field, implicit_score, sort; + + self = this; + search = self.prepareSearch(search, options); + sort = (!search.query && options.sort_empty) || options.sort; + + /** + * Fetches the specified sort field value + * from a search result item. + * + * @param {string} name + * @param {object} result + * @return {mixed} + */ + get_field = function(name, result) { + if (name === '$score') return result.score; + return getattr(self.items[result.id], name, options.nesting); + }; + + // parse options + fields = []; + if (sort) { + for (i = 0, n = sort.length; i < n; i++) { + if (search.query || sort[i].field !== '$score') { + fields.push(sort[i]); + } + } + } + + // the "$score" field is implied to be the primary + // sort field, unless it's manually specified + if (search.query) { + implicit_score = true; + for (i = 0, n = fields.length; i < n; i++) { + if (fields[i].field === '$score') { + implicit_score = false; + break; + } + } + if (implicit_score) { + fields.unshift({field: '$score', direction: 'desc'}); + } + } else { + for (i = 0, n = fields.length; i < n; i++) { + if (fields[i].field === '$score') { + fields.splice(i, 1); + break; + } + } + } + + multipliers = []; + for (i = 0, n = fields.length; i < n; i++) { + multipliers.push(fields[i].direction === 'desc' ? -1 : 1); + } + + // build function + fields_count = fields.length; + if (!fields_count) { + return null; + } else if (fields_count === 1) { + field = fields[0].field; + multiplier = multipliers[0]; + return function(a, b) { + return multiplier * cmp( + get_field(field, a), + get_field(field, b) + ); + }; + } else { + return function(a, b) { + var i, result, a_value, b_value, field; + for (i = 0; i < fields_count; i++) { + field = fields[i].field; + result = multipliers[i] * cmp( + get_field(field, a), + get_field(field, b) + ); + if (result) return result; + } + return 0; + }; + } + }; + + /** + * Parses a search query and returns an object + * with tokens and fields ready to be populated + * with results. + * + * @param {string} query + * @param {object} options + * @returns {object} + */ + Sifter.prototype.prepareSearch = function(query, options) { + if (typeof query === 'object') return query; + + options = extend({}, options); + + var option_fields = options.fields; + var option_sort = options.sort; + var option_sort_empty = options.sort_empty; + + if (option_fields && !is_array(option_fields)) options.fields = [option_fields]; + if (option_sort && !is_array(option_sort)) options.sort = [option_sort]; + if (option_sort_empty && !is_array(option_sort_empty)) options.sort_empty = [option_sort_empty]; + + return { + options : options, + query : String(query || '').toLowerCase(), + tokens : this.tokenize(query), + total : 0, + items : [] + }; + }; + + /** + * Searches through all items and returns a sorted array of matches. + * + * The `options` parameter can contain: + * + * - fields {string|array} + * - sort {array} + * - score {function} + * - filter {bool} + * - limit {integer} + * + * Returns an object containing: + * + * - options {object} + * - query {string} + * - tokens {array} + * - total {int} + * - items {array} + * + * @param {string} query + * @param {object} options + * @returns {object} + */ + Sifter.prototype.search = function(query, options) { + var self = this, value, score, search, calculateScore; + var fn_sort; + var fn_score; + + search = this.prepareSearch(query, options); + options = search.options; + query = search.query; + + // generate result scoring function + fn_score = options.score || self.getScoreFunction(search); + + // perform search and sort + if (query.length) { + self.iterator(self.items, function(item, id) { + score = fn_score(item); + if (options.filter === false || score > 0) { + search.items.push({'score': score, 'id': id}); + } + }); + } else { + self.iterator(self.items, function(item, id) { + search.items.push({'score': 1, 'id': id}); + }); + } + + fn_sort = self.getSortFunction(search, options); + if (fn_sort) search.items.sort(fn_sort); + + // apply limits + search.total = search.items.length; + if (typeof options.limit === 'number') { + search.items = search.items.slice(0, options.limit); + } + + return search; + }; + + // utilities + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + var cmp = function(a, b) { + if (typeof a === 'number' && typeof b === 'number') { + return a > b ? 1 : (a < b ? -1 : 0); + } + a = asciifold(String(a || '')); + b = asciifold(String(b || '')); + if (a > b) return 1; + if (b > a) return -1; + return 0; + }; + + var extend = function(a, b) { + var i, n, k, object; + for (i = 1, n = arguments.length; i < n; i++) { + object = arguments[i]; + if (!object) continue; + for (k in object) { + if (object.hasOwnProperty(k)) { + a[k] = object[k]; + } + } + } + return a; + }; + + /** + * A property getter resolving dot-notation + * @param {Object} obj The root object to fetch property on + * @param {String} name The optionally dotted property name to fetch + * @param {Boolean} nesting Handle nesting or not + * @return {Object} The resolved property value + */ + var getattr = function(obj, name, nesting) { + if (!obj || !name) return; + if (!nesting) return obj[name]; + var names = name.split("."); + while(names.length && (obj = obj[names.shift()])); + return obj; + }; + + var trim = function(str) { + return (str + '').replace(/^\s+|\s+$|/g, ''); + }; + + var escape_regex = function(str) { + return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); + }; + + var is_array = Array.isArray || (typeof $ !== 'undefined' && $.isArray) || function(object) { + return Object.prototype.toString.call(object) === '[object Array]'; + }; + + var DIACRITICS = { + 'a': '[aḀá¸Ä‚ăÂâÇǎȺⱥȦȧẠạÄäÀàÃáĀÄÃãÅåąĄÃąĄ]', + 'b': '[bâ¢Î²Î’B฿ðŒá›’]', + 'c': '[cĆćĈĉČÄÄŠÄ‹CÌ„c̄ÇçḈḉȻȼƇƈɕᴄCc]', + 'd': '[dÄŽÄḊḋá¸á¸‘Ḍá¸á¸’ḓḎá¸ÄÄ‘D̦d̦ƉɖƊɗƋƌᵭá¶á¶‘ȡᴅDdð]', + 'e': '[eÉéÈèÊêḘḙĚěĔĕẼẽḚḛẺẻĖėËëĒēȨȩĘęᶒɆɇȄȅẾếỀá»á»„ễỂểḜá¸á¸–á¸—á¸”á¸•È†È‡áº¸áº¹á»†á»‡â±¸á´‡ï¼¥ï½…É˜ÇÆÆÎµ]', + 'f': '[fƑƒḞḟ]', + 'g': '[gɢ₲ǤǥĜÄĞğĢģƓɠĠġ]', + 'h': '[hĤĥĦħḨḩẖẖḤḥḢḣɦʰǶƕ]', + 'i': '[iÃíÌìĬĭÎîÇÇÃïḮḯĨĩĮįĪīỈỉȈȉȊȋỊịḬḭƗɨɨ̆ᵻᶖİiIıɪIi]', + 'j': '[jȷĴĵɈɉÊɟʲ]', + 'k': '[kƘƙê€êḰḱǨǩḲḳḴḵκϰ₭]', + 'l': '[lÅłĽľĻļĹĺḶḷḸḹḼḽḺḻĿŀȽƚⱠⱡⱢɫɬᶅɭȴʟLl]', + 'n': '[nŃńǸǹŇňÑñṄṅŅņṆṇṊṋṈṉN̈n̈ÆÉ²È Æžáµ°á¶‡É³ÈµÉ´ï¼®ï½ŽÅŠÅ‹]', + 'o': '[oØøÖöÓóÒòÔôǑǒÅőŎÅÈ®È¯á»Œá»ÆŸÉµÆ Æ¡á»Žá»ÅŒÅÕõǪǫȌÈÕ•Ö…]', + 'p': '[pṔṕṖṗⱣᵽƤƥᵱ]', + 'q': '[qê–ê—Ê ÉŠÉ‹ê˜ê™q̃]', + 'r': '[rŔŕɌÉŘřŖŗṘṙÈȑȒȓṚṛⱤɽ]', + 's': '[sŚśṠṡṢṣꞨꞩŜÅŠšŞşȘșS̈s̈]', + 't': '[tŤťṪṫŢţṬṭƮʈȚțṰṱṮṯƬƭ]', + 'u': '[uŬŭɄʉỤụÜüÚúÙùÛûǓǔŰűŬŭƯưỦủŪūŨũŲųȔȕ∪]', + 'v': '[vṼṽṾṿƲʋêžêŸâ±±Ê‹]', + 'w': '[wẂẃẀáºÅ´Åµáº„ẅẆẇẈẉ]', + 'x': '[xẌáºáºŠáº‹Ï‡]', + 'y': '[yÃýỲỳŶŷŸÿỸỹẎáºá»´á»µÉŽÉƳƴ]', + 'z': '[zŹźáºáº‘ŽžŻżẒẓẔẕƵƶ]' + }; + + var asciifold = (function() { + var i, n, k, chunk; + var foreignletters = ''; + var lookup = {}; + for (k in DIACRITICS) { + if (DIACRITICS.hasOwnProperty(k)) { + chunk = DIACRITICS[k].substring(2, DIACRITICS[k].length - 1); + foreignletters += chunk; + for (i = 0, n = chunk.length; i < n; i++) { + lookup[chunk.charAt(i)] = k; + } + } + } + var regexp = new RegExp('[' + foreignletters + ']', 'g'); + return function(str) { + return str.replace(regexp, function(foreignletter) { + return lookup[foreignletter]; + }).toLowerCase(); + }; + })(); + + + // export + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + return Sifter; +})); + + + +/** + * microplugin.js + * Copyright (c) 2013 Brian Reavis & contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this + * file except in compliance with the License. You may obtain a copy of the License at: + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF + * ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + * + * @author Brian Reavis + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + define('microplugin', factory); + } else if (typeof exports === 'object') { + module.exports = factory(); + } else { + root.MicroPlugin = factory(); + } +}(this, function() { + var MicroPlugin = {}; + + MicroPlugin.mixin = function(Interface) { + Interface.plugins = {}; + + /** + * Initializes the listed plugins (with options). + * Acceptable formats: + * + * List (without options): + * ['a', 'b', 'c'] + * + * List (with options): + * [{'name': 'a', options: {}}, {'name': 'b', options: {}}] + * + * Hash (with options): + * {'a': { ... }, 'b': { ... }, 'c': { ... }} + * + * @param {mixed} plugins + */ + Interface.prototype.initializePlugins = function(plugins) { + var i, n, key; + var self = this; + var queue = []; + + self.plugins = { + names : [], + settings : {}, + requested : {}, + loaded : {} + }; + + if (utils.isArray(plugins)) { + for (i = 0, n = plugins.length; i < n; i++) { + if (typeof plugins[i] === 'string') { + queue.push(plugins[i]); + } else { + self.plugins.settings[plugins[i].name] = plugins[i].options; + queue.push(plugins[i].name); + } + } + } else if (plugins) { + for (key in plugins) { + if (plugins.hasOwnProperty(key)) { + self.plugins.settings[key] = plugins[key]; + queue.push(key); + } + } + } + + while (queue.length) { + self.require(queue.shift()); + } + }; + + Interface.prototype.loadPlugin = function(name) { + var self = this; + var plugins = self.plugins; + var plugin = Interface.plugins[name]; + + if (!Interface.plugins.hasOwnProperty(name)) { + throw new Error('Unable to find "' + name + '" plugin'); + } + + plugins.requested[name] = true; + plugins.loaded[name] = plugin.fn.apply(self, [self.plugins.settings[name] || {}]); + plugins.names.push(name); + }; + + /** + * Initializes a plugin. + * + * @param {string} name + */ + Interface.prototype.require = function(name) { + var self = this; + var plugins = self.plugins; + + if (!self.plugins.loaded.hasOwnProperty(name)) { + if (plugins.requested[name]) { + throw new Error('Plugin has circular dependency ("' + name + '")'); + } + self.loadPlugin(name); + } + + return plugins.loaded[name]; + }; + + /** + * Registers a plugin. + * + * @param {string} name + * @param {function} fn + */ + Interface.define = function(name, fn) { + Interface.plugins[name] = { + 'name' : name, + 'fn' : fn + }; + }; + }; + + var utils = { + isArray: Array.isArray || function(vArg) { + return Object.prototype.toString.call(vArg) === '[object Array]'; + } + }; + + return MicroPlugin; +})); + +/** + * selectize.js (v0.12.6) + * Copyright (c) 2013–2015 Brian Reavis & contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this + * file except in compliance with the License. You may obtain a copy of the License at: + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF + * ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + * + * @author Brian Reavis + */ + +/*jshint curly:false */ +/*jshint browser:true */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + define('selectize', ['jquery','sifter','microplugin'], factory); + } else if (typeof exports === 'object') { + module.exports = factory(require('jquery'), require('sifter'), require('microplugin')); + } else { + root.Selectize = factory(root.jQuery, root.Sifter, root.MicroPlugin); + } +}(this, function($, Sifter, MicroPlugin) { + 'use strict'; + + var highlight = function($element, pattern) { + if (typeof pattern === 'string' && !pattern.length) return; + var regex = (typeof pattern === 'string') ? new RegExp(pattern, 'i') : pattern; + + var highlight = function(node) { + var skip = 0; + // Wrap matching part of text node with highlighting , e.g. + // Soccer -> Soccer for regex = /soc/i + if (node.nodeType === 3) { + var pos = node.data.search(regex); + if (pos >= 0 && node.data.length > 0) { + var match = node.data.match(regex); + var spannode = document.createElement('span'); + spannode.className = 'highlight'; + var middlebit = node.splitText(pos); + var endbit = middlebit.splitText(match[0].length); + var middleclone = middlebit.cloneNode(true); + spannode.appendChild(middleclone); + middlebit.parentNode.replaceChild(spannode, middlebit); + skip = 1; + } + } + // Recurse element node, looking for child text nodes to highlight, unless element + // is childless, + + + + + + + + + + + diff --git a/hesk/theme/hesk3/customer/create-ticket/create-ticket-confirmation.php b/hesk/theme/hesk3/customer/create-ticket/create-ticket-confirmation.php new file mode 100644 index 0000000..750ea28 --- /dev/null +++ b/hesk/theme/hesk3/customer/create-ticket/create-ticket-confirmation.php @@ -0,0 +1,137 @@ + + + + + + + <?php echo $hesk_settings['hesk_title']; ?> + + + + + + + + + + + + + +
    +
    +
    +
    +
    + + +
    +
    + + $value): ?> + + +
    +
    + +
    +
    +
    + +
    +
    +
    +
    +

    +

    + : +

    +

    + + + +

    +
    +
    +
    +
    + +
    +
    + + + + + + + + + + + + diff --git a/hesk/theme/hesk3/customer/create-ticket/create-ticket.php b/hesk/theme/hesk3/customer/create-ticket/create-ticket.php new file mode 100644 index 0000000..4992f9e --- /dev/null +++ b/hesk/theme/hesk3/customer/create-ticket/create-ticket.php @@ -0,0 +1,443 @@ + + + + + + + <?php echo $hesk_settings['tmp_title']; ?> + + + + + + + + + + + + + + +
    +
    +
    +
    +
    + + +
    +
    + + $value): ?> + + +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +

    +
    + + + +
    + +

    +
    + + +
    +
    +
    +
    + + +
    +
    + + + required> +
    +
    + +
    + + required> +
    + +
    + +
    + + +
    + 0): + ?> +
    + +
    + +
    + + required> +
    + +
    + + + + + +
    + 0): ?> +
    + +
    +
    + +
    +
    +
    '; + } + ?> +
    + +
    +
    +
    + +
    +

    + + +
    + + + +
    + +
    + +
    + + <?php echo $hesklang['sec_img']; ?> + + + + + + + + +
    + +
    +
    + +
    +
    + : +
      +
    • .
    • +
    • .
    • +
    +
    + : +
      +
    • +
    • +
    +
    +
    + + + + + +
    + +
    +
    +
    + +
    + +
    + + + + + + + + + +'; + echo ''; +} +?> + + + + + + + diff --git a/hesk/theme/hesk3/customer/css/app.css b/hesk/theme/hesk3/customer/css/app.css new file mode 100644 index 0000000..2f80bdd --- /dev/null +++ b/hesk/theme/hesk3/customer/css/app.css @@ -0,0 +1,2192 @@ +@charset "UTF-8"; +a, abbr, acronym, address, applet, article, aside, audio, b, big, blockquote, body, canvas, caption, center, cite, code, dd, del, details, dfn, div, dl, dt, em, embed, fieldset, figcaption, figure, footer, form, h1, h2, h3, h4, h5, h6, header, hgroup, html, i, iframe, img, ins, kbd, label, legend, li, mark, menu, nav, object, ol, output, p, pre, q, ruby, s, samp, section, small, span, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, time, tr, tt, u, ul, var, video { margin: 0; padding: 0; border: 0; font-size: 100%; vertical-align: baseline; } + +/* HTML5 display-role reset for older browsers */ +article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } + +body { line-height: 1; } + +ol, ul { list-style: none; } + +blockquote, q { quotes: none; } + +blockquote:after, blockquote:before { content: ''; content: none; } + +q:after, q:before { content: ''; content: none; } + +table { border-collapse: collapse; border-spacing: 0; } + +a { text-decoration: none; color: #26282a; transition: color 250ms ease; } + +a:hover { text-decoration: none; } + +.footer a, .notification a { text-decoration: underline ! important; color: #1776ea; } + +.footer a:hover, .notification a:hover { text-decoration: none ! important;} + +.icon-01-normal-knowledge-b { width: 1.2em; height: 1em; fill: none; } + +.icon-01-normal-team { width: 1.41em; height: 1em; fill: #FFF; } + +.icon-01-normal-tickets { width: 0.82em; height: 1em; fill: #FFF; } + +.icon-actions { width: 1.23em; height: 1em; fill: #1776EA; } + +.icon-add { width: 1em; height: 1em; fill: #1776EA; } + +.icon-anonymize { width: 0.88em; height: 1em; fill: #C5CAD4; } + +.icon-assign-no { width: 0.96em; height: 1em; fill: #26282A; } + +.icon-assign-plus { width: 1em; height: 1em; fill: #26282A; } + +.icon-assign { width: 0.86em; height: 1em; fill: #26282A; } + +.icon-attach { width: 1em; height: 1em; fill: #C5CAD4; } + +.icon-back { width: 3.33em; height: 1em; fill: #26282A; } + +.icon-calendar { width: 1em; height: 1em; fill: #1776EA; } + +.icon-categories { width: 1em; height: 1em; fill: #FFF; } + +.icon-chevron-down { width: 1.33em; height: 1em; fill: #26282A; } + +.icon-chevron-left { width: 1em; height: 1em; fill: initial; } + +.icon-chevron-right { width: 1em; height: 1em; fill: initial; } + +.icon-close-mobile { width: 1em; height: 1em; fill: #FFF; } + +.icon-close { width: 1em; height: 1em; fill: #C5CAD4; } + +.icon-cross { width: 1em; height: 1em; fill: #C5CAD4; } + +.icon-delete { width: 0.94em; height: 1em; fill: #C5CAD4; } + +.icon-dismiss { width: 1em; height: 1em; fill: #1776EA; } + +.icon-document { width: 0.83em; height: 1em; fill: #959EB0; } + +.icon-down { width: 1.33em; height: 1em; fill: #26282A; } + +.icon-edit-ticket { width: 1em; height: 1em; fill: #C5CAD4; } + +.icon-edit { width: 1em; height: 1em; fill: #1776EA; } + +.icon-export { width: 1em; height: 1em; fill: #C5CAD4; } + +.icon-eye-close { width: 1.33em; height: 1em; fill: #C5CAD4; } + +.icon-eye-open { width: 1em; height: 1em; fill: #C5CAD4; } + +.icon-filters { width: 1em; height: 1em; fill: #1776EA; } + +.icon-folder { width: 1.22em; height: 1em; fill: #959EB0; } + +.icon-info { width: 1em; height: 1em; fill: #959EB0; } + +.icon-inquiries { width: 1em; height: 1em; fill: #959EB0; } + +.icon-knowledge { width: 1.2em; height: 1em; fill: #FFF; } + +.icon-label { width: 1.33em; height: 1em; fill: #959EB0; } + +.icon-lock { width: 0.88em; height: 1em; fill: #C5CAD4; } + +.icon-log-out { width: 1em; height: 1em; fill: #959EB0; } + +.icon-mail-small { width: 1.14em; height: 1em; fill: #C5CAD4; } + +.icon-mail { width: 1.22em; height: 1em; fill: #C5CAD4; } + +.icon-menu-mobile { width: 1.14em; height: 1em; fill: #FFF; } + +.icon-menu { width: 1.43em; height: 1em; fill: #FFF; } + +.icon-merge { width: 1em; height: 1em; fill: #26282A; } + +.icon-move-to { width: 1em; height: 1em; fill: #26282A; } + +.icon-no-photo { width: 0.68em; height: 1em; fill: #FFF; } + +.icon-note { width: 1em; height: 1em; fill: #C5CAD4; } + +.icon-notes-2 { width: 1em; height: 1em; fill: none; } + +.icon-notification { width: 0.91em; height: 1em; fill: #C5CAD4; } + +.icon-pause { width: 1em; height: 1em; fill: #959EB0; } + +.icon-pin { width: 0.63em; height: 1em; fill: #959EB0; } + +.icon-print { width: 1em; height: 1em; fill: #C5CAD4; } + +.icon-priority { width: 1em; height: 1em; fill: #26282A; } + +.icon-refresh { width: 1em; height: 1em; fill: #C5CAD4; } + +.icon-reports { width: 1.22em; height: 1em; fill: #FFF; } + +.icon-search-type-knowledge { width: 1.2em; height: 1em; fill: #FFF; } + +.icon-search-type-team { width: 1.41em; height: 1em; fill: #FFF; } + +.icon-search-type-templates { width: 1em; height: 1em; fill: #FFF; } + +.icon-search-type-tickets { width: 0.82em; height: 1em; fill: #FFF; } + +.icon-search { width: 1em; height: 1em; fill: #C5CAD4; } + +.icon-select { width: 0.5em; height: 1em; fill: #959EB0; } + +.icon-settings { width: 1em; height: 1em; fill: #FFF; } + +.icon-star-filled { width: 5.6em; height: 1em; fill: #EEB707; } + +.icon-star-stroke { width: 5.6em; height: 1em; fill: #DFE4EC; } + +.icon-status { width: 0.88em; height: 1em; fill: #26282A; } + +.icon-submit-ticket { width: 0.83em; height: 1em; fill: #959EB0; } + +.icon-support { width: 1em; height: 1em; fill: #959EB0; } + +.icon-tag { width: 1.33em; height: 1em; fill: #C5CAD4; } + +.icon-team { width: 1.41em; height: 1em; fill: #FFF; } + +.icon-templates { width: 1em; height: 1em; fill: #FFF; } + +.icon-tick { width: 1.38em; height: 1em; fill: #002D73; } + +.icon-tickets { width: 0.82em; height: 1em; fill: #FFF; } + +.icon-tools { width: 1em; height: 1em; fill: #FFF; } + +.icon-warning { width: 1em; height: 1em; fill: initial; } + +/*************** SCROLLBAR BASE CSS ***************/ +.scroll-wrapper { overflow: hidden !important; padding: 0 !important; position: relative; } + +.scroll-wrapper > .scroll-content { border: none !important; box-sizing: content-box !important; height: auto; left: 0; margin: 0; max-height: none; max-width: none !important; overflow: scroll !important; padding: 0; position: relative !important; top: 0; width: auto !important; } + +.scroll-wrapper > .scroll-content::-webkit-scrollbar { height: 0; width: 0; } + +.scroll-wrapper.scroll--rtl { direction: rtl; } + +.scroll-element { box-sizing: content-box; display: none; } + +.scroll-element div { box-sizing: content-box; } + +.scroll-element .scroll-bar, .scroll-element .scroll-arrow { cursor: default; } + +.scroll-element.scroll-x.scroll-scrollx_visible, .scroll-element.scroll-y.scroll-scrolly_visible { display: block; } + +.scroll-textarea > .scroll-content { overflow: hidden !important; } + +.scroll-textarea > .scroll-content > textarea { border: none !important; box-sizing: border-box; height: 100% !important; margin: 0; max-height: none !important; max-width: none !important; overflow: scroll !important; outline: none; padding: 2px; position: relative !important; top: 0; width: 100% !important; } + +.scroll-textarea > .scroll-content > textarea::-webkit-scrollbar { height: 0; width: 0; } + +/*************** SIMPLE INNER SCROLLBAR ***************/ +.scrollbar-inner > .scroll-element, .scrollbar-inner > .scroll-element div { border: none; margin: 0; padding: 0; position: absolute; z-index: 10; } + +.scrollbar-inner > .scroll-element div { display: block; height: 100%; left: 0; top: 0; width: 100%; } + +.scrollbar-inner > .scroll-element.scroll-x { bottom: 2px; height: 8px; left: 0; width: 100%; } + +.scrollbar-inner > .scroll-element.scroll-y { height: 100%; right: 2px; top: 0; width: 8px; } + +.scrollbar-inner > .scroll-element .scroll-element_outer { overflow: hidden; } + +.scrollbar-inner > .scroll-element .scroll-element_outer, .scrollbar-inner > .scroll-element .scroll-element_track, .scrollbar-inner > .scroll-element .scroll-bar { border-radius: 8px; } + +.scrollbar-inner > .scroll-element .scroll-element_track, .scrollbar-inner > .scroll-element .scroll-bar { -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=40)"; filter: alpha(opacity=40); opacity: 0.4; } + +.scrollbar-inner > .scroll-element .scroll-element_track { background-color: #e0e0e0; } + +.scrollbar-inner > .scroll-element .scroll-bar { background-color: #c2c2c2; } + +.scrollbar-inner > .scroll-element:hover .scroll-bar { background-color: #919191; } + +.scrollbar-inner > .scroll-element.scroll-draggable .scroll-bar { background-color: #919191; } + +/* update scrollbar offset if both scrolls are visible */ +.scrollbar-inner > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_track { left: -12px; } + +.scrollbar-inner > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_track { top: -12px; } + +.scrollbar-inner > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_size { left: -12px; } + +.scrollbar-inner > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_size { top: -12px; } + +/*************** SIMPLE OUTER SCROLLBAR ***************/ +.scrollbar-outer > .scroll-element, .scrollbar-outer > .scroll-element div { border: none; margin: 0; padding: 0; position: absolute; z-index: 10; } + +.scrollbar-outer > .scroll-element { background-color: #ffffff; } + +.scrollbar-outer > .scroll-element div { display: block; height: 100%; left: 0; top: 0; width: 100%; } + +.scrollbar-outer > .scroll-element.scroll-x { bottom: 0; height: 12px; left: 0; width: 100%; } + +.scrollbar-outer > .scroll-element.scroll-y { height: 100%; right: 0; top: 0; width: 4px; } + +.scroll-element.scroll-x .scroll-element_outer { height: 8px; top: 2px; } + +.scroll-element.scroll-y .scroll-element_outer { left: 0px; width: 4px; } + +.scroll-element .scroll-element_outer { overflow: hidden; } + +.scroll-element .scroll-element_track { background-color: transparent; } + +.scroll-element .scroll-element_outer, .scroll-element .scroll-element_track, .scroll-element .scroll-bar { border-radius: 0px; } + +.scroll-element .scroll-bar { background-color: #dfe4ec; } + +.scroll-element .scroll-bar:hover { background-color: #dfe4ec; } + +.scroll-element.scroll-draggable .scroll-bar { background-color: #dfe4ec; } + +/* scrollbar height/width & offset from container borders */ +.scrollbar-outer > .scroll-content.scroll-scrolly_visible { left: -12px; margin-left: 12px; } + +.scrollbar-outer > .scroll-content.scroll-scrollx_visible { top: -12px; margin-top: 12px; } + +.scrollbar-outer > .scroll-element.scroll-x .scroll-bar { min-width: 10px; } + +.scrollbar-outer > .scroll-element.scroll-y .scroll-bar { min-height: 10px; } + +/* update scrollbar offset if both scrolls are visible */ +.scrollbar-outer > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_track { left: -14px; } + +.scrollbar-outer > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_track { top: -14px; } + +.scrollbar-outer > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_size { left: -14px; } + +.scrollbar-outer > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_size { top: -14px; } + +/*************** SCROLLBAR MAC OS X ***************/ +.scrollbar-macosx > .scroll-element, .scrollbar-macosx > .scroll-element div { background: none; border: none; margin: 0; padding: 0; position: absolute; z-index: 10; } + +.scrollbar-macosx > .scroll-element div { display: block; height: 100%; left: 0; top: 0; width: 100%; } + +.scrollbar-macosx > .scroll-element .scroll-element_track { display: none; } + +.scrollbar-macosx > .scroll-element .scroll-bar { background-color: #6C6E71; display: block; -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; filter: alpha(opacity=0); opacity: 0; border-radius: 7px; transition: opacity 0.2s linear; } + +.scrollbar-macosx:hover > .scroll-element .scroll-bar, .scrollbar-macosx > .scroll-element.scroll-draggable .scroll-bar { -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=70)"; filter: alpha(opacity=70); opacity: 0.7; } + +.scrollbar-macosx > .scroll-element.scroll-x { bottom: 0px; height: 0px; left: 0; min-width: 100%; overflow: visible; width: 100%; } + +.scrollbar-macosx > .scroll-element.scroll-y { height: 100%; min-height: 100%; right: 0px; top: 0; width: 0px; } + +/* scrollbar height/width & offset from container borders */ +.scrollbar-macosx > .scroll-element.scroll-x .scroll-bar { height: 7px; min-width: 10px; top: -9px; } + +.scrollbar-macosx > .scroll-element.scroll-y .scroll-bar { left: -9px; min-height: 10px; width: 7px; } + +.scrollbar-macosx > .scroll-element.scroll-x .scroll-element_outer { left: 2px; } + +.scrollbar-macosx > .scroll-element.scroll-x .scroll-element_size { left: -4px; } + +.scrollbar-macosx > .scroll-element.scroll-y .scroll-element_outer { top: 2px; } + +.scrollbar-macosx > .scroll-element.scroll-y .scroll-element_size { top: -4px; } + +/* update scrollbar offset if both scrolls are visible */ +.scrollbar-macosx > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_size { left: -11px; } + +.scrollbar-macosx > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_size { top: -11px; } + +/*************** SCROLLBAR LIGHT ***************/ +.scrollbar-light > .scroll-element, .scrollbar-light > .scroll-element div { border: none; margin: 0; overflow: hidden; padding: 0; position: absolute; z-index: 10; } + +.scrollbar-light > .scroll-element { background-color: #ffffff; } + +.scrollbar-light > .scroll-element div { display: block; height: 100%; left: 0; top: 0; width: 100%; } + +.scrollbar-light > .scroll-element .scroll-element_outer { border-radius: 10px; } + +.scrollbar-light > .scroll-element .scroll-element_size { background: #dbdbdb; background: url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIxMDAlIiB5Mj0iMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2RiZGJkYiIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiNlOGU4ZTgiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+"); background: linear-gradient(to right, #dbdbdb 0%, #e8e8e8 100%); border-radius: 10px; } + +.scrollbar-light > .scroll-element.scroll-x { bottom: 0; height: 17px; left: 0; min-width: 100%; width: 100%; } + +.scrollbar-light > .scroll-element.scroll-y { height: 100%; min-height: 100%; right: 0; top: 0; width: 17px; } + +.scrollbar-light > .scroll-element .scroll-bar { background: #fefefe; background: url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIxMDAlIiB5Mj0iMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2ZlZmVmZSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiNmNWY1ZjUiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+"); background: linear-gradient(to right, #fefefe 0%, #f5f5f5 100%); border: 1px solid #dbdbdb; border-radius: 10px; } + +/* scrollbar height/width & offset from container borders */ +.scrollbar-light > .scroll-content.scroll-scrolly_visible { left: -17px; margin-left: 17px; } + +.scrollbar-light > .scroll-content.scroll-scrollx_visible { top: -17px; margin-top: 17px; } + +.scrollbar-light > .scroll-element.scroll-x .scroll-bar { height: 10px; min-width: 10px; top: 0px; } + +.scrollbar-light > .scroll-element.scroll-y .scroll-bar { left: 0px; min-height: 10px; width: 10px; } + +.scrollbar-light > .scroll-element.scroll-x .scroll-element_outer { height: 12px; left: 2px; top: 2px; } + +.scrollbar-light > .scroll-element.scroll-x .scroll-element_size { left: -4px; } + +.scrollbar-light > .scroll-element.scroll-y .scroll-element_outer { left: 2px; top: 2px; width: 12px; } + +.scrollbar-light > .scroll-element.scroll-y .scroll-element_size { top: -4px; } + +/* update scrollbar offset if both scrolls are visible */ +.scrollbar-light > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_size { left: -19px; } + +.scrollbar-light > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_size { top: -19px; } + +.scrollbar-light > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_track { left: -19px; } + +.scrollbar-light > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_track { top: -19px; } + +/*************** SCROLLBAR RAIL ***************/ +.scrollbar-rail > .scroll-element, .scrollbar-rail > .scroll-element div { border: none; margin: 0; overflow: hidden; padding: 0; position: absolute; z-index: 10; } + +.scrollbar-rail > .scroll-element { background-color: #ffffff; } + +.scrollbar-rail > .scroll-element div { display: block; height: 100%; left: 0; top: 0; width: 100%; } + +.scrollbar-rail > .scroll-element .scroll-element_size { background-color: #999; background-color: rgba(0, 0, 0, 0.3); } + +.scrollbar-rail > .scroll-element .scroll-element_outer:hover .scroll-element_size { background-color: #666; background-color: rgba(0, 0, 0, 0.5); } + +.scrollbar-rail > .scroll-element.scroll-x { bottom: 0; height: 12px; left: 0; min-width: 100%; padding: 3px 0 2px; width: 100%; } + +.scrollbar-rail > .scroll-element.scroll-y { height: 100%; min-height: 100%; padding: 0 2px 0 3px; right: 0; top: 0; width: 12px; } + +.scrollbar-rail > .scroll-element .scroll-bar { background-color: #d0b9a0; border-radius: 2px; box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.5); } + +.scrollbar-rail > .scroll-element .scroll-element_outer:hover .scroll-bar { box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.6); } + +/* scrollbar height/width & offset from container borders */ +.scrollbar-rail > .scroll-content.scroll-scrolly_visible { left: -17px; margin-left: 17px; } + +.scrollbar-rail > .scroll-content.scroll-scrollx_visible { margin-top: 17px; top: -17px; } + +.scrollbar-rail > .scroll-element.scroll-x .scroll-bar { height: 10px; min-width: 10px; top: 1px; } + +.scrollbar-rail > .scroll-element.scroll-y .scroll-bar { left: 1px; min-height: 10px; width: 10px; } + +.scrollbar-rail > .scroll-element.scroll-x .scroll-element_outer { height: 15px; left: 5px; } + +.scrollbar-rail > .scroll-element.scroll-x .scroll-element_size { height: 2px; left: -10px; top: 5px; } + +.scrollbar-rail > .scroll-element.scroll-y .scroll-element_outer { top: 5px; width: 15px; } + +.scrollbar-rail > .scroll-element.scroll-y .scroll-element_size { left: 5px; top: -10px; width: 2px; } + +/* update scrollbar offset if both scrolls are visible */ +.scrollbar-rail > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_size { left: -25px; } + +.scrollbar-rail > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_size { top: -25px; } + +.scrollbar-rail > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_track { left: -25px; } + +.scrollbar-rail > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_track { top: -25px; } + +/*************** SCROLLBAR DYNAMIC ***************/ +.scrollbar-dynamic > .scroll-element, .scrollbar-dynamic > .scroll-element div { background: none; border: none; margin: 0; padding: 0; position: absolute; z-index: 10; } + +.scrollbar-dynamic > .scroll-element div { display: block; height: 100%; left: 0; top: 0; width: 100%; } + +.scrollbar-dynamic > .scroll-element.scroll-x { bottom: 2px; height: 7px; left: 0; min-width: 100%; width: 100%; } + +.scrollbar-dynamic > .scroll-element.scroll-y { height: 100%; min-height: 100%; right: 2px; top: 0; width: 7px; } + +.scrollbar-dynamic > .scroll-element .scroll-element_outer { opacity: 0.3; border-radius: 12px; } + +.scrollbar-dynamic > .scroll-element .scroll-element_size { background-color: #cccccc; opacity: 0; border-radius: 12px; transition: opacity 0.2s; } + +.scrollbar-dynamic > .scroll-element .scroll-bar { background-color: #6c6e71; border-radius: 7px; } + +/* scrollbar height/width & offset from container borders */ +.scrollbar-dynamic > .scroll-element.scroll-x .scroll-bar { bottom: 0; height: 7px; min-width: 24px; top: auto; } + +.scrollbar-dynamic > .scroll-element.scroll-y .scroll-bar { left: auto; min-height: 24px; right: 0; width: 7px; } + +.scrollbar-dynamic > .scroll-element.scroll-x .scroll-element_outer { bottom: 0; top: auto; left: 2px; transition: height 0.2s; } + +.scrollbar-dynamic > .scroll-element.scroll-y .scroll-element_outer { left: auto; right: 0; top: 2px; transition: width 0.2s; } + +.scrollbar-dynamic > .scroll-element.scroll-x .scroll-element_size { left: -4px; } + +.scrollbar-dynamic > .scroll-element.scroll-y .scroll-element_size { top: -4px; } + +/* update scrollbar offset if both scrolls are visible */ +.scrollbar-dynamic > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_size { left: -11px; } + +.scrollbar-dynamic > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_size { top: -11px; } + +/* hover & drag */ +.scrollbar-dynamic > .scroll-element:hover .scroll-element_outer, .scrollbar-dynamic > .scroll-element.scroll-draggable .scroll-element_outer { overflow: hidden; -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=70)"; filter: alpha(opacity=70); opacity: 0.7; } + +.scrollbar-dynamic > .scroll-element:hover .scroll-element_outer .scroll-element_size, .scrollbar-dynamic > .scroll-element.scroll-draggable .scroll-element_outer .scroll-element_size { opacity: 1; } + +.scrollbar-dynamic > .scroll-element:hover .scroll-element_outer .scroll-bar, .scrollbar-dynamic > .scroll-element.scroll-draggable .scroll-element_outer .scroll-bar { height: 100%; width: 100%; border-radius: 12px; } + +.scrollbar-dynamic > .scroll-element.scroll-x:hover .scroll-element_outer, .scrollbar-dynamic > .scroll-element.scroll-x.scroll-draggable .scroll-element_outer { height: 20px; min-height: 7px; } + +.scrollbar-dynamic > .scroll-element.scroll-y:hover .scroll-element_outer, .scrollbar-dynamic > .scroll-element.scroll-y.scroll-draggable .scroll-element_outer { min-width: 7px; width: 20px; } + +/*************** SCROLLBAR GOOGLE CHROME ***************/ +.scrollbar-chrome > .scroll-element, .scrollbar-chrome > .scroll-element div { border: none; margin: 0; overflow: hidden; padding: 0; position: absolute; z-index: 10; } + +.scrollbar-chrome > .scroll-element { background-color: #ffffff; } + +.scrollbar-chrome > .scroll-element div { display: block; height: 100%; left: 0; top: 0; width: 100%; } + +.scrollbar-chrome > .scroll-element .scroll-element_track { background: #f1f1f1; border: 1px solid #dbdbdb; } + +.scrollbar-chrome > .scroll-element.scroll-x { bottom: 0; height: 16px; left: 0; min-width: 100%; width: 100%; } + +.scrollbar-chrome > .scroll-element.scroll-y { height: 100%; min-height: 100%; right: 0; top: 0; width: 16px; } + +.scrollbar-chrome > .scroll-element .scroll-bar { background-color: #d9d9d9; border: 1px solid #bdbdbd; cursor: default; border-radius: 2px; } + +.scrollbar-chrome > .scroll-element .scroll-bar:hover { background-color: #c2c2c2; border-color: #a9a9a9; } + +.scrollbar-chrome > .scroll-element.scroll-draggable .scroll-bar { background-color: #919191; border-color: #7e7e7e; } + +/* scrollbar height/width & offset from container borders */ +.scrollbar-chrome > .scroll-content.scroll-scrolly_visible { left: -16px; margin-left: 16px; } + +.scrollbar-chrome > .scroll-content.scroll-scrollx_visible { top: -16px; margin-top: 16px; } + +.scrollbar-chrome > .scroll-element.scroll-x .scroll-bar { height: 8px; min-width: 10px; top: 3px; } + +.scrollbar-chrome > .scroll-element.scroll-y .scroll-bar { left: 3px; min-height: 10px; width: 8px; } + +.scrollbar-chrome > .scroll-element.scroll-x .scroll-element_outer { border-left: 1px solid #dbdbdb; } + +.scrollbar-chrome > .scroll-element.scroll-x .scroll-element_track { height: 14px; left: -3px; } + +.scrollbar-chrome > .scroll-element.scroll-x .scroll-element_size { height: 14px; left: -4px; } + +.scrollbar-chrome > .scroll-element.scroll-y .scroll-element_outer { border-top: 1px solid #dbdbdb; } + +.scrollbar-chrome > .scroll-element.scroll-y .scroll-element_track { top: -3px; width: 14px; } + +.scrollbar-chrome > .scroll-element.scroll-y .scroll-element_size { top: -4px; width: 14px; } + +/* update scrollbar offset if both scrolls are visible */ +.scrollbar-chrome > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_size { left: -19px; } + +.scrollbar-chrome > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_size { top: -19px; } + +.scrollbar-chrome > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_track { left: -19px; } + +.scrollbar-chrome > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_track { top: -19px; } + +/** selectize.css (v0.12.6) Copyright (c) 2013–2015 Brian Reavis & contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @author Brian Reavis */ +.selectize-control.plugin-drag_drop.multi > .selectize-input > div.ui-sortable-placeholder { visibility: visible !important; background: #f2f2f2 !important; background: rgba(0, 0, 0, 0.06) !important; border: 0 none !important; box-shadow: inset 0 0 12px 4px #fff; } + +.selectize-control.plugin-drag_drop .ui-sortable-placeholder::after { content: '!'; visibility: hidden; } + +.selectize-control.plugin-drag_drop .ui-sortable-helper { box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); } + +.selectize-dropdown-header { position: relative; padding: 5px 8px; border-bottom: 1px solid #d0d0d0; background: #f8f8f8; border-radius: 3px 3px 0 0; } + +.selectize-dropdown-header-close { position: absolute; right: 8px; top: 50%; color: #303030; opacity: 0.4; margin-top: -12px; line-height: 20px; font-size: 20px !important; } + +.selectize-dropdown-header-close:hover { color: #000000; } + +.selectize-dropdown.plugin-optgroup_columns .optgroup { border-right: 1px solid #f2f2f2; border-top: 0 none; float: left; box-sizing: border-box; } + +.selectize-dropdown.plugin-optgroup_columns .optgroup:last-child { border-right: 0 none; } + +.selectize-dropdown.plugin-optgroup_columns .optgroup:before { display: none; } + +.selectize-dropdown.plugin-optgroup_columns .optgroup-header { border-top: 0 none; } + +.selectize-control.plugin-remove_button [data-value] { position: relative; padding-right: 24px !important; } + +.selectize-control.plugin-remove_button [data-value] .remove { z-index: 1; /* fixes ie bug (see #392) */ position: absolute; top: 0; right: 0; bottom: 0; width: 17px; text-align: center; font-weight: bold; font-size: 12px; color: inherit; text-decoration: none; vertical-align: middle; display: inline-block; padding: 2px 0 0 0; border-left: 1px solid #d0d0d0; border-radius: 0 2px 2px 0; box-sizing: border-box; } + +.selectize-control.plugin-remove_button [data-value] .remove:hover { background: rgba(0, 0, 0, 0.05); } + +.selectize-control.plugin-remove_button [data-value].active .remove { border-left-color: #cacaca; } + +.selectize-control.plugin-remove_button .disabled [data-value] .remove:hover { background: none; } + +.selectize-control.plugin-remove_button .disabled [data-value] .remove { border-left-color: #ffffff; } + +.selectize-control.plugin-remove_button .remove-single { position: absolute; right: 0; top: 0; font-size: 23px; } + +.selectize-control { position: relative; } + +.selectize-dropdown, .selectize-input, .selectize-input input { color: #303030; font-family: inherit; font-size: 13px; line-height: 18px; -webkit-font-smoothing: inherit; } + +.selectize-input, .selectize-control.single .selectize-input.input-active { background: #fff; cursor: text; display: inline-block; } + +.selectize-input { border: 1px solid #d0d0d0; padding: 8px 8px; display: inline-block; width: 100%; overflow: hidden; position: relative; z-index: 1; box-sizing: border-box; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.1); border-radius: 3px; } + +.selectize-control.multi .selectize-input.has-items { /* padding: 6px 8px 3px; */ } + +.selectize-input.full { background-color: #fff; } + +.selectize-input.disabled, .selectize-input.disabled * { cursor: default !important; } + +.selectize-input.focus { box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.15); } + +.selectize-input.dropdown-active { border-radius: 3px 3px 0 0; } + +.selectize-input > * { vertical-align: baseline; display: -moz-inline-stack; display: inline-block; zoom: 1; *display: inline; } + +.selectize-control.multi .selectize-input > div { cursor: pointer; margin: 0 3px 3px 0; padding: 2px 6px; background: #f2f2f2; color: #303030; border: 0 solid #d0d0d0; } + +.selectize-control.multi .selectize-input > div.active { background: #e8e8e8; color: #303030; border: 0 solid #cacaca; } + +.selectize-control.multi .selectize-input.disabled > div, .selectize-control.multi .selectize-input.disabled > div.active { color: #7d7d7d; background: #ffffff; border: 0 solid #ffffff; } + +.selectize-input > input { display: inline-block !important; padding: 0 !important; min-height: 0 !important; max-height: none !important; max-width: 100% !important; margin: 0 2px 0 0 !important; text-indent: 0 !important; border: 0 none !important; background: none !important; line-height: inherit !important; -webkit-user-select: auto !important; box-shadow: none !important; } + +.selectize-input > input::-ms-clear { display: none; } + +.selectize-input > input:focus { outline: none !important; } + +.selectize-input::after { content: ' '; display: block; clear: left; } + +.selectize-input.dropdown-active::before { content: ' '; display: block; position: absolute; background: #f0f0f0; height: 1px; bottom: 0; left: 0; right: 0; } + +.selectize-dropdown { position: absolute; z-index: 10; border: 1px solid #d0d0d0; background: #fff; margin: -1px 0 0 0; border-top: 0 none; box-sizing: border-box; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); border-radius: 0 0 3px 3px; } + +.selectize-dropdown [data-selectable] { cursor: pointer; overflow: hidden; } + +.selectize-dropdown [data-selectable] .highlight { background: rgba(125, 168, 208, 0.2); border-radius: 1px; } + +.selectize-dropdown .option, .selectize-dropdown .optgroup-header { padding: 5px 8px; } + +.selectize-dropdown .option, .selectize-dropdown [data-disabled], .selectize-dropdown [data-disabled] [data-selectable].option { cursor: inherit; opacity: 0.5; } + +.selectize-dropdown [data-selectable].option { opacity: 1; } + +.selectize-dropdown .optgroup:first-child .optgroup-header { border-top: 0 none; } + +.selectize-dropdown .optgroup-header { color: #303030; background: #fff; cursor: default; } + +.selectize-dropdown .active { background-color: #f5fafd; color: #495c68; } + +.selectize-dropdown .active.create { color: #495c68; } + +.selectize-dropdown .create { color: rgba(48, 48, 48, 0.5); } + +.selectize-dropdown-content { overflow-y: auto; overflow-x: hidden; max-height: 200px; -webkit-overflow-scrolling: touch; } + +.selectize-control.single .selectize-input, .selectize-control.single .selectize-input input { cursor: pointer; } + +.selectize-control.single .selectize-input.input-active, .selectize-control.single .selectize-input.input-active input { cursor: text; } + +.selectize-control.single .selectize-input:after { content: ' '; display: block; position: absolute; top: 50%; right: 15px; margin-top: -3px; width: 0; height: 0; border-style: solid; border-width: 5px 5px 0 5px; border-color: #808080 transparent transparent transparent; } + +.selectize-control.single .selectize-input.dropdown-active:after { margin-top: -4px; border-width: 0 5px 5px 5px; border-color: transparent transparent #808080 transparent; } + +.selectize-control.rtl.single .selectize-input:after { left: 15px; right: auto; } + +.selectize-control.rtl .selectize-input > input { margin: 0 4px 0 -2px !important; } + +.selectize-control .selectize-input.disabled { opacity: 0.5; background-color: #fafafa; } + +.datepicker--cells { display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; } + +.datepicker--cell { border-radius: 4px; box-sizing: border-box; cursor: pointer; display: -ms-flexbox; display: flex; position: relative; -ms-flex-align: center; align-items: center; -ms-flex-pack: center; justify-content: center; height: 32px; z-index: 1; } + +.datepicker--cell.-focus- { background: #f0f0f0; } + +.datepicker--cell.-current- { color: #4EB5E6; } + +.datepicker--cell.-current-.-focus- { color: #4a4a4a; } + +.datepicker--cell.-current-.-in-range- { color: #4EB5E6; } + +.datepicker--cell.-in-range- { background: rgba(92, 196, 239, 0.1); color: #4a4a4a; border-radius: 0; } + +.datepicker--cell.-in-range-.-focus- { background-color: rgba(92, 196, 239, 0.2); } + +.datepicker--cell.-disabled- { cursor: default; color: #aeaeae; } + +.datepicker--cell.-disabled-.-focus- { color: #aeaeae; } + +.datepicker--cell.-disabled-.-in-range- { color: #a1a1a1; } + +.datepicker--cell.-disabled-.-current-.-focus- { color: #aeaeae; } + +.datepicker--cell.-range-from- { border: 1px solid rgba(92, 196, 239, 0.5); background-color: rgba(92, 196, 239, 0.1); border-radius: 4px 0 0 4px; } + +.datepicker--cell.-range-to- { border: 1px solid rgba(92, 196, 239, 0.5); background-color: rgba(92, 196, 239, 0.1); border-radius: 0 4px 4px 0; } + +.datepicker--cell.-selected-, .datepicker--cell.-selected-.-current- { color: #fff; background: #5cc4ef; } + +.datepicker--cell.-range-from-.-range-to- { border-radius: 4px; } + +.datepicker--cell.-selected- { border: none; } + +.datepicker--cell.-selected-.-focus- { background: #45bced; } + +.datepicker--cell:empty { cursor: default; } + +.datepicker--days-names { display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; margin: 8px 0 3px; } + +.datepicker--day-name { color: #FF9A19; display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; -ms-flex-pack: center; justify-content: center; -ms-flex: 1; flex: 1; text-align: center; text-transform: uppercase; font-size: .8em; } + +.-only-timepicker- .datepicker--content, .datepicker--body, .datepicker-inline .datepicker--pointer { display: none; } + +.datepicker--cell-day { width: 14.28571%; } + +.datepicker--cells-months { height: 170px; } + +.datepicker--cell-month { width: 33.33%; height: 25%; } + +.datepicker--cells-years, .datepicker--years { height: 170px; } + +.datepicker--cell-year { width: 25%; height: 33.33%; } + +.datepickers-container { position: absolute; left: 0; top: 0; } + +@media print { .datepickers-container { display: none; } } + +.datepicker { background: #fff; border: 1px solid #dbdbdb; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); border-radius: 4px; box-sizing: content-box; font-family: Tahoma,sans-serif; font-size: 14px; color: #4a4a4a; width: 250px; position: absolute; left: -100000px; opacity: 0; transition: opacity .3s ease,transform .3s ease,left 0s .3s; z-index: 100; } + +.datepicker.-from-top- { -ms-transform: translateY(-8px); transform: translateY(-8px); } + +.datepicker.-from-right- { -ms-transform: translateX(8px); transform: translateX(8px); } + +.datepicker.-from-bottom- { -ms-transform: translateY(8px); transform: translateY(8px); } + +.datepicker.-from-left- { -ms-transform: translateX(-8px); transform: translateX(-8px); } + +.datepicker.active { opacity: 1; -ms-transform: translate(0); transform: translate(0); transition: opacity .3s ease,transform .3s ease,left 0s 0s; } + +.datepicker-inline .datepicker { border-color: #d7d7d7; box-shadow: none; position: static; left: auto; right: auto; opacity: 1; -ms-transform: none; transform: none; } + +.datepicker--content { box-sizing: content-box; padding: 4px; } + +.datepicker--pointer { position: absolute; background: #fff; border-top: 1px solid #dbdbdb; border-right: 1px solid #dbdbdb; width: 10px; height: 10px; z-index: -1; } + +.datepicker--nav-action:hover, .datepicker--nav-title:hover { background: #f0f0f0; } + +.-top-center- .datepicker--pointer, .-top-left- .datepicker--pointer, .-top-right- .datepicker--pointer { top: calc(100% - 4px); -ms-transform: rotate(135deg); transform: rotate(135deg); } + +.-right-bottom- .datepicker--pointer, .-right-center- .datepicker--pointer, .-right-top- .datepicker--pointer { right: calc(100% - 4px); -ms-transform: rotate(225deg); transform: rotate(225deg); } + +.-bottom-center- .datepicker--pointer, .-bottom-left- .datepicker--pointer, .-bottom-right- .datepicker--pointer { bottom: calc(100% - 4px); -ms-transform: rotate(315deg); transform: rotate(315deg); } + +.-left-bottom- .datepicker--pointer, .-left-center- .datepicker--pointer, .-left-top- .datepicker--pointer { left: calc(100% - 4px); -ms-transform: rotate(45deg); transform: rotate(45deg); } + +.-bottom-left- .datepicker--pointer, .-top-left- .datepicker--pointer { left: 10px; } + +.-bottom-right- .datepicker--pointer, .-top-right- .datepicker--pointer { right: 10px; } + +.-bottom-center- .datepicker--pointer, .-top-center- .datepicker--pointer { left: calc(50% - 10px / 2); } + +.-left-top- .datepicker--pointer, .-right-top- .datepicker--pointer { top: 10px; } + +.-left-bottom- .datepicker--pointer, .-right-bottom- .datepicker--pointer { bottom: 10px; } + +.-left-center- .datepicker--pointer, .-right-center- .datepicker--pointer { top: calc(50% - 10px / 2); } + +.datepicker--body.active { display: block; } + +.datepicker--nav { display: -ms-flexbox; display: flex; -ms-flex-pack: justify; justify-content: space-between; border-bottom: 1px solid #efefef; min-height: 32px; padding: 4px; } + +.-only-timepicker- .datepicker--nav { display: none; } + +.datepicker--nav-action, .datepicker--nav-title { display: -ms-flexbox; display: flex; cursor: pointer; -ms-flex-align: center; align-items: center; -ms-flex-pack: center; justify-content: center; } + +.datepicker--nav-action { width: 32px; border-radius: 4px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } + +.datepicker--nav-action.-disabled- { visibility: hidden; } + +.datepicker--nav-action svg { width: 32px; height: 32px; } + +.datepicker--nav-action path { fill: none; stroke: #9c9c9c; stroke-width: 2px; } + +.datepicker--nav-title { border-radius: 4px; padding: 0 8px; } + +.datepicker--buttons, .datepicker--time { border-top: 1px solid #efefef; padding: 4px; } + +.datepicker--nav-title i { font-style: normal; color: #9c9c9c; margin-left: 5px; } + +.datepicker--nav-title.-disabled- { cursor: default; background: 0 0; } + +.datepicker--buttons { display: -ms-flexbox; display: flex; } + +.datepicker--button { color: #4EB5E6; cursor: pointer; border-radius: 4px; -ms-flex: 1; flex: 1; display: -ms-inline-flexbox; display: inline-flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; height: 32px; } + +.datepicker--button:hover { color: #4a4a4a; background: #f0f0f0; } + +.datepicker--time { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; position: relative; } + +.datepicker--time.-am-pm- .datepicker--time-sliders { -ms-flex: 0 1 138px; flex: 0 1 138px; max-width: 138px; } + +.-only-timepicker- .datepicker--time { border-top: none; } + +.datepicker--time-sliders { -ms-flex: 0 1 153px; flex: 0 1 153px; margin-right: 10px; max-width: 153px; } + +.datepicker--time-label { display: none; font-size: 12px; } + +.datepicker--time-current { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; -ms-flex: 1; flex: 1; font-size: 14px; text-align: center; margin: 0 0 0 10px; } + +.datepicker--time-current-colon { margin: 0 2px 3px; line-height: 1; } + +.datepicker--time-current-hours, .datepicker--time-current-minutes { line-height: 1; font-size: 19px; font-family: "Century Gothic",CenturyGothic,AppleGothic,sans-serif; position: relative; z-index: 1; } + +.datepicker--time-current-hours:after, .datepicker--time-current-minutes:after { content: ''; background: #f0f0f0; border-radius: 4px; position: absolute; left: -2px; top: -3px; right: -2px; bottom: -2px; z-index: -1; opacity: 0; } + +.datepicker--time-current-hours.-focus-:after, .datepicker--time-current-minutes.-focus-:after { opacity: 1; } + +.datepicker--time-current-ampm { text-transform: uppercase; -ms-flex-item-align: end; align-self: flex-end; color: #9c9c9c; margin-left: 6px; font-size: 11px; margin-bottom: 1px; } + +.datepicker--time-row { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; font-size: 11px; height: 17px; background: linear-gradient(to right, #dedede, #dedede) left 50%/100% 1px no-repeat; } + +.datepicker--time-row:first-child { margin-bottom: 4px; } + +.datepicker--time-row input[type=range] { background: 0 0; cursor: pointer; -ms-flex: 1; flex: 1; height: 100%; padding: 0; margin: 0; -webkit-appearance: none; } + +.datepicker--time-row input[type=range]::-ms-tooltip { display: none; } + +.datepicker--time-row input[type=range]:hover::-webkit-slider-thumb { border-color: #b8b8b8; } + +.datepicker--time-row input[type=range]:hover::-moz-range-thumb { border-color: #b8b8b8; } + +.datepicker--time-row input[type=range]:hover::-ms-thumb { border-color: #b8b8b8; } + +.datepicker--time-row input[type=range]:focus { outline: 0; } + +.datepicker--time-row input[type=range]:focus::-webkit-slider-thumb { background: #5cc4ef; border-color: #5cc4ef; } + +.datepicker--time-row input[type=range]:focus::-moz-range-thumb { background: #5cc4ef; border-color: #5cc4ef; } + +.datepicker--time-row input[type=range]:focus::-ms-thumb { background: #5cc4ef; border-color: #5cc4ef; } + +.datepicker--time-row input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; box-sizing: border-box; height: 12px; width: 12px; border-radius: 3px; border: 1px solid #dedede; background: #fff; cursor: pointer; transition: background .2s; margin-top: -6px; } + +.datepicker--time-row input[type=range]::-moz-range-thumb { box-sizing: border-box; height: 12px; width: 12px; border-radius: 3px; border: 1px solid #dedede; background: #fff; cursor: pointer; transition: background .2s; } + +.datepicker--time-row input[type=range]::-ms-thumb { box-sizing: border-box; height: 12px; width: 12px; border-radius: 3px; border: 1px solid #dedede; background: #fff; cursor: pointer; transition: background .2s; } + +.datepicker--time-row input[type=range]::-webkit-slider-runnable-track { border: none; height: 1px; cursor: pointer; color: transparent; background: 0 0; } + +.datepicker--time-row input[type=range]::-moz-range-track { border: none; height: 1px; cursor: pointer; color: transparent; background: 0 0; } + +.datepicker--time-row input[type=range]::-ms-track { border: none; height: 1px; cursor: pointer; color: transparent; background: 0 0; } + +.datepicker--time-row input[type=range]::-ms-fill-lower { background: 0 0; } + +.datepicker--time-row input[type=range]::-ms-fill-upper { background: 0 0; } + +.datepicker--time-row span { padding: 0 12px; } + +.datepicker--time-icon { color: #9c9c9c; border: 1px solid; border-radius: 50%; font-size: 16px; position: relative; margin: 0 5px -1px 0; width: 1em; height: 1em; } + +.datepicker--time-icon:after, .datepicker--time-icon:before { content: ''; background: currentColor; position: absolute; } + +.datepicker--time-icon:after { height: .4em; width: 1px; left: calc(50% - 1px); top: calc(50% + 1px); -ms-transform: translateY(-100%); transform: translateY(-100%); } + +.datepicker--time-icon:before { width: .4em; height: 1px; top: calc(50% + 1px); left: calc(50% - 1px); } + +.datepicker--cell-day.-other-month-, .datepicker--cell-year.-other-decade- { color: #dedede; } + +.datepicker--cell-day.-other-month-:hover, .datepicker--cell-year.-other-decade-:hover { color: #c5c5c5; } + +.-disabled-.-focus-.datepicker--cell-day.-other-month-, .-disabled-.-focus-.datepicker--cell-year.-other-decade- { color: #dedede; } + +.-selected-.datepicker--cell-day.-other-month-, .-selected-.datepicker--cell-year.-other-decade- { color: #fff; background: #a2ddf6; } + +.-selected-.-focus-.datepicker--cell-day.-other-month-, .-selected-.-focus-.datepicker--cell-year.-other-decade- { background: #8ad5f4; } + +.-in-range-.datepicker--cell-day.-other-month-, .-in-range-.datepicker--cell-year.-other-decade- { background-color: rgba(92, 196, 239, 0.1); color: #ccc; } + +.-in-range-.-focus-.datepicker--cell-day.-other-month-, .-in-range-.-focus-.datepicker--cell-year.-other-decade- { background-color: rgba(92, 196, 239, 0.2); } + +.datepicker--cell-day.-other-month-:empty, .datepicker--cell-year.-other-decade-:empty { background: 0 0; border: none; } + +.xdsoft_autocomplete, .xdsoft_autocomplete div, .xdsoft_autocomplete span { /* -moz-box-sizing: border-box !important; box-sizing: border-box !important;*/ } + +.xdsoft_autocomplete { display: inline; position: relative; word-spacing: normal; text-transform: none; text-indent: 0px; text-shadow: none; text-align: start; } + +.xdsoft_autocomplete .xdsoft_input { position: relative; z-index: 2; } + +.xdsoft_autocomplete .xdsoft_autocomplete_dropdown { position: absolute; border: 1px solid #ccc; border-top-color: #d9d9d9; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); -webkit-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); cursor: default; display: none; z-index: 1001; margin-top: -1px; background-color: #fff; min-width: 100%; overflow: auto; } + +.xdsoft_autocomplete .xdsoft_autocomplete_hint { position: absolute; z-index: 1; color: #ccc !important; -webkit-text-fill-color: #ccc !important; text-fill-color: #ccc !important; overflow: hidden !important; white-space: pre !important; } + +.xdsoft_autocomplete .xdsoft_autocomplete_hint span { color: transparent; opacity: 0.0; } + +.xdsoft_autocomplete .xdsoft_autocomplete_dropdown > .xdsoft_autocomplete_copyright { color: #ddd; font-size: 10px; text-decoration: none; right: 5px; position: absolute; margin-top: -15px; z-index: 1002; } + +.xdsoft_autocomplete .xdsoft_autocomplete_dropdown > div { background: #fff; white-space: nowrap; cursor: pointer; line-height: 1.5em; padding: 2px 0px 2px 0px; } + +.xdsoft_autocomplete .xdsoft_autocomplete_dropdown > div.active { background: #0097CF; color: #FFFFFF; } + +@font-face { font-family: "Lato"; src: url("../fonts/Lato-Regular.eot"); src: url("../fonts/Lato-Regular.eot?#iefix") format("embedded-opentype"), url("../fonts/Lato-Regular.woff2") format("woff2"), url("../fonts/Lato-Regular.woff") format("woff"), url("../fonts/Lato-Regular.ttf") format("truetype"), url("../fonts/Lato-Regular.svg#Lato-Regular") format("svg"); font-weight: normal; font-style: normal; } + +@font-face { font-family: "Lato"; src: url("../fonts/Lato-Bold.eot"); src: url("../fonts/Lato-Bold.eot?#iefix") format("embedded-opentype"), url("../fonts/Lato-Bold.woff2") format("woff2"), url("../fonts/Lato-Bold.woff") format("woff"), url("../fonts/Lato-Bold.ttf") format("truetype"), url("../fonts/Lato-Bold.svg#Lato-Bold") format("svg"); font-weight: bold; font-style: normal; } + +html { box-sizing: border-box; } + +*, *::before, *::after { box-sizing: inherit; } + +:root { font-family: "Lato", Arial, sans-serif; line-height: 1.57; } + +:root * { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-overflow-scrolling: touch; } + +img { max-width: 100%; } + +picture source, picture img { width: 100%; height: 100%; object-fit: cover; object-position: center; } + +.m0 { margin: 0 !important; } + +.mt0 { margin-top: 0 !important; } + +.mr0 { margin-right: 0 !important; } + +.mb0 { margin-bottom: 0 !important; } + +.ml0 { margin-left: 0 !important; } + +.p0 { padding: 0 !important; } + +.pt0 { padding-top: 0 !important; } + +.pr0 { padding-right: 0 !important; } + +.pb0 { padding-bottom: 0 !important; } + +.pl0 { padding-left: 0 !important; } + +.mt2 { margin-top: 24px; } + +.ml1 { margin-left: 12px; } + +.bg-absolute { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 0; background-color: #fcfcfc; } + +.bg-absolute img { display: block; width: 100%; height: 100%; object-fit: cover; object-position: center bottom; } + +img { border: 0; } + +img:not([src]):not([srcset]) { visibility: hidden; } + +.lazyload { animation-name: fade; animation-duration: 1s; } + +@keyframes fade { from { opacity: 0; } + to { opacity: 1; } } + +.overflow-y-scroll { overflow-y: auto; } + +.overflow-x-scroll { overflow-x: auto; overflow-y: hidden; } + +.icon { transition: all 0.3s ease; } + +.icon-chevron-down { font-size: 8px; } + +.link { color: #1776ea; } + +.d-flex { display: -ms-flexbox; display: flex; } + +.d-flex-center { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; } + +.justify-content-center { -ms-flex-pack: center; justify-content: center; } + +.font-weight-bold { font-weight: 700; } + +.text-center { text-align: center; } + +.c_battleship-grey { color: #6b7480; } + +.badge { position: absolute; right: 0; top: 0; display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; width: 16px; height: 16px; background-color: #38bc7d; font-size: 8px; font-weight: 600; line-height: 1; letter-spacing: 0.1px; text-align: center; color: #ffffff; border-radius: 50%; } + +.dropdown, .dropdown-select, .with-label { display: -ms-inline-flexbox; display: inline-flex; -ms-flex-align: center; align-items: center; position: relative; cursor: pointer; } + +.dropdown .icon-chevron-down, .dropdown-select .icon-chevron-down, .with-label .icon-chevron-down { fill: #002d73; } + +.dropdown label, .dropdown-select label, .with-label label { cursor: pointer; color: #002d73; white-space: nowrap; } + +.dropdown .label, .dropdown-select .label, .with-label .label { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; color: #002d73; cursor: pointer; } + +.dropdown .label .icon-chevron-down, .dropdown-select .label .icon-chevron-down, .with-label .label .icon-chevron-down { -ms-flex-preferred-size: 8px; flex-basis: 8px; -ms-flex-negative: 0; flex-shrink: 0; } + +.dropdown.active .icon-chevron-down, .dropdown-select.active .icon-chevron-down, .with-label.active .icon-chevron-down { -ms-transform: rotate(180deg); transform: rotate(180deg); } + +.dropdown.left .dropdown-list, .dropdown-select.left .dropdown-list, .with-label.left .dropdown-list { left: 0; } + +.dropdown.center .dropdown-list, .dropdown-select.center .dropdown-list, .with-label.center .dropdown-list { left: 50%; -ms-transform: translateX(-50%); transform: translateX(-50%); } + +.dropdown.right .dropdown-list, .dropdown-select.right .dropdown-list, .with-label.right .dropdown-list { right: 0; } + +.dropdown.priority[data-value="low"] span, .dropdown-select.priority[data-value="low"] span, .with-label.priority[data-value="low"] span { padding-left: 24px; background: url("../img/label-low.svg") no-repeat left center; } + +.dropdown.priority[data-value="medium"] span, .dropdown-select.priority[data-value="medium"] span, .with-label.priority[data-value="medium"] span { padding-left: 24px; background: url("../img/label-medium.svg") no-repeat left center; } + +.dropdown.priority[data-value="high"] span, .dropdown-select.priority[data-value="high"] span, .with-label.priority[data-value="high"] span { padding-left: 24px; background: url("../img/label-high.svg") no-repeat left center; } + +.dropdown.priority[data-value="critical"] span, .dropdown-select.priority[data-value="critical"] span, .with-label.priority[data-value="critical"] span { padding-left: 24px; background: url("../img/label-critical.svg") no-repeat left center; } + +.dropdown.priority [data-option="low"], .dropdown-select.priority [data-option="low"], .with-label.priority [data-option="low"] { padding-left: 47px; background: url("../img/label-low.svg") no-repeat 21px center; } + +.dropdown.priority [data-option="medium"], .dropdown-select.priority [data-option="medium"], .with-label.priority [data-option="medium"] { padding-left: 47px; background: url("../img/label-medium.svg") no-repeat 21px center; } + +.dropdown.priority [data-option="high"], .dropdown-select.priority [data-option="high"], .with-label.priority [data-option="high"] { padding-left: 47px; background: url("../img/label-high.svg") no-repeat 21px center; } + +.dropdown.priority [data-option="critical"], .dropdown-select.priority [data-option="critical"], .with-label.priority [data-option="critical"] { padding-left: 47px; background: url("../img/label-critical.svg") no-repeat 21px center; } + +.dropdown > span, .dropdown-select > span, .with-label > span { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } + +.dropdown select, .dropdown-select select, .with-label select { display: none; } + +.dropdown .icon-chevron-down, .dropdown-select .icon-chevron-down, .with-label .icon-chevron-down { margin-top: 1px; width: 8px; height: 8px; margin-left: 8px; transition: all 250ms ease; } + +.dropdown .dropdown-list, .dropdown-select .dropdown-list, .with-label .dropdown-list { display: none; border-radius: 2px; box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); background-color: #fff; list-style: none; margin: 0; padding: 0; position: absolute; top: 100%; z-index: 10; } + +.dropdown .dropdown-list .separator, .dropdown-select .dropdown-list .separator, .with-label .dropdown-list .separator { height: 1px; background-color: #dfe4ec; } + +.dropdown .dropdown-list > li, .dropdown-select .dropdown-list > li, .with-label .dropdown-list > li { height: 40px; display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; white-space: nowrap; padding: 0 16px; color: #002d73; } + +.dropdown .dropdown-list > li.selected, .dropdown-select .dropdown-list > li.selected, .with-label .dropdown-list > li.selected { display: none; } + +.dropdown .dropdown-list > li a, .dropdown-select .dropdown-list > li a, .with-label .dropdown-list > li a { width: 100%; height: 100%; display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; color: #002d73; } + +.dropdown .dropdown-list > li a:hover, .dropdown-select .dropdown-list > li a:hover, .with-label .dropdown-list > li a:hover { color: #002d73; } + +.dropdown .dropdown-list > li svg, .dropdown-select .dropdown-list > li svg, .with-label .dropdown-list > li svg { transition: all 250ms ease; fill: #959eb0; margin-right: 8px; width: 16px; height: 16px; } + +.dropdown .dropdown-list > li:hover, .dropdown-select .dropdown-list > li:hover, .with-label .dropdown-list > li:hover { background-color: #f5f8ff; transition: all 250ms ease; } + +.dropdown .dropdown-list > li:hover svg, .dropdown-select .dropdown-list > li:hover svg, .with-label .dropdown-list > li:hover svg { fill: #002d73; } + +.accordion .accordion-title { cursor: pointer; } + +.accordion .accordion-body { display: none; } + +.accordion.visible .accordion-title svg { -ms-transform: rotate(180deg); transform: rotate(180deg); } + +body.noscroll { width: 100%; height: 100% !important; position: fixed; top: 0; bottom: 0; overflow: hidden; } + +.modal { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 30; background-color: rgba(38, 40, 42, 0.8); text-align: center; display: none; } + +.modal::before { content: ""; display: inline-block; height: 100%; margin-left: -0.05em; vertical-align: middle; } + +.modal .modal__body { padding: 40px 24px; box-shadow: 0 8px 16px 0 rgba(38, 40, 42, 0.1); background-color: #fff; margin: auto; display: inline-block; position: relative; width: 440px; vertical-align: middle; } + +.modal .modal__body .modal__close { position: absolute; width: 32px; height: 32px; display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; top: 0; right: 0; cursor: pointer; } + +.modal .modal__body .modal__close .icon-close { width: 8px; height: 8px; } + +.modal .modal__body .modal__close:hover .icon-close { fill: #002d73; } + +.modal .modal__body h3 { font-family: "Lato", Arial, sans-serif; font-size: 18px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: 1.22; letter-spacing: 0.1px; text-align: center; } + +.modal .modal__body .modal__description { margin-top: 24px; font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; text-align: center; } + +.modal .modal__body .modal__buttons { margin-top: 32px; display: -ms-flexbox; display: flex; -ms-flex-pack: justify; justify-content: space-between; } + +.modal .modal__body .modal__buttons button { width: 176px; } + +@media screen and (max-width: 900px) { .modal .modal__body { width: 90%; } + .modal .modal__body .btn { height: 40px !important; } + .modal .modal__body .modal__buttons { -ms-flex-pack: center; justify-content: center; -ms-flex-wrap: wrap; flex-wrap: wrap; } + .modal .modal__body .modal__buttons .btn { margin: 0 8px 16px 8px; } } + +.dropdown.priority .low { fill: #959eb0 !important; } + +.dropdown.priority .medium { fill: #38bc7d !important; } + +.dropdown.priority .hight { fill: #ffc200 !important; } + +.dropdown.priority .critical { fill: #e64342 !important; } + +.nowrap { white-space: nowrap; } + +button { font-family: "Lato", Arial, sans-serif; color: #26282a; } + +.btn { display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; height: 32px; padding: 5px 12px; background-color: transparent; border: none; outline: none; cursor: pointer; font-size: 13px; font-weight: normal; border-radius: 2px; transition: all 250ms ease; } + +.btn > .icon + span, .btn > span + .icon { margin-left: 8px; } + +.btn .icon { fill: currentColor; } + +@media screen and (max-width: 900px) { .btn { cursor: default; } } + +.btn-transparent { background-color: #ffffff; border: 1px solid #c5cad4; font-size: 14px; font-weight: normal; letter-spacing: 0.1px; color: #6b7480; } + +.btn.cancel { width: 120px; height: 40px; border: 1px solid #002d73; color: #002d73; } + +.btn-empty { padding: 0; } + +.btn-full { width: 152px; height: 40px; background-color: #1776ea; color: #fff; font-weight: 600; transition: all 250ms ease; text-decoration: none; } + +.notification a.btn-full { color: #fff ! important; text-decoration: none ! important; } + +.btn-full:hover { background-color: #025cca; } + +.btn-full.disabled, .btn-full:disabled { width: auto; border-color: #f0f2f5; background-color: #f0f2f5; color: #959eb0; } + +.btn--blue { color: #1776ea; } + +.btn--blue .icon { fill: currentColor; } + +.btn-border { width: 152px; height: 40px; border: 1px solid #002d73; color: #002d73; padding: 0; } + +.btn--blue-border { width: auto; padding: 0 16px; display: -ms-inline-flexbox; display: inline-flex; height: 48px; border: 1px solid #1776ea; color: #1776ea; font-weight: 600; } + +.btn--blue-border:hover { border-color: #025cca; color: #025cca; } + +.btn-banner { width: 176px; background-color: #f0f2f5; color: #002d73; font-weight: 600; } + +[ripple] { position: relative; overflow: hidden; } + +[ripple]::before { content: ""; display: block; position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: 10; } + +[ripple] .ripple--container { position: absolute; top: 0; right: 0; bottom: 0; left: 0; } + +[ripple] .ripple--container span { -ms-transform: scale(0); transform: scale(0); border-radius: 100%; position: absolute; opacity: 0.23; background-color: #fff; animation: ripple 500ms; } + +.btn-border .ripple--container span, .btn--blue-border .ripple--container span { background-color: rgba(141, 156, 183, 0.1); opacity: 1; } + +@keyframes ripple { to { opacity: 0; + transform: scale(2); } } + +@media (max-width: 900px) { .btn--blue-border, .btn-full { height: 32px !important; } } + +*::-webkit-input-placeholder { /* Chrome/Opera/Safari */ color: #959eb0; } + +*::-moz-placeholder { /* Firefox 19+ */ color: #959eb0; } + +*:-ms-input-placeholder { /* IE 10+ */ color: #959eb0; } + +*:-moz-placeholder { /* Firefox 18- */ color: #959eb0; } + +input { outline: none; } + +input::-ms-clear { display: none; } + +.form { font-size: 14px; } + +.form .checkbox-custom { padding: 0; } + +.form textarea.form-control { height: 155px; resize: none; font-family: "Lato", Arial, sans-serif; } + +.form.invalid .error-message { display: block; } + +.form.invalid .form-control.isError { + border-color: #e64342; +} + +.form__title { margin-bottom: 1.5rem; font-size: 1.5rem; line-height: 1.33; } + +.input-group { position: relative; } + +.input-group-append--icon { position: absolute; right: 17px; top: 0; bottom: 0; margin: auto; display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; background-color: transparent; border: none; z-index: 3; cursor: pointer; } + +.input-group-append--icon:hover .icon { fill: #1776ea; } + +.input-group-append--icon .icon { fill: #c5cad4; font-size: 12px; } + +.input-group-append--icon .icon-eye-close { font-size: 12px; } + +.form-group { position: relative; margin-bottom: 16px; } + +.form-group label { display: block; margin-bottom: 4px; color: #959eb0; } + +.form-group .form-control__error { display: none; margin-top: 12px; padding: 9px; color: #e64342; text-align: center; background-color: rgba(230, 67, 66, 0.05); } + +.form-group.error .form-control__error { display: block; } + +.form-group.error input { border-color: #e64342; } + +.form input.form-control, .form textarea.form-control { height: 40px; width: 100%; padding: 4px 12px; font-size: 14px; border-radius: 2px; border: solid 1px #d4d6e3; background-color: #fff; font-weight: normal; font-style: normal; font-stretch: normal; line-height: normal; letter-spacing: 0.1px; -webkit-appearance: none; outline: none; color: #26282a; transition: all 250ms ease; } + +.form input.form-control:-ms-input-placeholder, .form textarea.form-control:-ms-input-placeholder { color: #959eb0; } + +.form input.form-control::placeholder, .form textarea.form-control::placeholder { color: #959eb0; } + +.form input.form-control:hover, .form textarea.form-control:hover { border-color: #959eb0; } + +.form input.form-control:focus, .form textarea.form-control:focus { color: #000; border-color: #1776ea; outline: none; box-shadow: none; } + +.error-message { display: none; padding: 9px; color: #e64342; text-align: center; background-color: rgba(230, 67, 66, 0.05); } + +.invalid-feedback { display: none; position: absolute; top: 100%; left: 0; margin-top: 0.2rem; font-size: 12px; } + +.invalid .form-control { border-color: #e64342; } + +.invalid .invalid-feedback { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; color: #e64342; } + +.form__submit { margin-top: 24px; display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; } + +.form__search { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; width: 100%; height: 100%; padding: 0px 16px 0 32px; position: relative; background-color: #fff; position: relative; box-sizing: border-box; } + +.form__search .search--type { font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; color: #959eb0; margin-right: 4px; display: none; text-transform: capitalize; cursor: pointer; } + +.form__search .form__search_type { position: absolute; top: 100%; left: 0; width: 100%; box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); background-color: #fff; padding: 9px 16px 24px 16px; z-index: 1; display: none; } + +.form__search .form__search_type h5 { margin-left: 8px; font-size: 14px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; color: #26282a; } + +.form__search .form__search_type .type--list { margin: 8px -16px 0 -16px; } + +.form__search .form__search_type .type--list li { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; color: #002d73; height: 40px; transition: all 250ms ease; padding: 0 16px; cursor: pointer; } + +.form__search .form__search_type .type--list li:hover { background-color: #f5f8ff; } + +.form__search .form__search_type .type--list li:last-child { margin-bottom: 0; } + +.form__search .form__search_type .type--list li .icon { margin-right: 8px; fill: #959eb0; transition: all 250ms ease; } + +.form__search .form__search_results { position: absolute; top: 100%; left: 0; width: 100%; box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); background-color: #fff; padding: 8px 24px 0px 24px; z-index: 1; display: none; } + +.form__search .form__search_results h5 { font-size: 12px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.5; letter-spacing: 0.1px; color: #6b7480; } + +.form__search .form__search_results .results--list { margin: 0 -24px; } + +.form__search .form__search_results .results--list li { height: 40px; display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; color: #26282a; transition: all 250ms ease; padding: 0 24px; } + +.form__search .form__search_results .results--list li > *:last-child { overflow: hidden; text-overflow: ellipsis; margin-right: 0; } + +.form__search .form__search_results .results--list li:hover { background-color: #f5f8ff; } + +.form__search .form__search_results .results--list li span, .form__search .form__search_results .results--list li a { margin-right: 16px; white-space: nowrap; } + +.form__search .form__search_results .results--list li a { color: #1776ea; transition: all 250ms ease; } + +.form__search .form__search_results .results--list li a:hover { color: #025cca; } + +.form__search .form__search_results .results--list li b { background-color: #fff5d0; } + +.form__search.focus .icon-search { fill: #002d73 !important; } + +.form__search.value .icon-search { fill: #002d73 !important; } + +.form__search.value .search-clear { opacity: 1 !important; } + +.form__search input { font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; color: #26282a; } + +.form__search button[type="submit"] { margin-right: 8px; } + +.form__search .icon-search { font-size: 19.7px; } + +.form__search .form__control { background-color: transparent; width: 100%; border: none; height: 70%; cursor: pointer; } + +.form__search .form__control::-webkit-input-placeholder { /* Chrome/Opera/Safari */ color: #959eb0; transition: all 250ms ease; } + +.form__search .form__control::-moz-placeholder { /* Firefox 19+ */ color: #959eb0; transition: all 250ms ease; } + +.form__search .form__control:-ms-input-placeholder { /* IE 10+ */ color: #959eb0; transition: all 250ms ease; } + +.form__search .form__control:-moz-placeholder { /* Firefox 18- */ color: #959eb0; transition: all 250ms ease; } + +.form__search .form__control:hover::-webkit-input-placeholder { /* Chrome/Opera/Safari */ color: #6b7480; } + +.form__search .form__control:hover::-moz-placeholder { /* Firefox 19+ */ color: #6b7480; } + +.form__search .form__control:hover:-ms-input-placeholder { /* IE 10+ */ color: #6b7480; } + +.form__search .form__control:hover:-moz-placeholder { /* Firefox 18- */ color: #6b7480; } + +.form__search.type .form__control { cursor: initial; } + +.checkbox-custom { position: relative; display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; min-height: 16px; } + +.checkbox-custom [type="checkbox"]:checked, .checkbox-custom [type="checkbox"]:not(:checked) { position: absolute; left: -9999px; } + +.checkbox-custom [type="checkbox"] + label { transition: all 250ms ease; } + +.checkbox-custom [type="checkbox"]:not(:checked) + label { position: relative; padding-left: 24px; cursor: pointer; line-height: 1.2; letter-spacing: normal; color: #959eb0; } + +.checkbox-custom [type="checkbox"]:checked + label { position: relative; padding-left: 24px; cursor: pointer; line-height: 1.2; letter-spacing: normal; color: #002d73; } + +.checkbox-custom [type="checkbox"]:checked + label:before, .checkbox-custom [type="checkbox"]:not(:checked) + label:before { content: ""; position: absolute; left: 0; top: 0; width: 16px; height: 16px; border-radius: 2px; background: #fff; border: 1px solid #959eb0; } + +.checkbox-custom [type="checkbox"]:checked + label:after, .checkbox-custom [type="checkbox"]:not(:checked) + label:after { content: ""; width: 12px; height: 12px; position: absolute; top: 2px; left: 2px; transition: all 0.2s ease; background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='11' height='8' viewBox='0 0 11 8'%3E%3Cpath fill='%23002D73' fill-rule='evenodd' d='M9.043 0L3.246 5.128 1.623 3.692 0 5.128 3.246 8l7.42-6.564z'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: center; } + +.checkbox-custom [type="checkbox"]:not(:checked) + label:after { opacity: 0; -ms-transform: scale(0); transform: scale(0); } + +.checkbox-custom [type="checkbox"]:checked + label:after { opacity: 1; -ms-transform: scale(1); transform: scale(1); } + +.checkbox-custom [type="checkbox"]:disabled:checked + label:before, .checkbox-custom [type="checkbox"]:disabled:not(:checked) + label:before { border-color: #ccc; background-color: #eee; } + +.checkbox-custom [type="checkbox"]:disabled:checked + label:after { background: #aaa; } + +.invalid .checkbox-custom [type="checkbox"]:not(:checked):required + label:before { border-color: #e64342; } + +.radio-custom { position: relative; display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; min-height: 16px; } + +.radio-custom [type="radio"]:checked, .radio-custom [type="radio"]:not(:checked) { position: absolute; left: -9999px; } + +.radio-custom [type="radio"]:checked + label, .radio-custom [type="radio"]:not(:checked) + label { position: relative; padding-left: 24px; cursor: pointer; line-height: 1.2; letter-spacing: normal; color: #002257; } + +.radio-custom [type="radio"]:checked + label:before, .radio-custom [type="radio"]:not(:checked) + label:before { content: ""; position: absolute; left: 0; top: 0; width: 16px; height: 16px; border-radius: 2px; background: #fff; border-radius: 50%; border: 1px solid #002d73; } + +.radio-custom [type="radio"]:checked + label:after, .radio-custom [type="radio"]:not(:checked) + label:after { content: ""; width: 8px; height: 8px; position: absolute; top: 4px; left: 4px; transition: all 0.2s ease; background-color: #002d73; border-radius: 50%; } + +.radio-custom [type="radio"]:not(:checked) + label:after { opacity: 0; -ms-transform: scale(0); transform: scale(0); } + +.radio-custom [type="radio"]:checked + label:after { opacity: 1; -ms-transform: scale(1); transform: scale(1); } + +.radio-custom [type="radio"]:disabled:checked + label:before, .radio-custom [type="radio"]:disabled:not(:checked) + label:before { border-color: #ccc; background-color: #eee; } + +.radio-custom [type="radio"]:disabled:checked + label:after { background: #aaa; } + +.invalid .radio-custom [type="radio"]:not(:checked):required + label:before { border-color: #e64342; } + +.select-custom { position: relative; height: 32px; color: inherit; } + +.select-custom select { display: none; } + +.select-selected { max-width: 200px; } + +/*style the arrow inside the select element:*/ +.select-selected:after { position: absolute; content: ""; top: 12px; right: 10px; width: 10px; height: 6px; background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='6' viewBox='0 0 8 6'%3E%3Cpath fill='%2326282A' fill-rule='evenodd' d='M4.303 5.07l3.553-3.552a.434.434 0 0 0 .128-.309A.434.434 0 0 0 7.856.9L7.595.64a.437.437 0 0 0-.618 0L3.994 3.622 1.007.635a.434.434 0 0 0-.618 0L.128.897A.434.434 0 0 0 0 1.206c0 .117.045.226.128.309L3.684 5.07a.434.434 0 0 0 .31.127.434.434 0 0 0 .31-.127z'/%3E%3C/svg%3E"); background-size: 10px 6px; background-repeat: no-repeat; } + +.select-selected.select-arrow-active:after { -ms-transform: scaleY(-1); transform: scaleY(-1); filter: FlipY; -ms-filter: "FlipY"; } + +.select-items div, .select-selected { padding: 8px 8px; line-height: 1; cursor: pointer; } + +.select-items { position: absolute; top: 100%; left: 0; right: 0; z-index: 5; padding: 6px 0 12px; box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); background-color: #ffffff; } + +.select-hide { display: none; } + +.select-items div:hover, .same-as-selected { color: #1776ea; } + +.select-custom--stretched { box-shadow: none; } + +.select-custom--stretched .select-selected { width: 100%; } + +.select--priority .select-selected { padding-left: 24px; } + +.select--priority .select-selected[data-value="critical"] + div + select + .priority-label { background-color: #e64342; } + +.select--priority .select-selected[data-value="low"] + div + select + .priority-label { background-color: #959eb0; } + +.select--priority .select-selected[data-value="medium"] + div + select + .priority-label { background-color: #38bc7d; } + +.select--priority .select-selected[data-value="high"] + div + select + .priority-label { background-color: #ffc200; } + +.priority-label { position: absolute; top: 0; bottom: 0; margin: auto; left: 0; display: inline-block; width: 16px; height: 12px; border-top-left-radius: 2px; border-bottom-left-radius: 2px; } + +.priority-label:after { content: ""; position: absolute; right: 0; top: 0; width: 0; height: 0; border-style: solid; border-width: 6px 4px 6px 0; border-color: transparent #ffffff transparent transparent; } + +.switch-checkbox { display: -ms-inline-flexbox; display: inline-flex; -ms-flex-align: center; align-items: center; } + +.switch-checkbox input[type="checkbox"] { display: none; } + +.switch-checkbox .switch-checkbox__bullet { width: 32px; height: 16px; background-color: #fff; border: 1px solid #dfe4ec; border-radius: 8px; transition: all 250ms ease; position: relative; } + +.switch-checkbox .switch-checkbox__bullet i { display: block; width: 14px; height: 14px; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.16); background-color: #fff; border-radius: 50%; position: absolute; top: 0; left: 0; right: initial; transition: all 250ms ease; } + +.switch-checkbox .switch-checkbox__bullet i svg { width: 8px; height: 8px; position: absolute; left: 50%; top: 50%; -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); transition: all 250ms ease; } + +.switch-checkbox .switch-checkbox__bullet i svg.icon-tick { opacity: 0; } + +.switch-checkbox input[type="checkbox"]:checked + .switch-checkbox__bullet { background-color: #002d73; border-color: #002d73; } + +.switch-checkbox input[type="checkbox"]:checked + .switch-checkbox__bullet i { left: 100%; -ms-transform: translateX(-100%); transform: translateX(-100%); } + +.switch-checkbox input[type="checkbox"]:checked + .switch-checkbox__bullet i .icon-close { opacity: 0; } + +.switch-checkbox input[type="checkbox"]:checked + .switch-checkbox__bullet i .icon-tick { opacity: 1; } + +.switch-checkbox span { margin-left: 16px; transition: all 250ms ease; line-height: 1.2; } + +.switch-checkbox a { margin-left: 16px; transition: all 250ms ease; color: #1776ea; line-height: 1.2; } + +.switch-checkbox a:hover { color: #025cca; } + +.block--attach { margin-top: 8px; display: -ms-inline-flexbox; display: inline-flex; -ms-flex-align: center; align-items: center; position: relative; font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; color: #1776ea; transition: all 250ms ease; cursor: pointer !important; } + +.block--attach input[type="file"] { opacity: 0; position: absolute; top: 0; left: 0; width: 100%; height: 100%; cursor: pointer !important; } + +.block--attach .icon-attach { width: 16px; height: 16px; fill: #1776ea; margin-right: 8px; } + +.block--attach:hover { color: #025cca; } + +.block--attach:hover .icon-attach { fill: #025cca; } + +.selectize-input { padding: 11px 12px; border: solid 1px #d4d6e3; transition: all 250ms ease; } + +.selectize-input.input-active { border: solid 1px #1776ea !important; } + +.selectize-input:hover { border: solid 1px #959eb0; } + +.selectize-control.input-tags { line-height: 1; margin-left: 24px; } + +.selectize-control.multi .selectize-input > div { margin: 0 6px 0 0; padding: 0; background: transparent; color: #26282a; border: none; } + +.selectize-control { display: -ms-flexbox; display: flex; } + +.selectize-control .selectize-input { margin-top: 16px; border-radius: 2px; border: solid 1px #d4d6e3; box-shadow: none; min-width: 320px; padding: 0 12px; height: 40px; display: -ms-flexbox !important; display: flex !important; -ms-flex-align: center; align-items: center; transition: all 250ms ease; z-index: 11; } + +.selectize-control .selectize-input:after { border: none !important; background: transparent url("../img/chevron-down.svg") no-repeat center; width: 8px !important; height: 8px !important; opacity: 0.25 !important; transition: all 250ms ease; } + +.selectize-control .selectize-input.focus::after { -ms-transform: rotate(180deg); transform: rotate(180deg); } + +.selectize-control .selectize-dropdown { box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); border: none; } + +.selectize-control .selectize-dropdown .option { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; height: 40px; padding: 0 16px; color: #002d73; } + +.selectize-control .selectize-dropdown .option.active { background-color: #f5f8ff; } + +@media screen and (max-width: 900px) { .form__search .form__search_results .results--list li { font-size: 13px; } } + +.main__content.ticket { padding: 23px 32px 50px 16px; display: -ms-flexbox; display: flex; -ms-flex-pack: justify; justify-content: space-between; } + +.main__content.ticket .icon-chevron-down { margin-top: 1px; } + +@media screen and (max-width: 900px) { .main__content.ticket { padding: 16px 12px 24px 12px; -ms-flex-direction: column; flex-direction: column; } + .main__content.ticket .ticket__body { margin: 0 0 16px 0; padding-top: 72px; } + .main__content.ticket .ticket__body .block--head { -ms-flex-direction: column; flex-direction: column; -ms-flex-align: start; align-items: flex-start; } + .main__content.ticket .ticket__body .block--head time { margin-left: 0; margin-bottom: 8px; } + .main__content.ticket .ticket__body .block--head .more { margin-left: 0; } + .main__content.ticket .block--submit { -ms-flex-pack: justify; justify-content: space-between; -ms-flex-wrap: wrap; flex-wrap: wrap; } + .main__content.ticket .block--submit .btn { height: 40px !important; margin: 0 auto 16px auto; } + .main__content.ticket .block--submit .btn-full { -ms-flex-order: 1; order: 1; } + .main__content.ticket .block--submit .btn-border { -ms-flex-order: 2; order: 2; } + .main__content.ticket .block--submit::before { content: ""; -ms-flex-order: 3; order: 3; width: 100%; height: 0; } + .main__content.ticket .block--submit .submit-us { -ms-flex-order: 4; order: 4; margin: 0 auto 0 auto; } + .main__content.ticket .block--submit .submit-us .dropdown-list { top: calc(100% + 8px); left: 50%; -ms-transform: translateX(-50%); transform: translateX(-50%); } + .main__content.ticket .ticket__params { width: 100%; } + .main__content.ticket .ticket__params .params--bar { position: absolute; top: 72px; left: 12px; right: 12px; } } + +.ticket__body { -ms-flex-positive: 1; flex-grow: 1; margin-right: 24px; } + +.ticket__body_block { background-color: #fff; margin-bottom: 24px; border-radius: 2px; box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); padding: 24px; } + +.ticket__body_block.response { box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); border: solid 4px #c3ead8; } + +.ticket__body_block h2 { font-size: 24px; font-weight: bold; line-height: 1.17; letter-spacing: 0.12px; color: #26282a; } + +.ticket__body_block h3 { font-family: "Lato", Arial, sans-serif; font-size: 18px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: 1.22; letter-spacing: 0.1px; } + +.ticket__body_block .block--head { display: -ms-flexbox; display: flex; margin-top: 16px; -ms-flex-align: center; align-items: center; font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; } + +.ticket__body_block .block--head .contact { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; position: relative; } + +.ticket__body_block .block--head .contact > span { color: #959eb0; } + +.ticket__body_block .block--head .contact b { margin-left: 8px; font-weight: bold; } + +.ticket__body_block .block--head .contact .dropdown { margin-left: 8px; cursor: pointer; position: static; } + +.ticket__body_block .block--head .contact .dropdown span { font-weight: bold; } + +.ticket__body_block .block--head .contact .dropdown .dropdown-list li { padding: 0 12px; font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; } + +.ticket__body_block .block--head .contact .dropdown .dropdown-list li:nth-child(1), .ticket__body_block .block--head .contact .dropdown .dropdown-list li:nth-child(2) { background-color: transparent !important; cursor: auto; } + +.ticket__body_block .block--head .contact .dropdown .dropdown-list li .title { color: #959eb0; margin-right: 8px; width: 36px; } + +.ticket__body_block .block--head .contact .dropdown .dropdown-list li .value { font-weight: normal; color: #26282a; } + +.ticket__body_block .block--head .contact .dropdown .dropdown-list li a { color: #002d73; } + +.ticket__body_block .block--head .contact .icon-chevron-down { width: 8px; height: 8px; } + +.ticket__body_block .block--head .date { color: #6b7480; } + +.ticket__body_block .block--head .more { margin-left: auto; color: #1776ea; display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; cursor: pointer; margin-right: -24px; padding-right: 24px; } + +.ticket__body_block .block--head .more span { color: #1776ea; } + +.ticket__body_block .block--head .more .icon-chevron-down { fill: #1776ea; width: 8px; height: 8px; } + +.ticket__body_block .block--head .more .dropdown-list a { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; width: 100%; height: 100%; } + +.ticket__body_block .block--description { margin: 16px 0; font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.71; letter-spacing: 0.1px; } + +.ticket__body_block .block--description p, .ticket__body_block .block--description ul { margin: 0 0 28px 0; } + +.ticket__body_block .block--description p:last-child, .ticket__body_block .block--description ul:last-child { margin: 0; } + +.ticket__body_block .block--description ul.list { list-style-type: disc; padding-left: 30px; } + +.ticket__body_block .block--notes { margin-top: 26px; } + +.ticket__body_block .block--notes .note { border: solid 1px #f3e3a7; background-color: #fff5d0; padding: 8px 8px 16px 8px; margin-bottom: 8px; } + +.ticket__body_block .block--notes .note .note__head { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; -ms-flex-pack: justify; justify-content: space-between; } + +.ticket__body_block .block--notes .note .note__head .name { font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; color: #959eb0; } + +.ticket__body_block .block--notes .note .note__head .name span { margin-right: 8px; } + +.ticket__body_block .block--notes .note .note__head .name b { color: #26282a; margin-right: 24px; } + +.ticket__body_block .block--notes .note .note__head .name time { color: #6b7480; white-space: nowrap; } + +.ticket__body_block .block--notes .note .note__head .actions { display: -ms-flexbox; display: flex; margin-top: -5px; } + +.ticket__body_block .block--notes .note .note__head .actions button { width: 32px; height: 32px; display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; margin-left: 16px; } + +.ticket__body_block .block--notes .note .note__head .actions button svg { width: 16px; height: 16px; fill: #c5cad4; } + +.ticket__body_block .block--notes .note .note__head .actions button:hover svg { fill: #002d73; } + +.ticket__body_block .block--notes .note .note__description { margin-top: 16px; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.71; letter-spacing: 0.1px; color: #26282a; } + +.ticket__body_block .block--uploads { margin-top: 26px; display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; } + +.ticket__body_block .block--uploads + .block--uploads { margin-top: 16px; } + +.ticket__body_block .block--uploads .icon-attach { width: 16px; height: 16px; fill: #c5cad4; margin-right: 8px; } + +.ticket__body_block .block--uploads a { color: #1776ea; transition: all 250ms ease; } + +.ticket__body_block .block--uploads a:hover { color: #025cca; } + +.ticket__body_block .block--suggested { margin-top: 32px; display: -ms-flexbox; display: flex; -ms-flex-direction: column; flex-direction: column; font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; -ms-flex-align: baseline; align-items: baseline; } + +.ticket__body_block .block--suggested b { font-weight: bold; margin-bottom: 8px; } + +.ticket__body_block .block--suggested a { color: #1776ea; transition: all 250ms ease; } + +.ticket__body_block .block--suggested a:hover { color: #025cca; } + +.ticket__body_block .block--timer { height: 48px; box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); background-color: #fff; display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; } + +.ticket__body_block .block--timer span { font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; color: #959eb0; } + +.ticket__body_block .block--timer b { margin: 0 26px 0 8px; font-weight: bold; } + +.ticket__body_block .block--timer a { width: 32px; height: 32px; display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; margin-right: 8px; } + +.ticket__body_block .block--timer a svg { width: 16px; height: 16px; fill: #959eb0; transition: all 250ms ease; } + +.ticket__body_block .block--timer a:hover svg { fill: #002d73; } + +.ticket__body_block .block--message { margin-top: 16px; height: 119px; border-radius: 2px; border: solid 1px #d4d6e3; background-color: #fff; position: relative; overflow: hidden; } + +.ticket__body_block .block--message .scroll-textarea { width: 100%; height: 119px; } + +.ticket__body_block .block--message textarea { outline: none; border: none; width: 100%; min-height: 100%; background: transparent; padding: 8px 12px; font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.71; letter-spacing: 0.1px; resize: none; } + +.ticket__body_block .block--message .placeholder { position: absolute; top: 8px; left: 12px; font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; z-index: 0; letter-spacing: 0.1px; color: #959eb0; } + +.ticket__body_block .block--message .placeholder a { color: #1776ea; transition: all 250ms ease; } + +.ticket__body_block .block--message .placeholder a:hover { color: #025cca; } + +.ticket__body_block .block--attach-list { margin-top: 16px; } + +.ticket__body_block .block--attach-list div { width: 284px; height: 32px; padding-left: 8px; border-radius: 2px; background-color: #f5f8ff; display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; position: relative; -ms-flex-pack: justify; justify-content: space-between; margin-bottom: 4px; } + +.ticket__body_block .block--attach-list div i { width: 32px; height: 32px; display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; cursor: pointer; } + +.ticket__body_block .block--attach-list div i svg { width: 7px; height: 7px; fill: #c5cad4; } + +.ticket__body_block .block--attach-list div i:hover svg { width: 7px; height: 7px; fill: #959eb0; } + +.ticket__body_block .block--checkboxs { margin-top: 24px; display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; -ms-flex-align: center; align-items: center; border-bottom: 1px solid #dfe4ec; } + +.ticket__body_block .block--checkboxs .checkbox-custom { margin-bottom: 16px; font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; margin-right: 40px; } + +.ticket__body_block .block--checkboxs .checkbox-custom .dropdown-select { margin-left: 6px; } + +.ticket__body_block .block--checkboxs .checkbox-custom .dropdown-select > span, .ticket__body_block .block--checkboxs .checkbox-custom .dropdown-select li { color: #959eb0; transition: all 250ms ease; } + +.ticket__body_block .block--checkboxs .checkbox-custom .dropdown-select svg { fill: #959eb0; } + +.ticket__body_block .block--checkboxs .checkbox-custom label { color: #959eb0; transition: all 250ms ease; display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; } + +.ticket__body_block .block--checkboxs .checkbox-custom input[type="checkbox"]:checked + label { color: #002d73; } + +.ticket__body_block .block--checkboxs .checkbox-custom input[type="checkbox"]:checked + label::before { border-color: #002d73; } + +.ticket__body_block .block--checkboxs .checkbox-custom input[type="checkbox"]:checked + label svg { fill: #002d73; } + +.ticket__body_block .block--checkboxs .checkbox-custom.checked .dropdown-select > span, .ticket__body_block .block--checkboxs .checkbox-custom.checked .dropdown-select li { color: #002d73; } + +.ticket__body_block .block--submit { margin-top: 24px; display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; } + +.ticket__body_block .block--submit button { margin-right: 24px; } + +.ticket__body_block .block--submit .submit-us { margin-left: auto; display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; position: relative; font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; color: #1776ea; } + +.ticket__body_block .block--submit .submit-us span { margin-left: 6px; color: #1776ea; } + +.ticket__body_block .block--submit .submit-us .icon-chevron-down { width: 8px; height: 8px; margin-left: 4px; fill: #1776ea; } + +.ticket__body_block .block--submit .submit-us .dropdown-list { left: calc(100% + 8px); top: 50%; -ms-transform: translateY(-50%); transform: translateY(-50%); } + +.ticket__replies { margin: -8px 0 16px 0px; } + +.ticket__replies .ticket__replies_link { font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; color: #1776ea; display: -ms-inline-flexbox; display: inline-flex; -ms-flex-align: center; align-items: center; margin-left: 24px; cursor: pointer; transition: all 250ms ease; } + +.ticket__replies .ticket__replies_link:hover { color: #025cca; } + +.ticket__replies .ticket__replies_link:hover .icon-chevron-down { fill: #025cca; } + +.ticket__replies .ticket__replies_link b { font-weight: bold; margin-left: 6px; } + +.ticket__replies .ticket__replies_link .icon-chevron-down { margin-left: 8px; width: 8px; height: 8px; fill: #1776ea; transition: all 250ms ease; } + +.ticket__replies .ticket__replies_link.visible .icon-chevron-down { -ms-transform: rotate(180deg); transform: rotate(180deg); } + +.ticket__replies .ticket__replies_list { padding-top: 16px; display: none; } + +.ticket__params { width: 320px; -ms-flex-negative: 0; flex-shrink: 0; } + +.ticket__params .params--bar { height: 48px; border-radius: 2px; box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); background-color: #fff; display: -ms-flexbox; display: flex; -ms-flex-pack: justify; justify-content: space-between; padding-left: 16px; } + +.ticket__params .params--bar a { width: 48px; height: 48px; display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; } + +.ticket__params .params--bar a svg { width: 16px; height: 16px; fill: #959eb0; } + +.ticket__params .params--bar a:hover svg { fill: #002d73; } + +.ticket__params .params--bar .dropdown { width: 65px; height: 48px; box-sizing: content-box; display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; border-left: 1px solid #dfe4ec; } + +.ticket__params .params--bar .dropdown label { width: 100%; height: 100%; display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; } + +.ticket__params .params--bar .dropdown label svg { width: 16px; height: 16px; fill: #959eb0; transition: all 250ms ease; margin: 0; } + +.ticket__params .params--bar .dropdown:hover svg { fill: #002d73; } + +.ticket__params .params--bar .dropdown .dropdown-list li a { -ms-flex-pack: start; justify-content: flex-start; } + +.ticket__params .params--bar .dropdown .dropdown-list li svg { margin-right: 8px; } + +.ticket__params .params--block { border-radius: 2px; box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); background-color: #fff; margin-top: 16px; } + +.ticket__params .params--block.params { padding: 25px 16px; } + +.ticket__params .params--block.params .title { width: 135px; } + +.ticket__params .params--block.params .icon-label { width: 16px; height: 16px; margin-right: 8px; } + +.ticket__params .params--block.params [data-value="low"] .icon-label { fill: #959eb0; } + +.ticket__params .params--block.details .title, .ticket__params .params--block.contacts .title, .ticket__params .params--block.history .title { width: 106px; } + +.ticket__params .params--block .row { display: -ms-flexbox; display: flex; font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; margin-bottom: 18px; } + +.ticket__params .params--block .row:last-child { margin-bottom: 0; } + +.ticket__params .params--block .row .title { color: #959eb0; -ms-flex-negative: 0; flex-shrink: 0; } + +.ticket__params .params--block h4 { height: 48px; display: -ms-flexbox; display: flex; -ms-flex-pack: justify; justify-content: space-between; -ms-flex-align: center; align-items: center; font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; margin: 0; padding: 0 16px; } + +.ticket__params .params--block h4 .icon-chevron-down { width: 8px; height: 8px; fill: #c5cad4; } + +.ticket__params .params--block .accordion-body { padding: 16px; } + +.main__content.notifications { padding: 40px 32px 32px 16px; } + +.main__content.notifications h2 { padding-left: 16px; font-size: 18px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: 1.22; letter-spacing: 0.1px; } + +.main__content.notifications .notifications__list { margin-top: 16px; width: 100%; max-width: 496px; box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); background-color: #fff; padding: 8px; } + +.main__content.notifications .notifications__list li { display: -ms-flexbox; display: flex; -ms-flex-pack: justify; justify-content: space-between; -ms-flex-align: center; align-items: center; padding: 16px; } + +.main__content.notifications .notifications__list li:nth-child(odd) { background-color: #f9fafd; } + +.main__content.notifications .notifications__list li.new { border-left: 2px solid #1776ea; } + +.main__content.notifications .notifications__list li.new h5 { font-weight: bold; } + +.main__content.notifications .notifications__list li h5 { font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; margin-right: 16px; } + +.main__content.notifications .notifications__list li h5 a { color: #002d73; } + +.main__content.notifications .notifications__list li time { font-size: 10px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: normal; letter-spacing: 0.1px; text-align: right; color: #6b7480; } + +.main__content.notifications .pagination-wrap { width: 100%; max-width: 496px; margin: 24px 0 0 0; } + +.footer { margin-top: 16px; padding: 10px 16px 16px; color: #6b7480; } + +.pagination-wrap { margin: 24px auto 16px; } + +.pagination { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; -ms-flex-pack: center; justify-content: center; } + +.pagination a { color: #002d73; transition: all 250ms ease; } + +.pagination a:hover { background-color: #f1f2f5; } + +.pagination__nav-btn { margin: 0 5px; } + +.pagination__list { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; } + +.pagination__item.is-current .pagination__link { background-color: #dfe4ec; } + +.pagination__stroke { display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; width: 32px; height: 32px; border-radius: 2px; font-size: 12px; font-weight: 500; letter-spacing: normal; text-align: center; color: #002d73; } + +.pagination__link { display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; width: 32px; height: 32px; border-radius: 2px; font-size: 12px; font-weight: 500; letter-spacing: normal; text-align: center; color: #002d73; } + +.pagination__amount { margin-top: 24px; text-align: center; font-weight: bold; } + +.breadcrumbs { margin-bottom: 20px; } + +.breadcrumbs__inner { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; -ms-flex-wrap: wrap; flex-wrap: wrap; padding: 12px 0; font-size: 12px; } + +.breadcrumbs__inner a { display: -ms-inline-flexbox; display: inline-flex; -ms-flex-align: center; align-items: center; font-size: inherit; font-weight: normal; line-height: 1.5; letter-spacing: 0.1px; color: #1776ea; } + +.breadcrumbs__inner a:hover { color: #025cca; } + +.breadcrumbs__inner .icon { fill: currentColor; font-size: 8px; margin: 0 0.4em 0 0.5em; } + +.search__title { margin: 0 0 24px; font-size: 24px; font-weight: bold; line-height: 1.17; letter-spacing: 0.12px; color: #26282a; text-align: center; } + +.search__form { background-color: #ffefdc; padding: 16px; } + +.search__form .form-group { position: relative; margin: 0 auto; display: -ms-flexbox; display: flex; width: 100%; max-width: 752px; } + +.search__form .form-group input { width: 100%; height: 56px; padding: 17px 16px 17px 56px; background-color: #ffffff; border-color: transparent; font-size: 14px; transition: all 0.3s ease; } + +.search__form .form-group input:-ms-input-placeholder { line-height: 1.57; letter-spacing: 0.1px; color: #6b7480; } + +.search__form .form-group input::placeholder { line-height: 1.57; letter-spacing: 0.1px; color: #6b7480; } + +.search__form .form-group input:hover, .search__form .form-group input:focus { box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); } + +.search__form .form-group .icon-search { font-size: 20px; fill: #1776ea; } + +.search__form .search__submit { padding: 0; position: absolute; top: 0; bottom: 0; left: 24px; margin: auto; } + +.form-group { position: relative; } + +.form-group .search-clear { width: 32px; height: 32px; position: absolute; top: calc(50% - 16px); right: 12px; display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; cursor: pointer; z-index: 1; opacity: 0; transition: all 250ms ease; } + +.form-group .search-clear .icon { width: 16px; height: 16px; fill: #c5cad4; } + +.form-group .search-clear:hover .icon { fill: #002d73; } + +.alert { margin-top: 24px; border: solid 1px #1776ea; background-color: #f5f8ff; } + +.alert .icon-warning { fill: #1776ea; font-size: 22px; } + +.alert.warning { border: solid 1px #f3e3a7; background-color: #fff5d0; } + +.alert.warning .icon-warning { fill: #eeb707; } + +.alert.success { border: solid 1px #9fe4c3; background-color: #e5fff2; } + +.alert.success .icon-warning { fill: #38bc7d; } + +.alert.danger { border: solid 1px #f38b8b; background-color: #fdf5f5; } + +.alert.danger .icon-warning { fill: #e64342; } + +.alert.danger .alert__title { color: #e64342; } + +.alert.none { border: none; background-color: #fff; } + +.alert.none .icon-warning { fill: #000; } + +.alert__inner { padding: 24px; } + +.alert__head { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; } + +.alert__head .icon + .alert__title { margin-left: 12px; } + +.alert__title { font-size: 14px; font-weight: bold; letter-spacing: 0.1px; color: #26282a; } + +.alert__descr { margin-top: 12px; } + +.cust-help .lightgrey { color: #959eb0; } + +.cust-help .highlighted { background-color: #e5fff2; } + +.cust-help .italic { font-style: italic; } + +.cust-help .ml-1 { margin-left: 8px; } + +.cust-help .h-3 { font-size: 18px; font-weight: bold; line-height: 1.22; letter-spacing: 0.13px; color: #26282a; } + +.cust-help .text-center { text-align: center; } + +.cust-help .text-bold { font-weight: 700; } + +.cust-help .wrapper { margin: 0 !important; background-color: #fff; } + +.cust-help .header { border-bottom: 1px solid #dfe4ec; } + +.cust-help .header .dropdown-select .label { color: #1776ea; letter-spacing: 0.1px; } + +.cust-help .header .dropdown-select .label .icon { fill: currentColor; } + +.cust-help .header__logo { font-size: 18px; font-weight: 900; line-height: normal; color: rgb(197, 202, 212); } + +.cust-help .header__inner { display: -ms-flexbox; display: flex; -ms-flex-pack: justify; justify-content: space-between; -ms-flex-align: center; align-items: center; padding: 13px 0; } + +.cust-help .contr { max-width: 1070px; width: 100%; margin: 0 auto; padding: 0 15px; } + +.cust-help .btn:hover .icon { fill: #002d73; } + +.tabbed__head { margin: 0; border-bottom: 2px solid #dfe4ec; display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; } + +.tabbed__head .tabbed__head_tabs { display: -ms-flexbox; display: flex; -ms-flex-align: end; align-items: flex-end; } + +.tabbed__head .tabbed__head_tabs li { min-width: 150px; padding: 6px 16px; text-align: center; cursor: pointer; font-size: 14px; font-weight: 700; line-height: 1.57; letter-spacing: 0.1px; color: #6b7480; display: -ms-inline-flexbox; display: inline-flex; -ms-flex-align: center; align-items: center; -ms-flex-pack: center; justify-content: center; border-bottom: 2px solid #dfe4ec; transition: all 250ms ease; margin-bottom: -2px; } + +.tabbed__head .tabbed__head_tabs li:not(.current):hover { background-color: #f5f8ff; } + +.tabbed__head .tabbed__head_tabs li b { font-weight: bold; margin-left: 6px; } + +.tabbed__head .tabbed__head_tabs li.current { border-bottom-color: #4c6587; color: #26282a; } + +.tabbed__tabs .tabbed__tabs_tab { display: -ms-flexbox; display: flex; -ms-flex-pack: justify; justify-content: space-between; -ms-flex-wrap: wrap; flex-wrap: wrap; display: none; } + +.tabbed__tabs .tabbed__tabs_tab.is-visible { display: -ms-flexbox; display: flex; } + +.icon-in-circle { width: 40px; height: 40px; -ms-flex-negative: 0; flex-shrink: 0; display: -ms-inline-flexbox; display: inline-flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; background-color: #f5f8ff; border-radius: 50%; } + +.icon-in-circle .icon { fill: #959eb0; font-size: 20px; } + +.nav { display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-wrap: wrap; flex-wrap: wrap; margin: 16px 0; } + +.navlink { display: -ms-inline-flexbox; display: inline-flex; -ms-flex-align: center; align-items: center; width: 100%; max-width: 344px; margin: 16px; padding: 16px; box-shadow: 0 4px 8px 0 rgba(38, 40, 42, 0.1); background-color: #ffffff; letter-spacing: 0.1px; color: #6b7480; transition: 0.3s all ease; } + +.navlink:hover { box-shadow: 0 8px 16px 0 rgba(38, 40, 42, 0.1); } + +.navlink .navlink__title { font-size: 14px; font-weight: 700; line-height: 1.5; color: #002d73; } + +.navlink .navlink__descr { font-size: 12px; } + +.navlink .icon-in-circle { margin-right: 12px; } + +.article { margin-top: 44px; } + +.article .block__head { padding-bottom: 32px; border-bottom: 1px solid #dfe4ec; } + +.article__heading { margin: 12px 0; font-size: 20px; font-weight: bold; line-height: 1.4; color: #002d73; letter-spacing: 0.1px; text-align: center; } + +.article__heading a { color: inherit; } + +.article__heading a .icon-in-circle + span { margin-left: 8px; } + +.article__footer { display: -ms-flexbox; display: flex; -ms-flex-direction: column; flex-direction: column; -ms-flex-align: center; align-items: center; margin: 32px 0 8px; } + +.article__footer .link { height: 40px; margin-top: 48px; font-size: 13px; font-weight: 600; text-align: center; color: #1776ea; } + +.btn-toggler { display: none; } + +.btn-toggler.is-opened { -ms-transform: scaleY(-1); transform: scaleY(-1); } + +.btn-toggler .icon { width: 10px !important; height: 10px !important; } + +@media screen and (max-width: 768px) { .ticket--article .ticket__body { -ms-flex-order: 1; order: 1; } + .ticket--article .ticket__params { -ms-flex-order: 2; order: 2; display: -ms-flexbox; display: flex; -ms-flex-direction: column; flex-direction: column; -ms-flex-flow: column-reverse; flex-flow: column-reverse; } + .ticket--article .ticket__params .params--block { margin-top: 32px; } + .btn-toggler { display: -ms-inline-flexbox; display: inline-flex; } + .params--block.collapsed-on-xs .accordion-title > span { display: none; } + .params--block.collapsed-on-xs .accordion-body { display: none; } + .block--head > .d-flex { -ms-flex-wrap: wrap; flex-wrap: wrap; } } + +.preview { display: -ms-flexbox; display: flex; width: 100%; padding: 24px 16px; border-bottom: 1px solid #dfe4ec; } + +.preview:hover { background-color: #f9fafd; } + +.preview:hover .icon-in-circle .icon { fill: #1776ea; } + +.preview .icon-in-circle { margin-top: -8px; margin-right: 12px; } + +.preview .preview__title { margin-bottom: 10px; font-size: 16px; font-weight: bold; line-height: 1.38; letter-spacing: 0.11px; color: #1776ea; } + +@media screen and (max-width: 580px) { .preview { padding: 24px 0; -ms-flex-wrap: wrap; flex-wrap: wrap; } + .preview .preview__text { width: 100%; -ms-flex-order: 3; order: 3; } } + +.rate { display: -ms-inline-flexbox; display: inline-flex; margin-left: auto; font-size: 12px; letter-spacing: 0.1px; } + +.rate .icon { margin: 0 2px; } + +.rate .star-rate + span { font-size: 12px; margin-left: 8px; } + +.preview__text { max-width: 678px; } + +.preview__text p { margin-top: 8px; } + +.block__head { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; -ms-flex-pack: center; justify-content: center; text-align: center; } + +.content { margin: 48px 0 56px; } + +.content .block__head { margin-bottom: 16px; } + +.topics { display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; padding: 32px 22px 0; border-radius: 2px; box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); } + +@media screen and (max-width: 580px) { .topics { box-shadow: none; padding: 32px 0 0; } + .topics .topics__list { padding-left: 16px; } } + +.topics__block { width: 50%; margin-bottom: 16px; } + +@media screen and (max-width: 580px) { .topics__block { width: 100%; } } + +.topics__title { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; font-size: 16px; font-weight: bold; line-height: 1.38; letter-spacing: 0.11px; color: #002d73; } + +.topics__title .icon { font-size: 18px; fill: #959eb0; margin-right: 8px; } + +.topics__list { color: #1776ea; padding-left: 46px; } + +.topics__list li { position: relative; } + +.topics__list li:before { content: ""; position: absolute; left: -14px; top: 0.7em; display: inline-block; width: 4px; height: 4px; border-radius: 50%; background-color: currentColor; } + +.topics__list li.text-bold::before { display: none; } + +.topics__list a { display: -ms-flexbox; display: flex; margin: 16px 0; line-height: 1.57; letter-spacing: 0.1px; color: #1776ea; } + +.topics__list a:hover { color: #025cca; } + +.divider { display: block; margin: 32px 0; height: 1px; background-color: #dfe4ec; } + +.form-group.required label:after, .form-group.required .label:after, label.required:after, .label.required:after { content: "*"; position: absolute; right: -0.5em; font-size: 18px; font-weight: bold; line-height: 1.22; color: #e02020; } + +.label { display: -ms-inline-flexbox; display: inline-flex; position: relative; color: #959eb0; } + +.article__heading--form { margin: 0px 0 32px; } + +.article__heading + .article-heading-tip { margin-top: -32px; } + +.article-heading-tip { display: -ms-flexbox; display: flex; -ms-flex-align: start; align-items: flex-start; -ms-flex-pack: center; justify-content: center; margin: 4px auto 32px; text-align: center; font-size: 12px; letter-spacing: 0.1px; color: #6b7480; } + +.form-submit-ticket { margin-bottom: 24px; padding: 24px 32px 56px; border-radius: 2px; box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); background-color: #fff; } + +.form-submit-ticket .form-groups { max-width: 320px; } + +.form-submit-ticket .form-groups.centered { margin: auto; } + +.form-submit-ticket .form-group, .form-submit-ticket .param { max-width: 560px; margin-bottom: 32px; } + +.form-submit-ticket textarea.form-control { height: 200px; } + +.captcha-block { margin: 24px auto; max-width: 288px; text-align: center; } + +.captcha-block .label { margin-top: 4px; } + +.captcha-block .form-captcha { position: relative; display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; margin: 16px 0; } + +.captcha-block .form-captcha img { width: 100%; } + +.btn-refresh { position: absolute; top: 0; bottom: 0; right: -40px; margin: auto; } + +.btn-refresh .icon { fill: #c5cad4; font-size: 16px; } + +.form .label { display: -ms-inline-flexbox; display: inline-flex; } + +.form h3 { font-size: 16px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: 1.38; letter-spacing: 0.1px; } + +.attach .block--attach { margin-top: 0; } + +.attach .attach-tooltype { margin-top: 8px; } + +.attach .attach-tooltype > span { font-size: 12px; font-weight: normal; font-style: italic; font-stretch: normal; line-height: 1.5; letter-spacing: 0.1px; color: #6b7480; margin-right: 4px; } + +.attach .tooltype ul li { margin-bottom: 8px; padding-left: 12px; position: relative; } + +.attach .tooltype ul li:last-child { margin-bottom: 0; } + +.attach .tooltype ul li::before { content: ""; display: block; width: 4px; height: 4px; border-radius: 50%; background-color: #6b7480; position: absolute; top: 6px; left: 0; } + +.param { display: block; } + +.param .checkbox-custom { margin-top: 16px; } + +.param .label { margin-right: 8px; } + +.param .label.required { margin-right: 16px; } + +.param.calendar { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; } + +.param.calendar h3 { margin-right: 16px; } + +.param.calendar .calendar--button { position: relative; margin-right: 16px; } + +.param.calendar .calendar--button input { width: 48px; height: 48px; position: absolute; top: 0; left: 0; visibility: hidden; } + +.param.calendar .calendar--button button { width: 48px; height: 48px; background-color: #fff; border: none; outline: none; display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; border-radius: 2px; box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); transition: all 250ms ease; position: relative; z-index: 1; cursor: pointer; } + +.param.calendar .calendar--button button svg { transition: all 250ms ease; } + +.param.calendar .calendar--button button.active svg { fill: #002d73; } + +.param.calendar .calendar--button button:hover { box-shadow: 0 8px 16px 0 rgba(38, 40, 42, 0.1); } + +.param.calendar .calendar--button button .icon-calendar { width: 20px; height: 20px; } + +.param.calendar .calendar--value { font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; color: #6b7480; padding-right: 25px; position: relative; display: none; } + +.param.calendar .calendar--value input { display: none; } + +.param.calendar .calendar--value .close { display: block; width: 16px; height: 16px; display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; cursor: pointer; position: absolute; top: 3px; right: 0; } + +.param.calendar .calendar--value .close:hover svg { fill: #002d73; } + +.param.calendar .calendar--value .close svg { width: 6px; height: 6px; fill: #959eb0; transition: all 250ms ease; } + +.param--attach { display: -ms-flexbox; display: flex; -ms-flex-align: start; align-items: flex-start; } + +.param--attach .label { margin-right: 22px; } + +.form-footer { display: -ms-flexbox; display: flex; -ms-flex-direction: column; flex-direction: column; -ms-flex-align: center; align-items: center; -ms-flex-pack: center; justify-content: center; } + +.form-footer .btn { width: 240px; height: 56px; } + +.form-footer .link { display: -ms-inline-flexbox; display: inline-flex; -ms-flex-align: center; align-items: center; height: 40px; margin-top: 32px; font-size: 13px; font-weight: 600; text-align: center; color: #1776ea; } + +.ticket__body_block .block--head { margin-top: 0; } + +@media screen and (max-width: 768px) { .ticket { -ms-flex-wrap: wrap; flex-wrap: wrap; -ms-flex-pack: end; justify-content: flex-end; } + .ticket__body { width: 100%; margin-right: 0; -ms-flex-order: 2; order: 2; } + .ticket__params { width: 100%; margin-bottom: 32px; } } + +.block--head { -ms-flex-pack: justify; justify-content: space-between; } + +.block--head .contact { margin-right: 16px; } + +.block--head .contact span + * { margin-left: 8px; } + +.block--head .contact span + span { color: #26282a !important; } + +.btn-action { padding: 0; } + +.btn-action .icon { fill: #959eb0; font-size: 16px; } + +.ticket__body_block { padding: 16px 24px; } + +.ticket__body_block.naked { padding: 0; box-shadow: none; } + +.ticket__block-footer { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; -ms-flex-pack: end; justify-content: flex-end; margin-top: 24px; letter-spacing: 0.1px; color: #959eb0; } + +.ticket__block-footer > * { margin-left: 12px; } + +.ticket { display: -ms-flexbox; display: flex; } + +.ticket__params .params--block { margin: 0; } + +.ticket__params .params--block .accordion-title .link { display: -ms-inline-flexbox; display: inline-flex; -ms-flex-align: center; align-items: center; } + +.ticket__params .params--block .accordion-title .link .icon { fill: currentColor; } + +.ticket__params .params--block + .params--block { margin-top: 32px; } + +.ticket__params .params--block .accordion-body { padding-top: 0; } + +.ticket__params .params--block .list { color: #1776ea; padding-left: 10px; } + +.ticket__params .params--block .list a { line-height: 1.57; letter-spacing: 0.1px; color: inherit; } + +.ticket__params .params--block .list li { position: relative; margin-top: 16px; } + +.ticket__params .params--block .list li:before { content: ""; position: absolute; left: -10px; top: 0.7em; display: inline-block; width: 4px; height: 4px; border-radius: 50%; background-color: currentColor; } + +.ticket__params .params--block .list li:first-child { margin-top: 0; } + +.form--reply { margin: 24px 0; } + +.form--reply textarea { height: 200px !important; } + +.form__submit { display: -ms-flexbox; display: flex; -ms-flex-direction: column; flex-direction: column; -ms-flex-align: center; align-items: center; } + +.with-label { cursor: default; } + +#loader { position: fixed; top: 0; right: 0; bottom: 0; left: 0; background-color: #fff; z-index: 100; } + +.wrapper { display: -ms-flexbox; display: flex; width: 100%; min-height: 100vh; font-family: "Lato", Arial, sans-serif; color: #26282a; font-size: 14px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; background-color: #fcfcfc; } + +@media screen and (max-width: 900px) { .wrapper { margin-top: 48px; } } + +.main { display: -ms-flexbox; display: flex; -ms-flex-direction: column; flex-direction: column; width: 100%; } + +.main__content { -ms-flex-positive: 1; flex-grow: 1; } + +.clearfix { overflow: auto; } + +.notification { + background-color: #fff; + box-shadow: 0 4px 8px 0 rgba(0, 41, 89, 0.1); + padding: 20px 28px 20px 28px; + font-family: "Lato", Arial, sans-serif; + position: relative; + display: block; + margin-bottom: 24px; +} + +.notification::before { + content: ""; + width: 8px; + height: 100%; + position: absolute; + top: 0; + left: 0; +} + +.notification.red { + background-color: #fff5f5; +} + +.notification.red::before { + background-color: #e64342; +} + +.notification.orange { + background-color: #ffffcc; +} + +.notification.orange::before { + background-color: #eeb707; +} + +.notification.green { + background-color: #f0fff4; +} + +.notification.green::before { + background-color: #38bc7d; +} + +.notification.blue { + background-color: #ebf8ff; +} + +.notification.blue::before { + background-color: #002d73; +} + +.notification b { + font-weight: bold; +} + +.notification-flash { width: 320px; z-index: 20; background-color: #fff; box-shadow: 0 4px 8px 0 rgba(0, 41, 89, 0.1); padding: 24px 32px 16px 32px; font-family: "Lato", Arial, sans-serif; position: absolute; top: 144px; right: 32px; display: none; } + +.notification-flash::before { content: ""; width: 8px; height: 100%; position: absolute; top: 0; left: 0; } + +.notification-flash.red::before { background-color: #e64342; } + +.notification-flash.orange::before { background-color: #eeb707; } + +.notification-flash.green::before { background-color: #38bc7d; } + +.notification-flash.blue::before { background-color: #002d73; } + +.notification-flash .close { width: 16px; height: 16px; display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; position: absolute; top: 8px; right: 8px; cursor: pointer; } + +.notification-flash .close svg { width: 8px; height: 8px; fill: #c5cad4; } + +.notification-flash .notification--title { font-size: 14px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; color: #26282a; } + +.notification-flash .notification--text { margin-top: 4px; font-size: 12px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.5; letter-spacing: 0.1px; color: #6b7480; } + +.notification-flash .btn { margin-top: 16px; width: 96px; } + +@media screen and (max-width: 900px) { .notification-flash { top: 0 !important; right: 0; width: 100%; position: fixed; } + .notification-flash .close { width: 32px; height: 32px; top: 50%; -ms-transform: translateY(-50%); transform: translateY(-50%); } } + +.tooltype { display: -ms-inline-flexbox; display: inline-flex; vertical-align: middle; cursor: pointer; position: relative; } + +.tooltype .icon-info { width: 16px; height: 16px; fill: #959eb0; transition: all 250ms ease; } + +.tooltype:hover .icon-info { fill: #002d73; } + +.tooltype:hover .tooltype__content { display: block; } + +.tooltype .tooltype__content { position: absolute; box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); z-index: 10; font-family: "Lato", Arial, sans-serif; font-size: 12px; font-weight: normal; font-style: normal; font-stretch: normal; line-height: 1.5; letter-spacing: 0.1px; color: #6b7480; text-transform: initial; width: 260px; display: none; } + +.tooltype .tooltype__content .tooltype__wrapper { background-color: #fff; padding: 12px 24px 14px 14px; position: relative; z-index: 1; white-space: normal; } + +.tooltype .tooltype__content a { color: #1776ea; transition: all 250ms ease; } + +.tooltype .tooltype__content a:hover { color: #025cca; } + +.tooltype .tooltype__content::before { content: ""; display: block; width: 8px; height: 8px; background-color: #fff; -ms-transform: rotate(45deg); transform: rotate(45deg); position: absolute; box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); z-index: 0; } + +@media screen and (max-width: 900px) { .tooltype .tooltype__content { position: fixed !important; top: 50% !important; left: 50% !important; -ms-transform: translate(-50%, -50%) !important; transform: translate(-50%, -50%) !important; } + .tooltype .tooltype__content::before { display: none; } } + +.tooltype.right .tooltype__content { top: 50%; -ms-transform: translateY(-50%); transform: translateY(-50%); left: calc(100% + 4px); } + +.tooltype.right .tooltype__content::before { top: calc(50% - 4px); left: -4px; } + +.tooltype.top .tooltype__content { left: 50%; -ms-transform: translateX(-50%); transform: translateX(-50%); bottom: calc(100% + 4px); } + +.tooltype.top .tooltype__content::before { left: calc(50% - 4px); bottom: -4px; } + +.datepicker { font-family: "Lato", Arial, sans-serif; font-size: 14px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; width: 368px; box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); border: none; } + +.datepicker .datepicker--pointer { bottom: 20px; box-shadow: 0 2px 8px 0 rgba(38, 40, 42, 0.1); border: none; } + +.datepicker .datepicker--cells-years, .datepicker .datepicker--years { height: auto; } + +.datepicker .datepicker--cells-years .datepicker--cell, .datepicker .datepicker--years .datepicker--cell { margin: 0 8px !important; } + +.datepicker .datepicker--cells-months { height: auto; } + +.datepicker .datepicker--cells-months .datepicker--cell { margin: 0 8px !important; } + +.datepicker .datepicker--content { padding: 4px 16px; background-color: #fff; } + +.datepicker .datepicker--nav { border-bottom: none; -ms-flex-pack: center; justify-content: center; font-weight: bold; color: #26282a; background-color: #fff; height: 48px; } + +.datepicker .datepicker--nav i { color: #26282a; } + +.datepicker .datepicker--cells { -ms-flex-pack: justify; justify-content: space-between; } + +.datepicker .datepicker--cells .datepicker--cell { width: 40px; height: 40px; border-radius: 50%; margin: 0 3px 8px 3px; transition: all 250ms ease; } + +.datepicker .datepicker--cells .datepicker--cell.-current- { color: #38bc7d; } + +.datepicker .datepicker--cells .datepicker--cell.-selected- { background-color: #38bc7d; color: #fff; } + +.datepicker .datepicker--cells .datepicker--cell:hover:not(.-selected-) { background-color: #f5f8ff; } + +.datepicker .datepicker--days-names { border-bottom: 1px solid #dfe4ec; margin: 0; padding-bottom: 8px; margin-bottom: 8px; } + +.datepicker .datepicker--days-names .datepicker--day-name { width: 48px; font-family: "Lato", Arial, sans-serif; color: #959eb0; font-size: 14px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: 1.57; letter-spacing: 0.1px; text-align: center; text-transform: none; } + +@media screen and (max-width: 900px) { .datepicker.active { top: 48vh !important; left: 50vw !important; -ms-transform: translate(-50%, -50%) !important; transform: translate(-50%, -50%) !important; position: fixed; } } + +.notification-bar { position: fixed; top: 0; left: 0; width: 100%; display: none; background-color: #1776ea; } + +.notification-bar .close { display: block; width: 24px; height: 24px; position: absolute; right: 40px; top: calc(50% - 12px); cursor: pointer; } + +.notification-bar .close:hover svg { fill: #dfe4ec; } + +.notification-bar .close svg { width: 8px; height: 8px; fill: #fff; } + +.notification-bar .notification--text { color: #fff; display: -ms-flexbox; display: flex; -ms-flex-pack: center; justify-content: center; -ms-flex-align: center; align-items: center; width: 100%; min-height: 48px; } + +.notification-bar .btn { color: #fff; border-color: #fff; width: 96px; height: 32px; margin-left: 32px; } + +.notification-bar.green { background-color: #38bc7d; } + +.notification-bar.red { background-color: #e64342; } + +.notification-bar.orange { background-color: #eeb707; } + +.notification-bar.blue { background-color: #002d73; } + +.notification-bar.white { background-color: #fff; border-top: solid 1px #d4d6e3; border-bottom: solid 1px #d4d6e3; } + +.notification-bar.white .notification--text { color: #26282a; } + +.notification-bar.white .btn { color: #002d73; border-color: #002d73; } + +.notification-bar.white svg { fill: #c5cad4; } + +.star-rate { position: relative; width: 84px; height: 15px; } + +.star-rate .icon-star-stroke { position: absolute; top: 0; left: 0; z-index: 1; width: 84px; height: 15px; } + +.star-rate .star-filled { position: absolute; top: 0; left: 0; width: 0; height: 15px; overflow: hidden; line-height: 1; } + +.star-rate .star-filled .icon-star-filled { width: 84px; height: 15px; } + +.star-rate.rate-05 .star-filled, .star-rate.rate-5 .star-filled { z-index: 2; width: 10%; } + +.star-rate.rate-10 .star-filled { z-index: 2; width: 20%; } + +.star-rate.rate-15 .star-filled { z-index: 2; width: 30%; } + +.star-rate.rate-20 .star-filled { z-index: 2; width: 40%; } + +.star-rate.rate-25 .star-filled { z-index: 2; width: 50%; } + +.star-rate.rate-30 .star-filled { z-index: 2; width: 60%; } + +.star-rate.rate-35 .star-filled { z-index: 2; width: 70%; } + +.star-rate.rate-40 .star-filled { z-index: 2; width: 80%; } + +.star-rate.rate-45 .star-filled { z-index: 2; width: 90%; } + +.star-rate.rate-50 .star-filled { z-index: 2; width: 100%; } + +.main__content.notice-flash { margin-top: 20px; } \ No newline at end of file diff --git a/hesk/theme/hesk3/customer/css/app.min.css b/hesk/theme/hesk3/customer/css/app.min.css new file mode 100644 index 0000000..38fe53e --- /dev/null +++ b/hesk/theme/hesk3/customer/css/app.min.css @@ -0,0 +1 @@ +@charset "UTF-8";a,abbr,acronym,address,applet,article,aside,audio,b,big,blockquote,body,canvas,caption,center,cite,code,dd,del,details,dfn,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,html,i,iframe,img,ins,kbd,label,legend,li,mark,menu,nav,object,ol,output,p,pre,q,ruby,s,samp,section,small,span,strike,strong,sub,summary,sup,table,tbody,td,tfoot,th,thead,time,tr,tt,u,ul,var,video{margin:0;padding:0;border:0;font-size:100%;vertical-align:baseline}article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block}body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}blockquote:after,blockquote:before{content:'';content:none}q:after,q:before{content:'';content:none}table{border-collapse:collapse;border-spacing:0}a{text-decoration:none;color:#26282a;transition:color 250ms ease}a:hover{text-decoration:none}.footer a,.notification a{text-decoration:underline!important;color:#1776ea}.footer a:hover,.notification a:hover{text-decoration:none!important}.icon-01-normal-knowledge-b{width:1.2em;height:1em;fill:none}.icon-01-normal-team{width:1.41em;height:1em;fill:#FFF}.icon-01-normal-tickets{width:.82em;height:1em;fill:#FFF}.icon-actions{width:1.23em;height:1em;fill:#1776EA}.icon-add{width:1em;height:1em;fill:#1776EA}.icon-anonymize{width:.88em;height:1em;fill:#C5CAD4}.icon-assign-no{width:.96em;height:1em;fill:#26282A}.icon-assign-plus{width:1em;height:1em;fill:#26282A}.icon-assign{width:.86em;height:1em;fill:#26282A}.icon-attach{width:1em;height:1em;fill:#C5CAD4}.icon-back{width:3.33em;height:1em;fill:#26282A}.icon-calendar{width:1em;height:1em;fill:#1776EA}.icon-categories{width:1em;height:1em;fill:#FFF}.icon-chevron-down{width:1.33em;height:1em;fill:#26282A}.icon-chevron-left{width:1em;height:1em;fill:initial}.icon-chevron-right{width:1em;height:1em;fill:initial}.icon-close-mobile{width:1em;height:1em;fill:#FFF}.icon-close{width:1em;height:1em;fill:#C5CAD4}.icon-cross{width:1em;height:1em;fill:#C5CAD4}.icon-delete{width:.94em;height:1em;fill:#C5CAD4}.icon-dismiss{width:1em;height:1em;fill:#1776EA}.icon-document{width:.83em;height:1em;fill:#959EB0}.icon-down{width:1.33em;height:1em;fill:#26282A}.icon-edit-ticket{width:1em;height:1em;fill:#C5CAD4}.icon-edit{width:1em;height:1em;fill:#1776EA}.icon-export{width:1em;height:1em;fill:#C5CAD4}.icon-eye-close{width:1.33em;height:1em;fill:#C5CAD4}.icon-eye-open{width:1em;height:1em;fill:#C5CAD4}.icon-filters{width:1em;height:1em;fill:#1776EA}.icon-folder{width:1.22em;height:1em;fill:#959EB0}.icon-info{width:1em;height:1em;fill:#959EB0}.icon-inquiries{width:1em;height:1em;fill:#959EB0}.icon-knowledge{width:1.2em;height:1em;fill:#FFF}.icon-label{width:1.33em;height:1em;fill:#959EB0}.icon-lock{width:.88em;height:1em;fill:#C5CAD4}.icon-log-out{width:1em;height:1em;fill:#959EB0}.icon-mail-small{width:1.14em;height:1em;fill:#C5CAD4}.icon-mail{width:1.22em;height:1em;fill:#C5CAD4}.icon-menu-mobile{width:1.14em;height:1em;fill:#FFF}.icon-menu{width:1.43em;height:1em;fill:#FFF}.icon-merge{width:1em;height:1em;fill:#26282A}.icon-move-to{width:1em;height:1em;fill:#26282A}.icon-no-photo{width:.68em;height:1em;fill:#FFF}.icon-note{width:1em;height:1em;fill:#C5CAD4}.icon-notes-2{width:1em;height:1em;fill:none}.icon-notification{width:.91em;height:1em;fill:#C5CAD4}.icon-pause{width:1em;height:1em;fill:#959EB0}.icon-pin{width:.63em;height:1em;fill:#959EB0}.icon-print{width:1em;height:1em;fill:#C5CAD4}.icon-priority{width:1em;height:1em;fill:#26282A}.icon-refresh{width:1em;height:1em;fill:#C5CAD4}.icon-reports{width:1.22em;height:1em;fill:#FFF}.icon-search-type-knowledge{width:1.2em;height:1em;fill:#FFF}.icon-search-type-team{width:1.41em;height:1em;fill:#FFF}.icon-search-type-templates{width:1em;height:1em;fill:#FFF}.icon-search-type-tickets{width:.82em;height:1em;fill:#FFF}.icon-search{width:1em;height:1em;fill:#C5CAD4}.icon-select{width:.5em;height:1em;fill:#959EB0}.icon-settings{width:1em;height:1em;fill:#FFF}.icon-star-filled{width:5.6em;height:1em;fill:#EEB707}.icon-star-stroke{width:5.6em;height:1em;fill:#DFE4EC}.icon-status{width:.88em;height:1em;fill:#26282A}.icon-submit-ticket{width:.83em;height:1em;fill:#959EB0}.icon-support{width:1em;height:1em;fill:#959EB0}.icon-tag{width:1.33em;height:1em;fill:#C5CAD4}.icon-team{width:1.41em;height:1em;fill:#FFF}.icon-templates{width:1em;height:1em;fill:#FFF}.icon-tick{width:1.38em;height:1em;fill:#002D73}.icon-tickets{width:.82em;height:1em;fill:#FFF}.icon-tools{width:1em;height:1em;fill:#FFF}.icon-warning{width:1em;height:1em;fill:initial}.scroll-wrapper{overflow:hidden!important;padding:0!important;position:relative}.scroll-wrapper > .scroll-content{border:none!important;box-sizing:content-box!important;height:auto;left:0;margin:0;max-height:none;max-width:none!important;overflow:scroll!important;padding:0;position:relative!important;top:0;width:auto!important}.scroll-wrapper > .scroll-content::-webkit-scrollbar{height:0;width:0}.scroll-wrapper.scroll--rtl{direction:rtl}.scroll-element{box-sizing:content-box;display:none}.scroll-element div{box-sizing:content-box}.scroll-element .scroll-bar,.scroll-element .scroll-arrow{cursor:default}.scroll-element.scroll-x.scroll-scrollx_visible,.scroll-element.scroll-y.scroll-scrolly_visible{display:block}.scroll-textarea > .scroll-content{overflow:hidden!important}.scroll-textarea > .scroll-content > textarea{border:none!important;box-sizing:border-box;height:100%!important;margin:0;max-height:none!important;max-width:none!important;overflow:scroll!important;outline:none;padding:2px;position:relative!important;top:0;width:100%!important}.scroll-textarea > .scroll-content > textarea::-webkit-scrollbar{height:0;width:0}.scrollbar-inner > .scroll-element,.scrollbar-inner > .scroll-element div{border:none;margin:0;padding:0;position:absolute;z-index:10}.scrollbar-inner > .scroll-element div{display:block;height:100%;left:0;top:0;width:100%}.scrollbar-inner > .scroll-element.scroll-x{bottom:2px;height:8px;left:0;width:100%}.scrollbar-inner > .scroll-element.scroll-y{height:100%;right:2px;top:0;width:8px}.scrollbar-inner > .scroll-element .scroll-element_outer{overflow:hidden}.scrollbar-inner > .scroll-element .scroll-element_outer,.scrollbar-inner > .scroll-element .scroll-element_track,.scrollbar-inner > .scroll-element .scroll-bar{border-radius:8px}.scrollbar-inner > .scroll-element .scroll-element_track,.scrollbar-inner > .scroll-element .scroll-bar{-ms-filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=40);filter:alpha(opacity=40);opacity:.4}.scrollbar-inner > .scroll-element .scroll-element_track{background-color:#e0e0e0}.scrollbar-inner > .scroll-element .scroll-bar{background-color:#c2c2c2}.scrollbar-inner > .scroll-element:hover .scroll-bar{background-color:#919191}.scrollbar-inner > .scroll-element.scroll-draggable .scroll-bar{background-color:#919191}.scrollbar-inner > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_track{left:-12px}.scrollbar-inner > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_track{top:-12px}.scrollbar-inner > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_size{left:-12px}.scrollbar-inner > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_size{top:-12px}.scrollbar-outer > .scroll-element,.scrollbar-outer > .scroll-element div{border:none;margin:0;padding:0;position:absolute;z-index:10}.scrollbar-outer > .scroll-element{background-color:#fff}.scrollbar-outer > .scroll-element div{display:block;height:100%;left:0;top:0;width:100%}.scrollbar-outer > .scroll-element.scroll-x{bottom:0;height:12px;left:0;width:100%}.scrollbar-outer > .scroll-element.scroll-y{height:100%;right:0;top:0;width:4px}.scroll-element.scroll-x .scroll-element_outer{height:8px;top:2px}.scroll-element.scroll-y .scroll-element_outer{left:0;width:4px}.scroll-element .scroll-element_outer{overflow:hidden}.scroll-element .scroll-element_track{background-color:transparent}.scroll-element .scroll-element_outer,.scroll-element .scroll-element_track,.scroll-element .scroll-bar{border-radius:0}.scroll-element .scroll-bar{background-color:#dfe4ec}.scroll-element .scroll-bar:hover{background-color:#dfe4ec}.scroll-element.scroll-draggable .scroll-bar{background-color:#dfe4ec}.scrollbar-outer > .scroll-content.scroll-scrolly_visible{left:-12px;margin-left:12px}.scrollbar-outer > .scroll-content.scroll-scrollx_visible{top:-12px;margin-top:12px}.scrollbar-outer > .scroll-element.scroll-x .scroll-bar{min-width:10px}.scrollbar-outer > .scroll-element.scroll-y .scroll-bar{min-height:10px}.scrollbar-outer > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_track{left:-14px}.scrollbar-outer > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_track{top:-14px}.scrollbar-outer > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_size{left:-14px}.scrollbar-outer > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_size{top:-14px}.scrollbar-macosx > .scroll-element,.scrollbar-macosx > .scroll-element div{background:none;border:none;margin:0;padding:0;position:absolute;z-index:10}.scrollbar-macosx > .scroll-element div{display:block;height:100%;left:0;top:0;width:100%}.scrollbar-macosx > .scroll-element .scroll-element_track{display:none}.scrollbar-macosx > .scroll-element .scroll-bar{background-color:#6C6E71;display:block;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=0);filter:alpha(opacity=0);opacity:0;border-radius:7px;transition:opacity .2s linear}.scrollbar-macosx:hover > .scroll-element .scroll-bar,.scrollbar-macosx > .scroll-element.scroll-draggable .scroll-bar{-ms-filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=70);filter:alpha(opacity=70);opacity:.7}.scrollbar-macosx > .scroll-element.scroll-x{bottom:0;height:0;left:0;min-width:100%;overflow:visible;width:100%}.scrollbar-macosx > .scroll-element.scroll-y{height:100%;min-height:100%;right:0;top:0;width:0}.scrollbar-macosx > .scroll-element.scroll-x .scroll-bar{height:7px;min-width:10px;top:-9px}.scrollbar-macosx > .scroll-element.scroll-y .scroll-bar{left:-9px;min-height:10px;width:7px}.scrollbar-macosx > .scroll-element.scroll-x .scroll-element_outer{left:2px}.scrollbar-macosx > .scroll-element.scroll-x .scroll-element_size{left:-4px}.scrollbar-macosx > .scroll-element.scroll-y .scroll-element_outer{top:2px}.scrollbar-macosx > .scroll-element.scroll-y .scroll-element_size{top:-4px}.scrollbar-macosx > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_size{left:-11px}.scrollbar-macosx > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_size{top:-11px}.scrollbar-light > .scroll-element,.scrollbar-light > .scroll-element div{border:none;margin:0;overflow:hidden;padding:0;position:absolute;z-index:10}.scrollbar-light > .scroll-element{background-color:#fff}.scrollbar-light > .scroll-element div{display:block;height:100%;left:0;top:0;width:100%}.scrollbar-light > .scroll-element .scroll-element_outer{border-radius:10px}.scrollbar-light > .scroll-element .scroll-element_size{background:#dbdbdb;background:url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIxMDAlIiB5Mj0iMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2RiZGJkYiIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiNlOGU4ZTgiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);background:linear-gradient(to right,#dbdbdb 0%,#e8e8e8 100%);border-radius:10px}.scrollbar-light > .scroll-element.scroll-x{bottom:0;height:17px;left:0;min-width:100%;width:100%}.scrollbar-light > .scroll-element.scroll-y{height:100%;min-height:100%;right:0;top:0;width:17px}.scrollbar-light > .scroll-element .scroll-bar{background:#fefefe;background:url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIxMDAlIiB5Mj0iMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2ZlZmVmZSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiNmNWY1ZjUiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);background:linear-gradient(to right,#fefefe 0%,#f5f5f5 100%);border:1px solid #dbdbdb;border-radius:10px}.scrollbar-light > .scroll-content.scroll-scrolly_visible{left:-17px;margin-left:17px}.scrollbar-light > .scroll-content.scroll-scrollx_visible{top:-17px;margin-top:17px}.scrollbar-light > .scroll-element.scroll-x .scroll-bar{height:10px;min-width:10px;top:0}.scrollbar-light > .scroll-element.scroll-y .scroll-bar{left:0;min-height:10px;width:10px}.scrollbar-light > .scroll-element.scroll-x .scroll-element_outer{height:12px;left:2px;top:2px}.scrollbar-light > .scroll-element.scroll-x .scroll-element_size{left:-4px}.scrollbar-light > .scroll-element.scroll-y .scroll-element_outer{left:2px;top:2px;width:12px}.scrollbar-light > .scroll-element.scroll-y .scroll-element_size{top:-4px}.scrollbar-light > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_size{left:-19px}.scrollbar-light > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_size{top:-19px}.scrollbar-light > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_track{left:-19px}.scrollbar-light > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_track{top:-19px}.scrollbar-rail > .scroll-element,.scrollbar-rail > .scroll-element div{border:none;margin:0;overflow:hidden;padding:0;position:absolute;z-index:10}.scrollbar-rail > .scroll-element{background-color:#fff}.scrollbar-rail > .scroll-element div{display:block;height:100%;left:0;top:0;width:100%}.scrollbar-rail > .scroll-element .scroll-element_size{background-color:#999;background-color:rgba(0,0,0,0.3)}.scrollbar-rail > .scroll-element .scroll-element_outer:hover .scroll-element_size{background-color:#666;background-color:rgba(0,0,0,0.5)}.scrollbar-rail > .scroll-element.scroll-x{bottom:0;height:12px;left:0;min-width:100%;padding:3px 0 2px;width:100%}.scrollbar-rail > .scroll-element.scroll-y{height:100%;min-height:100%;padding:0 2px 0 3px;right:0;top:0;width:12px}.scrollbar-rail > .scroll-element .scroll-bar{background-color:#d0b9a0;border-radius:2px;box-shadow:1px 1px 3px rgba(0,0,0,0.5)}.scrollbar-rail > .scroll-element .scroll-element_outer:hover .scroll-bar{box-shadow:1px 1px 3px rgba(0,0,0,0.6)}.scrollbar-rail > .scroll-content.scroll-scrolly_visible{left:-17px;margin-left:17px}.scrollbar-rail > .scroll-content.scroll-scrollx_visible{margin-top:17px;top:-17px}.scrollbar-rail > .scroll-element.scroll-x .scroll-bar{height:10px;min-width:10px;top:1px}.scrollbar-rail > .scroll-element.scroll-y .scroll-bar{left:1px;min-height:10px;width:10px}.scrollbar-rail > .scroll-element.scroll-x .scroll-element_outer{height:15px;left:5px}.scrollbar-rail > .scroll-element.scroll-x .scroll-element_size{height:2px;left:-10px;top:5px}.scrollbar-rail > .scroll-element.scroll-y .scroll-element_outer{top:5px;width:15px}.scrollbar-rail > .scroll-element.scroll-y .scroll-element_size{left:5px;top:-10px;width:2px}.scrollbar-rail > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_size{left:-25px}.scrollbar-rail > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_size{top:-25px}.scrollbar-rail > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_track{left:-25px}.scrollbar-rail > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_track{top:-25px}.scrollbar-dynamic > .scroll-element,.scrollbar-dynamic > .scroll-element div{background:none;border:none;margin:0;padding:0;position:absolute;z-index:10}.scrollbar-dynamic > .scroll-element div{display:block;height:100%;left:0;top:0;width:100%}.scrollbar-dynamic > .scroll-element.scroll-x{bottom:2px;height:7px;left:0;min-width:100%;width:100%}.scrollbar-dynamic > .scroll-element.scroll-y{height:100%;min-height:100%;right:2px;top:0;width:7px}.scrollbar-dynamic > .scroll-element .scroll-element_outer{opacity:.3;border-radius:12px}.scrollbar-dynamic > .scroll-element .scroll-element_size{background-color:#ccc;opacity:0;border-radius:12px;transition:opacity .2s}.scrollbar-dynamic > .scroll-element .scroll-bar{background-color:#6c6e71;border-radius:7px}.scrollbar-dynamic > .scroll-element.scroll-x .scroll-bar{bottom:0;height:7px;min-width:24px;top:auto}.scrollbar-dynamic > .scroll-element.scroll-y .scroll-bar{left:auto;min-height:24px;right:0;width:7px}.scrollbar-dynamic > .scroll-element.scroll-x .scroll-element_outer{bottom:0;top:auto;left:2px;transition:height .2s}.scrollbar-dynamic > .scroll-element.scroll-y .scroll-element_outer{left:auto;right:0;top:2px;transition:width .2s}.scrollbar-dynamic > .scroll-element.scroll-x .scroll-element_size{left:-4px}.scrollbar-dynamic > .scroll-element.scroll-y .scroll-element_size{top:-4px}.scrollbar-dynamic > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_size{left:-11px}.scrollbar-dynamic > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_size{top:-11px}.scrollbar-dynamic > .scroll-element:hover .scroll-element_outer,.scrollbar-dynamic > .scroll-element.scroll-draggable .scroll-element_outer{overflow:hidden;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=70);filter:alpha(opacity=70);opacity:.7}.scrollbar-dynamic > .scroll-element:hover .scroll-element_outer .scroll-element_size,.scrollbar-dynamic > .scroll-element.scroll-draggable .scroll-element_outer .scroll-element_size{opacity:1}.scrollbar-dynamic > .scroll-element:hover .scroll-element_outer .scroll-bar,.scrollbar-dynamic > .scroll-element.scroll-draggable .scroll-element_outer .scroll-bar{height:100%;width:100%;border-radius:12px}.scrollbar-dynamic > .scroll-element.scroll-x:hover .scroll-element_outer,.scrollbar-dynamic > .scroll-element.scroll-x.scroll-draggable .scroll-element_outer{height:20px;min-height:7px}.scrollbar-dynamic > .scroll-element.scroll-y:hover .scroll-element_outer,.scrollbar-dynamic > .scroll-element.scroll-y.scroll-draggable .scroll-element_outer{min-width:7px;width:20px}.scrollbar-chrome > .scroll-element,.scrollbar-chrome > .scroll-element div{border:none;margin:0;overflow:hidden;padding:0;position:absolute;z-index:10}.scrollbar-chrome > .scroll-element{background-color:#fff}.scrollbar-chrome > .scroll-element div{display:block;height:100%;left:0;top:0;width:100%}.scrollbar-chrome > .scroll-element .scroll-element_track{background:#f1f1f1;border:1px solid #dbdbdb}.scrollbar-chrome > .scroll-element.scroll-x{bottom:0;height:16px;left:0;min-width:100%;width:100%}.scrollbar-chrome > .scroll-element.scroll-y{height:100%;min-height:100%;right:0;top:0;width:16px}.scrollbar-chrome > .scroll-element .scroll-bar{background-color:#d9d9d9;border:1px solid #bdbdbd;cursor:default;border-radius:2px}.scrollbar-chrome > .scroll-element .scroll-bar:hover{background-color:#c2c2c2;border-color:#a9a9a9}.scrollbar-chrome > .scroll-element.scroll-draggable .scroll-bar{background-color:#919191;border-color:#7e7e7e}.scrollbar-chrome > .scroll-content.scroll-scrolly_visible{left:-16px;margin-left:16px}.scrollbar-chrome > .scroll-content.scroll-scrollx_visible{top:-16px;margin-top:16px}.scrollbar-chrome > .scroll-element.scroll-x .scroll-bar{height:8px;min-width:10px;top:3px}.scrollbar-chrome > .scroll-element.scroll-y .scroll-bar{left:3px;min-height:10px;width:8px}.scrollbar-chrome > .scroll-element.scroll-x .scroll-element_outer{border-left:1px solid #dbdbdb}.scrollbar-chrome > .scroll-element.scroll-x .scroll-element_track{height:14px;left:-3px}.scrollbar-chrome > .scroll-element.scroll-x .scroll-element_size{height:14px;left:-4px}.scrollbar-chrome > .scroll-element.scroll-y .scroll-element_outer{border-top:1px solid #dbdbdb}.scrollbar-chrome > .scroll-element.scroll-y .scroll-element_track{top:-3px;width:14px}.scrollbar-chrome > .scroll-element.scroll-y .scroll-element_size{top:-4px;width:14px}.scrollbar-chrome > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_size{left:-19px}.scrollbar-chrome > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_size{top:-19px}.scrollbar-chrome > .scroll-element.scroll-x.scroll-scrolly_visible .scroll-element_track{left:-19px}.scrollbar-chrome > .scroll-element.scroll-y.scroll-scrollx_visible .scroll-element_track{top:-19px}.selectize-control.plugin-drag_drop.multi > .selectize-input > div.ui-sortable-placeholder{visibility:visible!important;background:#f2f2f2!important;background:rgba(0,0,0,0.06)!important;border:0 none!important;box-shadow:inset 0 0 12px 4px #fff}.selectize-control.plugin-drag_drop .ui-sortable-placeholder::after{content:'!';visibility:hidden}.selectize-control.plugin-drag_drop .ui-sortable-helper{box-shadow:0 2px 5px rgba(0,0,0,0.2)}.selectize-dropdown-header{position:relative;padding:5px 8px;border-bottom:1px solid #d0d0d0;background:#f8f8f8;border-radius:3px 3px 0 0}.selectize-dropdown-header-close{position:absolute;right:8px;top:50%;color:#303030;opacity:.4;margin-top:-12px;line-height:20px;font-size:20px!important}.selectize-dropdown-header-close:hover{color:#000}.selectize-dropdown.plugin-optgroup_columns .optgroup{border-right:1px solid #f2f2f2;border-top:0 none;float:left;box-sizing:border-box}.selectize-dropdown.plugin-optgroup_columns .optgroup:last-child{border-right:0 none}.selectize-dropdown.plugin-optgroup_columns .optgroup:before{display:none}.selectize-dropdown.plugin-optgroup_columns .optgroup-header{border-top:0 none}.selectize-control.plugin-remove_button [data-value]{position:relative;padding-right:24px!important}.selectize-control.plugin-remove_button [data-value] .remove{z-index:1;position:absolute;top:0;right:0;bottom:0;width:17px;text-align:center;font-weight:700;font-size:12px;color:inherit;text-decoration:none;vertical-align:middle;display:inline-block;padding:2px 0 0;border-left:1px solid #d0d0d0;border-radius:0 2px 2px 0;box-sizing:border-box}.selectize-control.plugin-remove_button [data-value] .remove:hover{background:rgba(0,0,0,0.05)}.selectize-control.plugin-remove_button [data-value].active .remove{border-left-color:#cacaca}.selectize-control.plugin-remove_button .disabled [data-value] .remove:hover{background:none}.selectize-control.plugin-remove_button .disabled [data-value] .remove{border-left-color:#fff}.selectize-control.plugin-remove_button .remove-single{position:absolute;right:0;top:0;font-size:23px}.selectize-control{position:relative}.selectize-dropdown,.selectize-input,.selectize-input input{color:#303030;font-family:inherit;font-size:13px;line-height:18px;-webkit-font-smoothing:inherit}.selectize-input,.selectize-control.single .selectize-input.input-active{background:#fff;cursor:text;display:inline-block}.selectize-input{border:1px solid #d0d0d0;padding:8px;display:inline-block;width:100%;overflow:hidden;position:relative;z-index:1;box-sizing:border-box;box-shadow:inset 0 1px 1px rgba(0,0,0,0.1);border-radius:3px}.selectize-input.full{background-color:#fff}.selectize-input.disabled,.selectize-input.disabled *{cursor:default!important}.selectize-input.focus{box-shadow:inset 0 1px 2px rgba(0,0,0,0.15)}.selectize-input.dropdown-active{border-radius:3px 3px 0 0}.selectize-input > *{vertical-align:baseline;display:-moz-inline-stack;display:inline-block;zoom:1;*display:inline}.selectize-control.multi .selectize-input > div{cursor:pointer;margin:0 3px 3px 0;padding:2px 6px;background:#f2f2f2;color:#303030;border:0 solid #d0d0d0}.selectize-control.multi .selectize-input > div.active{background:#e8e8e8;color:#303030;border:0 solid #cacaca}.selectize-control.multi .selectize-input.disabled > div,.selectize-control.multi .selectize-input.disabled > div.active{color:#7d7d7d;background:#fff;border:0 solid #fff}.selectize-input > input{display:inline-block!important;padding:0!important;min-height:0!important;max-height:none!important;max-width:100%!important;margin:0 2px 0 0 !important;text-indent:0!important;border:0 none!important;background:none!important;line-height:inherit!important;-webkit-user-select:auto!important;box-shadow:none!important}.selectize-input > input::-ms-clear{display:none}.selectize-input > input:focus{outline:none!important}.selectize-input::after{content:' ';display:block;clear:left}.selectize-input.dropdown-active::before{content:' ';display:block;position:absolute;background:#f0f0f0;height:1px;bottom:0;left:0;right:0}.selectize-dropdown{position:absolute;z-index:10;border:1px solid #d0d0d0;background:#fff;margin:-1px 0 0;border-top:0 none;box-sizing:border-box;box-shadow:0 1px 3px rgba(0,0,0,0.1);border-radius:0 0 3px 3px}.selectize-dropdown [data-selectable]{cursor:pointer;overflow:hidden}.selectize-dropdown [data-selectable] .highlight{background:rgba(125,168,208,0.2);border-radius:1px}.selectize-dropdown .option,.selectize-dropdown .optgroup-header{padding:5px 8px}.selectize-dropdown .option,.selectize-dropdown [data-disabled],.selectize-dropdown [data-disabled] [data-selectable].option{cursor:inherit;opacity:.5}.selectize-dropdown [data-selectable].option{opacity:1}.selectize-dropdown .optgroup:first-child .optgroup-header{border-top:0 none}.selectize-dropdown .optgroup-header{color:#303030;background:#fff;cursor:default}.selectize-dropdown .active{background-color:#f5fafd;color:#495c68}.selectize-dropdown .active.create{color:#495c68}.selectize-dropdown .create{color:rgba(48,48,48,0.5)}.selectize-dropdown-content{overflow-y:auto;overflow-x:hidden;max-height:200px;-webkit-overflow-scrolling:touch}.selectize-control.single .selectize-input,.selectize-control.single .selectize-input input{cursor:pointer}.selectize-control.single .selectize-input.input-active,.selectize-control.single .selectize-input.input-active input{cursor:text}.selectize-control.single .selectize-input:after{content:' ';display:block;position:absolute;top:50%;right:15px;margin-top:-3px;width:0;height:0;border-style:solid;border-width:5px 5px 0;border-color:gray transparent transparent}.selectize-control.single .selectize-input.dropdown-active:after{margin-top:-4px;border-width:0 5px 5px;border-color:transparent transparent gray}.selectize-control.rtl.single .selectize-input:after{left:15px;right:auto}.selectize-control.rtl .selectize-input > input{margin:0 4px 0 -2px !important}.selectize-control .selectize-input.disabled{opacity:.5;background-color:#fafafa}.datepicker--cells{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap}.datepicker--cell{border-radius:4px;box-sizing:border-box;cursor:pointer;display:-ms-flexbox;display:flex;position:relative;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;height:32px;z-index:1}.datepicker--cell.-focus-{background:#f0f0f0}.datepicker--cell.-current-{color:#4EB5E6}.datepicker--cell.-current-.-focus-{color:#4a4a4a}.datepicker--cell.-current-.-in-range-{color:#4EB5E6}.datepicker--cell.-in-range-{background:rgba(92,196,239,0.1);color:#4a4a4a;border-radius:0}.datepicker--cell.-in-range-.-focus-{background-color:rgba(92,196,239,0.2)}.datepicker--cell.-disabled-{cursor:default;color:#aeaeae}.datepicker--cell.-disabled-.-focus-{color:#aeaeae}.datepicker--cell.-disabled-.-in-range-{color:#a1a1a1}.datepicker--cell.-disabled-.-current-.-focus-{color:#aeaeae}.datepicker--cell.-range-from-{border:1px solid rgba(92,196,239,0.5);background-color:rgba(92,196,239,0.1);border-radius:4px 0 0 4px}.datepicker--cell.-range-to-{border:1px solid rgba(92,196,239,0.5);background-color:rgba(92,196,239,0.1);border-radius:0 4px 4px 0}.datepicker--cell.-selected-,.datepicker--cell.-selected-.-current-{color:#fff;background:#5cc4ef}.datepicker--cell.-range-from-.-range-to-{border-radius:4px}.datepicker--cell.-selected-{border:none}.datepicker--cell.-selected-.-focus-{background:#45bced}.datepicker--cell:empty{cursor:default}.datepicker--days-names{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;margin:8px 0 3px}.datepicker--day-name{color:#FF9A19;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;-ms-flex:1;flex:1;text-align:center;text-transform:uppercase;font-size:.8em}.-only-timepicker- .datepicker--content,.datepicker--body,.datepicker-inline .datepicker--pointer{display:none}.datepicker--cell-day{width:14.28571%}.datepicker--cells-months{height:170px}.datepicker--cell-month{width:33.33%;height:25%}.datepicker--cells-years,.datepicker--years{height:170px}.datepicker--cell-year{width:25%;height:33.33%}.datepickers-container{position:absolute;left:0;top:0}@media print{.datepickers-container{display:none}}.datepicker{background:#fff;border:1px solid #dbdbdb;box-shadow:0 4px 12px rgba(0,0,0,0.15);border-radius:4px;box-sizing:content-box;font-family:Tahoma,sans-serif;font-size:14px;color:#4a4a4a;width:250px;position:absolute;left:-100000px;opacity:0;transition:opacity .3s ease,transform .3s ease,left 0 .3s;z-index:100}.datepicker.-from-top-{-ms-transform:translateY(-8px);transform:translateY(-8px)}.datepicker.-from-right-{-ms-transform:translateX(8px);transform:translateX(8px)}.datepicker.-from-bottom-{-ms-transform:translateY(8px);transform:translateY(8px)}.datepicker.-from-left-{-ms-transform:translateX(-8px);transform:translateX(-8px)}.datepicker.active{opacity:1;-ms-transform:translate(0);transform:translate(0);transition:opacity .3s ease,transform .3s ease,left 0 0}.datepicker-inline .datepicker{border-color:#d7d7d7;box-shadow:none;position:static;left:auto;right:auto;opacity:1;-ms-transform:none;transform:none}.datepicker--content{box-sizing:content-box;padding:4px}.datepicker--pointer{position:absolute;background:#fff;border-top:1px solid #dbdbdb;border-right:1px solid #dbdbdb;width:10px;height:10px;z-index:-1}.datepicker--nav-action:hover,.datepicker--nav-title:hover{background:#f0f0f0}.-top-center- .datepicker--pointer,.-top-left- .datepicker--pointer,.-top-right- .datepicker--pointer{top:calc(100% - 4px);-ms-transform:rotate(135deg);transform:rotate(135deg)}.-right-bottom- .datepicker--pointer,.-right-center- .datepicker--pointer,.-right-top- .datepicker--pointer{right:calc(100% - 4px);-ms-transform:rotate(225deg);transform:rotate(225deg)}.-bottom-center- .datepicker--pointer,.-bottom-left- .datepicker--pointer,.-bottom-right- .datepicker--pointer{bottom:calc(100% - 4px);-ms-transform:rotate(315deg);transform:rotate(315deg)}.-left-bottom- .datepicker--pointer,.-left-center- .datepicker--pointer,.-left-top- .datepicker--pointer{left:calc(100% - 4px);-ms-transform:rotate(45deg);transform:rotate(45deg)}.-bottom-left- .datepicker--pointer,.-top-left- .datepicker--pointer{left:10px}.-bottom-right- .datepicker--pointer,.-top-right- .datepicker--pointer{right:10px}.-bottom-center- .datepicker--pointer,.-top-center- .datepicker--pointer{left:calc(50% - 10px / 2)}.-left-top- .datepicker--pointer,.-right-top- .datepicker--pointer{top:10px}.-left-bottom- .datepicker--pointer,.-right-bottom- .datepicker--pointer{bottom:10px}.-left-center- .datepicker--pointer,.-right-center- .datepicker--pointer{top:calc(50% - 10px / 2)}.datepicker--body.active{display:block}.datepicker--nav{display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between;border-bottom:1px solid #efefef;min-height:32px;padding:4px}.-only-timepicker- .datepicker--nav{display:none}.datepicker--nav-action,.datepicker--nav-title{display:-ms-flexbox;display:flex;cursor:pointer;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center}.datepicker--nav-action{width:32px;border-radius:4px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.datepicker--nav-action.-disabled-{visibility:hidden}.datepicker--nav-action svg{width:32px;height:32px}.datepicker--nav-action path{fill:none;stroke:#9c9c9c;stroke-width:2px}.datepicker--nav-title{border-radius:4px;padding:0 8px}.datepicker--buttons,.datepicker--time{border-top:1px solid #efefef;padding:4px}.datepicker--nav-title i{font-style:normal;color:#9c9c9c;margin-left:5px}.datepicker--nav-title.-disabled-{cursor:default;background:0 0}.datepicker--buttons{display:-ms-flexbox;display:flex}.datepicker--button{color:#4EB5E6;cursor:pointer;border-radius:4px;-ms-flex:1;flex:1;display:-ms-inline-flexbox;display:inline-flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;height:32px}.datepicker--button:hover{color:#4a4a4a;background:#f0f0f0}.datepicker--time{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;position:relative}.datepicker--time.-am-pm- .datepicker--time-sliders{-ms-flex:0 1 138px;flex:0 1 138px;max-width:138px}.-only-timepicker- .datepicker--time{border-top:none}.datepicker--time-sliders{-ms-flex:0 1 153px;flex:0 1 153px;margin-right:10px;max-width:153px}.datepicker--time-label{display:none;font-size:12px}.datepicker--time-current{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex:1;flex:1;font-size:14px;text-align:center;margin:0 0 0 10px}.datepicker--time-current-colon{margin:0 2px 3px;line-height:1}.datepicker--time-current-hours,.datepicker--time-current-minutes{line-height:1;font-size:19px;font-family:"Century Gothic",CenturyGothic,AppleGothic,sans-serif;position:relative;z-index:1}.datepicker--time-current-hours:after,.datepicker--time-current-minutes:after{content:'';background:#f0f0f0;border-radius:4px;position:absolute;left:-2px;top:-3px;right:-2px;bottom:-2px;z-index:-1;opacity:0}.datepicker--time-current-hours.-focus-:after,.datepicker--time-current-minutes.-focus-:after{opacity:1}.datepicker--time-current-ampm{text-transform:uppercase;-ms-flex-item-align:end;align-self:flex-end;color:#9c9c9c;margin-left:6px;font-size:11px;margin-bottom:1px}.datepicker--time-row{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;font-size:11px;height:17px;background:linear-gradient(to right,#dedede,#dedede) left 50%/100% 1px no-repeat}.datepicker--time-row:first-child{margin-bottom:4px}.datepicker--time-row input[type=range]{background:0 0;cursor:pointer;-ms-flex:1;flex:1;height:100%;padding:0;margin:0;-webkit-appearance:none}.datepicker--time-row input[type=range]::-ms-tooltip{display:none}.datepicker--time-row input[type=range]:hover::-webkit-slider-thumb{border-color:#b8b8b8}.datepicker--time-row input[type=range]:hover::-moz-range-thumb{border-color:#b8b8b8}.datepicker--time-row input[type=range]:hover::-ms-thumb{border-color:#b8b8b8}.datepicker--time-row input[type=range]:focus{outline:0}.datepicker--time-row input[type=range]:focus::-webkit-slider-thumb{background:#5cc4ef;border-color:#5cc4ef}.datepicker--time-row input[type=range]:focus::-moz-range-thumb{background:#5cc4ef;border-color:#5cc4ef}.datepicker--time-row input[type=range]:focus::-ms-thumb{background:#5cc4ef;border-color:#5cc4ef}.datepicker--time-row input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;box-sizing:border-box;height:12px;width:12px;border-radius:3px;border:1px solid #dedede;background:#fff;cursor:pointer;transition:background .2s;margin-top:-6px}.datepicker--time-row input[type=range]::-moz-range-thumb{box-sizing:border-box;height:12px;width:12px;border-radius:3px;border:1px solid #dedede;background:#fff;cursor:pointer;transition:background .2s}.datepicker--time-row input[type=range]::-ms-thumb{box-sizing:border-box;height:12px;width:12px;border-radius:3px;border:1px solid #dedede;background:#fff;cursor:pointer;transition:background .2s}.datepicker--time-row input[type=range]::-webkit-slider-runnable-track{border:none;height:1px;cursor:pointer;color:transparent;background:0 0}.datepicker--time-row input[type=range]::-moz-range-track{border:none;height:1px;cursor:pointer;color:transparent;background:0 0}.datepicker--time-row input[type=range]::-ms-track{border:none;height:1px;cursor:pointer;color:transparent;background:0 0}.datepicker--time-row input[type=range]::-ms-fill-lower{background:0 0}.datepicker--time-row input[type=range]::-ms-fill-upper{background:0 0}.datepicker--time-row span{padding:0 12px}.datepicker--time-icon{color:#9c9c9c;border:1px solid;border-radius:50%;font-size:16px;position:relative;margin:0 5px -1px 0;width:1em;height:1em}.datepicker--time-icon:after,.datepicker--time-icon:before{content:'';background:currentColor;position:absolute}.datepicker--time-icon:after{height:.4em;width:1px;left:calc(50% - 1px);top:calc(50% + 1px);-ms-transform:translateY(-100%);transform:translateY(-100%)}.datepicker--time-icon:before{width:.4em;height:1px;top:calc(50% + 1px);left:calc(50% - 1px)}.datepicker--cell-day.-other-month-,.datepicker--cell-year.-other-decade-{color:#dedede}.datepicker--cell-day.-other-month-:hover,.datepicker--cell-year.-other-decade-:hover{color:#c5c5c5}.-disabled-.-focus-.datepicker--cell-day.-other-month-,.-disabled-.-focus-.datepicker--cell-year.-other-decade-{color:#dedede}.-selected-.datepicker--cell-day.-other-month-,.-selected-.datepicker--cell-year.-other-decade-{color:#fff;background:#a2ddf6}.-selected-.-focus-.datepicker--cell-day.-other-month-,.-selected-.-focus-.datepicker--cell-year.-other-decade-{background:#8ad5f4}.-in-range-.datepicker--cell-day.-other-month-,.-in-range-.datepicker--cell-year.-other-decade-{background-color:rgba(92,196,239,0.1);color:#ccc}.-in-range-.-focus-.datepicker--cell-day.-other-month-,.-in-range-.-focus-.datepicker--cell-year.-other-decade-{background-color:rgba(92,196,239,0.2)}.datepicker--cell-day.-other-month-:empty,.datepicker--cell-year.-other-decade-:empty{background:0 0;border:none}.xdsoft_autocomplete{display:inline;position:relative;word-spacing:normal;text-transform:none;text-indent:0;text-shadow:none;text-align:start}.xdsoft_autocomplete .xdsoft_input{position:relative;z-index:2}.xdsoft_autocomplete .xdsoft_autocomplete_dropdown{position:absolute;border:1px solid #ccc;border-top-color:#d9d9d9;box-shadow:0 2px 4px rgba(0,0,0,0.2);-webkit-box-shadow:0 2px 4px rgba(0,0,0,0.2);cursor:default;display:none;z-index:1001;margin-top:-1px;background-color:#fff;min-width:100%;overflow:auto}.xdsoft_autocomplete .xdsoft_autocomplete_hint{position:absolute;z-index:1;color:#ccc!important;-webkit-text-fill-color:#ccc!important;text-fill-color:#ccc!important;overflow:hidden!important;white-space:pre!important}.xdsoft_autocomplete .xdsoft_autocomplete_hint span{color:transparent;opacity:0}.xdsoft_autocomplete .xdsoft_autocomplete_dropdown > .xdsoft_autocomplete_copyright{color:#ddd;font-size:10px;text-decoration:none;right:5px;position:absolute;margin-top:-15px;z-index:1002}.xdsoft_autocomplete .xdsoft_autocomplete_dropdown > div{background:#fff;white-space:nowrap;cursor:pointer;line-height:1.5em;padding:2px 0}.xdsoft_autocomplete .xdsoft_autocomplete_dropdown > div.active{background:#0097CF;color:#FFF}@font-face{font-family:"Lato";src:url(../fonts/Lato-Regular.eot);src:url(../fonts/Lato-Regular.eot?#iefix) format("embedded-opentype"),url(../fonts/Lato-Regular.woff2) format("woff2"),url(../fonts/Lato-Regular.woff) format("woff"),url(../fonts/Lato-Regular.ttf) format("truetype"),url(../fonts/Lato-Regular.svg#Lato-Regular) format("svg");font-weight:400;font-style:normal}@font-face{font-family:"Lato";src:url(../fonts/Lato-Bold.eot);src:url(../fonts/Lato-Bold.eot?#iefix) format("embedded-opentype"),url(../fonts/Lato-Bold.woff2) format("woff2"),url(../fonts/Lato-Bold.woff) format("woff"),url(../fonts/Lato-Bold.ttf) format("truetype"),url(../fonts/Lato-Bold.svg#Lato-Bold) format("svg");font-weight:700;font-style:normal}html{box-sizing:border-box}*,::before,::after{box-sizing:inherit}:root{font-family:"Lato",Arial,sans-serif;line-height:1.57}:root *{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-overflow-scrolling:touch}img{max-width:100%}picture source,picture img{width:100%;height:100%;object-fit:cover;object-position:center}.m0{margin:0!important}.mt0{margin-top:0!important}.mr0{margin-right:0!important}.mb0{margin-bottom:0!important}.ml0{margin-left:0!important}.p0{padding:0!important}.pt0{padding-top:0!important}.pr0{padding-right:0!important}.pb0{padding-bottom:0!important}.pl0{padding-left:0!important}.mt2{margin-top:24px}.ml1{margin-left:12px}.bg-absolute{position:absolute;top:0;left:0;width:100%;height:100%;z-index:0;background-color:#fcfcfc}.bg-absolute img{display:block;width:100%;height:100%;object-fit:cover;object-position:center bottom}img{border:0}img:not([src]):not([srcset]){visibility:hidden}.lazyload{animation-name:fade;animation-duration:1s}@keyframes fade{from{opacity:0}to{opacity:1}}.overflow-y-scroll{overflow-y:auto}.overflow-x-scroll{overflow-x:auto;overflow-y:hidden}.icon{transition:all .3s ease}.icon-chevron-down{font-size:8px}.link{color:#1776ea}.d-flex{display:-ms-flexbox;display:flex}.d-flex-center{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.justify-content-center{-ms-flex-pack:center;justify-content:center}.font-weight-bold{font-weight:700}.text-center{text-align:center}.c_battleship-grey{color:#6b7480}.badge{position:absolute;right:0;top:0;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;width:16px;height:16px;background-color:#38bc7d;font-size:8px;font-weight:600;line-height:1;letter-spacing:.1px;text-align:center;color:#fff;border-radius:50%}.dropdown,.dropdown-select,.with-label{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;position:relative;cursor:pointer}.dropdown .icon-chevron-down,.dropdown-select .icon-chevron-down,.with-label .icon-chevron-down{fill:#002d73}.dropdown label,.dropdown-select label,.with-label label{cursor:pointer;color:#002d73;white-space:nowrap}.dropdown .label,.dropdown-select .label,.with-label .label{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;color:#002d73;cursor:pointer}.dropdown .label .icon-chevron-down,.dropdown-select .label .icon-chevron-down,.with-label .label .icon-chevron-down{-ms-flex-preferred-size:8px;flex-basis:8px;-ms-flex-negative:0;flex-shrink:0}.dropdown.active .icon-chevron-down,.dropdown-select.active .icon-chevron-down,.with-label.active .icon-chevron-down{-ms-transform:rotate(180deg);transform:rotate(180deg)}.dropdown.left .dropdown-list,.dropdown-select.left .dropdown-list,.with-label.left .dropdown-list{left:0}.dropdown.center .dropdown-list,.dropdown-select.center .dropdown-list,.with-label.center .dropdown-list{left:50%;-ms-transform:translateX(-50%);transform:translateX(-50%)}.dropdown.right .dropdown-list,.dropdown-select.right .dropdown-list,.with-label.right .dropdown-list{right:0}.dropdown.priority[data-value="low"] span,.dropdown-select.priority[data-value="low"] span,.with-label.priority[data-value="low"] span{padding-left:24px;background:url(../img/label-low.svg) no-repeat left center}.dropdown.priority[data-value="medium"] span,.dropdown-select.priority[data-value="medium"] span,.with-label.priority[data-value="medium"] span{padding-left:24px;background:url(../img/label-medium.svg) no-repeat left center}.dropdown.priority[data-value="high"] span,.dropdown-select.priority[data-value="high"] span,.with-label.priority[data-value="high"] span{padding-left:24px;background:url(../img/label-high.svg) no-repeat left center}.dropdown.priority[data-value="critical"] span,.dropdown-select.priority[data-value="critical"] span,.with-label.priority[data-value="critical"] span{padding-left:24px;background:url(../img/label-critical.svg) no-repeat left center}.dropdown.priority [data-option="low"],.dropdown-select.priority [data-option="low"],.with-label.priority [data-option="low"]{padding-left:47px;background:url(../img/label-low.svg) no-repeat 21px center}.dropdown.priority [data-option="medium"],.dropdown-select.priority [data-option="medium"],.with-label.priority [data-option="medium"]{padding-left:47px;background:url(../img/label-medium.svg) no-repeat 21px center}.dropdown.priority [data-option="high"],.dropdown-select.priority [data-option="high"],.with-label.priority [data-option="high"]{padding-left:47px;background:url(../img/label-high.svg) no-repeat 21px center}.dropdown.priority [data-option="critical"],.dropdown-select.priority [data-option="critical"],.with-label.priority [data-option="critical"]{padding-left:47px;background:url(../img/label-critical.svg) no-repeat 21px center}.dropdown > span,.dropdown-select > span,.with-label > span{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.dropdown select,.dropdown-select select,.with-label select{display:none}.dropdown .icon-chevron-down,.dropdown-select .icon-chevron-down,.with-label .icon-chevron-down{margin-top:1px;width:8px;height:8px;margin-left:8px;transition:all 250ms ease}.dropdown .dropdown-list,.dropdown-select .dropdown-list,.with-label .dropdown-list{display:none;border-radius:2px;box-shadow:0 2px 8px 0 rgba(38,40,42,0.1);background-color:#fff;list-style:none;margin:0;padding:0;position:absolute;top:100%;z-index:10}.dropdown .dropdown-list .separator,.dropdown-select .dropdown-list .separator,.with-label .dropdown-list .separator{height:1px;background-color:#dfe4ec}.dropdown .dropdown-list > li,.dropdown-select .dropdown-list > li,.with-label .dropdown-list > li{height:40px;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;white-space:nowrap;padding:0 16px;color:#002d73}.dropdown .dropdown-list > li.selected,.dropdown-select .dropdown-list > li.selected,.with-label .dropdown-list > li.selected{display:none}.dropdown .dropdown-list > li a,.dropdown-select .dropdown-list > li a,.with-label .dropdown-list > li a{width:100%;height:100%;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;color:#002d73}.dropdown .dropdown-list > li a:hover,.dropdown-select .dropdown-list > li a:hover,.with-label .dropdown-list > li a:hover{color:#002d73}.dropdown .dropdown-list > li svg,.dropdown-select .dropdown-list > li svg,.with-label .dropdown-list > li svg{transition:all 250ms ease;fill:#959eb0;margin-right:8px;width:16px;height:16px}.dropdown .dropdown-list > li:hover,.dropdown-select .dropdown-list > li:hover,.with-label .dropdown-list > li:hover{background-color:#f5f8ff;transition:all 250ms ease}.dropdown .dropdown-list > li:hover svg,.dropdown-select .dropdown-list > li:hover svg,.with-label .dropdown-list > li:hover svg{fill:#002d73}.accordion .accordion-title{cursor:pointer}.accordion .accordion-body{display:none}.accordion.visible .accordion-title svg{-ms-transform:rotate(180deg);transform:rotate(180deg)}body.noscroll{width:100%;height:100%!important;position:fixed;top:0;bottom:0;overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:30;background-color:rgba(38,40,42,0.8);text-align:center;display:none}.modal::before{content:"";display:inline-block;height:100%;margin-left:-.05em;vertical-align:middle}.modal .modal__body{padding:40px 24px;box-shadow:0 8px 16px 0 rgba(38,40,42,0.1);background-color:#fff;margin:auto;display:inline-block;position:relative;width:440px;vertical-align:middle}.modal .modal__body .modal__close{position:absolute;width:32px;height:32px;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;top:0;right:0;cursor:pointer}.modal .modal__body .modal__close .icon-close{width:8px;height:8px}.modal .modal__body .modal__close:hover .icon-close{fill:#002d73}.modal .modal__body h3{font-family:"Lato",Arial,sans-serif;font-size:18px;font-weight:700;font-style:normal;font-stretch:normal;line-height:1.22;letter-spacing:.1px;text-align:center}.modal .modal__body .modal__description{margin-top:24px;font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;text-align:center}.modal .modal__body .modal__buttons{margin-top:32px;display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between}.modal .modal__body .modal__buttons button{width:176px}@media screen and (max-width: 900px){.modal .modal__body{width:90%}.modal .modal__body .btn{height:40px!important}.modal .modal__body .modal__buttons{-ms-flex-pack:center;justify-content:center;-ms-flex-wrap:wrap;flex-wrap:wrap}.modal .modal__body .modal__buttons .btn{margin:0 8px 16px}}.dropdown.priority .low{fill:#959eb0!important}.dropdown.priority .medium{fill:#38bc7d!important}.dropdown.priority .hight{fill:#ffc200!important}.dropdown.priority .critical{fill:#e64342!important}.nowrap{white-space:nowrap}button{font-family:"Lato",Arial,sans-serif;color:#26282a}.btn{display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;height:32px;padding:5px 12px;background-color:transparent;border:none;outline:none;cursor:pointer;font-size:13px;font-weight:400;border-radius:2px;transition:all 250ms ease}.btn > .icon + span,.btn > span + .icon{margin-left:8px}.btn .icon{fill:currentColor}@media screen and (max-width: 900px){.btn{cursor:default}}.btn-transparent{background-color:#fff;border:1px solid #c5cad4;font-size:14px;font-weight:400;letter-spacing:.1px;color:#6b7480}.btn.cancel{width:120px;height:40px;border:1px solid #002d73;color:#002d73}.btn-empty{padding:0}.btn-full{width:152px;height:40px;background-color:#1776ea;color:#fff;font-weight:600;transition:all 250ms ease;text-decoration:none}.notification a.btn-full{color:#fff!important;text-decoration:none!important}.btn-full:hover{background-color:#025cca}.btn-full.disabled,.btn-full:disabled{width:auto;border-color:#f0f2f5;background-color:#f0f2f5;color:#959eb0}.btn--blue{color:#1776ea}.btn--blue .icon{fill:currentColor}.btn-border{width:152px;height:40px;border:1px solid #002d73;color:#002d73;padding:0}.btn--blue-border{width:auto;padding:0 16px;display:-ms-inline-flexbox;display:inline-flex;height:48px;border:1px solid #1776ea;color:#1776ea;font-weight:600}.btn--blue-border:hover{border-color:#025cca;color:#025cca}.btn-banner{width:176px;background-color:#f0f2f5;color:#002d73;font-weight:600}[ripple]{position:relative;overflow:hidden}[ripple]::before{content:"";display:block;position:absolute;top:0;right:0;bottom:0;left:0;z-index:10}[ripple] .ripple--container{position:absolute;top:0;right:0;bottom:0;left:0}[ripple] .ripple--container span{-ms-transform:scale(0);transform:scale(0);border-radius:100%;position:absolute;opacity:.23;background-color:#fff;animation:ripple 500ms}.btn-border .ripple--container span,.btn--blue-border .ripple--container span{background-color:rgba(141,156,183,0.1);opacity:1}@keyframes ripple{to{opacity:0;transform:scale(2)}}@media (max-width: 900px){.btn--blue-border,.btn-full{height:32px!important}}::-webkit-input-placeholder{color:#959eb0}::-moz-placeholder{color:#959eb0}:-ms-input-placeholder{color:#959eb0}:-moz-placeholder{color:#959eb0}input{outline:none}input::-ms-clear{display:none}.form{font-size:14px}.form .checkbox-custom{padding:0}.form textarea.form-control{height:155px;resize:none;font-family:"Lato",Arial,sans-serif}.form.invalid .error-message{display:block}.form.invalid .form-control.isError{border-color:#e64342}.form__title{margin-bottom:1.5rem;font-size:1.5rem;line-height:1.33}.input-group{position:relative}.input-group-append--icon{position:absolute;right:17px;top:0;bottom:0;margin:auto;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;background-color:transparent;border:none;z-index:3;cursor:pointer}.input-group-append--icon:hover .icon{fill:#1776ea}.input-group-append--icon .icon{fill:#c5cad4;font-size:12px}.input-group-append--icon .icon-eye-close{font-size:12px}.form-group{position:relative;margin-bottom:16px}.form-group label{display:block;margin-bottom:4px;color:#959eb0}.form-group .form-control__error{display:none;margin-top:12px;padding:9px;color:#e64342;text-align:center;background-color:rgba(230,67,66,0.05)}.form-group.error .form-control__error{display:block}.form-group.error input{border-color:#e64342}.form input.form-control,.form textarea.form-control{height:40px;width:100%;padding:4px 12px;font-size:14px;border-radius:2px;border:solid 1px #d4d6e3;background-color:#fff;font-weight:400;font-style:normal;font-stretch:normal;line-height:normal;letter-spacing:.1px;-webkit-appearance:none;outline:none;color:#26282a;transition:all 250ms ease}.form input.form-control:-ms-input-placeholder,.form textarea.form-control:-ms-input-placeholder{color:#959eb0}.form input.form-control::placeholder,.form textarea.form-control::placeholder{color:#959eb0}.form input.form-control:hover,.form textarea.form-control:hover{border-color:#959eb0}.form input.form-control:focus,.form textarea.form-control:focus{color:#000;border-color:#1776ea;outline:none;box-shadow:none}.error-message{display:none;padding:9px;color:#e64342;text-align:center;background-color:rgba(230,67,66,0.05)}.invalid-feedback{display:none;position:absolute;top:100%;left:0;margin-top:.2rem;font-size:12px}.invalid .form-control{border-color:#e64342}.invalid .invalid-feedback{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;color:#e64342}.form__submit{margin-top:24px;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center}.form__search{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;width:100%;height:100%;padding:0 16px 0 32px;position:relative;background-color:#fff;position:relative;box-sizing:border-box}.form__search .search--type{font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;color:#959eb0;margin-right:4px;display:none;text-transform:capitalize;cursor:pointer}.form__search .form__search_type{position:absolute;top:100%;left:0;width:100%;box-shadow:0 2px 8px 0 rgba(38,40,42,0.1);background-color:#fff;padding:9px 16px 24px;z-index:1;display:none}.form__search .form__search_type h5{margin-left:8px;font-size:14px;font-weight:700;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;color:#26282a}.form__search .form__search_type .type--list{margin:8px -16px 0}.form__search .form__search_type .type--list li{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;color:#002d73;height:40px;transition:all 250ms ease;padding:0 16px;cursor:pointer}.form__search .form__search_type .type--list li:hover{background-color:#f5f8ff}.form__search .form__search_type .type--list li:last-child{margin-bottom:0}.form__search .form__search_type .type--list li .icon{margin-right:8px;fill:#959eb0;transition:all 250ms ease}.form__search .form__search_results{position:absolute;top:100%;left:0;width:100%;box-shadow:0 2px 8px 0 rgba(38,40,42,0.1);background-color:#fff;padding:8px 24px 0;z-index:1;display:none}.form__search .form__search_results h5{font-size:12px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.5;letter-spacing:.1px;color:#6b7480}.form__search .form__search_results .results--list{margin:0 -24px}.form__search .form__search_results .results--list li{height:40px;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;color:#26282a;transition:all 250ms ease;padding:0 24px}.form__search .form__search_results .results--list li > :last-child{overflow:hidden;text-overflow:ellipsis;margin-right:0}.form__search .form__search_results .results--list li:hover{background-color:#f5f8ff}.form__search .form__search_results .results--list li span,.form__search .form__search_results .results--list li a{margin-right:16px;white-space:nowrap}.form__search .form__search_results .results--list li a{color:#1776ea;transition:all 250ms ease}.form__search .form__search_results .results--list li a:hover{color:#025cca}.form__search .form__search_results .results--list li b{background-color:#fff5d0}.form__search.focus .icon-search{fill:#002d73!important}.form__search.value .icon-search{fill:#002d73!important}.form__search.value .search-clear{opacity:1!important}.form__search input{font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;color:#26282a}.form__search button[type="submit"]{margin-right:8px}.form__search .icon-search{font-size:19.7px}.form__search .form__control{background-color:transparent;width:100%;border:none;height:70%;cursor:pointer}.form__search .form__control::-webkit-input-placeholder{color:#959eb0;transition:all 250ms ease}.form__search .form__control::-moz-placeholder{color:#959eb0;transition:all 250ms ease}.form__search .form__control:-ms-input-placeholder{color:#959eb0;transition:all 250ms ease}.form__search .form__control:-moz-placeholder{color:#959eb0;transition:all 250ms ease}.form__search .form__control:hover::-webkit-input-placeholder{color:#6b7480}.form__search .form__control:hover::-moz-placeholder{color:#6b7480}.form__search .form__control:hover:-ms-input-placeholder{color:#6b7480}.form__search .form__control:hover:-moz-placeholder{color:#6b7480}.form__search.type .form__control{cursor:initial}.checkbox-custom{position:relative;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;min-height:16px}.checkbox-custom [type="checkbox"]:checked,.checkbox-custom [type="checkbox"]:not(:checked){position:absolute;left:-9999px}.checkbox-custom [type="checkbox"] + label{transition:all 250ms ease}.checkbox-custom [type="checkbox"]:not(:checked) + label{position:relative;padding-left:24px;cursor:pointer;line-height:1.2;letter-spacing:normal;color:#959eb0}.checkbox-custom [type="checkbox"]:checked + label{position:relative;padding-left:24px;cursor:pointer;line-height:1.2;letter-spacing:normal;color:#002d73}.checkbox-custom [type="checkbox"]:checked + label:before,.checkbox-custom [type="checkbox"]:not(:checked) + label:before{content:"";position:absolute;left:0;top:0;width:16px;height:16px;border-radius:2px;background:#fff;border:1px solid #959eb0}.checkbox-custom [type="checkbox"]:checked + label:after,.checkbox-custom [type="checkbox"]:not(:checked) + label:after{content:"";width:12px;height:12px;position:absolute;top:2px;left:2px;transition:all .2s ease;background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='11' height='8' viewBox='0 0 11 8'%3E%3Cpath fill='%23002D73' fill-rule='evenodd' d='M9.043 0L3.246 5.128 1.623 3.692 0 5.128 3.246 8l7.42-6.564z'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:center}.checkbox-custom [type="checkbox"]:not(:checked) + label:after{opacity:0;-ms-transform:scale(0);transform:scale(0)}.checkbox-custom [type="checkbox"]:checked + label:after{opacity:1;-ms-transform:scale(1);transform:scale(1)}.checkbox-custom [type="checkbox"]:disabled:checked + label:before,.checkbox-custom [type="checkbox"]:disabled:not(:checked) + label:before{border-color:#ccc;background-color:#eee}.checkbox-custom [type="checkbox"]:disabled:checked + label:after{background:#aaa}.invalid .checkbox-custom [type="checkbox"]:not(:checked):required + label:before{border-color:#e64342}.radio-custom{position:relative;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;min-height:16px}.radio-custom [type="radio"]:checked,.radio-custom [type="radio"]:not(:checked){position:absolute;left:-9999px}.radio-custom [type="radio"]:checked + label,.radio-custom [type="radio"]:not(:checked) + label{position:relative;padding-left:24px;cursor:pointer;line-height:1.2;letter-spacing:normal;color:#002257}.radio-custom [type="radio"]:checked + label:before,.radio-custom [type="radio"]:not(:checked) + label:before{content:"";position:absolute;left:0;top:0;width:16px;height:16px;border-radius:2px;background:#fff;border-radius:50%;border:1px solid #002d73}.radio-custom [type="radio"]:checked + label:after,.radio-custom [type="radio"]:not(:checked) + label:after{content:"";width:8px;height:8px;position:absolute;top:4px;left:4px;transition:all .2s ease;background-color:#002d73;border-radius:50%}.radio-custom [type="radio"]:not(:checked) + label:after{opacity:0;-ms-transform:scale(0);transform:scale(0)}.radio-custom [type="radio"]:checked + label:after{opacity:1;-ms-transform:scale(1);transform:scale(1)}.radio-custom [type="radio"]:disabled:checked + label:before,.radio-custom [type="radio"]:disabled:not(:checked) + label:before{border-color:#ccc;background-color:#eee}.radio-custom [type="radio"]:disabled:checked + label:after{background:#aaa}.invalid .radio-custom [type="radio"]:not(:checked):required + label:before{border-color:#e64342}.select-custom{position:relative;height:32px;color:inherit}.select-custom select{display:none}.select-selected{max-width:200px}.select-selected:after{position:absolute;content:"";top:12px;right:10px;width:10px;height:6px;background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='6' viewBox='0 0 8 6'%3E%3Cpath fill='%2326282A' fill-rule='evenodd' d='M4.303 5.07l3.553-3.552a.434.434 0 0 0 .128-.309A.434.434 0 0 0 7.856.9L7.595.64a.437.437 0 0 0-.618 0L3.994 3.622 1.007.635a.434.434 0 0 0-.618 0L.128.897A.434.434 0 0 0 0 1.206c0 .117.045.226.128.309L3.684 5.07a.434.434 0 0 0 .31.127.434.434 0 0 0 .31-.127z'/%3E%3C/svg%3E");background-size:10px 6px;background-repeat:no-repeat}.select-selected.select-arrow-active:after{-ms-transform:scaleY(-1);transform:scaleY(-1);filter:FlipY;-ms-filter:FlipY}.select-items div,.select-selected{padding:8px;line-height:1;cursor:pointer}.select-items{position:absolute;top:100%;left:0;right:0;z-index:5;padding:6px 0 12px;box-shadow:0 2px 8px 0 rgba(38,40,42,0.1);background-color:#fff}.select-hide{display:none}.select-items div:hover,.same-as-selected{color:#1776ea}.select-custom--stretched{box-shadow:none}.select-custom--stretched .select-selected{width:100%}.select--priority .select-selected{padding-left:24px}.select--priority .select-selected[data-value="critical"] + div + select + .priority-label{background-color:#e64342}.select--priority .select-selected[data-value="low"] + div + select + .priority-label{background-color:#959eb0}.select--priority .select-selected[data-value="medium"] + div + select + .priority-label{background-color:#38bc7d}.select--priority .select-selected[data-value="high"] + div + select + .priority-label{background-color:#ffc200}.priority-label{position:absolute;top:0;bottom:0;margin:auto;left:0;display:inline-block;width:16px;height:12px;border-top-left-radius:2px;border-bottom-left-radius:2px}.priority-label:after{content:"";position:absolute;right:0;top:0;width:0;height:0;border-style:solid;border-width:6px 4px 6px 0;border-color:transparent #fff transparent transparent}.switch-checkbox{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center}.switch-checkbox input[type="checkbox"]{display:none}.switch-checkbox .switch-checkbox__bullet{width:32px;height:16px;background-color:#fff;border:1px solid #dfe4ec;border-radius:8px;transition:all 250ms ease;position:relative}.switch-checkbox .switch-checkbox__bullet i{display:block;width:14px;height:14px;box-shadow:0 1px 2px 0 rgba(0,0,0,0.16);background-color:#fff;border-radius:50%;position:absolute;top:0;left:0;right:initial;transition:all 250ms ease}.switch-checkbox .switch-checkbox__bullet i svg{width:8px;height:8px;position:absolute;left:50%;top:50%;-ms-transform:translate(-50%,-50%);transform:translate(-50%,-50%);transition:all 250ms ease}.switch-checkbox .switch-checkbox__bullet i svg.icon-tick{opacity:0}.switch-checkbox input[type="checkbox"]:checked + .switch-checkbox__bullet{background-color:#002d73;border-color:#002d73}.switch-checkbox input[type="checkbox"]:checked + .switch-checkbox__bullet i{left:100%;-ms-transform:translateX(-100%);transform:translateX(-100%)}.switch-checkbox input[type="checkbox"]:checked + .switch-checkbox__bullet i .icon-close{opacity:0}.switch-checkbox input[type="checkbox"]:checked + .switch-checkbox__bullet i .icon-tick{opacity:1}.switch-checkbox span{margin-left:16px;transition:all 250ms ease;line-height:1.2}.switch-checkbox a{margin-left:16px;transition:all 250ms ease;color:#1776ea;line-height:1.2}.switch-checkbox a:hover{color:#025cca}.block--attach{margin-top:8px;display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;position:relative;font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;color:#1776ea;transition:all 250ms ease;cursor:pointer!important}.block--attach input[type="file"]{opacity:0;position:absolute;top:0;left:0;width:100%;height:100%;cursor:pointer!important}.block--attach .icon-attach{width:16px;height:16px;fill:#1776ea;margin-right:8px}.block--attach:hover{color:#025cca}.block--attach:hover .icon-attach{fill:#025cca}.selectize-input{padding:11px 12px;border:solid 1px #d4d6e3;transition:all 250ms ease}.selectize-input.input-active{border:solid 1px #1776ea!important}.selectize-input:hover{border:solid 1px #959eb0}.selectize-control.input-tags{line-height:1;margin-left:24px}.selectize-control.multi .selectize-input > div{margin:0 6px 0 0;padding:0;background:transparent;color:#26282a;border:none}.selectize-control{display:-ms-flexbox;display:flex}.selectize-control .selectize-input{margin-top:16px;border-radius:2px;border:solid 1px #d4d6e3;box-shadow:none;min-width:320px;padding:0 12px;height:40px;display:-ms-flexbox!important;display:flex!important;-ms-flex-align:center;align-items:center;transition:all 250ms ease;z-index:11}.selectize-control .selectize-input:after{border:none!important;background:transparent url(../img/chevron-down.svg) no-repeat center;width:8px!important;height:8px!important;opacity:.25!important;transition:all 250ms ease}.selectize-control .selectize-input.focus::after{-ms-transform:rotate(180deg);transform:rotate(180deg)}.selectize-control .selectize-dropdown{box-shadow:0 2px 8px 0 rgba(38,40,42,0.1);border:none}.selectize-control .selectize-dropdown .option{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;height:40px;padding:0 16px;color:#002d73}.selectize-control .selectize-dropdown .option.active{background-color:#f5f8ff}@media screen and (max-width: 900px){.form__search .form__search_results .results--list li{font-size:13px}}.main__content.ticket{padding:23px 32px 50px 16px;display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between}.main__content.ticket .icon-chevron-down{margin-top:1px}@media screen and (max-width: 900px){.main__content.ticket{padding:16px 12px 24px;-ms-flex-direction:column;flex-direction:column}.main__content.ticket .ticket__body{margin:0 0 16px;padding-top:72px}.main__content.ticket .ticket__body .block--head{-ms-flex-direction:column;flex-direction:column;-ms-flex-align:start;align-items:flex-start}.main__content.ticket .ticket__body .block--head time{margin-left:0;margin-bottom:8px}.main__content.ticket .ticket__body .block--head .more{margin-left:0}.main__content.ticket .block--submit{-ms-flex-pack:justify;justify-content:space-between;-ms-flex-wrap:wrap;flex-wrap:wrap}.main__content.ticket .block--submit .btn{height:40px!important;margin:0 auto 16px}.main__content.ticket .block--submit .btn-full{-ms-flex-order:1;order:1}.main__content.ticket .block--submit .btn-border{-ms-flex-order:2;order:2}.main__content.ticket .block--submit::before{content:"";-ms-flex-order:3;order:3;width:100%;height:0}.main__content.ticket .block--submit .submit-us{-ms-flex-order:4;order:4;margin:0 auto}.main__content.ticket .block--submit .submit-us .dropdown-list{top:calc(100% + 8px);left:50%;-ms-transform:translateX(-50%);transform:translateX(-50%)}.main__content.ticket .ticket__params{width:100%}.main__content.ticket .ticket__params .params--bar{position:absolute;top:72px;left:12px;right:12px}}.ticket__body{-ms-flex-positive:1;flex-grow:1;margin-right:24px}.ticket__body_block{background-color:#fff;margin-bottom:24px;border-radius:2px;box-shadow:0 2px 8px 0 rgba(38,40,42,0.1);padding:24px}.ticket__body_block.response{box-shadow:0 2px 8px 0 rgba(38,40,42,0.1);border:solid 4px #c3ead8}.ticket__body_block h2{font-size:24px;font-weight:700;line-height:1.17;letter-spacing:.12px;color:#26282a}.ticket__body_block h3{font-family:"Lato",Arial,sans-serif;font-size:18px;font-weight:700;font-style:normal;font-stretch:normal;line-height:1.22;letter-spacing:.1px}.ticket__body_block .block--head{display:-ms-flexbox;display:flex;margin-top:16px;-ms-flex-align:center;align-items:center;font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px}.ticket__body_block .block--head .contact{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;position:relative}.ticket__body_block .block--head .contact > span{color:#959eb0}.ticket__body_block .block--head .contact b{margin-left:8px;font-weight:700}.ticket__body_block .block--head .contact .dropdown{margin-left:8px;cursor:pointer;position:static}.ticket__body_block .block--head .contact .dropdown span{font-weight:700}.ticket__body_block .block--head .contact .dropdown .dropdown-list li{padding:0 12px;font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px}.ticket__body_block .block--head .contact .dropdown .dropdown-list li:nth-child(1),.ticket__body_block .block--head .contact .dropdown .dropdown-list li:nth-child(2){background-color:transparent!important;cursor:auto}.ticket__body_block .block--head .contact .dropdown .dropdown-list li .title{color:#959eb0;margin-right:8px;width:36px}.ticket__body_block .block--head .contact .dropdown .dropdown-list li .value{font-weight:400;color:#26282a}.ticket__body_block .block--head .contact .dropdown .dropdown-list li a{color:#002d73}.ticket__body_block .block--head .contact .icon-chevron-down{width:8px;height:8px}.ticket__body_block .block--head .date{color:#6b7480}.ticket__body_block .block--head .more{margin-left:auto;color:#1776ea;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;cursor:pointer;margin-right:-24px;padding-right:24px}.ticket__body_block .block--head .more span{color:#1776ea}.ticket__body_block .block--head .more .icon-chevron-down{fill:#1776ea;width:8px;height:8px}.ticket__body_block .block--head .more .dropdown-list a{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;width:100%;height:100%}.ticket__body_block .block--description{margin:16px 0;font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.71;letter-spacing:.1px}.ticket__body_block .block--description p,.ticket__body_block .block--description ul{margin:0 0 28px}.ticket__body_block .block--description p:last-child,.ticket__body_block .block--description ul:last-child{margin:0}.ticket__body_block .block--description ul.list{list-style-type:disc;padding-left:30px}.ticket__body_block .block--notes{margin-top:26px}.ticket__body_block .block--notes .note{border:solid 1px #f3e3a7;background-color:#fff5d0;padding:8px 8px 16px;margin-bottom:8px}.ticket__body_block .block--notes .note .note__head{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:justify;justify-content:space-between}.ticket__body_block .block--notes .note .note__head .name{font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;color:#959eb0}.ticket__body_block .block--notes .note .note__head .name span{margin-right:8px}.ticket__body_block .block--notes .note .note__head .name b{color:#26282a;margin-right:24px}.ticket__body_block .block--notes .note .note__head .name time{color:#6b7480;white-space:nowrap}.ticket__body_block .block--notes .note .note__head .actions{display:-ms-flexbox;display:flex;margin-top:-5px}.ticket__body_block .block--notes .note .note__head .actions button{width:32px;height:32px;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;margin-left:16px}.ticket__body_block .block--notes .note .note__head .actions button svg{width:16px;height:16px;fill:#c5cad4}.ticket__body_block .block--notes .note .note__head .actions button:hover svg{fill:#002d73}.ticket__body_block .block--notes .note .note__description{margin-top:16px;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.71;letter-spacing:.1px;color:#26282a}.ticket__body_block .block--uploads{margin-top:26px;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px}.ticket__body_block .block--uploads + .block--uploads{margin-top:16px}.ticket__body_block .block--uploads .icon-attach{width:16px;height:16px;fill:#c5cad4;margin-right:8px}.ticket__body_block .block--uploads a{color:#1776ea;transition:all 250ms ease}.ticket__body_block .block--uploads a:hover{color:#025cca}.ticket__body_block .block--suggested{margin-top:32px;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;-ms-flex-align:baseline;align-items:baseline}.ticket__body_block .block--suggested b{font-weight:700;margin-bottom:8px}.ticket__body_block .block--suggested a{color:#1776ea;transition:all 250ms ease}.ticket__body_block .block--suggested a:hover{color:#025cca}.ticket__body_block .block--timer{height:48px;box-shadow:0 2px 8px 0 rgba(38,40,42,0.1);background-color:#fff;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center}.ticket__body_block .block--timer span{font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;color:#959eb0}.ticket__body_block .block--timer b{margin:0 26px 0 8px;font-weight:700}.ticket__body_block .block--timer a{width:32px;height:32px;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;margin-right:8px}.ticket__body_block .block--timer a svg{width:16px;height:16px;fill:#959eb0;transition:all 250ms ease}.ticket__body_block .block--timer a:hover svg{fill:#002d73}.ticket__body_block .block--message{margin-top:16px;height:119px;border-radius:2px;border:solid 1px #d4d6e3;background-color:#fff;position:relative;overflow:hidden}.ticket__body_block .block--message .scroll-textarea{width:100%;height:119px}.ticket__body_block .block--message textarea{outline:none;border:none;width:100%;min-height:100%;background:transparent;padding:8px 12px;font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.71;letter-spacing:.1px;resize:none}.ticket__body_block .block--message .placeholder{position:absolute;top:8px;left:12px;font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;z-index:0;letter-spacing:.1px;color:#959eb0}.ticket__body_block .block--message .placeholder a{color:#1776ea;transition:all 250ms ease}.ticket__body_block .block--message .placeholder a:hover{color:#025cca}.ticket__body_block .block--attach-list{margin-top:16px}.ticket__body_block .block--attach-list div{width:284px;height:32px;padding-left:8px;border-radius:2px;background-color:#f5f8ff;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;position:relative;-ms-flex-pack:justify;justify-content:space-between;margin-bottom:4px}.ticket__body_block .block--attach-list div i{width:32px;height:32px;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;cursor:pointer}.ticket__body_block .block--attach-list div i svg{width:7px;height:7px;fill:#c5cad4}.ticket__body_block .block--attach-list div i:hover svg{width:7px;height:7px;fill:#959eb0}.ticket__body_block .block--checkboxs{margin-top:24px;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:center;align-items:center;border-bottom:1px solid #dfe4ec}.ticket__body_block .block--checkboxs .checkbox-custom{margin-bottom:16px;font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;margin-right:40px}.ticket__body_block .block--checkboxs .checkbox-custom .dropdown-select{margin-left:6px}.ticket__body_block .block--checkboxs .checkbox-custom .dropdown-select > span,.ticket__body_block .block--checkboxs .checkbox-custom .dropdown-select li{color:#959eb0;transition:all 250ms ease}.ticket__body_block .block--checkboxs .checkbox-custom .dropdown-select svg{fill:#959eb0}.ticket__body_block .block--checkboxs .checkbox-custom label{color:#959eb0;transition:all 250ms ease;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.ticket__body_block .block--checkboxs .checkbox-custom input[type="checkbox"]:checked + label{color:#002d73}.ticket__body_block .block--checkboxs .checkbox-custom input[type="checkbox"]:checked + label::before{border-color:#002d73}.ticket__body_block .block--checkboxs .checkbox-custom input[type="checkbox"]:checked + label svg{fill:#002d73}.ticket__body_block .block--checkboxs .checkbox-custom.checked .dropdown-select > span,.ticket__body_block .block--checkboxs .checkbox-custom.checked .dropdown-select li{color:#002d73}.ticket__body_block .block--submit{margin-top:24px;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.ticket__body_block .block--submit button{margin-right:24px}.ticket__body_block .block--submit .submit-us{margin-left:auto;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;position:relative;font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;color:#1776ea}.ticket__body_block .block--submit .submit-us span{margin-left:6px;color:#1776ea}.ticket__body_block .block--submit .submit-us .icon-chevron-down{width:8px;height:8px;margin-left:4px;fill:#1776ea}.ticket__body_block .block--submit .submit-us .dropdown-list{left:calc(100% + 8px);top:50%;-ms-transform:translateY(-50%);transform:translateY(-50%)}.ticket__replies{margin:-8px 0 16px}.ticket__replies .ticket__replies_link{font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;color:#1776ea;display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;margin-left:24px;cursor:pointer;transition:all 250ms ease}.ticket__replies .ticket__replies_link:hover{color:#025cca}.ticket__replies .ticket__replies_link:hover .icon-chevron-down{fill:#025cca}.ticket__replies .ticket__replies_link b{font-weight:700;margin-left:6px}.ticket__replies .ticket__replies_link .icon-chevron-down{margin-left:8px;width:8px;height:8px;fill:#1776ea;transition:all 250ms ease}.ticket__replies .ticket__replies_link.visible .icon-chevron-down{-ms-transform:rotate(180deg);transform:rotate(180deg)}.ticket__replies .ticket__replies_list{padding-top:16px;display:none}.ticket__params{width:320px;-ms-flex-negative:0;flex-shrink:0}.ticket__params .params--bar{height:48px;border-radius:2px;box-shadow:0 2px 8px 0 rgba(38,40,42,0.1);background-color:#fff;display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between;padding-left:16px}.ticket__params .params--bar a{width:48px;height:48px;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center}.ticket__params .params--bar a svg{width:16px;height:16px;fill:#959eb0}.ticket__params .params--bar a:hover svg{fill:#002d73}.ticket__params .params--bar .dropdown{width:65px;height:48px;box-sizing:content-box;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;border-left:1px solid #dfe4ec}.ticket__params .params--bar .dropdown label{width:100%;height:100%;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center}.ticket__params .params--bar .dropdown label svg{width:16px;height:16px;fill:#959eb0;transition:all 250ms ease;margin:0}.ticket__params .params--bar .dropdown:hover svg{fill:#002d73}.ticket__params .params--bar .dropdown .dropdown-list li a{-ms-flex-pack:start;justify-content:flex-start}.ticket__params .params--bar .dropdown .dropdown-list li svg{margin-right:8px}.ticket__params .params--block{border-radius:2px;box-shadow:0 2px 8px 0 rgba(38,40,42,0.1);background-color:#fff;margin-top:16px}.ticket__params .params--block.params{padding:25px 16px}.ticket__params .params--block.params .title{width:135px}.ticket__params .params--block.params .icon-label{width:16px;height:16px;margin-right:8px}.ticket__params .params--block.params [data-value="low"] .icon-label{fill:#959eb0}.ticket__params .params--block.details .title,.ticket__params .params--block.contacts .title,.ticket__params .params--block.history .title{width:106px}.ticket__params .params--block .row{display:-ms-flexbox;display:flex;font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;margin-bottom:18px}.ticket__params .params--block .row:last-child{margin-bottom:0}.ticket__params .params--block .row .title{color:#959eb0;-ms-flex-negative:0;flex-shrink:0}.ticket__params .params--block h4{height:48px;display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between;-ms-flex-align:center;align-items:center;font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:700;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;margin:0;padding:0 16px}.ticket__params .params--block h4 .icon-chevron-down{width:8px;height:8px;fill:#c5cad4}.ticket__params .params--block .accordion-body{padding:16px}.main__content.notifications{padding:40px 32px 32px 16px}.main__content.notifications h2{padding-left:16px;font-size:18px;font-weight:700;font-style:normal;font-stretch:normal;line-height:1.22;letter-spacing:.1px}.main__content.notifications .notifications__list{margin-top:16px;width:100%;max-width:496px;box-shadow:0 2px 8px 0 rgba(38,40,42,0.1);background-color:#fff;padding:8px}.main__content.notifications .notifications__list li{display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between;-ms-flex-align:center;align-items:center;padding:16px}.main__content.notifications .notifications__list li:nth-child(odd){background-color:#f9fafd}.main__content.notifications .notifications__list li.new{border-left:2px solid #1776ea}.main__content.notifications .notifications__list li.new h5{font-weight:700}.main__content.notifications .notifications__list li h5{font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;margin-right:16px}.main__content.notifications .notifications__list li h5 a{color:#002d73}.main__content.notifications .notifications__list li time{font-size:10px;font-weight:700;font-style:normal;font-stretch:normal;line-height:normal;letter-spacing:.1px;text-align:right;color:#6b7480}.main__content.notifications .pagination-wrap{width:100%;max-width:496px;margin:24px 0 0}.footer{margin-top:16px;padding:10px 16px 16px;color:#6b7480}.pagination-wrap{margin:24px auto 16px}.pagination{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center}.pagination a{color:#002d73;transition:all 250ms ease}.pagination a:hover{background-color:#f1f2f5}.pagination__nav-btn{margin:0 5px}.pagination__list{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.pagination__item.is-current .pagination__link{background-color:#dfe4ec}.pagination__stroke{display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;width:32px;height:32px;border-radius:2px;font-size:12px;font-weight:500;letter-spacing:normal;text-align:center;color:#002d73}.pagination__link{display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;width:32px;height:32px;border-radius:2px;font-size:12px;font-weight:500;letter-spacing:normal;text-align:center;color:#002d73}.pagination__amount{margin-top:24px;text-align:center;font-weight:700}.breadcrumbs{margin-bottom:20px}.breadcrumbs__inner{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-wrap:wrap;flex-wrap:wrap;padding:12px 0;font-size:12px}.breadcrumbs__inner a{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;font-size:inherit;font-weight:400;line-height:1.5;letter-spacing:.1px;color:#1776ea}.breadcrumbs__inner a:hover{color:#025cca}.breadcrumbs__inner .icon{fill:currentColor;font-size:8px;margin:0 .4em 0 .5em}.search__title{margin:0 0 24px;font-size:24px;font-weight:700;line-height:1.17;letter-spacing:.12px;color:#26282a;text-align:center}.search__form{background-color:#ffefdc;padding:16px}.search__form .form-group{position:relative;margin:0 auto;display:-ms-flexbox;display:flex;width:100%;max-width:752px}.search__form .form-group input{width:100%;height:56px;padding:17px 16px 17px 56px;background-color:#fff;border-color:transparent;font-size:14px;transition:all .3s ease}.search__form .form-group input:-ms-input-placeholder{line-height:1.57;letter-spacing:.1px;color:#6b7480}.search__form .form-group input::placeholder{line-height:1.57;letter-spacing:.1px;color:#6b7480}.search__form .form-group input:hover,.search__form .form-group input:focus{box-shadow:0 2px 8px 0 rgba(38,40,42,0.1)}.search__form .form-group .icon-search{font-size:20px;fill:#1776ea}.search__form .search__submit{padding:0;position:absolute;top:0;bottom:0;left:24px;margin:auto}.form-group{position:relative}.form-group .search-clear{width:32px;height:32px;position:absolute;top:calc(50% - 16px);right:12px;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;cursor:pointer;z-index:1;opacity:0;transition:all 250ms ease}.form-group .search-clear .icon{width:16px;height:16px;fill:#c5cad4}.form-group .search-clear:hover .icon{fill:#002d73}.alert{margin-top:24px;border:solid 1px #1776ea;background-color:#f5f8ff}.alert .icon-warning{fill:#1776ea;font-size:22px}.alert.warning{border:solid 1px #f3e3a7;background-color:#fff5d0}.alert.warning .icon-warning{fill:#eeb707}.alert.success{border:solid 1px #9fe4c3;background-color:#e5fff2}.alert.success .icon-warning{fill:#38bc7d}.alert.danger{border:solid 1px #f38b8b;background-color:#fdf5f5}.alert.danger .icon-warning{fill:#e64342}.alert.danger .alert__title{color:#e64342}.alert.none{border:none;background-color:#fff}.alert.none .icon-warning{fill:#000}.alert__inner{padding:24px}.alert__head{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.alert__head .icon + .alert__title{margin-left:12px}.alert__title{font-size:14px;font-weight:700;letter-spacing:.1px;color:#26282a}.alert__descr{margin-top:12px}.cust-help .lightgrey{color:#959eb0}.cust-help .highlighted{background-color:#e5fff2}.cust-help .italic{font-style:italic}.cust-help .ml-1{margin-left:8px}.cust-help .h-3{font-size:18px;font-weight:700;line-height:1.22;letter-spacing:.13px;color:#26282a}.cust-help .text-center{text-align:center}.cust-help .text-bold{font-weight:700}.cust-help .wrapper{margin:0!important;background-color:#fff}.cust-help .header{border-bottom:1px solid #dfe4ec}.cust-help .header .dropdown-select .label{color:#1776ea;letter-spacing:.1px}.cust-help .header .dropdown-select .label .icon{fill:currentColor}.cust-help .header__logo{font-size:18px;font-weight:900;line-height:normal;color:#c5cad4}.cust-help .header__inner{display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between;-ms-flex-align:center;align-items:center;padding:13px 0}.cust-help .contr{max-width:1070px;width:100%;margin:0 auto;padding:0 15px}.cust-help .btn:hover .icon{fill:#002d73}.tabbed__head{margin:0;border-bottom:2px solid #dfe4ec;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center}.tabbed__head .tabbed__head_tabs{display:-ms-flexbox;display:flex;-ms-flex-align:end;align-items:flex-end}.tabbed__head .tabbed__head_tabs li{min-width:150px;padding:6px 16px;text-align:center;cursor:pointer;font-size:14px;font-weight:700;line-height:1.57;letter-spacing:.1px;color:#6b7480;display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;border-bottom:2px solid #dfe4ec;transition:all 250ms ease;margin-bottom:-2px}.tabbed__head .tabbed__head_tabs li:not(.current):hover{background-color:#f5f8ff}.tabbed__head .tabbed__head_tabs li b{font-weight:700;margin-left:6px}.tabbed__head .tabbed__head_tabs li.current{border-bottom-color:#4c6587;color:#26282a}.tabbed__tabs .tabbed__tabs_tab{display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between;-ms-flex-wrap:wrap;flex-wrap:wrap;display:none}.tabbed__tabs .tabbed__tabs_tab.is-visible{display:-ms-flexbox;display:flex}.icon-in-circle{width:40px;height:40px;-ms-flex-negative:0;flex-shrink:0;display:-ms-inline-flexbox;display:inline-flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;background-color:#f5f8ff;border-radius:50%}.icon-in-circle .icon{fill:#959eb0;font-size:20px}.nav{display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-wrap:wrap;flex-wrap:wrap;margin:16px 0}.navlink{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;width:100%;max-width:344px;margin:16px;padding:16px;box-shadow:0 4px 8px 0 rgba(38,40,42,0.1);background-color:#fff;letter-spacing:.1px;color:#6b7480;transition:.3s all ease}.navlink:hover{box-shadow:0 8px 16px 0 rgba(38,40,42,0.1)}.navlink .navlink__title{font-size:14px;font-weight:700;line-height:1.5;color:#002d73}.navlink .navlink__descr{font-size:12px}.navlink .icon-in-circle{margin-right:12px}.article{margin-top:44px}.article .block__head{padding-bottom:32px;border-bottom:1px solid #dfe4ec}.article__heading{margin:12px 0;font-size:20px;font-weight:700;line-height:1.4;color:#002d73;letter-spacing:.1px;text-align:center}.article__heading a{color:inherit}.article__heading a .icon-in-circle + span{margin-left:8px}.article__footer{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;-ms-flex-align:center;align-items:center;margin:32px 0 8px}.article__footer .link{height:40px;margin-top:48px;font-size:13px;font-weight:600;text-align:center;color:#1776ea}.btn-toggler{display:none}.btn-toggler.is-opened{-ms-transform:scaleY(-1);transform:scaleY(-1)}.btn-toggler .icon{width:10px!important;height:10px!important}@media screen and (max-width: 768px){.ticket--article .ticket__body{-ms-flex-order:1;order:1}.ticket--article .ticket__params{-ms-flex-order:2;order:2;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;-ms-flex-flow:column-reverse;flex-flow:column-reverse}.ticket--article .ticket__params .params--block{margin-top:32px}.btn-toggler{display:-ms-inline-flexbox;display:inline-flex}.params--block.collapsed-on-xs .accordion-title > span{display:none}.params--block.collapsed-on-xs .accordion-body{display:none}.block--head > .d-flex{-ms-flex-wrap:wrap;flex-wrap:wrap}}.preview{display:-ms-flexbox;display:flex;width:100%;padding:24px 16px;border-bottom:1px solid #dfe4ec}.preview:hover{background-color:#f9fafd}.preview:hover .icon-in-circle .icon{fill:#1776ea}.preview .icon-in-circle{margin-top:-8px;margin-right:12px}.preview .preview__title{margin-bottom:10px;font-size:16px;font-weight:700;line-height:1.38;letter-spacing:.11px;color:#1776ea}@media screen and (max-width: 580px){.preview{padding:24px 0;-ms-flex-wrap:wrap;flex-wrap:wrap}.preview .preview__text{width:100%;-ms-flex-order:3;order:3}}.rate{display:-ms-inline-flexbox;display:inline-flex;margin-left:auto;font-size:12px;letter-spacing:.1px}.rate .icon{margin:0 2px}.rate .star-rate + span{font-size:12px;margin-left:8px}.preview__text{max-width:678px}.preview__text p{margin-top:8px}.block__head{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;text-align:center}.content{margin:48px 0 56px}.content .block__head{margin-bottom:16px}.topics{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;padding:32px 22px 0;border-radius:2px;box-shadow:0 2px 8px 0 rgba(38,40,42,0.1)}@media screen and (max-width: 580px){.topics{box-shadow:none;padding:32px 0 0}.topics .topics__list{padding-left:16px}}.topics__block{width:50%;margin-bottom:16px}@media screen and (max-width: 580px){.topics__block{width:100%}}.topics__title{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;font-size:16px;font-weight:700;line-height:1.38;letter-spacing:.11px;color:#002d73}.topics__title .icon{font-size:18px;fill:#959eb0;margin-right:8px}.topics__list{color:#1776ea;padding-left:46px}.topics__list li{position:relative}.topics__list li:before{content:"";position:absolute;left:-14px;top:.7em;display:inline-block;width:4px;height:4px;border-radius:50%;background-color:currentColor}.topics__list li.text-bold::before{display:none}.topics__list a{display:-ms-flexbox;display:flex;margin:16px 0;line-height:1.57;letter-spacing:.1px;color:#1776ea}.topics__list a:hover{color:#025cca}.divider{display:block;margin:32px 0;height:1px;background-color:#dfe4ec}.form-group.required label:after,.form-group.required .label:after,label.required:after,.label.required:after{content:"*";position:absolute;right:-.5em;font-size:18px;font-weight:700;line-height:1.22;color:#e02020}.label{display:-ms-inline-flexbox;display:inline-flex;position:relative;color:#959eb0}.article__heading--form{margin:0 0 32px}.article__heading + .article-heading-tip{margin-top:-32px}.article-heading-tip{display:-ms-flexbox;display:flex;-ms-flex-align:start;align-items:flex-start;-ms-flex-pack:center;justify-content:center;margin:4px auto 32px;text-align:center;font-size:12px;letter-spacing:.1px;color:#6b7480}.form-submit-ticket{margin-bottom:24px;padding:24px 32px 56px;border-radius:2px;box-shadow:0 2px 8px 0 rgba(38,40,42,0.1);background-color:#fff}.form-submit-ticket .form-groups{max-width:320px}.form-submit-ticket .form-groups.centered{margin:auto}.form-submit-ticket .form-group,.form-submit-ticket .param{max-width:560px;margin-bottom:32px}.form-submit-ticket textarea.form-control{height:200px}.captcha-block{margin:24px auto;max-width:288px;text-align:center}.captcha-block .label{margin-top:4px}.captcha-block .form-captcha{position:relative;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;margin:16px 0}.captcha-block .form-captcha img{width:100%}.btn-refresh{position:absolute;top:0;bottom:0;right:-40px;margin:auto}.btn-refresh .icon{fill:#c5cad4;font-size:16px}.form .label{display:-ms-inline-flexbox;display:inline-flex}.form h3{font-size:16px;font-weight:700;font-style:normal;font-stretch:normal;line-height:1.38;letter-spacing:.1px}.attach .block--attach{margin-top:0}.attach .attach-tooltype{margin-top:8px}.attach .attach-tooltype > span{font-size:12px;font-weight:400;font-style:italic;font-stretch:normal;line-height:1.5;letter-spacing:.1px;color:#6b7480;margin-right:4px}.attach .tooltype ul li{margin-bottom:8px;padding-left:12px;position:relative}.attach .tooltype ul li:last-child{margin-bottom:0}.attach .tooltype ul li::before{content:"";display:block;width:4px;height:4px;border-radius:50%;background-color:#6b7480;position:absolute;top:6px;left:0}.param{display:block}.param .checkbox-custom{margin-top:16px}.param .label{margin-right:8px}.param .label.required{margin-right:16px}.param.calendar{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.param.calendar h3{margin-right:16px}.param.calendar .calendar--button{position:relative;margin-right:16px}.param.calendar .calendar--button input{width:48px;height:48px;position:absolute;top:0;left:0;visibility:hidden}.param.calendar .calendar--button button{width:48px;height:48px;background-color:#fff;border:none;outline:none;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;border-radius:2px;box-shadow:0 2px 8px 0 rgba(38,40,42,0.1);transition:all 250ms ease;position:relative;z-index:1;cursor:pointer}.param.calendar .calendar--button button svg{transition:all 250ms ease}.param.calendar .calendar--button button.active svg{fill:#002d73}.param.calendar .calendar--button button:hover{box-shadow:0 8px 16px 0 rgba(38,40,42,0.1)}.param.calendar .calendar--button button .icon-calendar{width:20px;height:20px}.param.calendar .calendar--value{font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;color:#6b7480;padding-right:25px;position:relative;display:none}.param.calendar .calendar--value input{display:none}.param.calendar .calendar--value .close{display:block;width:16px;height:16px;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;cursor:pointer;position:absolute;top:3px;right:0}.param.calendar .calendar--value .close:hover svg{fill:#002d73}.param.calendar .calendar--value .close svg{width:6px;height:6px;fill:#959eb0;transition:all 250ms ease}.param--attach{display:-ms-flexbox;display:flex;-ms-flex-align:start;align-items:flex-start}.param--attach .label{margin-right:22px}.form-footer{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center}.form-footer .btn{width:240px;height:56px}.form-footer .link{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;height:40px;margin-top:32px;font-size:13px;font-weight:600;text-align:center;color:#1776ea}.ticket__body_block .block--head{margin-top:0}@media screen and (max-width: 768px){.ticket{-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-pack:end;justify-content:flex-end}.ticket__body{width:100%;margin-right:0;-ms-flex-order:2;order:2}.ticket__params{width:100%;margin-bottom:32px}}.block--head{-ms-flex-pack:justify;justify-content:space-between}.block--head .contact{margin-right:16px}.block--head .contact span + *{margin-left:8px}.block--head .contact span + span{color:#26282a!important}.btn-action{padding:0}.btn-action .icon{fill:#959eb0;font-size:16px}.ticket__body_block{padding:16px 24px}.ticket__body_block.naked{padding:0;box-shadow:none}.ticket__block-footer{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:end;justify-content:flex-end;margin-top:24px;letter-spacing:.1px;color:#959eb0}.ticket__block-footer > *{margin-left:12px}.ticket{display:-ms-flexbox;display:flex}.ticket__params .params--block{margin:0}.ticket__params .params--block .accordion-title .link{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center}.ticket__params .params--block .accordion-title .link .icon{fill:currentColor}.ticket__params .params--block + .params--block{margin-top:32px}.ticket__params .params--block .accordion-body{padding-top:0}.ticket__params .params--block .list{color:#1776ea;padding-left:10px}.ticket__params .params--block .list a{line-height:1.57;letter-spacing:.1px;color:inherit}.ticket__params .params--block .list li{position:relative;margin-top:16px}.ticket__params .params--block .list li:before{content:"";position:absolute;left:-10px;top:.7em;display:inline-block;width:4px;height:4px;border-radius:50%;background-color:currentColor}.ticket__params .params--block .list li:first-child{margin-top:0}.form--reply{margin:24px 0}.form--reply textarea{height:200px!important}.form__submit{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;-ms-flex-align:center;align-items:center}.with-label{cursor:default}#loader{position:fixed;top:0;right:0;bottom:0;left:0;background-color:#fff;z-index:100}.wrapper{display:-ms-flexbox;display:flex;width:100%;min-height:100vh;font-family:"Lato",Arial,sans-serif;color:#26282a;font-size:14px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;background-color:#fcfcfc}@media screen and (max-width: 900px){.wrapper{margin-top:48px}}.main{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;width:100%}.main__content{-ms-flex-positive:1;flex-grow:1}.clearfix{overflow:auto}.notification{background-color:#fff;box-shadow:0 4px 8px 0 rgba(0,41,89,0.1);padding:20px 28px;font-family:"Lato",Arial,sans-serif;position:relative;display:block;margin-bottom:24px}.notification::before{content:"";width:8px;height:100%;position:absolute;top:0;left:0}.notification.red{background-color:#fff5f5}.notification.red::before{background-color:#e64342}.notification.orange{background-color:#ffc}.notification.orange::before{background-color:#eeb707}.notification.green{background-color:#f0fff4}.notification.green::before{background-color:#38bc7d}.notification.blue{background-color:#ebf8ff}.notification.blue::before{background-color:#002d73}.notification b{font-weight:700}.notification-flash{width:320px;z-index:20;background-color:#fff;box-shadow:0 4px 8px 0 rgba(0,41,89,0.1);padding:24px 32px 16px;font-family:"Lato",Arial,sans-serif;position:absolute;top:144px;right:32px;display:none}.notification-flash::before{content:"";width:8px;height:100%;position:absolute;top:0;left:0}.notification-flash.red::before{background-color:#e64342}.notification-flash.orange::before{background-color:#eeb707}.notification-flash.green::before{background-color:#38bc7d}.notification-flash.blue::before{background-color:#002d73}.notification-flash .close{width:16px;height:16px;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;position:absolute;top:8px;right:8px;cursor:pointer}.notification-flash .close svg{width:8px;height:8px;fill:#c5cad4}.notification-flash .notification--title{font-size:14px;font-weight:700;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;color:#26282a}.notification-flash .notification--text{margin-top:4px;font-size:12px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.5;letter-spacing:.1px;color:#6b7480}.notification-flash .btn{margin-top:16px;width:96px}@media screen and (max-width: 900px){.notification-flash{top:0!important;right:0;width:100%;position:fixed}.notification-flash .close{width:32px;height:32px;top:50%;-ms-transform:translateY(-50%);transform:translateY(-50%)}}.tooltype{display:-ms-inline-flexbox;display:inline-flex;vertical-align:middle;cursor:pointer;position:relative}.tooltype .icon-info{width:16px;height:16px;fill:#959eb0;transition:all 250ms ease}.tooltype:hover .icon-info{fill:#002d73}.tooltype:hover .tooltype__content{display:block}.tooltype .tooltype__content{position:absolute;box-shadow:0 2px 8px 0 rgba(38,40,42,0.1);z-index:10;font-family:"Lato",Arial,sans-serif;font-size:12px;font-weight:400;font-style:normal;font-stretch:normal;line-height:1.5;letter-spacing:.1px;color:#6b7480;text-transform:initial;width:260px;display:none}.tooltype .tooltype__content .tooltype__wrapper{background-color:#fff;padding:12px 24px 14px 14px;position:relative;z-index:1;white-space:normal}.tooltype .tooltype__content a{color:#1776ea;transition:all 250ms ease}.tooltype .tooltype__content a:hover{color:#025cca}.tooltype .tooltype__content::before{content:"";display:block;width:8px;height:8px;background-color:#fff;-ms-transform:rotate(45deg);transform:rotate(45deg);position:absolute;box-shadow:0 2px 8px 0 rgba(38,40,42,0.1);z-index:0}@media screen and (max-width: 900px){.tooltype .tooltype__content{position:fixed!important;top:50%!important;left:50%!important;-ms-transform:translate(-50%,-50%)!important;transform:translate(-50%,-50%)!important}.tooltype .tooltype__content::before{display:none}}.tooltype.right .tooltype__content{top:50%;-ms-transform:translateY(-50%);transform:translateY(-50%);left:calc(100% + 4px)}.tooltype.right .tooltype__content::before{top:calc(50% - 4px);left:-4px}.tooltype.top .tooltype__content{left:50%;-ms-transform:translateX(-50%);transform:translateX(-50%);bottom:calc(100% + 4px)}.tooltype.top .tooltype__content::before{left:calc(50% - 4px);bottom:-4px}.datepicker{font-family:"Lato",Arial,sans-serif;font-size:14px;font-weight:700;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;width:368px;box-shadow:0 2px 8px 0 rgba(38,40,42,0.1);border:none}.datepicker .datepicker--pointer{bottom:20px;box-shadow:0 2px 8px 0 rgba(38,40,42,0.1);border:none}.datepicker .datepicker--cells-years,.datepicker .datepicker--years{height:auto}.datepicker .datepicker--cells-years .datepicker--cell,.datepicker .datepicker--years .datepicker--cell{margin:0 8px!important}.datepicker .datepicker--cells-months{height:auto}.datepicker .datepicker--cells-months .datepicker--cell{margin:0 8px!important}.datepicker .datepicker--content{padding:4px 16px;background-color:#fff}.datepicker .datepicker--nav{border-bottom:none;-ms-flex-pack:center;justify-content:center;font-weight:700;color:#26282a;background-color:#fff;height:48px}.datepicker .datepicker--nav i{color:#26282a}.datepicker .datepicker--cells{-ms-flex-pack:justify;justify-content:space-between}.datepicker .datepicker--cells .datepicker--cell{width:40px;height:40px;border-radius:50%;margin:0 3px 8px;transition:all 250ms ease}.datepicker .datepicker--cells .datepicker--cell.-current-{color:#38bc7d}.datepicker .datepicker--cells .datepicker--cell.-selected-{background-color:#38bc7d;color:#fff}.datepicker .datepicker--cells .datepicker--cell:hover:not(.-selected-){background-color:#f5f8ff}.datepicker .datepicker--days-names{border-bottom:1px solid #dfe4ec;margin:0;padding-bottom:8px;margin-bottom:8px}.datepicker .datepicker--days-names .datepicker--day-name{width:48px;font-family:"Lato",Arial,sans-serif;color:#959eb0;font-size:14px;font-weight:700;font-style:normal;font-stretch:normal;line-height:1.57;letter-spacing:.1px;text-align:center;text-transform:none}@media screen and (max-width: 900px){.datepicker.active{top:48vh!important;left:50vw!important;-ms-transform:translate(-50%,-50%)!important;transform:translate(-50%,-50%)!important;position:fixed}}.notification-bar{position:fixed;top:0;left:0;width:100%;display:none;background-color:#1776ea}.notification-bar .close{display:block;width:24px;height:24px;position:absolute;right:40px;top:calc(50% - 12px);cursor:pointer}.notification-bar .close:hover svg{fill:#dfe4ec}.notification-bar .close svg{width:8px;height:8px;fill:#fff}.notification-bar .notification--text{color:#fff;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;width:100%;min-height:48px}.notification-bar .btn{color:#fff;border-color:#fff;width:96px;height:32px;margin-left:32px}.notification-bar.green{background-color:#38bc7d}.notification-bar.red{background-color:#e64342}.notification-bar.orange{background-color:#eeb707}.notification-bar.blue{background-color:#002d73}.notification-bar.white{background-color:#fff;border-top:solid 1px #d4d6e3;border-bottom:solid 1px #d4d6e3}.notification-bar.white .notification--text{color:#26282a}.notification-bar.white .btn{color:#002d73;border-color:#002d73}.notification-bar.white svg{fill:#c5cad4}.star-rate{position:relative;width:84px;height:15px}.star-rate .icon-star-stroke{position:absolute;top:0;left:0;z-index:1;width:84px;height:15px}.star-rate .star-filled{position:absolute;top:0;left:0;width:0;height:15px;overflow:hidden;line-height:1}.star-rate .star-filled .icon-star-filled{width:84px;height:15px}.star-rate.rate-05 .star-filled,.star-rate.rate-5 .star-filled{z-index:2;width:10%}.star-rate.rate-10 .star-filled{z-index:2;width:20%}.star-rate.rate-15 .star-filled{z-index:2;width:30%}.star-rate.rate-20 .star-filled{z-index:2;width:40%}.star-rate.rate-25 .star-filled{z-index:2;width:50%}.star-rate.rate-30 .star-filled{z-index:2;width:60%}.star-rate.rate-35 .star-filled{z-index:2;width:70%}.star-rate.rate-40 .star-filled{z-index:2;width:80%}.star-rate.rate-45 .star-filled{z-index:2;width:90%}.star-rate.rate-50 .star-filled{z-index:2;width:100%}.main__content.notice-flash{margin-top:20px} \ No newline at end of file diff --git a/hesk/theme/hesk3/customer/error.php b/hesk/theme/hesk3/customer/error.php new file mode 100644 index 0000000..5bf88cb --- /dev/null +++ b/hesk/theme/hesk3/customer/error.php @@ -0,0 +1,116 @@ + + + + + + + <?php echo $hesk_settings['hesk_title']; ?> + + + + + + + + + + + + + +
    +
    +
    +
    +
    + +
    +
    +
    + +
    +
    +
    +
    +
    + + + +
    + +
    +
    +

    + +

    + +
    +
    + +
    + +

    + +

    +
    +
    +
    +
    + +
    +
    + + + diff --git a/hesk/theme/hesk3/customer/fonts/Lato-Bold.eot b/hesk/theme/hesk3/customer/fonts/Lato-Bold.eot new file mode 100644 index 0000000..3b814bf Binary files /dev/null and b/hesk/theme/hesk3/customer/fonts/Lato-Bold.eot differ diff --git a/hesk/theme/hesk3/customer/fonts/Lato-Bold.ttf b/hesk/theme/hesk3/customer/fonts/Lato-Bold.ttf new file mode 100644 index 0000000..1923614 Binary files /dev/null and b/hesk/theme/hesk3/customer/fonts/Lato-Bold.ttf differ diff --git a/hesk/theme/hesk3/customer/fonts/Lato-Bold.woff b/hesk/theme/hesk3/customer/fonts/Lato-Bold.woff new file mode 100644 index 0000000..e3151a1 Binary files /dev/null and b/hesk/theme/hesk3/customer/fonts/Lato-Bold.woff differ diff --git a/hesk/theme/hesk3/customer/fonts/Lato-Bold.woff2 b/hesk/theme/hesk3/customer/fonts/Lato-Bold.woff2 new file mode 100644 index 0000000..2eecae9 Binary files /dev/null and b/hesk/theme/hesk3/customer/fonts/Lato-Bold.woff2 differ diff --git a/hesk/theme/hesk3/customer/fonts/Lato-Regular.eot b/hesk/theme/hesk3/customer/fonts/Lato-Regular.eot new file mode 100644 index 0000000..b18e3ca Binary files /dev/null and b/hesk/theme/hesk3/customer/fonts/Lato-Regular.eot differ diff --git a/hesk/theme/hesk3/customer/fonts/Lato-Regular.ttf b/hesk/theme/hesk3/customer/fonts/Lato-Regular.ttf new file mode 100644 index 0000000..9c5d904 Binary files /dev/null and b/hesk/theme/hesk3/customer/fonts/Lato-Regular.ttf differ diff --git a/hesk/theme/hesk3/customer/fonts/Lato-Regular.woff b/hesk/theme/hesk3/customer/fonts/Lato-Regular.woff new file mode 100644 index 0000000..cbf37e9 Binary files /dev/null and b/hesk/theme/hesk3/customer/fonts/Lato-Regular.woff differ diff --git a/hesk/theme/hesk3/customer/fonts/Lato-Regular.woff2 b/hesk/theme/hesk3/customer/fonts/Lato-Regular.woff2 new file mode 100644 index 0000000..c9ec687 Binary files /dev/null and b/hesk/theme/hesk3/customer/fonts/Lato-Regular.woff2 differ diff --git a/hesk/theme/hesk3/customer/header.php b/hesk/theme/hesk3/customer/header.php new file mode 100644 index 0000000..86057fe --- /dev/null +++ b/hesk/theme/hesk3/customer/header.php @@ -0,0 +1,3 @@ + + + diff --git a/hesk/theme/hesk3/customer/img/label-critical.svg b/hesk/theme/hesk3/customer/img/label-critical.svg new file mode 100644 index 0000000..ef60f16 --- /dev/null +++ b/hesk/theme/hesk3/customer/img/label-critical.svg @@ -0,0 +1,3 @@ + + + diff --git a/hesk/theme/hesk3/customer/img/label-high.svg b/hesk/theme/hesk3/customer/img/label-high.svg new file mode 100644 index 0000000..5302b5b --- /dev/null +++ b/hesk/theme/hesk3/customer/img/label-high.svg @@ -0,0 +1,3 @@ + + + diff --git a/hesk/theme/hesk3/customer/img/label-low.svg b/hesk/theme/hesk3/customer/img/label-low.svg new file mode 100644 index 0000000..625ec01 --- /dev/null +++ b/hesk/theme/hesk3/customer/img/label-low.svg @@ -0,0 +1,3 @@ + + + diff --git a/hesk/theme/hesk3/customer/img/label-medium.svg b/hesk/theme/hesk3/customer/img/label-medium.svg new file mode 100644 index 0000000..e17a6c4 --- /dev/null +++ b/hesk/theme/hesk3/customer/img/label-medium.svg @@ -0,0 +1,3 @@ + + + diff --git a/hesk/theme/hesk3/customer/img/no-photo.svg b/hesk/theme/hesk3/customer/img/no-photo.svg new file mode 100644 index 0000000..b33211b --- /dev/null +++ b/hesk/theme/hesk3/customer/img/no-photo.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/hesk/theme/hesk3/customer/img/sprite.svg b/hesk/theme/hesk3/customer/img/sprite.svg new file mode 100644 index 0000000..cb9c14b --- /dev/null +++ b/hesk/theme/hesk3/customer/img/sprite.svg @@ -0,0 +1,162 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + chevron-thin-left + + + + + chevron-thin-right + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/hesk/theme/hesk3/customer/index.php b/hesk/theme/hesk3/customer/index.php new file mode 100644 index 0000000..54e5abb --- /dev/null +++ b/hesk/theme/hesk3/customer/index.php @@ -0,0 +1,280 @@ + 'none', + '1' => 'success', + '2' => '', // Info has no CSS class + '3' => 'warning', + '4' => 'danger' +); + +require_once(TEMPLATE_PATH . 'customer/util/alerts.php'); +require_once(TEMPLATE_PATH . 'customer/util/kb-search.php'); +require_once(TEMPLATE_PATH . 'customer/util/rating.php'); +?> + + + + + + <?php echo $hesk_settings['hesk_title']; ?> + + + + + + + + + + + + + + + +
    +
    +
    +
    +
    + + +
    +
    + + $value): ?> + + +
    +
    + +
    +
    +
    + +
    +
    + + + + + + + + +
    +
    + +
    +
    + + + + + + + + + + + + + + diff --git a/hesk/theme/hesk3/customer/js/app.js b/hesk/theme/hesk3/customer/js/app.js new file mode 100644 index 0000000..0dfa1c8 --- /dev/null +++ b/hesk/theme/hesk3/customer/js/app.js @@ -0,0 +1,545 @@ +/*eslint-disable */ +$(document).ready(function() { + svg4everybody(); + + // button ripple + //$('[ripple]').append('
    '); + var cleanUp, + debounce, + i, + len, + ripple, + rippleContainer, + ripples, + showRipple, + outClose; + + debounce = function(func, delay) { + var inDebounce; + inDebounce = undefined; + return function() { + var args, context; + context = this; + args = arguments; + clearTimeout(inDebounce); + return (inDebounce = setTimeout(function() { + return func.apply(context, args); + }, delay)); + }; + }; + + showRipple = function(e) { + var pos, ripple, rippler, size, style, x, y; + ripple = this; + rippler = document.createElement("span"); + size = ripple.offsetWidth; + pos = ripple.getBoundingClientRect(); + x = e.offsetX - size / 2; + y = e.offsetY - size / 2; + style = + "top:" + + y + + "px; left: " + + x + + "px; height: " + + size + + "px; width: " + + size + + "px;"; + ripple.rippleContainer.appendChild(rippler); + return rippler.setAttribute("style", style); + }; + + cleanUp = function() { + while (this.rippleContainer.firstChild) { + this.rippleContainer.removeChild(this.rippleContainer.firstChild); + } + }; + + outClose = function(time) { + time = time ? time : 150; + // header notification + $(".profile__item--notification") + .removeClass("active") + .find(".notification-list") + .slideUp(time); + + // profile menu + $(".profile__user") + .removeClass("active") + .find(".profile__menu") + .slideUp(time); + + $(".dropdown, .dropdown-select").removeClass("active"); + $(".dropdown-list").slideUp(time, function() { + $(this) + .find(".assign--buttons") + .show(); + $(this) + .find(".assign--list") + .hide(); + }); + $(".form__search_type").slideUp(150); + $(".form__search_results").slideUp(150); + }; + + dropdownSelectRender = function(el) { + var select = $(el).find("select"); + var options = []; + var value; + select.find("option").each(function(i, el) { + options.push({ + val: $(el).val(), + text: $(el).text(), + selected: $(el).is(":selected") + }); + if ($(el).is(":selected")) { + value = $(el).text(); + } + }); + var template = + '
    ' + + value + + '
    "; + $(el).append(template); + }; + + ripples = document.querySelectorAll("[ripple]"); + + for (i = 0, len = ripples.length; i < len; i++) { + ripple = ripples[i]; + rippleContainer = document.createElement("div"); + rippleContainer.className = "ripple--container"; + ripple.addEventListener("mousedown", showRipple); + ripple.addEventListener("mouseup", debounce(cleanUp, 10000)); + ripple.rippleContainer = rippleContainer; + ripple.appendChild(rippleContainer); + } + + $('.checkbox-custom input[type="checkbox"]').change(function(e) { + if ($(e.target).is(":checked")) { + $(e.target) + .closest(".checkbox-custom") + .addClass("checked"); + } else { + $(e.target) + .closest(".checkbox-custom") + .removeClass("checked"); + } + }); + + // Custom select + var x, i, j, selElmnt, a, b, c; + /*look for any elements with the class "select-custom":*/ + x = document.getElementsByClassName("select-custom"); + for (i = 0; i < x.length; i++) { + selElmnt = x[i].getElementsByTagName("select")[0]; + /*for each element, create a new DIV that will act as the selected item:*/ + a = document.createElement("DIV"); + a.setAttribute("class", "select-selected"); + a.dataset.value = selElmnt[0].value; + a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML; + x[i].insertBefore(a, selElmnt); + // x[i].insertBefore(a, x[i].firstChild); + + /*for each element, create a new DIV that will contain the option list:*/ + b = document.createElement("DIV"); + b.setAttribute("class", "select-items select-hide"); + for (j = 1; j < selElmnt.length; j++) { + /*for each option in the original select element, + create a new DIV that will act as an option item:*/ + c = document.createElement("DIV"); + c.innerHTML = selElmnt.options[j].innerHTML; + c.addEventListener("click", function(e) { + /*when an item is clicked, update the original select box, + and the selected item:*/ + var y, i, k, s, h; + s = this.parentNode.parentNode.getElementsByTagName("select")[0]; + h = this.parentNode.previousSibling; + for (i = 0; i < s.length; i++) { + if (s.options[i].innerHTML == this.innerHTML) { + s.selectedIndex = i; + h.innerHTML = this.innerHTML; + y = this.parentNode.getElementsByClassName("same-as-selected"); + for (k = 0; k < y.length; k++) { + y[k].removeAttribute("class"); + } + this.setAttribute("class", "same-as-selected"); + h.dataset.value = s.options[i].getAttribute("value"); + break; + } + } + h.click(); + }); + b.appendChild(c); + } + x[i].insertBefore(b, selElmnt); + a.addEventListener("click", function(e) { + /*when the select box is clicked, close any other select boxes, + and open/close the current select box:*/ + e.stopPropagation(); + closeAllSelect(this); + this.nextSibling.classList.toggle("select-hide"); + this.classList.toggle("select-arrow-active"); + }); + } + + function closeAllSelect(elmnt) { + /*a function that will close all select boxes in the document, + except the current select box:*/ + var x, + y, + i, + arrNo = []; + x = document.getElementsByClassName("select-items"); + y = document.getElementsByClassName("select-selected"); + for (i = 0; i < y.length; i++) { + if (elmnt == y[i]) { + arrNo.push(i); + } else { + y[i].classList.remove("select-arrow-active"); + } + } + for (i = 0; i < x.length; i++) { + if (arrNo.indexOf(i)) { + x[i].classList.add("select-hide"); + } + } + + if (!$(elmnt.target).closest(".out-close").length) outClose(); + if ($(elmnt.target).closest(".dropdown").length) return; + + event.stopPropagation(); + } + + /*if the user clicks anywhere outside the select box, then close all select boxes:*/ + var documentClick = true; + $(document).click(closeAllSelect); + $(document).on("touchend", "body", function(e) { + if (documentClick) { + $(document).unbind("click"); + documentClick = false; + } + closeAllSelect(e); + }); + + /* =========================================================== + FORM VALIDATION + ============================================================*/ + $("#formNeedValidation").submit(function(e) { + console.log("object"); + $(".form-group.required .form-control").each(function(index) { + var value = $.trim($(this).val()).length; + if (!value) { + $(this) + .closest(".form-group") + .addClass("error"); + $(this) + .closest(".form") + .addClass("invalid"); + e.preventDefault(); + } + }); + }); + + $("#formNeedValidation input").keyup(function(e) { + if ($(e.target).val()) { + $(e.target).css({ borderColor: "#d4d6e3" }); + $(e.target) + .closest(".form-group") + .removeClass("error"); + } + }); + + /* =========================================================== + Dropdown & dropdown selects + ============================================================*/ + + $(".dropdown-select").each(function(i, el) { + dropdownSelectRender(el); + }); + + $("body").on("click", ".dropdown > label", function(e) { + if ( + $(e.currentTarget) + .closest(".dropdown") + .hasClass("active") + ) { + $(e.currentTarget) + .closest(".dropdown") + .removeClass("active") + .find(".dropdown-list") + .slideUp(150); + } else { + $(".dropdown").removeClass("active"); + $(".dropdown-list").slideUp(150); + $(e.currentTarget) + .closest(".dropdown") + .addClass("active") + .find(".dropdown-list") + .slideDown(150); + } + }); + $("body").on("click", ".dropdown-list > li", function(e) { + if ($(e.currentTarget).hasClass("noclose")) return; + $(e.currentTarget) + .closest(".dropdown") + .removeClass("active") + .find(".dropdown-list") + .slideUp(150); + }); + $("body").on("click", ".dropdown-select .label", function(e) { + if ( + $(e.currentTarget) + .closest(".dropdown-select") + .hasClass("active") + ) { + $(e.currentTarget) + .closest(".dropdown-select") + .removeClass("active") + .find(".dropdown-list") + .slideUp(150); + } else { + $(".dropdown-select").removeClass("active"); + $(".dropdown-list").slideUp(150); + $(e.currentTarget) + .closest(".dropdown-select") + .addClass("active") + .find(".dropdown-list") + .slideDown(150); + } + }); + $("body").on("click", ".dropdown-list > li", function(e) { + if ($(e.currentTarget).hasClass("noclose")) return; + $(e.currentTarget) + .closest(".dropdown") + .removeClass("active") + .find(".dropdown-list") + .slideUp(150); + }); + $("body").on("click", ".dropdown-select .dropdown-list li", function(e) { + var text, value; + value = $(e.currentTarget).attr("data-option"); + if ( + $(e.currentTarget) + .closest(".dropdown-select") + .hasClass("submit-us") + ) { + text = value.length + ? "Submit as " + $(e.currentTarget).text() + : $(e.currentTarget).text(); + text = + text + .toLowerCase() + .charAt(0) + .toUpperCase() + text.toLowerCase().substr(1); + } else { + text = $(e.currentTarget).text(); + } + $(e.currentTarget) + .closest(".dropdown-list") + .find("li") + .removeClass("selected"); + $(e.currentTarget).addClass("selected"); + $(e.currentTarget) + .closest(".dropdown-select") + .attr("data-value", value) + .find(".label span") + .text(text); + $(e.currentTarget) + .closest(".dropdown-select") + .removeClass("active"); + $(e.currentTarget) + .closest(".dropdown-list") + .slideUp(150); + $(e.currentTarget) + .closest(".dropdown-select") + .find('select option[value="' + value + '"]') + .prop("selected", true); + $(e.currentTarget).closest('.dropdown-select').find('select').trigger('change'); + }); + + // End Dropdown & dropdown selects + + /* =========================================================== + Ticket details + ============================================================*/ + $(".ticket__replies_link").click(function(e) { + if ($(e.currentTarget).hasClass("visible")) { + $(e.currentTarget).removeClass("visible"); + $(".ticket__replies_list").slideUp(150); + } else { + $(".ticket__replies_list").slideDown(150); + $(e.currentTarget).addClass("visible"); + } + }); + + // Ticket upload file + var ticketFiles = []; + $('.block--attach input[type="file"]').change(function(e) { + for (i = 0; i < e.target.files.length; i++) { + ticketFiles.push(e.target.files[i]); + var extension = + "." + + e.target.files[i].name.split(".")[ + e.target.files[i].name.split(".").length - 1 + ]; + var name = ""; + for (n = 0; n < e.target.files[i].name.split(".").length; n++) { + if (n < e.target.files[i].name.split(".").length - 1) { + name += e.target.files[i].name.split(".")[n]; + } + } + if (name.length > 16) + name = + name.slice(0, 10) + "..." + name.slice(name.length - 8, name.length); + var label = + "
    " + + name + + extension + + '
    '; + $(".block--attach-list").append(label); + $(".block--attach-list div").each(function(i, el) { + $(el).attr("data-i", i); + }); + } + }); + $("body").on("click", ".block--attach-list div i", function(e) { + var i = Number( + $(e.target) + .closest("div") + .attr("data-i") + ); + ticketFiles.splice(i, 1); + $(e.currentTarget) + .closest("div") + .slideUp(150, function() { + $(e.currentTarget) + .closest("div") + .remove(); + $(".block--attach-list div").each(function(i, el) { + $(el).attr("data-i", i); + }); + }); + console.log(ticketFiles); + }); + + $(".accordion-title").click(function(e) { + if ( + $(e.currentTarget) + .closest(".accordion") + .hasClass("visible") + ) { + $(e.currentTarget) + .closest(".accordion") + .find(".accordion-body") + .slideUp(150); + $(e.currentTarget) + .closest(".accordion") + .removeClass("visible"); + } else { + $(e.currentTarget) + .closest(".accordion") + .find(".accordion-body") + .slideDown(150); + $(e.currentTarget) + .closest(".accordion") + .addClass("visible"); + } + }); + + /* =========================================================== + Create ticket + ============================================================*/ + $(".datepicker").datepicker({ + language: "en", + position: "right bottom", + autoClose: true, + onSelect: function(formattedDate, date, inst) { + if (formattedDate.length) { + inst.$el + .parent() + .parent() + .find('.calendar--value').fadeIn(150).find('span').text(formattedDate); + } + }, + onHide: function(inst, animationCompleted) { + $(".ticket-create .param.calendar button").removeClass("active"); + } + }); + $(".ticket-create .param.calendar button").click(function(e) { + $(this).addClass("active"); + $(this).parent().find('.datepicker') + .data("datepicker") + .show(); + }); + $(".ticket-create .param.calendar .close").click(function(e) { + $(this).parent().parent() + .find('.calendar--button') + .find('.datepicker') + .data("datepicker") + .clear(); + $(".ticket-create .param.calendar .calendar--value").fadeOut( + 150, + function() { + $(this) + .find("span") + .text(""); + } + ); + }); + $('[data-action="create-ticket"]').click(function(e) { + $("body").addClass("noscroll"); + $(".right-bar.ticket-create").fadeIn(150); + }); + + /* =========================================================== + Tooltyps + ============================================================*/ + $("body").on("mouseenter", ".tooltype", function(e) { + $(this) + .find(".tooltype__content") + .fadeIn(150); + }); + $("body").on("mouseleave", ".tooltype", function(e) { + $(this) + .find(".tooltype__content") + .fadeOut(150); + }); + /* =========================================================== + start Customer help + ============================================================*/ + $(".tabbed__head_tabs li").click(function(e) { + var target = $(this).attr("data-link"); + $(".tabbed__head_tabs li").removeClass("current"); + $(this).addClass("current"); + $(".tabbed__tabs .tabbed__tabs_tab").removeClass("is-visible"); + $(".tabbed__tabs [data-tab=" + target + "]").addClass("is-visible"); + }); + $(".btn-toggler").click(function(e) { + $(this) + .closest(".params--block") + .find(".accordion-body") + .slideToggle(); + $(this).toggleClass("is-opened"); + }); + + // Never allow typing in dropdowns + $('.selectize-input input').prop('disabled', 'disabled'); +}); + +window.onload = function() { + $("#loader").fadeOut(150); +}; diff --git a/hesk/theme/hesk3/customer/js/app.min.js b/hesk/theme/hesk3/customer/js/app.min.js new file mode 100644 index 0000000..5f26621 --- /dev/null +++ b/hesk/theme/hesk3/customer/js/app.min.js @@ -0,0 +1,14 @@ +$(document).ready(function(){svg4everybody();var cleanUp,debounce,i,len,ripple,rippleContainer,ripples,showRipple,outClose;debounce=function(func,delay){var inDebounce;inDebounce=undefined;return function(){var args,context;context=this;args=arguments;clearTimeout(inDebounce);return(inDebounce=setTimeout(function(){return func.apply(context,args)},delay))}};showRipple=function(e){var pos,ripple,rippler,size,style,x,y;ripple=this;rippler=document.createElement("span");size=ripple.offsetWidth;pos=ripple.getBoundingClientRect();x=e.offsetX-size/2;y=e.offsetY-size/2;style="top:"+y+"px; left: "+x+"px; height: "+size+"px; width: "+size+"px;";ripple.rippleContainer.appendChild(rippler);return rippler.setAttribute("style",style)};cleanUp=function(){while(this.rippleContainer.firstChild){this.rippleContainer.removeChild(this.rippleContainer.firstChild)}};outClose=function(time){time=time?time:150;$(".profile__item--notification").removeClass("active").find(".notification-list").slideUp(time);$(".profile__user").removeClass("active").find(".profile__menu").slideUp(time);$(".dropdown, .dropdown-select").removeClass("active");$(".dropdown-list").slideUp(time,function(){$(this).find(".assign--buttons").show();$(this).find(".assign--list").hide()});$(".form__search_type").slideUp(150);$(".form__search_results").slideUp(150)};dropdownSelectRender=function(el){var select=$(el).find("select");var options=[];var value;select.find("option").each(function(i,el){options.push({val:$(el).val(),text:$(el).text(),selected:$(el).is(":selected")});if($(el).is(":selected")){value=$(el).text()}});var template='
    '+value+'
    ";$(el).append(template)};ripples=document.querySelectorAll("[ripple]");for(i=0,len=ripples.length;i label",function(e){if($(e.currentTarget).closest(".dropdown").hasClass("active")){$(e.currentTarget).closest(".dropdown").removeClass("active").find(".dropdown-list").slideUp(150)}else{$(".dropdown").removeClass("active");$(".dropdown-list").slideUp(150);$(e.currentTarget).closest(".dropdown").addClass("active").find(".dropdown-list").slideDown(150)}});$("body").on("click",".dropdown-list > li",function(e){if($(e.currentTarget).hasClass("noclose"))return;$(e.currentTarget).closest(".dropdown").removeClass("active").find(".dropdown-list").slideUp(150)});$("body").on("click",".dropdown-select .label",function(e){if($(e.currentTarget).closest(".dropdown-select").hasClass("active")){$(e.currentTarget).closest(".dropdown-select").removeClass("active").find(".dropdown-list").slideUp(150)}else{$(".dropdown-select").removeClass("active");$(".dropdown-list").slideUp(150);$(e.currentTarget).closest(".dropdown-select").addClass("active").find(".dropdown-list").slideDown(150)}});$("body").on("click",".dropdown-list > li",function(e){if($(e.currentTarget).hasClass("noclose"))return;$(e.currentTarget).closest(".dropdown").removeClass("active").find(".dropdown-list").slideUp(150)});$("body").on("click",".dropdown-select .dropdown-list li",function(e){var text,value;value=$(e.currentTarget).attr("data-option");if($(e.currentTarget).closest(".dropdown-select").hasClass("submit-us")){text=value.length?"Submit as "+$(e.currentTarget).text():$(e.currentTarget).text();text=text.toLowerCase().charAt(0).toUpperCase()+text.toLowerCase().substr(1)}else{text=$(e.currentTarget).text()} +$(e.currentTarget).closest(".dropdown-list").find("li").removeClass("selected");$(e.currentTarget).addClass("selected");$(e.currentTarget).closest(".dropdown-select").attr("data-value",value).find(".label span").text(text);$(e.currentTarget).closest(".dropdown-select").removeClass("active");$(e.currentTarget).closest(".dropdown-list").slideUp(150);$(e.currentTarget).closest(".dropdown-select").find('select option[value="'+value+'"]').prop("selected",!0);$(e.currentTarget).closest('.dropdown-select').find('select').trigger('change')});$(".ticket__replies_link").click(function(e){if($(e.currentTarget).hasClass("visible")){$(e.currentTarget).removeClass("visible");$(".ticket__replies_list").slideUp(150)}else{$(".ticket__replies_list").slideDown(150);$(e.currentTarget).addClass("visible")}});var ticketFiles=[];$('.block--attach input[type="file"]').change(function(e){for(i=0;i16) +name=name.slice(0,10)+"..."+name.slice(name.length-8,name.length);var label="
    "+name+extension+'
    ';$(".block--attach-list").append(label);$(".block--attach-list div").each(function(i,el){$(el).attr("data-i",i)})}});$("body").on("click",".block--attach-list div i",function(e){var i=Number($(e.target).closest("div").attr("data-i"));ticketFiles.splice(i,1);$(e.currentTarget).closest("div").slideUp(150,function(){$(e.currentTarget).closest("div").remove();$(".block--attach-list div").each(function(i,el){$(el).attr("data-i",i)})});console.log(ticketFiles)});$(".accordion-title").click(function(e){if($(e.currentTarget).closest(".accordion").hasClass("visible")){$(e.currentTarget).closest(".accordion").find(".accordion-body").slideUp(150);$(e.currentTarget).closest(".accordion").removeClass("visible")}else{$(e.currentTarget).closest(".accordion").find(".accordion-body").slideDown(150);$(e.currentTarget).closest(".accordion").addClass("visible")}});$(".datepicker").datepicker({language:"en",position:"right bottom",autoClose:!0,onSelect:function(formattedDate,date,inst){if(formattedDate.length){inst.$el.parent().parent().find('.calendar--value').fadeIn(150).find('span').text(formattedDate)}},onHide:function(inst,animationCompleted){$(".ticket-create .param.calendar button").removeClass("active")}});$(".ticket-create .param.calendar button").click(function(e){$(this).addClass("active");$(this).parent().find('.datepicker').data("datepicker").show()});$(".ticket-create .param.calendar .close").click(function(e){$(this).parent().parent().find('.calendar--button').find('.datepicker').data("datepicker").clear();$(".ticket-create .param.calendar .calendar--value").fadeOut(150,function(){$(this).find("span").text("")})});$('[data-action="create-ticket"]').click(function(e){$("body").addClass("noscroll");$(".right-bar.ticket-create").fadeIn(150)});$("body").on("mouseenter",".tooltype",function(e){$(this).find(".tooltype__content").fadeIn(150)});$("body").on("mouseleave",".tooltype",function(e){$(this).find(".tooltype__content").fadeOut(150)});$(".tabbed__head_tabs li").click(function(e){var target=$(this).attr("data-link");$(".tabbed__head_tabs li").removeClass("current");$(this).addClass("current");$(".tabbed__tabs .tabbed__tabs_tab").removeClass("is-visible");$(".tabbed__tabs [data-tab="+target+"]").addClass("is-visible")});$(".btn-toggler").click(function(e){$(this).closest(".params--block").find(".accordion-body").slideToggle();$(this).toggleClass("is-opened")});$('.selectize-input input').prop('disabled','disabled')});window.onload=function(){$("#loader").fadeOut(150)} \ No newline at end of file diff --git a/hesk/theme/hesk3/customer/js/datepicker.en.js b/hesk/theme/hesk3/customer/js/datepicker.en.js new file mode 100644 index 0000000..6097edd --- /dev/null +++ b/hesk/theme/hesk3/customer/js/datepicker.en.js @@ -0,0 +1,13 @@ +;(function ($) { $.fn.datepicker.language['en'] = { + days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + daysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], + daysMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + months: ['January','February','March','April','May','June', 'July','August','September','October','November','December'], + monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + today: 'Today', + clear: 'Clear', + dateFormat: 'mm/dd/yyyy', + timeFormat: 'hh:ii aa', + firstDay: 1 +}; })(jQuery); +//# sourceMappingURL=datepicker.en.js.map diff --git a/hesk/theme/hesk3/customer/js/datepicker.min.js b/hesk/theme/hesk3/customer/js/datepicker.min.js new file mode 100644 index 0000000..53df79a --- /dev/null +++ b/hesk/theme/hesk3/customer/js/datepicker.min.js @@ -0,0 +1,3 @@ +!function(t,e,i){!function(){var s,a,n,h="2.2.3",o="datepicker",r=".datepicker-here",c=!1,d='
    ',l={classes:"",inline:!1,language:"ru",startDate:new Date,firstDay:"",weekends:[6,0],dateFormat:"",altField:"",altFieldDateFormat:"@",toggleSelected:!0,keyboardNav:!0,position:"bottom left",offset:12,view:"days",minView:"days",showOtherMonths:!0,selectOtherMonths:!0,moveToOtherMonthsOnSelect:!0,showOtherYears:!0,selectOtherYears:!0,moveToOtherYearsOnSelect:!0,minDate:"",maxDate:"",disableNavWhenOutOfRange:!0,multipleDates:!1,multipleDatesSeparator:",",range:!1,todayButton:!1,clearButton:!1,showEvent:"focus",autoClose:!1,monthsField:"monthsShort",prevHtml:'',nextHtml:'',navTitles:{days:"MM, yyyy",months:"yyyy",years:"yyyy1 - yyyy2"},timepicker:!1,onlyTimepicker:!1,dateTimeSeparator:" ",timeFormat:"",minHours:0,maxHours:24,minMinutes:0,maxMinutes:59,hoursStep:1,minutesStep:1,onSelect:"",onShow:"",onHide:"",onChangeMonth:"",onChangeYear:"",onChangeDecade:"",onChangeView:"",onRenderCell:""},u={ctrlRight:[17,39],ctrlUp:[17,38],ctrlLeft:[17,37],ctrlDown:[17,40],shiftRight:[16,39],shiftUp:[16,38],shiftLeft:[16,37],shiftDown:[16,40],altUp:[18,38],altRight:[18,39],altLeft:[18,37],altDown:[18,40],ctrlShiftUp:[16,17,38]},m=function(t,a){this.el=t,this.$el=e(t),this.opts=e.extend(!0,{},l,a,this.$el.data()),s==i&&(s=e("body")),this.opts.startDate||(this.opts.startDate=new Date),"INPUT"==this.el.nodeName&&(this.elIsInput=!0),this.opts.altField&&(this.$altField="string"==typeof this.opts.altField?e(this.opts.altField):this.opts.altField),this.inited=!1,this.visible=!1,this.silent=!1,this.currentDate=this.opts.startDate,this.currentView=this.opts.view,this._createShortCuts(),this.selectedDates=[],this.views={},this.keys=[],this.minRange="",this.maxRange="",this._prevOnSelectValue="",this.init()};n=m,n.prototype={VERSION:h,viewIndexes:["days","months","years"],init:function(){c||this.opts.inline||!this.elIsInput||this._buildDatepickersContainer(),this._buildBaseHtml(),this._defineLocale(this.opts.language),this._syncWithMinMaxDates(),this.elIsInput&&(this.opts.inline||(this._setPositionClasses(this.opts.position),this._bindEvents()),this.opts.keyboardNav&&!this.opts.onlyTimepicker&&this._bindKeyboardEvents(),this.$datepicker.on("mousedown",this._onMouseDownDatepicker.bind(this)),this.$datepicker.on("mouseup",this._onMouseUpDatepicker.bind(this))),this.opts.classes&&this.$datepicker.addClass(this.opts.classes),this.opts.timepicker&&(this.timepicker=new e.fn.datepicker.Timepicker(this,this.opts),this._bindTimepickerEvents()),this.opts.onlyTimepicker&&this.$datepicker.addClass("-only-timepicker-"),this.views[this.currentView]=new e.fn.datepicker.Body(this,this.currentView,this.opts),this.views[this.currentView].show(),this.nav=new e.fn.datepicker.Navigation(this,this.opts),this.view=this.currentView,this.$el.on("clickCell.adp",this._onClickCell.bind(this)),this.$datepicker.on("mouseenter",".datepicker--cell",this._onMouseEnterCell.bind(this)),this.$datepicker.on("mouseleave",".datepicker--cell",this._onMouseLeaveCell.bind(this)),this.inited=!0},_createShortCuts:function(){this.minDate=this.opts.minDate?this.opts.minDate:new Date(-86399999136e5),this.maxDate=this.opts.maxDate?this.opts.maxDate:new Date(86399999136e5)},_bindEvents:function(){this.$el.on(this.opts.showEvent+".adp",this._onShowEvent.bind(this)),this.$el.on("mouseup.adp",this._onMouseUpEl.bind(this)),this.$el.on("blur.adp",this._onBlur.bind(this)),this.$el.on("keyup.adp",this._onKeyUpGeneral.bind(this)),e(t).on("resize.adp",this._onResize.bind(this)),e("body").on("mouseup.adp",this._onMouseUpBody.bind(this))},_bindKeyboardEvents:function(){this.$el.on("keydown.adp",this._onKeyDown.bind(this)),this.$el.on("keyup.adp",this._onKeyUp.bind(this)),this.$el.on("hotKey.adp",this._onHotKey.bind(this))},_bindTimepickerEvents:function(){this.$el.on("timeChange.adp",this._onTimeChange.bind(this))},isWeekend:function(t){return-1!==this.opts.weekends.indexOf(t)},_defineLocale:function(t){"string"==typeof t?(this.loc=e.fn.datepicker.language[t],this.loc||(console.warn("Can't find language \""+t+'" in Datepicker.language, will use "ru" instead'),this.loc=e.extend(!0,{},e.fn.datepicker.language.ru)),this.loc=e.extend(!0,{},e.fn.datepicker.language.ru,e.fn.datepicker.language[t])):this.loc=e.extend(!0,{},e.fn.datepicker.language.ru,t),this.opts.dateFormat&&(this.loc.dateFormat=this.opts.dateFormat),this.opts.timeFormat&&(this.loc.timeFormat=this.opts.timeFormat),""!==this.opts.firstDay&&(this.loc.firstDay=this.opts.firstDay),this.opts.timepicker&&(this.loc.dateFormat=[this.loc.dateFormat,this.loc.timeFormat].join(this.opts.dateTimeSeparator)),this.opts.onlyTimepicker&&(this.loc.dateFormat=this.loc.timeFormat);var i=this._getWordBoundaryRegExp;(this.loc.timeFormat.match(i("aa"))||this.loc.timeFormat.match(i("AA")))&&(this.ampm=!0)},_buildDatepickersContainer:function(){c=!0,s.append('
    '),a=e("#datepickers-container")},_buildBaseHtml:function(){var t,i=e('
    ');t="INPUT"==this.el.nodeName?this.opts.inline?i.insertAfter(this.$el):a:i.appendTo(this.$el),this.$datepicker=e(d).appendTo(t),this.$content=e(".datepicker--content",this.$datepicker),this.$nav=e(".datepicker--nav",this.$datepicker)},_triggerOnChange:function(){if(!this.selectedDates.length){if(""===this._prevOnSelectValue)return;return this._prevOnSelectValue="",this.opts.onSelect("","",this)}var t,e=this.selectedDates,i=n.getParsedDate(e[0]),s=this,a=new Date(i.year,i.month,i.date,i.hours,i.minutes);t=e.map(function(t){return s.formatDate(s.loc.dateFormat,t)}).join(this.opts.multipleDatesSeparator),(this.opts.multipleDates||this.opts.range)&&(a=e.map(function(t){var e=n.getParsedDate(t);return new Date(e.year,e.month,e.date,e.hours,e.minutes)})),this._prevOnSelectValue=t,this.opts.onSelect(t,a,this)},next:function(){var t=this.parsedDate,e=this.opts;switch(this.view){case"days":this.date=new Date(t.year,t.month+1,1),e.onChangeMonth&&e.onChangeMonth(this.parsedDate.month,this.parsedDate.year);break;case"months":this.date=new Date(t.year+1,t.month,1),e.onChangeYear&&e.onChangeYear(this.parsedDate.year);break;case"years":this.date=new Date(t.year+10,0,1),e.onChangeDecade&&e.onChangeDecade(this.curDecade)}},prev:function(){var t=this.parsedDate,e=this.opts;switch(this.view){case"days":this.date=new Date(t.year,t.month-1,1),e.onChangeMonth&&e.onChangeMonth(this.parsedDate.month,this.parsedDate.year);break;case"months":this.date=new Date(t.year-1,t.month,1),e.onChangeYear&&e.onChangeYear(this.parsedDate.year);break;case"years":this.date=new Date(t.year-10,0,1),e.onChangeDecade&&e.onChangeDecade(this.curDecade)}},formatDate:function(t,e){e=e||this.date;var i,s=t,a=this._getWordBoundaryRegExp,h=this.loc,o=n.getLeadingZeroNum,r=n.getDecade(e),c=n.getParsedDate(e),d=c.fullHours,l=c.hours,u=t.match(a("aa"))||t.match(a("AA")),m="am",p=this._replacer;switch(this.opts.timepicker&&this.timepicker&&u&&(i=this.timepicker._getValidHoursFromDate(e,u),d=o(i.hours),l=i.hours,m=i.dayPeriod),!0){case/@/.test(s):s=s.replace(/@/,e.getTime());case/aa/.test(s):s=p(s,a("aa"),m);case/AA/.test(s):s=p(s,a("AA"),m.toUpperCase());case/dd/.test(s):s=p(s,a("dd"),c.fullDate);case/d/.test(s):s=p(s,a("d"),c.date);case/DD/.test(s):s=p(s,a("DD"),h.days[c.day]);case/D/.test(s):s=p(s,a("D"),h.daysShort[c.day]);case/mm/.test(s):s=p(s,a("mm"),c.fullMonth);case/m/.test(s):s=p(s,a("m"),c.month+1);case/MM/.test(s):s=p(s,a("MM"),this.loc.months[c.month]);case/M/.test(s):s=p(s,a("M"),h.monthsShort[c.month]);case/ii/.test(s):s=p(s,a("ii"),c.fullMinutes);case/i/.test(s):s=p(s,a("i"),c.minutes);case/hh/.test(s):s=p(s,a("hh"),d);case/h/.test(s):s=p(s,a("h"),l);case/yyyy/.test(s):s=p(s,a("yyyy"),c.year);case/yyyy1/.test(s):s=p(s,a("yyyy1"),r[0]);case/yyyy2/.test(s):s=p(s,a("yyyy2"),r[1]);case/yy/.test(s):s=p(s,a("yy"),c.year.toString().slice(-2))}return s},_replacer:function(t,e,i){return t.replace(e,function(t,e,s,a){return e+i+a})},_getWordBoundaryRegExp:function(t){var e="\\s|\\.|-|/|\\\\|,|\\$|\\!|\\?|:|;";return new RegExp("(^|>|"+e+")("+t+")($|<|"+e+")","g")},selectDate:function(t){var e=this,i=e.opts,s=e.parsedDate,a=e.selectedDates,h=a.length,o="";if(Array.isArray(t))return void t.forEach(function(t){e.selectDate(t)});if(t instanceof Date){if(this.lastSelectedDate=t,this.timepicker&&this.timepicker._setTime(t),e._trigger("selectDate",t),this.timepicker&&(t.setHours(this.timepicker.hours),t.setMinutes(this.timepicker.minutes)),"days"==e.view&&t.getMonth()!=s.month&&i.moveToOtherMonthsOnSelect&&(o=new Date(t.getFullYear(),t.getMonth(),1)),"years"==e.view&&t.getFullYear()!=s.year&&i.moveToOtherYearsOnSelect&&(o=new Date(t.getFullYear(),0,1)),o&&(e.silent=!0,e.date=o,e.silent=!1,e.nav._render()),i.multipleDates&&!i.range){if(h===i.multipleDates)return;e._isSelected(t)||e.selectedDates.push(t)}else i.range?2==h?(e.selectedDates=[t],e.minRange=t,e.maxRange=""):1==h?(e.selectedDates.push(t),e.maxRange?e.minRange=t:e.maxRange=t,n.bigger(e.maxRange,e.minRange)&&(e.maxRange=e.minRange,e.minRange=t),e.selectedDates=[e.minRange,e.maxRange]):(e.selectedDates=[t],e.minRange=t):e.selectedDates=[t];e._setInputValue(),i.onSelect&&e._triggerOnChange(),i.autoClose&&!this.timepickerIsActive&&(i.multipleDates||i.range?i.range&&2==e.selectedDates.length&&e.hide():e.hide()),e.views[this.currentView]._render()}},removeDate:function(t){var e=this.selectedDates,i=this;if(t instanceof Date)return e.some(function(s,a){return n.isSame(s,t)?(e.splice(a,1),i.selectedDates.length?i.lastSelectedDate=i.selectedDates[i.selectedDates.length-1]:(i.minRange="",i.maxRange="",i.lastSelectedDate=""),i.views[i.currentView]._render(),i._setInputValue(),i.opts.onSelect&&i._triggerOnChange(),!0):void 0})},today:function(){this.silent=!0,this.view=this.opts.minView,this.silent=!1,this.date=new Date,this.opts.todayButton instanceof Date&&this.selectDate(this.opts.todayButton)},clear:function(){this.selectedDates=[],this.minRange="",this.maxRange="",this.views[this.currentView]._render(),this._setInputValue(),this.opts.onSelect&&this._triggerOnChange()},update:function(t,i){var s=arguments.length,a=this.lastSelectedDate;return 2==s?this.opts[t]=i:1==s&&"object"==typeof t&&(this.opts=e.extend(!0,this.opts,t)),this._createShortCuts(),this._syncWithMinMaxDates(),this._defineLocale(this.opts.language),this.nav._addButtonsIfNeed(),this.opts.onlyTimepicker||this.nav._render(),this.views[this.currentView]._render(),this.elIsInput&&!this.opts.inline&&(this._setPositionClasses(this.opts.position),this.visible&&this.setPosition(this.opts.position)),this.opts.classes&&this.$datepicker.addClass(this.opts.classes),this.opts.onlyTimepicker&&this.$datepicker.addClass("-only-timepicker-"),this.opts.timepicker&&(a&&this.timepicker._handleDate(a),this.timepicker._updateRanges(),this.timepicker._updateCurrentTime(),a&&(a.setHours(this.timepicker.hours),a.setMinutes(this.timepicker.minutes))),this._setInputValue(),this},_syncWithMinMaxDates:function(){var t=this.date.getTime();this.silent=!0,this.minTime>t&&(this.date=this.minDate),this.maxTime=this.minTime&&i<=this.maxTime,month:o>=this.minTime&&r<=this.maxTime,year:s.year>=a.year&&s.year<=h.year};return e?c[e]:c.day},_getDimensions:function(t){var e=t.offset();return{width:t.outerWidth(),height:t.outerHeight(),left:e.left,top:e.top}},_getDateFromCell:function(t){var e=this.parsedDate,s=t.data("year")||e.year,a=t.data("month")==i?e.month:t.data("month"),n=t.data("date")||1;return new Date(s,a,n)},_setPositionClasses:function(t){t=t.split(" ");var e=t[0],i=t[1],s="datepicker -"+e+"-"+i+"- -from-"+e+"-";this.visible&&(s+=" active"),this.$datepicker.removeAttr("class").addClass(s)},setPosition:function(t){t=t||this.opts.position;var e,i,s=this._getDimensions(this.$el),a=this._getDimensions(this.$datepicker),n=t.split(" "),h=this.opts.offset,o=n[0],r=n[1];switch(o){case"top":e=s.top-a.height-h;break;case"right":i=s.left+s.width+h;break;case"bottom":e=s.top+s.height+h;break;case"left":i=s.left-a.width-h}switch(r){case"top":e=s.top;break;case"right":i=s.left+s.width-a.width;break;case"bottom":e=s.top+s.height-a.height;break;case"left":i=s.left;break;case"center":/left|right/.test(o)?e=s.top+s.height/2-a.height/2:i=s.left+s.width/2-a.width/2}this.$datepicker.css({left:i,top:e})},show:function(){var t=this.opts.onShow;this.setPosition(this.opts.position),this.$datepicker.addClass("active"),this.visible=!0,t&&this._bindVisionEvents(t)},hide:function(){var t=this.opts.onHide;this.$datepicker.removeClass("active").css({left:"-100000px"}),this.focused="",this.keys=[],this.inFocus=!1,this.visible=!1,this.$el.blur(),t&&this._bindVisionEvents(t)},down:function(t){this._changeView(t,"down")},up:function(t){this._changeView(t,"up")},_bindVisionEvents:function(t){this.$datepicker.off("transitionend.dp"),t(this,!1),this.$datepicker.one("transitionend.dp",t.bind(this,this,!0))},_changeView:function(t,e){t=t||this.focused||this.date;var i="up"==e?this.viewIndex+1:this.viewIndex-1;i>2&&(i=2),0>i&&(i=0),this.silent=!0,this.date=new Date(t.getFullYear(),t.getMonth(),1),this.silent=!1,this.view=this.viewIndexes[i]},_handleHotKey:function(t){var e,i,s,a=n.getParsedDate(this._getFocusedDate()),h=this.opts,o=!1,r=!1,c=!1,d=a.year,l=a.month,u=a.date;switch(t){case"ctrlRight":case"ctrlUp":l+=1,o=!0;break;case"ctrlLeft":case"ctrlDown":l-=1,o=!0;break;case"shiftRight":case"shiftUp":r=!0,d+=1;break;case"shiftLeft":case"shiftDown":r=!0,d-=1;break;case"altRight":case"altUp":c=!0,d+=10;break;case"altLeft":case"altDown":c=!0,d-=10;break;case"ctrlShiftUp":this.up()}s=n.getDaysCount(new Date(d,l)),i=new Date(d,l,u),u>s&&(u=s),i.getTime()this.maxTime&&(i=this.maxDate),this.focused=i,e=n.getParsedDate(i),o&&h.onChangeMonth&&h.onChangeMonth(e.month,e.year),r&&h.onChangeYear&&h.onChangeYear(e.year),c&&h.onChangeDecade&&h.onChangeDecade(this.curDecade)},_registerKey:function(t){var e=this.keys.some(function(e){return e==t});e||this.keys.push(t)},_unRegisterKey:function(t){var e=this.keys.indexOf(t);this.keys.splice(e,1)},_isHotKeyPressed:function(){var t,e=!1,i=this,s=this.keys.sort();for(var a in u)t=u[a],s.length==t.length&&t.every(function(t,e){return t==s[e]})&&(i._trigger("hotKey",a),e=!0);return e},_trigger:function(t,e){this.$el.trigger(t,e)},_focusNextCell:function(t,e){e=e||this.cellType;var i=n.getParsedDate(this._getFocusedDate()),s=i.year,a=i.month,h=i.date;if(!this._isHotKeyPressed()){switch(t){case 37:"day"==e?h-=1:"","month"==e?a-=1:"","year"==e?s-=1:"";break;case 38:"day"==e?h-=7:"","month"==e?a-=3:"","year"==e?s-=4:"";break;case 39:"day"==e?h+=1:"","month"==e?a+=1:"","year"==e?s+=1:"";break;case 40:"day"==e?h+=7:"","month"==e?a+=3:"","year"==e?s+=4:""}var o=new Date(s,a,h);o.getTime()this.maxTime&&(o=this.maxDate),this.focused=o}},_getFocusedDate:function(){var t=this.focused||this.selectedDates[this.selectedDates.length-1],e=this.parsedDate;if(!t)switch(this.view){case"days":t=new Date(e.year,e.month,(new Date).getDate());break;case"months":t=new Date(e.year,e.month,1);break;case"years":t=new Date(e.year,0,1)}return t},_getCell:function(t,i){i=i||this.cellType;var s,a=n.getParsedDate(t),h='.datepicker--cell[data-year="'+a.year+'"]';switch(i){case"month":h='[data-month="'+a.month+'"]';break;case"day":h+='[data-month="'+a.month+'"][data-date="'+a.date+'"]'}return s=this.views[this.currentView].$el.find(h),s.length?s:e("")},destroy:function(){var t=this;t.$el.off(".adp").data("datepicker",""),t.selectedDates=[],t.focused="",t.views={},t.keys=[],t.minRange="",t.maxRange="",t.opts.inline||!t.elIsInput?t.$datepicker.closest(".datepicker-inline").remove():t.$datepicker.remove()},_handleAlreadySelectedDates:function(t,e){this.opts.range?this.opts.toggleSelected?this.removeDate(e):2!=this.selectedDates.length&&this._trigger("clickCell",e):this.opts.toggleSelected&&this.removeDate(e),this.opts.toggleSelected||(this.lastSelectedDate=t,this.opts.timepicker&&(this.timepicker._setTime(t),this.timepicker.update()))},_onShowEvent:function(t){this.visible||this.show()},_onBlur:function(){!this.inFocus&&this.visible&&this.hide()},_onMouseDownDatepicker:function(t){this.inFocus=!0},_onMouseUpDatepicker:function(t){this.inFocus=!1,t.originalEvent.inFocus=!0,t.originalEvent.timepickerFocus||this.$el.focus()},_onKeyUpGeneral:function(t){var e=this.$el.val();e||this.clear()},_onResize:function(){this.visible&&this.setPosition()},_onMouseUpBody:function(t){t.originalEvent.inFocus||this.visible&&!this.inFocus&&this.hide()},_onMouseUpEl:function(t){t.originalEvent.inFocus=!0,setTimeout(this._onKeyUpGeneral.bind(this),4)},_onKeyDown:function(t){var e=t.which;if(this._registerKey(e),e>=37&&40>=e&&(t.preventDefault(),this._focusNextCell(e)),13==e&&this.focused){if(this._getCell(this.focused).hasClass("-disabled-"))return;if(this.view!=this.opts.minView)this.down();else{var i=this._isSelected(this.focused,this.cellType);if(!i)return this.timepicker&&(this.focused.setHours(this.timepicker.hours),this.focused.setMinutes(this.timepicker.minutes)),void this.selectDate(this.focused);this._handleAlreadySelectedDates(i,this.focused)}}27==e&&this.hide()},_onKeyUp:function(t){var e=t.which;this._unRegisterKey(e)},_onHotKey:function(t,e){this._handleHotKey(e)},_onMouseEnterCell:function(t){var i=e(t.target).closest(".datepicker--cell"),s=this._getDateFromCell(i);this.silent=!0,this.focused&&(this.focused=""),i.addClass("-focus-"),this.focused=s,this.silent=!1,this.opts.range&&1==this.selectedDates.length&&(this.minRange=this.selectedDates[0],this.maxRange="",n.less(this.minRange,this.focused)&&(this.maxRange=this.minRange,this.minRange=""),this.views[this.currentView]._update())},_onMouseLeaveCell:function(t){var i=e(t.target).closest(".datepicker--cell");i.removeClass("-focus-"),this.silent=!0,this.focused="",this.silent=!1},_onTimeChange:function(t,e,i){var s=new Date,a=this.selectedDates,n=!1;a.length&&(n=!0,s=this.lastSelectedDate),s.setHours(e),s.setMinutes(i),n||this._getCell(s).hasClass("-disabled-")?(this._setInputValue(),this.opts.onSelect&&this._triggerOnChange()):this.selectDate(s)},_onClickCell:function(t,e){this.timepicker&&(e.setHours(this.timepicker.hours),e.setMinutes(this.timepicker.minutes)),this.selectDate(e)},set focused(t){if(!t&&this.focused){var e=this._getCell(this.focused);e.length&&e.removeClass("-focus-")}this._focused=t,this.opts.range&&1==this.selectedDates.length&&(this.minRange=this.selectedDates[0],this.maxRange="",n.less(this.minRange,this._focused)&&(this.maxRange=this.minRange,this.minRange="")),this.silent||(this.date=t)},get focused(){return this._focused},get parsedDate(){return n.getParsedDate(this.date)},set date(t){return t instanceof Date?(this.currentDate=t,this.inited&&!this.silent&&(this.views[this.view]._render(),this.nav._render(),this.visible&&this.elIsInput&&this.setPosition()),t):void 0},get date(){return this.currentDate},set view(t){return this.viewIndex=this.viewIndexes.indexOf(t),this.viewIndex<0?void 0:(this.prevView=this.currentView,this.currentView=t,this.inited&&(this.views[t]?this.views[t]._render():this.views[t]=new e.fn.datepicker.Body(this,t,this.opts),this.views[this.prevView].hide(),this.views[t].show(),this.nav._render(),this.opts.onChangeView&&this.opts.onChangeView(t),this.elIsInput&&this.visible&&this.setPosition()),t)},get view(){return this.currentView},get cellType(){return this.view.substring(0,this.view.length-1)},get minTime(){var t=n.getParsedDate(this.minDate);return new Date(t.year,t.month,t.date).getTime()},get maxTime(){var t=n.getParsedDate(this.maxDate);return new Date(t.year,t.month,t.date).getTime()},get curDecade(){return n.getDecade(this.date)}},n.getDaysCount=function(t){return new Date(t.getFullYear(),t.getMonth()+1,0).getDate()},n.getParsedDate=function(t){return{year:t.getFullYear(),month:t.getMonth(),fullMonth:t.getMonth()+1<10?"0"+(t.getMonth()+1):t.getMonth()+1,date:t.getDate(),fullDate:t.getDate()<10?"0"+t.getDate():t.getDate(),day:t.getDay(),hours:t.getHours(),fullHours:t.getHours()<10?"0"+t.getHours():t.getHours(),minutes:t.getMinutes(),fullMinutes:t.getMinutes()<10?"0"+t.getMinutes():t.getMinutes()}},n.getDecade=function(t){var e=10*Math.floor(t.getFullYear()/10);return[e,e+9]},n.template=function(t,e){return t.replace(/#\{([\w]+)\}/g,function(t,i){return e[i]||0===e[i]?e[i]:void 0})},n.isSame=function(t,e,i){if(!t||!e)return!1;var s=n.getParsedDate(t),a=n.getParsedDate(e),h=i?i:"day",o={day:s.date==a.date&&s.month==a.month&&s.year==a.year,month:s.month==a.month&&s.year==a.year,year:s.year==a.year};return o[h]},n.less=function(t,e,i){return t&&e?e.getTime()t.getTime():!1},n.getLeadingZeroNum=function(t){return parseInt(t)<10?"0"+t:t},n.resetTime=function(t){return"object"==typeof t?(t=n.getParsedDate(t),new Date(t.year,t.month,t.date)):void 0},e.fn.datepicker=function(t){return this.each(function(){if(e.data(this,o)){var i=e.data(this,o);i.opts=e.extend(!0,i.opts,t),i.update()}else e.data(this,o,new m(this,t))})},e.fn.datepicker.Constructor=m,e.fn.datepicker.language={ru:{days:["ВоÑкреÑенье","Понедельник","Вторник","Среда","Четверг","ПÑтница","Суббота"],daysShort:["ВоÑ","Пон","Вто","Сре","Чет","ПÑÑ‚","Суб"],daysMin:["Ð’Ñ","Пн","Ð’Ñ‚","Ср","Чт","Пт","Сб"],months:["Январь","Февраль","Март","Ðпрель","Май","Июнь","Июль","ÐвгуÑÑ‚","СентÑбрь","ОктÑбрь","ÐоÑбрь","Декабрь"],monthsShort:["Янв","Фев","Мар","Ðпр","Май","Июн","Июл","Ðвг","Сен","Окт","ÐоÑ","Дек"],today:"СегоднÑ",clear:"ОчиÑтить",dateFormat:"dd.mm.yyyy",timeFormat:"hh:ii",firstDay:1}},e(function(){e(r).datepicker()})}(),function(){var t={days:'
    ',months:'
    ',years:'
    '},s=e.fn.datepicker,a=s.Constructor;s.Body=function(t,i,s){this.d=t,this.type=i,this.opts=s,this.$el=e(""),this.opts.onlyTimepicker||this.init()},s.Body.prototype={init:function(){this._buildBaseHtml(),this._render(),this._bindEvents()},_bindEvents:function(){this.$el.on("click",".datepicker--cell",e.proxy(this._onClickCell,this))},_buildBaseHtml:function(){this.$el=e(t[this.type]).appendTo(this.d.$content),this.$names=e(".datepicker--days-names",this.$el),this.$cells=e(".datepicker--cells",this.$el)},_getDayNamesHtml:function(t,e,s,a){return e=e!=i?e:t,s=s?s:"",a=a!=i?a:0,a>7?s:7==e?this._getDayNamesHtml(t,0,s,++a):(s+='
    '+this.d.loc.daysMin[e]+"
    ",this._getDayNamesHtml(t,++e,s,++a))},_getCellContents:function(t,e){var i="datepicker--cell datepicker--cell-"+e,s=new Date,n=this.d,h=a.resetTime(n.minRange),o=a.resetTime(n.maxRange),r=n.opts,c=a.getParsedDate(t),d={},l=c.date;switch(e){case"day":n.isWeekend(c.day)&&(i+=" -weekend-"),c.month!=this.d.parsedDate.month&&(i+=" -other-month-",r.selectOtherMonths||(i+=" -disabled-"),r.showOtherMonths||(l=""));break;case"month":l=n.loc[n.opts.monthsField][c.month];break;case"year":var u=n.curDecade;l=c.year,(c.yearu[1])&&(i+=" -other-decade-",r.selectOtherYears||(i+=" -disabled-"),r.showOtherYears||(l=""))}return r.onRenderCell&&(d=r.onRenderCell(t,e)||{},l=d.html?d.html:l,i+=d.classes?" "+d.classes:""),r.range&&(a.isSame(h,t,e)&&(i+=" -range-from-"),a.isSame(o,t,e)&&(i+=" -range-to-"),1==n.selectedDates.length&&n.focused?((a.bigger(h,t)&&a.less(n.focused,t)||a.less(o,t)&&a.bigger(n.focused,t))&&(i+=" -in-range-"),a.less(o,t)&&a.isSame(n.focused,t)&&(i+=" -range-from-"),a.bigger(h,t)&&a.isSame(n.focused,t)&&(i+=" -range-to-")):2==n.selectedDates.length&&a.bigger(h,t)&&a.less(o,t)&&(i+=" -in-range-")),a.isSame(s,t,e)&&(i+=" -current-"),n.focused&&a.isSame(t,n.focused,e)&&(i+=" -focus-"),n._isSelected(t,e)&&(i+=" -selected-"),(!n._isInRange(t,e)||d.disabled)&&(i+=" -disabled-"),{html:l,classes:i}},_getDaysHtml:function(t){var e=a.getDaysCount(t),i=new Date(t.getFullYear(),t.getMonth(),1).getDay(),s=new Date(t.getFullYear(),t.getMonth(),e).getDay(),n=i-this.d.loc.firstDay,h=6-s+this.d.loc.firstDay;n=0>n?n+7:n,h=h>6?h-7:h;for(var o,r,c=-n+1,d="",l=c,u=e+h;u>=l;l++)r=t.getFullYear(),o=t.getMonth(),d+=this._getDayHtml(new Date(r,o,l));return d},_getDayHtml:function(t){var e=this._getCellContents(t,"day");return'
    '+e.html+"
    "},_getMonthsHtml:function(t){for(var e="",i=a.getParsedDate(t),s=0;12>s;)e+=this._getMonthHtml(new Date(i.year,s)),s++;return e},_getMonthHtml:function(t){var e=this._getCellContents(t,"month");return'
    '+e.html+"
    "},_getYearsHtml:function(t){var e=(a.getParsedDate(t),a.getDecade(t)),i=e[0]-1,s="",n=i;for(n;n<=e[1]+1;n++)s+=this._getYearHtml(new Date(n,0));return s},_getYearHtml:function(t){var e=this._getCellContents(t,"year");return'
    '+e.html+"
    "},_renderTypes:{days:function(){var t=this._getDayNamesHtml(this.d.loc.firstDay),e=this._getDaysHtml(this.d.currentDate);this.$cells.html(e),this.$names.html(t)},months:function(){var t=this._getMonthsHtml(this.d.currentDate);this.$cells.html(t)},years:function(){var t=this._getYearsHtml(this.d.currentDate);this.$cells.html(t)}},_render:function(){this.opts.onlyTimepicker||this._renderTypes[this.type].bind(this)()},_update:function(){var t,i,s,a=e(".datepicker--cell",this.$cells),n=this;a.each(function(a,h){i=e(this),s=n.d._getDateFromCell(e(this)),t=n._getCellContents(s,n.d.cellType),i.attr("class",t.classes)})},show:function(){this.opts.onlyTimepicker||(this.$el.addClass("active"),this.acitve=!0)},hide:function(){this.$el.removeClass("active"),this.active=!1},_handleClick:function(t){var e=t.data("date")||1,i=t.data("month")||0,s=t.data("year")||this.d.parsedDate.year,a=this.d;if(a.view!=this.opts.minView)return void a.down(new Date(s,i,e));var n=new Date(s,i,e),h=this.d._isSelected(n,this.d.cellType);return h?void a._handleAlreadySelectedDates.bind(a,h,n)():void a._trigger("clickCell",n)},_onClickCell:function(t){var i=e(t.target).closest(".datepicker--cell");i.hasClass("-disabled-")||this._handleClick.bind(this)(i)}}}(),function(){var t='
    #{prevHtml}
    #{title}
    #{nextHtml}
    ',i='
    ',s='#{label}',a=e.fn.datepicker,n=a.Constructor;a.Navigation=function(t,e){this.d=t,this.opts=e,this.$buttonsContainer="",this.init()},a.Navigation.prototype={init:function(){this._buildBaseHtml(),this._bindEvents()},_bindEvents:function(){this.d.$nav.on("click",".datepicker--nav-action",e.proxy(this._onClickNavButton,this)),this.d.$nav.on("click",".datepicker--nav-title",e.proxy(this._onClickNavTitle,this)),this.d.$datepicker.on("click",".datepicker--button",e.proxy(this._onClickNavButton,this))},_buildBaseHtml:function(){this.opts.onlyTimepicker||this._render(),this._addButtonsIfNeed()},_addButtonsIfNeed:function(){this.opts.todayButton&&this._addButton("today"),this.opts.clearButton&&this._addButton("clear")},_render:function(){var i=this._getTitle(this.d.currentDate),s=n.template(t,e.extend({title:i},this.opts));this.d.$nav.html(s),"years"==this.d.view&&e(".datepicker--nav-title",this.d.$nav).addClass("-disabled-"),this.setNavStatus()},_getTitle:function(t){return this.d.formatDate(this.opts.navTitles[this.d.view],t)},_addButton:function(t){this.$buttonsContainer.length||this._addButtonsContainer();var i={action:t,label:this.d.loc[t]},a=n.template(s,i);e("[data-action="+t+"]",this.$buttonsContainer).length||this.$buttonsContainer.append(a)},_addButtonsContainer:function(){this.d.$datepicker.append(i),this.$buttonsContainer=e(".datepicker--buttons",this.d.$datepicker)},setNavStatus:function(){if((this.opts.minDate||this.opts.maxDate)&&this.opts.disableNavWhenOutOfRange){var t=this.d.parsedDate,e=t.month,i=t.year,s=t.date;switch(this.d.view){case"days":this.d._isInRange(new Date(i,e-1,1),"month")||this._disableNav("prev"),this.d._isInRange(new Date(i,e+1,1),"month")||this._disableNav("next");break;case"months":this.d._isInRange(new Date(i-1,e,s),"year")||this._disableNav("prev"),this.d._isInRange(new Date(i+1,e,s),"year")||this._disableNav("next");break;case"years":var a=n.getDecade(this.d.date);this.d._isInRange(new Date(a[0]-1,0,1),"year")||this._disableNav("prev"),this.d._isInRange(new Date(a[1]+1,0,1),"year")||this._disableNav("next")}}},_disableNav:function(t){e('[data-action="'+t+'"]',this.d.$nav).addClass("-disabled-")},_activateNav:function(t){e('[data-action="'+t+'"]',this.d.$nav).removeClass("-disabled-")},_onClickNavButton:function(t){var i=e(t.target).closest("[data-action]"),s=i.data("action");this.d[s]()},_onClickNavTitle:function(t){return e(t.target).hasClass("-disabled-")?void 0:"days"==this.d.view?this.d.view="months":void(this.d.view="years")}}}(),function(){var t='
    #{hourVisible} : #{minValue}
    ',i=e.fn.datepicker,s=i.Constructor;i.Timepicker=function(t,e){this.d=t,this.opts=e,this.init()},i.Timepicker.prototype={init:function(){var t="input";this._setTime(this.d.date),this._buildHTML(),navigator.userAgent.match(/trident/gi)&&(t="change"),this.d.$el.on("selectDate",this._onSelectDate.bind(this)),this.$ranges.on(t,this._onChangeRange.bind(this)),this.$ranges.on("mouseup",this._onMouseUpRange.bind(this)),this.$ranges.on("mousemove focus ",this._onMouseEnterRange.bind(this)),this.$ranges.on("mouseout blur",this._onMouseOutRange.bind(this))},_setTime:function(t){var e=s.getParsedDate(t);this._handleDate(t),this.hours=e.hourst.getHours()&&(this.minMinutes=this.opts.minMinutes)},_setMaxTimeFromDate:function(t){ +this.maxHours=t.getHours(),this.maxMinutes=t.getMinutes(),this.d.lastSelectedDate&&this.d.lastSelectedDate.getHours()t?0:i.minHours,this.minMinutes=i.minMinutes<0||i.minMinutes>e?0:i.minMinutes,this.maxHours=i.maxHours<0||i.maxHours>t?t:i.maxHours,this.maxMinutes=i.maxMinutes<0||i.maxMinutes>e?e:i.maxMinutes},_validateHoursMinutes:function(t){this.hoursthis.maxHours&&(this.hours=this.maxHours),this.minutesthis.maxMinutes&&(this.minutes=this.maxMinutes)},_buildHTML:function(){var i=s.getLeadingZeroNum,a={hourMin:this.minHours,hourMax:i(this.maxHours),hourStep:this.opts.hoursStep,hourValue:this.hours,hourVisible:i(this.displayHours),minMin:this.minMinutes,minMax:i(this.maxMinutes),minStep:this.opts.minutesStep,minValue:i(this.minutes)},n=s.template(t,a);this.$timepicker=e(n).appendTo(this.d.$datepicker),this.$ranges=e('[type="range"]',this.$timepicker),this.$hours=e('[name="hours"]',this.$timepicker),this.$minutes=e('[name="minutes"]',this.$timepicker),this.$hoursText=e(".datepicker--time-current-hours",this.$timepicker),this.$minutesText=e(".datepicker--time-current-minutes",this.$timepicker),this.d.ampm&&(this.$ampm=e('').appendTo(e(".datepicker--time-current",this.$timepicker)).html(this.dayPeriod),this.$timepicker.addClass("-am-pm-"))},_updateCurrentTime:function(){var t=s.getLeadingZeroNum(this.displayHours),e=s.getLeadingZeroNum(this.minutes);this.$hoursText.html(t),this.$minutesText.html(e),this.d.ampm&&this.$ampm.html(this.dayPeriod)},_updateRanges:function(){this.$hours.attr({min:this.minHours,max:this.maxHours}).val(this.hours),this.$minutes.attr({min:this.minMinutes,max:this.maxMinutes}).val(this.minutes)},_handleDate:function(t){this._setDefaultMinMaxTime(),t&&(s.isSame(t,this.d.opts.minDate)?this._setMinTimeFromDate(this.d.opts.minDate):s.isSame(t,this.d.opts.maxDate)&&this._setMaxTimeFromDate(this.d.opts.maxDate)),this._validateHoursMinutes(t)},update:function(){this._updateRanges(),this._updateCurrentTime()},_getValidHoursFromDate:function(t,e){var i=t,a=t;t instanceof Date&&(i=s.getParsedDate(t),a=i.hours);var n=e||this.d.ampm,h="am";if(n)switch(!0){case 0==a:a=12;break;case 12==a:h="pm";break;case a>11:a-=12,h="pm"}return{hours:a,dayPeriod:h}},set hours(t){this._hours=t;var e=this._getValidHoursFromDate(t);this.displayHours=e.hours,this.dayPeriod=e.dayPeriod},get hours(){return this._hours},_onChangeRange:function(t){var i=e(t.target),s=i.attr("name");this.d.timepickerIsActive=!0,this[s]=i.val(),this._updateCurrentTime(),this.d._trigger("timeChange",[this.hours,this.minutes]),this._handleDate(this.d.lastSelectedDate),this.update()},_onSelectDate:function(t,e){this._handleDate(e),this.update()},_onMouseEnterRange:function(t){var i=e(t.target).attr("name");e(".datepicker--time-current-"+i,this.$timepicker).addClass("-focus-")},_onMouseOutRange:function(t){var i=e(t.target).attr("name");this.d.inFocus||e(".datepicker--time-current-"+i,this.$timepicker).removeClass("-focus-")},_onMouseUpRange:function(t){this.d.timepickerIsActive=!1}}}()}(window,jQuery); +//# sourceMappingURL=datepicker.min.js.map diff --git a/hesk/theme/hesk3/customer/js/hesk_functions.js b/hesk/theme/hesk3/customer/js/hesk_functions.js new file mode 100644 index 0000000..13bb4c0 --- /dev/null +++ b/hesk/theme/hesk3/customer/js/hesk_functions.js @@ -0,0 +1,165 @@ +var HESK_FUNCTIONS; +if (!HESK_FUNCTIONS) { + HESK_FUNCTIONS = {}; +} + +var heskKBfailed = false; +var heskKBquery = ''; +HESK_FUNCTIONS.getKbSearchSuggestions = function($input, callback) { + var d = document.form1; + var s = $input.val(); + + if (s !== '' && (heskKBquery !== s || heskKBfailed === true) ) + { + var params = "q=" + encodeURIComponent(s); + heskKBquery = s; + + $.ajax({ + url: 'suggest_articles.php', + method: 'POST', + dataType: 'json', + contentType: 'application/x-www-form-urlencoded', + data: params, + success: function(data) { + heskKBfailed = false; + callback(data); + }, + error: function(jqXHR, status, err) { + console.error(err); + heskKBfailed = true; + } + }); + } + + setTimeout(function() { HESK_FUNCTIONS.getKbSearchSuggestions($input, callback); }, 2000); +}; + +HESK_FUNCTIONS.getKbTicketSuggestions = function($subject, $message, callback) { + var d = document.form1; + var s = $subject.val(); + var m = $message.val(); + var query = s + " " + m; + + if (s !== '' && m !== '' && (heskKBquery !== query || heskKBfailed === true) ) + { + var params = "q=" + encodeURIComponent(query); + heskKBquery = query; + + $.ajax({ + url: 'suggest_articles.php', + method: 'POST', + dataType: 'json', + contentType: 'application/x-www-form-urlencoded', + data: params, + success: function(data) { + heskKBfailed = false; + callback(data); + }, + error: function(jqXHR, status, err) { + console.error(err); + heskKBfailed = true; + } + }); + } + + setTimeout(function() { HESK_FUNCTIONS.getKbTicketSuggestions($subject, $message, callback); }, 2000); +}; + +HESK_FUNCTIONS.openWindow = function(PAGE,HGT,WDT) { + var heskWin = window.open(PAGE,"Hesk_window","height="+HGT+",width="+WDT+",menubar=0,location=0,toolbar=0,status=0,resizable=1,scrollbars=1"); + heskWin.focus(); +}; + +HESK_FUNCTIONS.suggestEmail = function(emailField, displayDiv, isAdmin, allowMultiple) { + var email = document.getElementById(emailField).value; + var element = document.getElementById(displayDiv); + var path = isAdmin ? '../suggest_email.php' : 'suggest_email.php'; + + if (email !== '') { + var params = "e=" + encodeURIComponent(email) + "&ef=" + encodeURIComponent(emailField) + "&dd=" + encodeURIComponent(displayDiv); + + if (allowMultiple) { + params += "&am=1"; + } + + + /* + {0}: Div ID + {1}: Suggestion message (i.e. "Did you mean hesk@example.com?") + {2}: Original email + {3}: Suggested email (pre-escaped) + {4}: "Yes, fix it" + {5}: "No, leave it" + */ + var responseFormat = + '
    ' + + '
    ' + + '

    ' + + '

    {1}

    ' + + '' + + '{4}' + + ' | ' + + '' + + '{5}' + + '' + + '

    ' + + '
    ' + + '
    '; + + $.ajax({ + url: path, + method: 'POST', + dataType: 'json', + contentType: 'application/x-www-form-urlencoded', + data: params, + success: function(data) { + var $displayDiv = $('#' + displayDiv); + $displayDiv.html(''); + if (!data.length) { + $displayDiv.hide(); + } else { + $displayDiv.show(); + } + $.each(data, function() { + $displayDiv.append(responseFormat + .replace(/\{0}/g, this.id) + .replace(/\{1}/g, this.suggestText) + .replace(/\{2}/g, this.originalAddress) + .replace(/\{3}/g, this.formattedSuggestedEmail) + .replace(/\{4}/g, this.yesResponseText) + .replace(/\{5}/g, this.noResponseText)); + }); + }, + error: function(jqXHR, status, err) { + console.error(err); + } + }); + } +}; + +HESK_FUNCTIONS.applyEmailSuggestion = function(emailTypoId, emailField, originalEmail, formattedSuggestedEmail) { + var eml = document.getElementById(emailField).value; + var regex = new RegExp(originalEmail, "gi"); + document.getElementById(emailField).value = eml.replace(regex, formattedSuggestedEmail); + document.getElementById(emailTypoId).style.display = 'none'; +}; + +HESK_FUNCTIONS.rate = function(url, elementId) { + if (url.length === 0) { + return false; + } + + var element = document.getElementById(elementId); + + $.ajax({ + url: url, + method: 'GET', + dataType: 'text', + success: function(resp) { + element.innerHTML = resp; + }, + error: function(jqXHR, statusText, err) { + console.error(err); + } + }); +} \ No newline at end of file diff --git a/hesk/theme/hesk3/customer/js/hesk_functions.min.js b/hesk/theme/hesk3/customer/js/hesk_functions.min.js new file mode 100644 index 0000000..08eeb14 --- /dev/null +++ b/hesk/theme/hesk3/customer/js/hesk_functions.min.js @@ -0,0 +1,9 @@ +var HESK_FUNCTIONS;if(!HESK_FUNCTIONS){HESK_FUNCTIONS={}} +var heskKBfailed=!1;var heskKBquery='';HESK_FUNCTIONS.getKbSearchSuggestions=function($input,callback){var d=document.form1;var s=$input.val();if(s!==''&&(heskKBquery!==s||heskKBfailed===!0)) +{var params="q="+encodeURIComponent(s);heskKBquery=s;$.ajax({url:'suggest_articles.php',method:'POST',dataType:'json',contentType:'application/x-www-form-urlencoded',data:params,success:function(data){heskKBfailed=!1;callback(data)},error:function(jqXHR,status,err){console.error(err);heskKBfailed=!0}})} +setTimeout(function(){HESK_FUNCTIONS.getKbSearchSuggestions($input,callback)},2000)};HESK_FUNCTIONS.getKbTicketSuggestions=function($subject,$message,callback){var d=document.form1;var s=$subject.val();var m=$message.val();var query=s+" "+m;if(s!==''&&m!==''&&(heskKBquery!==query||heskKBfailed===!0)) +{var params="q="+encodeURIComponent(query);heskKBquery=query;$.ajax({url:'suggest_articles.php',method:'POST',dataType:'json',contentType:'application/x-www-form-urlencoded',data:params,success:function(data){heskKBfailed=!1;callback(data)},error:function(jqXHR,status,err){console.error(err);heskKBfailed=!0}})} +setTimeout(function(){HESK_FUNCTIONS.getKbTicketSuggestions($subject,$message,callback)},2000)};HESK_FUNCTIONS.openWindow=function(PAGE,HGT,WDT){var heskWin=window.open(PAGE,"Hesk_window","height="+HGT+",width="+WDT+",menubar=0,location=0,toolbar=0,status=0,resizable=1,scrollbars=1");heskWin.focus()};HESK_FUNCTIONS.suggestEmail=function(emailField,displayDiv,isAdmin,allowMultiple){var email=document.getElementById(emailField).value;var element=document.getElementById(displayDiv);var path=isAdmin?'../suggest_email.php':'suggest_email.php';if(email!==''){var params="e="+encodeURIComponent(email)+"&ef="+encodeURIComponent(emailField)+"&dd="+encodeURIComponent(displayDiv);if(allowMultiple){params+="&am=1"} +var responseFormat='
    '+'
    '+'

    '+'

    {1}

    '+''+'{4}'+' | '+''+'{5}'+''+'

    '+'
    '+'
    ';$.ajax({url:path,method:'POST',dataType:'json',contentType:'application/x-www-form-urlencoded',data:params,success:function(data){var $displayDiv=$('#'+displayDiv);$displayDiv.html('');if(!data.length){$displayDiv.hide()}else{$displayDiv.show()} +$.each(data,function(){$displayDiv.append(responseFormat.replace(/\{0}/g,this.id).replace(/\{1}/g,this.suggestText).replace(/\{2}/g,this.originalAddress).replace(/\{3}/g,this.formattedSuggestedEmail).replace(/\{4}/g,this.yesResponseText).replace(/\{5}/g,this.noResponseText))})},error:function(jqXHR,status,err){console.error(err)}})}};HESK_FUNCTIONS.applyEmailSuggestion=function(emailTypoId,emailField,originalEmail,formattedSuggestedEmail){var eml=document.getElementById(emailField).value;var regex=new RegExp(originalEmail,"gi");document.getElementById(emailField).value=eml.replace(regex,formattedSuggestedEmail);document.getElementById(emailTypoId).style.display='none'};HESK_FUNCTIONS.rate=function(url,elementId){if(url.length===0){return!1} +var element=document.getElementById(elementId);$.ajax({url:url,method:'GET',dataType:'text',success:function(resp){element.innerHTML=resp},error:function(jqXHR,statusText,err){console.error(err)}})} \ No newline at end of file diff --git a/hesk/theme/hesk3/customer/js/jquery-3.4.1.min.js b/hesk/theme/hesk3/customer/js/jquery-3.4.1.min.js new file mode 100644 index 0000000..42a1299 --- /dev/null +++ b/hesk/theme/hesk3/customer/js/jquery-3.4.1.min.js @@ -0,0 +1,4 @@ +/*! jQuery v3.4.1 | (c) JS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],E=C.document,r=Object.getPrototypeOf,s=t.slice,g=t.concat,u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.4.1",k=function(e,t){return new k.fn.init(e,t)},p=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;function d(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp($),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+$),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ne=function(e,t,n){var r="0x"+t-65536;return r!=r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(m.childNodes),m.childNodes),t[m.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&((e?e.ownerDocument||e:m)!==C&&T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!A[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&U.test(t)){(s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=k),o=(l=h(t)).length;while(o--)l[o]="#"+s+" "+xe(l[o]);c=l.join(","),f=ee.test(t)&&ye(e.parentNode)||e}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){A(t,!0)}finally{s===k&&e.removeAttribute("id")}}}return g(t.replace(B,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[k]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:m;return r!==C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),m!==C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=k,!C.getElementsByName||!C.getElementsByName(k).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+k+"-]").length||v.push("~="),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+k+"+*").length||v.push(".#.+[+~]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",$)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e===C||e.ownerDocument===m&&y(m,e)?-1:t===C||t.ownerDocument===m&&y(m,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===C?-1:t===C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]===m?-1:s[r]===m?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if((e.ownerDocument||e)!==C&&T(e),d.matchesSelector&&E&&!A[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){A(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=p[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&p(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?k.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?k.grep(e,function(e){return e===n!==r}):"string"!=typeof n?k.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(k.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:L.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof k?t[0]:t,k.merge(this,k.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),D.test(r[1])&&k.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(k):k.makeArray(e,this)}).prototype=k.fn,q=k(E);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}k.fn.extend({has:function(e){var t=k(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,""],thead:[1,"","
    "],col:[2,"","
    "],tr:[2,"","
    "],td:[3,"","
    "],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?k.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;nx",y.noCloneChecked=!!me.cloneNode(!0).lastChild.defaultValue;var Te=/^key/,Ce=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ee=/^([^.]*)(?:\.(.+)|)/;function ke(){return!0}function Se(){return!1}function Ne(e,t){return e===function(){try{return E.activeElement}catch(e){}}()==("focus"===t)}function Ae(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)Ae(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Se;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return k().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=k.guid++)),e.each(function(){k.event.add(this,t,i,r,n)})}function De(e,i,o){o?(Q.set(e,i,!1),k.event.add(e,i,{namespace:!1,handler:function(e){var t,n,r=Q.get(this,i);if(1&e.isTrigger&&this[i]){if(r.length)(k.event.special[i]||{}).delegateType&&e.stopPropagation();else if(r=s.call(arguments),Q.set(this,i,r),t=o(this,i),this[i](),r!==(n=Q.get(this,i))||t?Q.set(this,i,!1):n={},r!==n)return e.stopImmediatePropagation(),e.preventDefault(),n.value}else r.length&&(Q.set(this,i,{value:k.event.trigger(k.extend(r[0],k.Event.prototype),r.slice(1),this)}),e.stopImmediatePropagation())}})):void 0===Q.get(e,i)&&k.event.add(e,i,ke)}k.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.get(t);if(v){n.handler&&(n=(o=n).handler,i=o.selector),i&&k.find.matchesSelector(ie,i),n.guid||(n.guid=k.guid++),(u=v.events)||(u=v.events={}),(a=v.handle)||(a=v.handle=function(e){return"undefined"!=typeof k&&k.event.triggered!==e.type?k.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(R)||[""]).length;while(l--)d=g=(s=Ee.exec(e[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=k.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=k.event.special[d]||{},c=k.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&k.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(d,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),k.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.hasData(e)&&Q.get(e);if(v&&(u=v.events)){l=(t=(t||"").match(R)||[""]).length;while(l--)if(d=g=(s=Ee.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d){f=k.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,v.handle)||k.removeEvent(e,d,v.handle),delete u[d])}else for(d in u)k.event.remove(e,d+t[l],n,r,!0);k.isEmptyObject(u)&&Q.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=k.event.fix(e),u=new Array(arguments.length),l=(Q.get(this,"events")||{})[s.type]||[],c=k.event.special[s.type]||{};for(u[0]=s,t=1;t\x20\t\r\n\f]*)[^>]*)\/>/gi,qe=/\s*$/g;function Oe(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&k(e).children("tbody")[0]||e}function Pe(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Re(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Me(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(Q.hasData(e)&&(o=Q.access(e),a=Q.set(t,o),l=o.events))for(i in delete a.handle,a.events={},l)for(n=0,r=l[i].length;n")},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=oe(e);if(!(y.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||k.isXMLDoc(e)))for(a=ve(c),r=0,i=(o=ve(e)).length;r").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Vt,Gt=[],Yt=/(=)\?(?=&|$)|\?\?/;k.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Gt.pop()||k.expando+"_"+kt++;return this[e]=!0,e}}),k.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Yt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Yt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Yt,"$1"+r):!1!==e.jsonp&&(e.url+=(St.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||k.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?k(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Gt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Vt=E.implementation.createHTMLDocument("").body).innerHTML="
    ",2===Vt.childNodes.length),k.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=D.exec(e))?[t.createElement(i[1])]:(i=we([e],t,o),o&&o.length&&k(o).remove(),k.merge([],i.childNodes)));var r,i,o},k.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(k.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},k.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){k.fn[t]=function(e){return this.on(t,e)}}),k.expr.pseudos.animated=function(t){return k.grep(k.timers,function(e){return t===e.elem}).length},k.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=k.css(e,"position"),c=k(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=k.css(e,"top"),u=k.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,k.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},k.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){k.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===k.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===k.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=k(e).offset()).top+=k.css(e,"borderTopWidth",!0),i.left+=k.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-k.css(r,"marginTop",!0),left:t.left-i.left-k.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===k.css(e,"position"))e=e.offsetParent;return e||ie})}}),k.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;k.fn[t]=function(e){return _(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),k.each(["top","left"],function(e,n){k.cssHooks[n]=ze(y.pixelPosition,function(e,t){if(t)return t=_e(e,n),$e.test(t)?k(e).position()[n]+"px":t})}),k.each({Height:"height",Width:"width"},function(a,s){k.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){k.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return _(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?k.css(e,t,i):k.style(e,t,n,i)},s,n?e:void 0,n)}})}),k.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){k.fn[n]=function(e,t){return 0 + */ +(function ($) { + 'use strict'; + var ARROWLEFT = 37, + ARROWRIGHT = 39, + ARROWUP = 38, + ARROWDOWN = 40, + TAB = 9, + CTRLKEY = 17, + SHIFTKEY = 16, + DEL = 46, + ENTER = 13, + ESC = 27, + BACKSPACE = 8, + AKEY = 65, + CKEY = 67, + VKEY = 86, + ZKEY = 90, + YKEY = 89, + defaultSetting = {}, + //currentInput = false, + ctrlDown = false, + shiftDown = false, + publics = {}, + accent_map = { + 'ẚ':'a','Ã':'a','á':'a','À':'a','à':'a','Ä‚':'a','ă':'a','Ắ':'a','ắ':'a','Ằ':'a','ằ':'a','Ẵ':'a','ẵ':'a','Ẳ':'a', + 'Ẫ':'a','ẫ':'a','Ẩ':'a','ẩ':'a','Ç':'a','ÇŽ':'a','Ã…':'a','Ã¥':'a','Ǻ':'a','Ç»':'a','Ä':'a','ä':'a','Çž':'a','ÇŸ':'a', + 'Ã':'a','ã':'a','Ȧ':'a','ȧ':'a','Ç ':'a','Ç¡':'a','Ä„':'a','Ä…':'a','Ä€':'a','Ä':'a','Ả':'a','ả':'a','È€':'a','È':'a', + 'È‚':'a','ȃ':'a','Ạ':'a','ạ':'a','Ặ':'a','ặ':'a','Ậ':'a','ậ':'a','Ḁ':'a','á¸':'a','Ⱥ':'a','â±¥':'a','Ǽ':'a','ǽ':'a', + 'Ç¢':'a','Ç£':'a','Ḃ':'b','ḃ':'b','Ḅ':'b','ḅ':'b','Ḇ':'b','ḇ':'b','Ƀ':'b','Æ€':'b','ᵬ':'b','Æ':'b','É“':'b','Æ‚':'b', + 'ƃ':'b','Ć':'c','ć':'c','Ĉ':'c','ĉ':'c','ÄŒ':'c','Ä':'c','ÄŠ':'c','Ä‹':'c','Ç':'c','ç':'c','Ḉ':'c','ḉ':'c','È»':'c', + 'ȼ':'c','Ƈ':'c','ƈ':'c','É•':'c','ÄŽ':'d','Ä':'d','Ḋ':'d','ḋ':'d','á¸':'d','ḑ':'d','Ḍ':'d','á¸':'d','Ḓ':'d','ḓ':'d', + 'Ḏ':'d','á¸':'d','Ä':'d','Ä‘':'d','áµ­':'d','Ɖ':'d','É–':'d','ÆŠ':'d','É—':'d','Æ‹':'d','ÆŒ':'d','È¡':'d','ð':'d','É':'e', + 'Æ':'e','ÆŽ':'e','Ç':'e','é':'e','È':'e','è':'e','Ä”':'e','Ä•':'e','Ê':'e','ê':'e','Ế':'e','ế':'e','Ề':'e','á»':'e', + 'Ễ':'e','á»…':'e','Ể':'e','ể':'e','Äš':'e','Ä›':'e','Ë':'e','ë':'e','Ẽ':'e','ẽ':'e','Ä–':'e','Ä—':'e','Ȩ':'e','È©':'e', + 'Ḝ':'e','á¸':'e','Ę':'e','Ä™':'e','Ä’':'e','Ä“':'e','Ḗ':'e','ḗ':'e','Ḕ':'e','ḕ':'e','Ẻ':'e','ẻ':'e','È„':'e','È…':'e', + 'Ȇ':'e','ȇ':'e','Ẹ':'e','ẹ':'e','Ệ':'e','ệ':'e','Ḙ':'e','ḙ':'e','Ḛ':'e','ḛ':'e','Ɇ':'e','ɇ':'e','Éš':'e','É':'e', + 'Ḟ':'f','ḟ':'f','áµ®':'f','Æ‘':'f','Æ’':'f','Ç´':'g','ǵ':'g','Äž':'g','ÄŸ':'g','Äœ':'g','Ä':'g','Ǧ':'g','ǧ':'g','Ä ':'g', + 'Ä¡':'g','Ä¢':'g','Ä£':'g','Ḡ':'g','ḡ':'g','Ǥ':'g','Ç¥':'g','Æ“':'g','É ':'g','Ĥ':'h','Ä¥':'h','Èž':'h','ÈŸ':'h','Ḧ':'h', + 'ḧ':'h','Ḣ':'h','ḣ':'h','Ḩ':'h','ḩ':'h','Ḥ':'h','ḥ':'h','Ḫ':'h','ḫ':'h','H':'h','̱':'h','ẖ':'h','Ħ':'h','ħ':'h', + 'â±§':'h','ⱨ':'h','Ã':'i','í':'i','ÃŒ':'i','ì':'i','Ĭ':'i','Ä­':'i','ÃŽ':'i','î':'i','Ç':'i','Ç':'i','Ã':'i','ï':'i', + 'Ḯ':'i','ḯ':'i','Ĩ':'i','Ä©':'i','İ':'i','i':'i','Ä®':'i','į':'i','Ī':'i','Ä«':'i','Ỉ':'i','ỉ':'i','Ȉ':'i','ȉ':'i', + 'ÈŠ':'i','È‹':'i','Ị':'i','ị':'i','Ḭ':'i','ḭ':'i','I':'i','ı':'i','Æ—':'i','ɨ':'i','Ä´':'j','ĵ':'j','J':'j','ÌŒ':'j', + 'ǰ':'j','È·':'j','Ɉ':'j','ɉ':'j','Ê':'j','ÉŸ':'j','Ê„':'j','Ḱ':'k','ḱ':'k','Ǩ':'k','Ç©':'k','Ķ':'k','Ä·':'k','Ḳ':'k', + 'ḳ':'k','Ḵ':'k','ḵ':'k','Ƙ':'k','Æ™':'k','Ⱪ':'k','ⱪ':'k','Ĺ':'a','ĺ':'l','Ľ':'l','ľ':'l','Ä»':'l','ļ':'l','Ḷ':'l', + 'ḷ':'l','Ḹ':'l','ḹ':'l','Ḽ':'l','ḽ':'l','Ḻ':'l','ḻ':'l','Å':'l','Å‚':'l','Ì£':'l','Ä¿':'l', + 'Å€':'l','Ƚ':'l','Æš':'l','â± ':'l','ⱡ':'l','â±¢':'l','É«':'l','ɬ':'l','É­':'l','È´':'l','Ḿ':'m','ḿ':'m','á¹€':'m','á¹':'m', + 'Ṃ':'m','ṃ':'m','ɱ':'m','Ń':'n','Å„':'n','Ǹ':'n','ǹ':'n','Ň':'n','ň':'n','Ñ':'n','ñ':'n','Ṅ':'n','á¹…':'n','Å…':'n', + 'ņ':'n','Ṇ':'n','ṇ':'n','Ṋ':'n','ṋ':'n','Ṉ':'n','ṉ':'n','Æ':'n','ɲ':'n','È ':'n','Æž':'n','ɳ':'n','ȵ':'n','N':'n', + '̈':'n','n':'n','Ó':'o','ó':'o','Ã’':'o','ò':'o','ÅŽ':'o','Å':'o','Ô':'o','ô':'o','á»':'o','ố':'o','á»’':'o', + 'ồ':'o','á»–':'o','á»—':'o','á»”':'o','ổ':'o','Ç‘':'o','Ç’':'o','Ö':'o','ö':'o','Ȫ':'o','È«':'o','Å':'o','Å‘':'o','Õ':'o', + 'õ':'o','Ṍ':'o','á¹':'o','Ṏ':'o','á¹':'o','Ȭ':'o','È­':'o','È®':'o','ȯ':'o','Ȱ':'o','ȱ':'o','Ø':'o','ø':'o','Ǿ':'o', + 'Ç¿':'o','Ǫ':'o','Ç«':'o','Ǭ':'o','Ç­':'o','ÅŒ':'o','Å':'o','á¹’':'o','ṓ':'o','á¹':'o','ṑ':'o','Ỏ':'o','á»':'o','ÈŒ':'o', + 'È':'o','ÈŽ':'o','È':'o','Æ ':'o','Æ¡':'o','Ớ':'o','á»›':'o','Ờ':'o','á»':'o','á» ':'o','ỡ':'o','Ở':'o','ở':'o','Ợ':'o', + 'ợ':'o','Ọ':'o','á»':'o','Ộ':'o','á»™':'o','ÆŸ':'o','ɵ':'o','á¹”':'p','ṕ':'p','á¹–':'p','á¹—':'p','â±£':'p','Ƥ':'p','Æ¥':'p', + 'P':'p','̃':'p','p':'p','Ê ':'q','ÉŠ':'q','É‹':'q','Å”':'r','Å•':'r','Ř':'r','Å™':'r','Ṙ':'r','á¹™':'r','Å–':'r', + 'Å—':'r','È':'r','È‘':'r','È’':'r','È“':'r','Ṛ':'r','á¹›':'r','Ṝ':'r','á¹':'r','Ṟ':'r','ṟ':'r','ÉŒ':'r','É':'r','áµ²':'r', + 'ɼ':'r','Ɽ':'r','ɽ':'r','ɾ':'r','áµ³':'r','ß':'s','Åš':'s','Å›':'s','Ṥ':'s','á¹¥':'s','Åœ':'s','Å':'s','Å ':'s','Å¡':'s', + 'Ṧ':'s','á¹§':'s','á¹ ':'s','ṡ':'s','ẛ':'s','Åž':'s','ÅŸ':'s','á¹¢':'s','á¹£':'s','Ṩ':'s','ṩ':'s','Ș':'s','È™':'s','Ê‚':'s', + 'S':'s','Ì©':'s','s':'s','Þ':'t','þ':'t','Ť':'t','Å¥':'t','T':'t','ẗ':'t','Ṫ':'t','ṫ':'t','Å¢':'t','Å£':'t','Ṭ':'t', + 'á¹­':'t','Èš':'t','È›':'t','á¹°':'t','á¹±':'t','á¹®':'t','ṯ':'t','Ŧ':'t','ŧ':'t','Ⱦ':'t','ⱦ':'t','áµµ':'t', + 'Æ«':'t','Ƭ':'t','Æ­':'t','Æ®':'t','ʈ':'t','ȶ':'t','Ú':'u','ú':'u','Ù':'u','ù':'u','Ŭ':'u','Å­':'u','Û':'u','û':'u', + 'Ç“':'u','Ç”':'u','Å®':'u','ů':'u','Ü':'u','ü':'u','Ç—':'u','ǘ':'u','Ç›':'u','Çœ':'u','Ç™':'u','Çš':'u','Ç•':'u','Ç–':'u', + 'Ű':'u','ű':'u','Ũ':'u','Å©':'u','Ṹ':'u','á¹¹':'u','Ų':'u','ų':'u','Ū':'u','Å«':'u','Ṻ':'u','á¹»':'u','Ủ':'u','á»§':'u', + 'È”':'u','È•':'u','È–':'u','È—':'u','Ư':'u','ư':'u','Ứ':'u','ứ':'u','Ừ':'u','ừ':'u','á»®':'u','ữ':'u','Ử':'u','á»­':'u', + 'á»°':'u','á»±':'u','Ụ':'u','ụ':'u','á¹²':'u','á¹³':'u','á¹¶':'u','á¹·':'u','á¹´':'u','á¹µ':'u','É„':'u','ʉ':'u','á¹¼':'v','á¹½':'v', + 'á¹¾':'v','ṿ':'v','Ʋ':'v','Ê‹':'v','Ẃ':'w','ẃ':'w','Ẁ':'w','áº':'w','Å´':'w','ŵ':'w','W':'w','ÌŠ':'w','ẘ':'w','Ẅ':'w', + 'ẅ':'w','Ẇ':'w','ẇ':'w','Ẉ':'w','ẉ':'w','Ẍ':'x','áº':'x','Ẋ':'x','ẋ':'x','Ã':'y','ý':'y','Ỳ':'y','ỳ':'y','Ŷ':'y', + 'Å·':'y','Y':'y','ẙ':'y','Ÿ':'y','ÿ':'y','Ỹ':'y','ỹ':'y','Ẏ':'y','áº':'y','Ȳ':'y','ȳ':'y','á»¶':'y','á»·':'y', + 'á»´':'y','ỵ':'y','Ê':'y','ÉŽ':'y','É':'y','Ƴ':'y','Æ´':'y','Ź':'z','ź':'z','áº':'z','ẑ':'z','Ž':'z','ž':'z','Å»':'z', + 'ż':'z','Ẓ':'z','ẓ':'z','Ẕ':'z','ẕ':'z','Ƶ':'z','ƶ':'z','Ȥ':'z','È¥':'z','Ê':'z','Ê‘':'z','Ⱬ':'z','ⱬ':'z','Ç®':'z', + 'ǯ':'z','ƺ':'z','ï¼’':'2','ï¼–':'6','ï¼¢':'B','F':'F','J':'J','ï¼®':'N','ï¼²':'R','ï¼¶':'V','Z':'Z','b':'b','f':'f','j':'j', + 'n':'n','ï½’':'r','ï½–':'v','z':'z','1':'1','5':'5','ï¼™':'9','A':'A','ï¼¥':'E','I':'I','ï¼­':'M','ï¼±':'Q','ï¼µ':'U','ï¼¹':'Y', + 'ï½':'a','ï½…':'e','i':'i','ï½':'m','q':'q','u':'u','ï½™':'y','ï¼':'0','ï¼”':'4','8':'8','D':'D','H':'H','L':'L','ï¼°':'P', + 'ï¼´':'T','X':'X','d':'d','h':'h','l':'l','ï½':'p','ï½”':'t','x':'x','3':'3','ï¼—':'7','ï¼£':'C','ï¼§':'G','K':'K','O':'O', + 'ï¼³':'S','ï¼·':'W','c':'c','g':'g','k':'k','ï½':'o','s':'s','ï½—':'w','ẳ':'a','Â':'a','â':'a','Ấ':'a','ấ':'a','Ầ':'a','ầ':'a' + }; + + if (window.getComputedStyle === undefined) { + window.getComputedStyle = (function () { + function getPixelSize(element, style, property, fontSize) { + var sizeWithSuffix = style[property], + size = parseFloat(sizeWithSuffix), + suffix = sizeWithSuffix.split(/\d/)[0], + rootSize; + + fontSize = fontSize !== null ? fontSize : /%|em/.test(suffix) && element.parentElement ? getPixelSize(element.parentElement, element.parentElement.currentStyle, 'fontSize', null) : 16; + rootSize = property === 'fontSize' ? fontSize : /width/i.test(property) ? element.clientWidth : element.clientHeight; + + return (suffix === 'em') ? size * fontSize : (suffix === 'in') ? size * 96 : (suffix === 'pt') ? size * 96 / 72 : (suffix === '%') ? size / 100 * rootSize : size; + } + + function setShortStyleProperty(style, property) { + var borderSuffix = property === 'border' ? 'Width' : '', + t = property + 'Top' + borderSuffix, + r = property + 'Right' + borderSuffix, + b = property + 'Bottom' + borderSuffix, + l = property + 'Left' + borderSuffix; + + style[property] = (style[t] === style[r] === style[b] === style[l] ? [style[t]] + : style[t] === style[b] && style[l] === style[r] ? [style[t], style[r]] + : style[l] === style[r] ? [style[t], style[r], style[b]] + : [style[t], style[r], style[b], style[l]]).join(' '); + } + + function CSSStyleDeclaration(element) { + var currentStyle = element.currentStyle, + style = this, + property, + fontSize = getPixelSize(element, currentStyle, 'fontSize', null); + + for (property in currentStyle) { + if (Object.prototype.hasOwnProperty.call(currentStyle, property)) { + if (/width|height|margin.|padding.|border.+W/.test(property) && style[property] !== 'auto') { + style[property] = getPixelSize(element, currentStyle, property, fontSize) + 'px'; + } else if (property === 'styleFloat') { + style.float = currentStyle[property]; + } else { + style[property] = currentStyle[property]; + } + } + } + + setShortStyleProperty(style, 'margin'); + setShortStyleProperty(style, 'padding'); + setShortStyleProperty(style, 'border'); + + style.fontSize = fontSize + 'px'; + + return style; + } + + CSSStyleDeclaration.prototype = { + constructor: CSSStyleDeclaration, + getPropertyPriority: function () {}, + getPropertyValue: function (prop) { + return this[prop] || ''; + }, + item: function () {}, + removeProperty: function () {}, + setProperty: function () {}, + getPropertyCSSValue: function () {} + }; + + function getComputedStyle(element) { + return new CSSStyleDeclaration(element); + } + + return getComputedStyle; + }(this)); + } + + + $(document) + .on('keydown.xdsoftctrl', function (e) { + if (e.keyCode === CTRLKEY) { + ctrlDown = true; + } + if (e.keyCode === SHIFTKEY) { + ctrlDown = true; + } + }) + .on('keyup.xdsoftctrl', function (e) { + if (e.keyCode === CTRLKEY) { + ctrlDown = false; + } + if (e.keyCode === SHIFTKEY) { + ctrlDown = false; + } + }); + + function accentReplace (s) { + if (!s) { return ''; } + var ret = '',i; + for (i=0; i < s.length; i+=1) { + ret += accent_map[s.charAt(i)] || s.charAt(i); + } + return ret; + } + + function escapeRegExp (str) { + return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); + } + + function getCaretPosition(input) { + if (!input) { + return; + } + if (input.selectionStart) { + return input.selectionStart; + } + if (document.selection) { + input.focus(); + var sel = document.selection.createRange(), + selLen = document.selection.createRange().text.length; + sel.moveStart('character', -input.value.length); + return sel.text.length - selLen; + } + } + + function setCaretPosition(input, pos) { + if (input.setSelectionRange) { + input.focus(); + input.setSelectionRange(pos, pos); + } else if (input.createTextRange) { + var range = input.createTextRange(); + range.collapse(true); + range.moveEnd('character', pos); + range.moveStart('character', pos); + range.select(); + } + } + + function isset(value) { + return value !== undefined; + } + + function safe_call(callback, args, callback2, defaultValue) { + if (isset(callback) && !$.isArray(callback)) { + return $.isFunction(callback) ? callback.apply(this,args):defaultValue; + } + if(isset(callback2)) { + return safe_call.call(this,callback2,args); + } + return defaultValue; + }; + + function __safe( callbackName,source,args,defaultValue ){ + var undefinedVar; + return safe_call.call( this, (isset(this.source[source])&& + Object.prototype.hasOwnProperty.call(this.source[source], callbackName)) ? this.source[source][callbackName] : undefinedVar, args, function(){ + return safe_call.call(this, + isset(this[callbackName][source])? + this[callbackName][source]:( + isset(this[callbackName][0])? + this[callbackName][0]:( + Object.prototype.hasOwnProperty.call(this, callbackName)? + this[callbackName]: + undefinedVar + ) + ), + args, + defaultSetting[callbackName][source]||defaultSetting[callbackName][0]||defaultSetting[callbackName], + defaultValue + ); + },defaultValue); + }; + + function __get( property,source ){ + if(!isset(source)) + source = 0; + + if( $.isArray(this.source) && isset(this.source[source]) && isset(this.source[source][property])) + return this.source[source][property]; + + if( isset(this[property]) ){ + if( $.isArray(this[property]) ){ + if( isset(this[property][source]) ) + return this[property][source]; + if( isset(this[property][0]) ) + return this[property][0]; + return null; + } + return this[property]; + } + + return null; + }; + + function loadRemote( url,sourceObject,done,debug ){ + if (sourceObject.xhr) { + sourceObject.xhr.abort(); + } + sourceObject.xhr = $.ajax($.extend(true,{ + url : url, + type : 'GET' , + async:true, + cache :false, + dataType : 'json' + },sourceObject.ajax)) + + .done(function( data ){ + done&&done.apply(this,$.makeArray(arguments)); + }) + + .fail(function( jqXHR, textStatus ){ + if( debug ) + console.log("Request failed: " + textStatus); + }); + } + + + function findRight( data,query ){ + var right = false,source; + + for (source = 0;source < data.length;source += 1) { + if( right = __safe.call(this,"findRight",source,[data[source],query,source]) ){ + return {right:right,source:source}; + } + } + + return false; + } + + function processData( data,query ){ + var source; + preparseData + .call( this,data,query ); + + for (source = 0;source < data.length;source += 1) { + data[source] = __safe.call(this, + 'filter', + source, + [data[source], query, source], + data[source] + ); + } + }; + + + function collectData( query,datasource,callback ){ + var options = this,source; + + if( $.isFunction(options.source) ){ + options.source.apply(options,[query,function(items){ + datasource = [items]; + safe_call.call(options,callback,[query]); + },datasource,0]); + }else{ + for (source = 0;source < options.source.length;source += 1) { + if ($.isArray(options.source[source])) { + datasource[source] = options.source[source]; + } else if ($.isFunction(options.source[source])) { + (function (source) { + options.source[source].apply(options,[query, function(items){ + if (!datasource[source]) { + datasource[source] = []; + } + + if (items && $.isArray(items)) { + switch (options.appendMethod) { + case 'replace': + datasource[source] = items; + break; + default: + datasource[source] = datasource[source].concat(items); + } + } + + safe_call.call(options,callback,[query]); + }, datasource,source]); + }(source)); + } else { + switch (options.source[source].type) { + case 'remote': + if (isset(options.source[source].url)) { + if (!isset(options.source[source].minLength) || query.length >= options.source[source].minLength){ + var url = __safe.call(options,'replace',source,[options.source[source].url,query],''); + if (!datasource[source]) { + datasource[source] = []; + } + (function (source) { + loadRemote(url,options.source[source], function(resp){ + datasource[source] = resp; + safe_call.call(options,callback,[query]); + },options.debug); + }(source)); + } + } + break; + default: + if( isset(options.source[source]['data']) ){ + datasource[source] = options.source[source]['data']; + }else{ + datasource[source] = options.source[source]; + } + } + } + } + } + safe_call.call(options,callback,[query]); + }; + + function preparseData( data,query ){ + for( var source=0;source=this.limit ) + break; + + $div = $(__safe.call(this, + 'render',source, + [data[source][i],source,i,query], + '' + )); + + $div.data('source',source); + $div.data('pid',i); + $div.data('item',data[source][i]); + + $divs.push($div); + } + } + + return $divs; + }; + + function getItem( $div,dataset ){ + if( isset($div.data('source')) && + isset($div.data('pid')) && + isset(dataset[$div.data('source')]) && + isset(dataset[$div.data('source')][$div.data('pid')]) + ){ + return dataset[$div.data('source')][$div.data('pid')]; + } + return false; + }; + + function getValue( $div,dataset ){ + var item = getItem($div,dataset); + + if( item ){ + return __safe.call(this, + 'getValue',$div.data('source'), + [item,$div.data('source')] + ); + }else{ + if( isset($div.data('value')) ){ + return decodeURIComponent($div.data('value')); + }else{ + return $div.html(); + } + } + }; + + defaultSetting = { + minLength: 0, + valueKey: 'value', + titleKey: 'title', + highlight: true, + + showHint: true, + + dropdownWidth: '100%', + dropdownStyle: {}, + itemStyle: {}, + hintStyle: false, + style: false, + + debug: true, + openOnFocus: false, + closeOnBlur: true, + + autoselect: false, + + accents: true, + replaceAccentsForRemote: true, + + limit: 20, + visibleLimit: 20, + visibleHeight: 0, + defaultHeightItem: 30, + + timeoutUpdate: 10, + + get: function (property, source) { + return __get.call(this,property,source); + }, + + replace: [ + function (url, query) { + if (this.replaceAccentsForRemote) { + query = accentReplace(query); + } + return url.replace('%QUERY%',encodeURIComponent(query)); + } + ], + + equal:function( value,query ){ + return query.toLowerCase()==value.substr(0,query.length).toLowerCase(); + }, + + findRight:[ + function(items,query,source){ + var results = [],value = '',i; + if (items) { + for (i = 0;i < items.length;i += 1) { + value = __safe.call(this,'getValue',source,[items[i],source]); + if (__safe.call(this, 'equal', source, [value,query,source], false)) { + return items[i]; + } + } + } + return false; + } + ], + + valid:[ + function (value, query) { + if (this.accents) { + value = accentReplace(value); + query = accentReplace(query); + } + return value.toLowerCase().indexOf(query.toLowerCase())!=-1; + + } + ], + + filter:[ + function (items, query, source) { + var results = [], value = '',i; + if (items) { + for (i = 0;i < items.length;i += 1) { + value = isset(items[i][this.get('valueKey', source)]) ? items[i][this.get('valueKey', source)] : items[i].toString(); + if (__safe.call(this, 'valid', source, [value, query])) { + results.push(items[i]); + } + } + } + return results; + } + ], + + preparse:function(items){ + return items; + }, + + getValue: [ + function (item, source) { + return isset(item[this.get('valueKey',source)])?item[this.get('valueKey',source)]:item.toString(); + } + ], + + getTitle: [ + function (item, source) { + return isset(item[this.get('titleKey',source)])?item[this.get('titleKey',source)]:item.toString(); + } + ], + + render: [ + function (item, source, pid, query) { + var value = __safe.call(this, "getValue", source, [item, source], defaultSetting.getValue[0].call(this, item, source)), + title = __safe.call(this, "getTitle", source, [item, source], defaultSetting.getTitle[0].call(this, item, source)), + _value = '', + _query = '', + _title = '', + hilite_hints = '', + highlighted = '', + c, h, i, + spos = 0; + + if (this.highlight) { + if (!this.accents) { + title = title.replace(new RegExp('('+escapeRegExp(query)+')','i'),'$1'); + }else{ + _title = accentReplace(title).toLowerCase().replace(/[<>]+/g, ''), + _query = accentReplace(query).toLowerCase().replace(/[<>]+/g, ''); + + hilite_hints = _title.replace(new RegExp(escapeRegExp(_query), 'g'), '<'+_query+'>'); + for (i=0;i < hilite_hints.length;i += 1) { + c = title.charAt(spos); + h = hilite_hints.charAt(i); + if (h === '<') { + highlighted += ''; + } else if (h === '>') { + highlighted += ''; + } else { + spos += 1; + highlighted += c; + } + } + title = highlighted; + } + } + + return '
    ' + +title+ + '
    '; + } + ], + appendMethod: 'concat', // supported merge and replace + source:[], + afterSelected: function() { + } + }; + function init( that,options ){ + if( $(that).hasClass('xdsoft_input') ) + return; + + var $box = $('
    '), + $dropdown = $('
    '), + $hint = $(''), + $input = $(that), + timer1 = 0, + intervalForVisibility, + dataset = [], + iOpen = false, + value = '', + currentValue = '', + currentSelect = '', + active = null, + pos = 0; + + //it can be used to access settings + $input.data('autocomplete_options', options); + + $dropdown + .on('mousedown', function(e) { + e.preventDefault(); + e.stopPropagation(); + }) + .on('updatescroll.xdsoft', function() { + var _act = $dropdown.find('.active'); + if (!_act.length) { + return; + } + + var top = _act.position().top, + actHght = _act.outerHeight(true), + scrlTop = $dropdown.scrollTop(), + hght = $dropdown.height(); + + if (top <0) { + $dropdown.scrollTop(scrlTop-Math.abs(top)); + } else if (top+actHght>hght) { + $dropdown.scrollTop(scrlTop+top+actHght-hght); + } + }); + + $box + .css({ + 'display':$input.css('display'), + 'width':$input.css('width') + }); + + if( options.style ) + $box.css(options.style); + + $input + .addClass('xdsoft_input') + .attr('autocomplete','off'); + + var xDown = null; + var yDown = null; + var isSwipe = false; + $dropdown + .on('mousemove','div',function(){ + if( $(this).hasClass('active') ) + return true; + $dropdown.find('div').removeClass('active'); + $(this).addClass('active'); + }) + .on('mousedown','div',function(e){ + $dropdown.find('div').removeClass('active'); + $(this).addClass('active'); + $input.trigger('pick.xdsoft'); + }) + .on('touchstart','div',function(e){ + xDown = e.originalEvent.touches[0].clientX; + yDown = e.originalEvent.touches[0].clientY; + }) + .on('touchend','div',function(e){ + if(isSwipe === false) { + $dropdown.find('div').removeClass('active'); + $(this).addClass('active'); + $input.trigger('pick.xdsoft'); + } + + isSwipe = false; + }) + .on('touchmove','div',function(e){ + if ( ! xDown || ! yDown ) { + return; + } + + var xUp = e.originalEvent.touches[0].clientX; + var yUp = e.originalEvent.touches[0].clientY; + + var xDiff = xDown - xUp; + var yDiff = yDown - yUp; + + if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) { + if ( xDiff > 0 ) { + isSwipe = 'left'; + } else { + isSwipe = 'right'; + } + } else { + if ( yDiff > 0 ) { + isSwipe = 'top'; + } else { + isSwipe = 'bottm'; + } + } + + xDown = null; + yDown = null; + }); + + function manageData(){ + if ($input.val()!=currentValue){ + currentValue = $input.val(); + } else { + return; + } + if (currentValue.length < options.minLength) { + $input.trigger('close.xdsoft'); + return; + } + collectData.call(options,currentValue,dataset,function( query ){ + if (query != currentValue) { + return; + } + var right; + processData.call(options, dataset,query); + + $input.trigger('updateContent.xdsoft'); + + if (options.showHint && currentValue.length && currentValue.length<=$input.prop('size') && (right = findRight.call(options,dataset,currentValue))) { + var title = __safe.call(options,'getTitle',right.source,[right.right,right.source]); + title = query + title.substr(query.length); + $hint.val(title); + } else { + $hint.val(''); + } + }); + + return; + } + + function manageKey (event) { + var key = event.keyCode, right; + + switch( key ){ + case AKEY: case CKEY: case VKEY: case ZKEY: case YKEY: + if (event.shiftKey || event.ctrlKey) { + return true; + } + break; + case SHIFTKEY: + case CTRLKEY: + return true; + break; + case ARROWRIGHT: + case ARROWLEFT: + if (ctrlDown || shiftDown || event.shiftKey || event.ctrlKey) { + return true; + } + value = $input.val(); + pos = getCaretPosition($input[0]); + if (key === ARROWRIGHT && pos === value.length) { + if (right = findRight.call(options, dataset, value)){ + $input.trigger('pick.xdsoft', [ + __safe.call(options, + 'getValue', right.source, + [right.right, right.source] + ) + ]); + } else { + $input.trigger('pick.xdsoft'); + } + event.preventDefault(); + return false; + } + return true; + case TAB: + return true; + case ENTER: + if (iOpen) { + if (options.autoselect) { + $input.trigger('pick.xdsoft'); + } else if (!options.autoselect && active) { + $input.trigger('pick.xdsoft'); + } else { + $input.trigger('close.xdsoft'); + return true; + } + event.preventDefault(); + return false; + } else { + return true; + } + break; + case ESC: + $input + .val(currentValue) + .trigger('close.xdsoft'); + event.preventDefault(); + return false; + case ARROWDOWN: + case ARROWUP: + if (!iOpen) { + $input.trigger('open.xdsoft'); + $input.trigger('updateContent.xdsoft'); + event.preventDefault(); + return false; + } + + active = $dropdown.find('div.active'); + + var next = key==ARROWDOWN?'next':'prev', timepick = true; + + if( active.length ){ + active.removeClass('active'); + if( active[next]().length ){ + active[next]().addClass('active'); + }else{ + $input.val(currentValue); + timepick = false; + } + }else{ + $dropdown.children().eq(key==ARROWDOWN?0:-1).addClass('active'); + } + + if( timepick ){ + $input.trigger('timepick.xdsoft'); + } + + $dropdown + .trigger('updatescroll.xdsoft'); + + event.preventDefault(); + return false; + } + return; + } + + $input + .data('xdsoft_autocomplete',dataset) + .after($box) + .on('pick.xdsoft', function( event,_value ){ + + $input.trigger('timepick.xdsoft',_value); + + currentSelect = currentValue = $input.val(); + + $input.trigger('close.xdsoft'); + + //currentInput = false; + + active = $dropdown.find('div.active').eq(0); + + if( !active.length ) + active = $dropdown.children().first(); + + $input.trigger('selected.xdsoft',[getItem(active,dataset)]); + + if (options.afterSelected) + options.afterSelected(); + }) + .on('timepick.xdsoft', function( event,_value ){ + active = $dropdown.find('div.active'); + + if( !active.length ) + active = $dropdown.children().first(); + + if( active.length ){ + if( !isset(_value) ){ + $input.val(getValue.call(options,active,dataset)); + }else{ + $input.val(_value); + } + $input.trigger('autocompleted.xdsoft',[getItem(active,dataset)]); + $hint.val(''); + setCaretPosition($input[0],$input.val().length); + } + }) + .on('keydown.xdsoft input.xdsoft cut.xdsoft paste.xdsoft', function( event ){ + var ret = manageKey(event); + + if (ret === false || ret === true) { + return ret; + } + + setTimeout(function(){ + manageData(); + },1); + + manageData(); + }) + .on('change.xdsoft', function( event ){ + currentValue = $input.val(); + }); + + currentValue = $input.val(); + + collectData.call(options, $input.val(),dataset,function( query ){ + processData.call(options,dataset,query); + }); + + if( options.openOnFocus ){ + $input.on('focusin.xdsoft',function(){ + $input.trigger('open.xdsoft'); + $input.trigger('updateContent.xdsoft'); + }); + } + + if( options.closeOnBlur ) + $input.on('focusout.xdsoft',function(){ + $input.trigger('close.xdsoft'); + }); + + $box + .append($input) + .append($dropdown); + + + var olderBackground = false, + timerUpdate = 0; + + $input + .on('updateHelperPosition.xdsoft',function(){ + clearTimeout(timerUpdate); + timerUpdate = setTimeout(function(){ + $box.css({ + 'display':$input.css('display'), + 'width':$input.css('width') + }); + $dropdown.css($.extend(true,{ + left:$input.position().left, + top:$input.position().top + parseInt($input.css('marginTop'))+parseInt($input[0].offsetHeight), + marginLeft:$input.css('marginLeft'), + marginRight:$input.css('marginRight'), + width:options.dropdownWidth=='100%'?$input[0].offsetWidth:options.dropdownWidth + },options.dropdownStyle)); + + if (options.showHint) { + var style = getComputedStyle($input[0], ""); + + $hint[0].style.cssText = style.cssText; + + $hint.css({ + 'box-sizing':style.boxSizing, + borderStyle:'solid', + borderCollapse:style.borderCollapse, + borderLeftWidth:style.borderLeftWidth, + borderRightWidth:style.borderRightWidth, + borderTopWidth:style.borderTopWidth, + borderBottomWidth:style.borderBottomWidth, + paddingBottom:style.paddingBottom, + marginBottom:style.marginBottom, + paddingTop:style.paddingTop, + marginTop:style.marginTop, + paddingLeft:style.paddingLeft, + marginLeft:style.marginLeft, + paddingRight:style.paddingRight, + marginRight:style.marginRight, + maxHeight:style.maxHeight, + minHeight:style.minHeight, + maxWidth:style.maxWidth, + minWidth:style.minWidth, + width:style.width, + letterSpacing:style.letterSpacing, + lineHeight:style.lineHeight, + outlineWidth:style.outlineWidth, + fontFamily:style.fontFamily, + fontVariant:style.fontVariant, + fontStyle:$input.css('fontStyle'), + fontSize:$input.css('fontSize'), + fontWeight:$input.css('fontWeight'), + flex:style.flex, + justifyContent:style.justifyContent, + borderRadius:style.borderRadius, + '-webkit-box-shadow':'none', + 'box-shadow':'none' + }); + + $input.css('font-size',$input.css('fontSize'))// fix bug with em font size + + $hint.innerHeight($input.innerHeight()); + + $hint.css($.extend(true,{ + position:'absolute', + zIndex:'1', + borderColor:'transparent', + outlineColor:'transparent', + left:$input.position().left, + top:$input.position().top, + background:$input.css('background') + },options.hintStyle)); + +// This code is not needed because we are already setting $hint in upper line +// if( olderBackground !== false ){ +// $hint.css('background',olderBackground); +// } else { +// olderBackground = $input.css('background'); +// } + + try{ + $input[0].style.setProperty('background', 'transparent', 'important'); + } catch(e) { + $input.css('background','transparent') + } + + $box + .append($hint); + } + }, options.timeoutUpdate||1); + }); + + if ($input.is(':visible')) { + $input + .trigger('updateHelperPosition.xdsoft'); + } else { + intervalForVisibility = setInterval(function () { + if ($input.is(':visible')) { + $input + .trigger('updateHelperPosition.xdsoft'); + clearInterval(intervalForVisibility); + } + },100); + } + + $(window).on('resize',function () { + $box.css({ + 'width':'auto' + }); + $input + .trigger('updateHelperPosition.xdsoft'); + }) + + $input + .on('close.xdsoft',function(){ + if (!iOpen) { + return; + } + + $dropdown + .hide(); + + $hint + .val(''); + + if (!options.autoselect) { + $input.val(currentValue); + } + + iOpen = false; + + //currentInput = false; + }) + + .on('updateContent.xdsoft',function(){ + var out = renderData.call(options,dataset,$input.val()), + hght = 10; + + if (out.length) { + $input.trigger('open.xdsoft'); + } else { + $input.trigger('close.xdsoft'); + return; + } + + $(out).each(function(){ + this.css($.extend(true,{ + paddingLeft:$input.css('paddingLeft'), + paddingRight:$input.css('paddingRight') + },options.itemStyle)); + }); + + $dropdown + .html(out); + + if (options.visibleHeight){ + hght = options.visibleHeight; + } else { + hght = options.visibleLimit * ((out[0] ? out[0].outerHeight(true) : 0) || options.defaultHeightItem) + 5; + } + + $dropdown + .css('maxHeight', hght+'px') + }) + + .on('open.xdsoft',function(){ + if( iOpen ) + return; + + $dropdown + .show(); + + iOpen = true; + + //currentInput = $input; + }) + .on('destroy.xdsoft',function(){ + $input.removeClass('xdsoft'); + $box.after($input); + $box.remove(); + clearTimeout(timer1); + clearTimeout(intervalForVisibility); + //currentInput = false; + $input.data('xdsoft_autocomplete',null); + $input + .off('.xdsoft') + }); + }; + + publics = { + destroy: function () { + return this.trigger('destroy.xdsoft'); + }, + update: function () { + return this.trigger('updateHelperPosition.xdsoft'); + }, + options: function (_options) { + if (this.data('autocomplete_options') && $.isPlainObject(_options)) { + this.data('autocomplete_options', $.extend(true, this.data('autocomplete_options'), _options)); + } + return this; + }, + setSource: function (_newsource, id) { + if(this.data('autocomplete_options') && ($.isPlainObject(_newsource) || $.isFunction(_newsource) || $.isArray(_newsource))) { + var options = this.data('autocomplete_options'), + dataset = this.data('xdsoft_autocomplete'), + source = options.source; + if (id!==undefined && !isNaN(id)) { + if ($.isPlainObject(_newsource) || $.isArray(_newsource)) { + source[id] = $.extend(true,$.isArray(_newsource) ? [] : {}, _newsource); + } else { + source[id] = _newsource; + } + } else { + if ($.isFunction(_newsource)) { + this.data('autocomplete_options').source = _newsource; + } else { + $.extend(true, source, _newsource); + } + } + + collectData.call(options, this.val(), dataset,function( query ){ + processData.call(options,dataset,query); + }); + } + return this; + }, + getSource: function (id) { + if (this.data('autocomplete_options')) { + var source = this.data('autocomplete_options').source; + if (id!==undefined && !isNaN(id) &&source[id]) { + return source[id]; + } else { + return source; + } + } + return null; + } + }; + + $.fn.autocomplete = function(_options, _second, _third){ + if ($.type(_options) === 'string' && publics[_options]) { + return publics[_options].call(this, _second, _third); + } + return this.each(function () { + var options = $.extend(true, {}, defaultSetting, _options); + init(this, options); + }); + }; +}(jQuery)); + +//# sourceMappingURL=jquery.autocomplete.js.map diff --git a/hesk/theme/hesk3/customer/js/jquery.scrollbar.min.js b/hesk/theme/hesk3/customer/js/jquery.scrollbar.min.js new file mode 100644 index 0000000..dec6477 --- /dev/null +++ b/hesk/theme/hesk3/customer/js/jquery.scrollbar.min.js @@ -0,0 +1,17 @@ +/** + * jQuery CSS Customizable Scrollbar + * + * Copyright 2015, Yuriy Khabarov + * Dual licensed under the MIT or GPL Version 2 licenses. + * + * If you found bug, please contact me via email <13real008@gmail.com> + * + * Compressed by http://jscompress.com/ + * + * @author Yuriy Khabarov aka Gromo + * @version 0.2.11 + * @url https://github.com/gromo/jquery.scrollbar/ + * + */ +!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],b):b("undefined"!=typeof exports?require("jquery"):a.jQuery)}(this,function(a){"use strict";function h(b){if(c.webkit&&!b)return{height:0,width:0};if(!c.data.outer){var d={border:"none","box-sizing":"content-box",height:"200px",margin:"0",padding:"0",width:"200px"};c.data.inner=a("
    ").css(a.extend({},d)),c.data.outer=a("
    ").css(a.extend({left:"-1000px",overflow:"scroll",position:"absolute",top:"-1000px"},d)).append(c.data.inner).appendTo("body")}return c.data.outer.scrollLeft(1e3).scrollTop(1e3),{height:Math.ceil(c.data.outer.offset().top-c.data.inner.offset().top||0),width:Math.ceil(c.data.outer.offset().left-c.data.inner.offset().left||0)}}function i(){var a=h(!0);return!(a.height||a.width)}function j(a){var b=a.originalEvent;return(!b.axis||b.axis!==b.HORIZONTAL_AXIS)&&!b.wheelDeltaX}var b=!1,c={data:{index:0,name:"scrollbar"},firefox:/firefox/i.test(navigator.userAgent),macosx:/mac/i.test(navigator.platform),msedge:/edge\/\d+/i.test(navigator.userAgent),msie:/(msie|trident)/i.test(navigator.userAgent),mobile:/android|webos|iphone|ipad|ipod|blackberry/i.test(navigator.userAgent),overlay:null,scroll:null,scrolls:[],webkit:/webkit/i.test(navigator.userAgent)&&!/edge\/\d+/i.test(navigator.userAgent)};c.scrolls.add=function(a){this.remove(a).push(a)},c.scrolls.remove=function(b){for(;a.inArray(b,this)>=0;)this.splice(a.inArray(b,this),1);return this};var d={autoScrollSize:!0,autoUpdate:!0,debug:!1,disableBodyScroll:!1,duration:200,ignoreMobile:!1,ignoreOverlay:!1,isRtl:!1,scrollStep:30,showArrows:!1,stepScrolling:!0,scrollx:null,scrolly:null,onDestroy:null,onFallback:null,onInit:null,onScroll:null,onUpdate:null},e=function(b){c.scroll||(c.overlay=i(),c.scroll=h(),g(),a(window).resize(function(){var a=!1;if(c.scroll&&(c.scroll.height||c.scroll.width)){var b=h();b.height===c.scroll.height&&b.width===c.scroll.width||(c.scroll=b,a=!0)}g(a)})),this.container=b,this.namespace=".scrollbar_"+c.data.index++,this.options=a.extend({},d,window.jQueryScrollbarOptions||{}),this.scrollTo=null,this.scrollx={},this.scrolly={},b.data(c.data.name,this),c.scrolls.add(this)};e.prototype={destroy:function(){if(this.wrapper){this.container.removeData(c.data.name),c.scrolls.remove(this);var b=this.container.scrollLeft(),d=this.container.scrollTop();this.container.insertBefore(this.wrapper).css({height:"",margin:"","max-height":""}).removeClass("scroll-content scroll-scrollx_visible scroll-scrolly_visible").off(this.namespace).scrollLeft(b).scrollTop(d),this.scrollx.scroll.removeClass("scroll-scrollx_visible").find("div").addBack().off(this.namespace),this.scrolly.scroll.removeClass("scroll-scrolly_visible").find("div").addBack().off(this.namespace),this.wrapper.remove(),a(document).add("body").off(this.namespace),a.isFunction(this.options.onDestroy)&&this.options.onDestroy.apply(this,[this.container])}},init:function(b){var d=this,e=this.container,f=this.containerWrapper||e,g=this.namespace,h=a.extend(this.options,b||{}),i={x:this.scrollx,y:this.scrolly},k=this.wrapper,l={},m={scrollLeft:e.scrollLeft(),scrollTop:e.scrollTop()};if(c.mobile&&h.ignoreMobile||c.overlay&&h.ignoreOverlay||c.macosx&&!c.webkit)return a.isFunction(h.onFallback)&&h.onFallback.apply(this,[e]),!1;if(k)l={height:"auto","margin-bottom":c.scroll.height*-1+"px","max-height":""},l[h.isRtl?"margin-left":"margin-right"]=c.scroll.width*-1+"px",f.css(l);else{if(this.wrapper=k=a("
    ").addClass("scroll-wrapper").addClass(e.attr("class")).css("position","absolute"===e.css("position")?"absolute":"relative").insertBefore(e).append(e),h.isRtl&&k.addClass("scroll--rtl"),e.is("textarea")&&(this.containerWrapper=f=a("
    ").insertBefore(e).append(e),k.addClass("scroll-textarea")),l={height:"auto","margin-bottom":c.scroll.height*-1+"px","max-height":""},l[h.isRtl?"margin-left":"margin-right"]=c.scroll.width*-1+"px",f.addClass("scroll-content").css(l),e.on("scroll"+g,function(b){var f=e.scrollLeft(),g=e.scrollTop();if(h.isRtl)switch(!0){case c.firefox:f=Math.abs(f);case c.msedge||c.msie:f=e[0].scrollWidth-e[0].clientWidth-f}a.isFunction(h.onScroll)&&h.onScroll.call(d,{maxScroll:i.y.maxScrollOffset,scroll:g,size:i.y.size,visible:i.y.visible},{maxScroll:i.x.maxScrollOffset,scroll:f,size:i.x.size,visible:i.x.visible}),i.x.isVisible&&i.x.scroll.bar.css("left",f*i.x.kx+"px"),i.y.isVisible&&i.y.scroll.bar.css("top",g*i.y.kx+"px")}),k.on("scroll"+g,function(){k.scrollTop(0).scrollLeft(0)}),h.disableBodyScroll){var n=function(a){j(a)?i.y.isVisible&&i.y.mousewheel(a):i.x.isVisible&&i.x.mousewheel(a)};k.on("MozMousePixelScroll"+g,n),k.on("mousewheel"+g,n),c.mobile&&k.on("touchstart"+g,function(b){var c=b.originalEvent.touches&&b.originalEvent.touches[0]||b,d={pageX:c.pageX,pageY:c.pageY},f={left:e.scrollLeft(),top:e.scrollTop()};a(document).on("touchmove"+g,function(a){var b=a.originalEvent.targetTouches&&a.originalEvent.targetTouches[0]||a;e.scrollLeft(f.left+d.pageX-b.pageX),e.scrollTop(f.top+d.pageY-b.pageY),a.preventDefault()}),a(document).on("touchend"+g,function(){a(document).off(g)})})}a.isFunction(h.onInit)&&h.onInit.apply(this,[e])}a.each(i,function(b,f){var k=null,l=1,m="x"===b?"scrollLeft":"scrollTop",n=h.scrollStep,o=function(){var a=e[m]();e[m](a+n),1==l&&a+n>=p&&(a=e[m]()),l==-1&&a+n<=p&&(a=e[m]()),e[m]()==a&&k&&k()},p=0;f.scroll||(f.scroll=d._getScroll(h["scroll"+b]).addClass("scroll-"+b),h.showArrows&&f.scroll.addClass("scroll-element_arrows_visible"),f.mousewheel=function(a){if(!f.isVisible||"x"===b&&j(a))return!0;if("y"===b&&!j(a))return i.x.mousewheel(a),!0;var c=a.originalEvent.wheelDelta*-1||a.originalEvent.detail,g=f.size-f.visible-f.offset;return c||("x"===b&&a.originalEvent.deltaX?c=40*a.originalEvent.deltaX:"y"===b&&a.originalEvent.deltaY&&(c=40*a.originalEvent.deltaY)),(c>0&&p0)&&(p+=c,p<0&&(p=0),p>g&&(p=g),d.scrollTo=d.scrollTo||{},d.scrollTo[m]=p,setTimeout(function(){d.scrollTo&&(e.stop().animate(d.scrollTo,240,"linear",function(){p=e[m]()}),d.scrollTo=null)},1)),a.preventDefault(),!1},f.scroll.on("MozMousePixelScroll"+g,f.mousewheel).on("mousewheel"+g,f.mousewheel).on("mouseenter"+g,function(){p=e[m]()}),f.scroll.find(".scroll-arrow, .scroll-element_track").on("mousedown"+g,function(g){if(1!=g.which)return!0;l=1;var i={eventOffset:g["x"===b?"pageX":"pageY"],maxScrollValue:f.size-f.visible-f.offset,scrollbarOffset:f.scroll.bar.offset()["x"===b?"left":"top"],scrollbarSize:f.scroll.bar["x"===b?"outerWidth":"outerHeight"]()},j=0,q=0;if(a(this).hasClass("scroll-arrow")){if(l=a(this).hasClass("scroll-arrow_more")?1:-1,n=h.scrollStep*l,p=l>0?i.maxScrollValue:0,h.isRtl)switch(!0){case c.firefox:p=l>0?0:i.maxScrollValue*-1;break;case c.msie||c.msedge:}}else l=i.eventOffset>i.scrollbarOffset+i.scrollbarSize?1:i.eventOffset','
    ','
    ','
    ','
    ','
    ','
    ','
    ','
    ',"
    ","
    ",'
    ','
    ','
    ',"
    ",'
    ','
    ',"
    ","
    ","
    "].join(""),simple:['
    ','
    ','
    ','
    ','
    ',"
    ","
    "].join("")};return c[b]&&(b=c[b]),b||(b=c.simple),b="string"==typeof b?a(b).appendTo(this.wrapper):a(b),a.extend(b,{bar:b.find(".scroll-bar"),size:b.find(".scroll-element_size"),track:b.find(".scroll-element_track")}),b},_handleMouseDown:function(b,c){var d=this.namespace;return a(document).on("blur"+d,function(){a(document).add("body").off(d),b&&b()}),a(document).on("dragstart"+d,function(a){return a.preventDefault(),!1}),a(document).on("mouseup"+d,function(){a(document).add("body").off(d),b&&b()}),a("body").on("selectstart"+d,function(a){return a.preventDefault(),!1}),c&&c.preventDefault(),!1},_updateScroll:function(b,d){var e=this.container,f=this.containerWrapper||e,g="scroll-scroll"+b+"_visible",h="x"===b?this.scrolly:this.scrollx,i=parseInt(this.container.css("x"===b?"left":"top"),10)||0,j=this.wrapper,k=d.size,l=d.visible+i;d.isVisible=k-l>1,d.isVisible?(d.scroll.addClass(g),h.scroll.addClass(g),f.addClass(g)):(d.scroll.removeClass(g),h.scroll.removeClass(g),f.removeClass(g)),"y"===b&&(e.is("textarea")||k10?(window.console&&console.log("Scroll updates exceed 10"),g=function(){}):(clearTimeout(a),a=setTimeout(g,300))}}();window.angular&&!function(a){a.module("jQueryScrollbar",[]).provider("jQueryScrollbar",function(){var b=d;return{setOptions:function(c){a.extend(b,c)},$get:function(){return{options:a.copy(b)}}}}).directive("jqueryScrollbar",["jQueryScrollbar","$parse",function(a,b){return{restrict:"AC",link:function(c,d,e){var f=b(e.jqueryScrollbar),g=f(c);d.scrollbar(g||a.options).on("$destroy",function(){d.scrollbar("destroy")})}}}])}(window.angular)}); +//# sourceMappingURL=jquery.scrollbar.min.js.map diff --git a/hesk/theme/hesk3/customer/js/selectize.js b/hesk/theme/hesk3/customer/js/selectize.js new file mode 100644 index 0000000..b63fb7c --- /dev/null +++ b/hesk/theme/hesk3/customer/js/selectize.js @@ -0,0 +1,3892 @@ +/** + * sifter.js + * Copyright (c) 2013 Brian Reavis & contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this + * file except in compliance with the License. You may obtain a copy of the License at: + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF + * ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + * + * @author Brian Reavis + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + define('sifter', factory); + } else if (typeof exports === 'object') { + module.exports = factory(); + } else { + root.Sifter = factory(); + } +}(this, function() { + + /** + * Textually searches arrays and hashes of objects + * by property (or multiple properties). Designed + * specifically for autocomplete. + * + * @constructor + * @param {array|object} items + * @param {object} items + */ + var Sifter = function(items, settings) { + this.items = items; + this.settings = settings || {diacritics: true}; + }; + + /** + * Splits a search string into an array of individual + * regexps to be used to match results. + * + * @param {string} query + * @returns {array} + */ + Sifter.prototype.tokenize = function(query) { + query = trim(String(query || '').toLowerCase()); + if (!query || !query.length) return []; + + var i, n, regex, letter; + var tokens = []; + var words = query.split(/ +/); + + for (i = 0, n = words.length; i < n; i++) { + regex = escape_regex(words[i]); + if (this.settings.diacritics) { + for (letter in DIACRITICS) { + if (DIACRITICS.hasOwnProperty(letter)) { + regex = regex.replace(new RegExp(letter, 'g'), DIACRITICS[letter]); + } + } + } + tokens.push({ + string : words[i], + regex : new RegExp(regex, 'i') + }); + } + + return tokens; + }; + + /** + * Iterates over arrays and hashes. + * + * ``` + * this.iterator(this.items, function(item, id) { + * // invoked for each item + * }); + * ``` + * + * @param {array|object} object + */ + Sifter.prototype.iterator = function(object, callback) { + var iterator; + if (is_array(object)) { + iterator = Array.prototype.forEach || function(callback) { + for (var i = 0, n = this.length; i < n; i++) { + callback(this[i], i, this); + } + }; + } else { + iterator = function(callback) { + for (var key in this) { + if (this.hasOwnProperty(key)) { + callback(this[key], key, this); + } + } + }; + } + + iterator.apply(object, [callback]); + }; + + /** + * Returns a function to be used to score individual results. + * + * Good matches will have a higher score than poor matches. + * If an item is not a match, 0 will be returned by the function. + * + * @param {object|string} search + * @param {object} options (optional) + * @returns {function} + */ + Sifter.prototype.getScoreFunction = function(search, options) { + var self, fields, tokens, token_count, nesting; + + self = this; + search = self.prepareSearch(search, options); + tokens = search.tokens; + fields = search.options.fields; + token_count = tokens.length; + nesting = search.options.nesting; + + /** + * Calculates how close of a match the + * given value is against a search token. + * + * @param {mixed} value + * @param {object} token + * @return {number} + */ + var scoreValue = function(value, token) { + var score, pos; + + if (!value) return 0; + value = String(value || ''); + pos = value.search(token.regex); + if (pos === -1) return 0; + score = token.string.length / value.length; + if (pos === 0) score += 0.5; + return score; + }; + + /** + * Calculates the score of an object + * against the search query. + * + * @param {object} token + * @param {object} data + * @return {number} + */ + var scoreObject = (function() { + var field_count = fields.length; + if (!field_count) { + return function() { return 0; }; + } + if (field_count === 1) { + return function(token, data) { + return scoreValue(getattr(data, fields[0], nesting), token); + }; + } + return function(token, data) { + for (var i = 0, sum = 0; i < field_count; i++) { + sum += scoreValue(getattr(data, fields[i], nesting), token); + } + return sum / field_count; + }; + })(); + + if (!token_count) { + return function() { return 0; }; + } + if (token_count === 1) { + return function(data) { + return scoreObject(tokens[0], data); + }; + } + + if (search.options.conjunction === 'and') { + return function(data) { + var score; + for (var i = 0, sum = 0; i < token_count; i++) { + score = scoreObject(tokens[i], data); + if (score <= 0) return 0; + sum += score; + } + return sum / token_count; + }; + } else { + return function(data) { + for (var i = 0, sum = 0; i < token_count; i++) { + sum += scoreObject(tokens[i], data); + } + return sum / token_count; + }; + } + }; + + /** + * Returns a function that can be used to compare two + * results, for sorting purposes. If no sorting should + * be performed, `null` will be returned. + * + * @param {string|object} search + * @param {object} options + * @return function(a,b) + */ + Sifter.prototype.getSortFunction = function(search, options) { + var i, n, self, field, fields, fields_count, multiplier, multipliers, get_field, implicit_score, sort; + + self = this; + search = self.prepareSearch(search, options); + sort = (!search.query && options.sort_empty) || options.sort; + + /** + * Fetches the specified sort field value + * from a search result item. + * + * @param {string} name + * @param {object} result + * @return {mixed} + */ + get_field = function(name, result) { + if (name === '$score') return result.score; + return getattr(self.items[result.id], name, options.nesting); + }; + + // parse options + fields = []; + if (sort) { + for (i = 0, n = sort.length; i < n; i++) { + if (search.query || sort[i].field !== '$score') { + fields.push(sort[i]); + } + } + } + + // the "$score" field is implied to be the primary + // sort field, unless it's manually specified + if (search.query) { + implicit_score = true; + for (i = 0, n = fields.length; i < n; i++) { + if (fields[i].field === '$score') { + implicit_score = false; + break; + } + } + if (implicit_score) { + fields.unshift({field: '$score', direction: 'desc'}); + } + } else { + for (i = 0, n = fields.length; i < n; i++) { + if (fields[i].field === '$score') { + fields.splice(i, 1); + break; + } + } + } + + multipliers = []; + for (i = 0, n = fields.length; i < n; i++) { + multipliers.push(fields[i].direction === 'desc' ? -1 : 1); + } + + // build function + fields_count = fields.length; + if (!fields_count) { + return null; + } else if (fields_count === 1) { + field = fields[0].field; + multiplier = multipliers[0]; + return function(a, b) { + return multiplier * cmp( + get_field(field, a), + get_field(field, b) + ); + }; + } else { + return function(a, b) { + var i, result, a_value, b_value, field; + for (i = 0; i < fields_count; i++) { + field = fields[i].field; + result = multipliers[i] * cmp( + get_field(field, a), + get_field(field, b) + ); + if (result) return result; + } + return 0; + }; + } + }; + + /** + * Parses a search query and returns an object + * with tokens and fields ready to be populated + * with results. + * + * @param {string} query + * @param {object} options + * @returns {object} + */ + Sifter.prototype.prepareSearch = function(query, options) { + if (typeof query === 'object') return query; + + options = extend({}, options); + + var option_fields = options.fields; + var option_sort = options.sort; + var option_sort_empty = options.sort_empty; + + if (option_fields && !is_array(option_fields)) options.fields = [option_fields]; + if (option_sort && !is_array(option_sort)) options.sort = [option_sort]; + if (option_sort_empty && !is_array(option_sort_empty)) options.sort_empty = [option_sort_empty]; + + return { + options : options, + query : String(query || '').toLowerCase(), + tokens : this.tokenize(query), + total : 0, + items : [] + }; + }; + + /** + * Searches through all items and returns a sorted array of matches. + * + * The `options` parameter can contain: + * + * - fields {string|array} + * - sort {array} + * - score {function} + * - filter {bool} + * - limit {integer} + * + * Returns an object containing: + * + * - options {object} + * - query {string} + * - tokens {array} + * - total {int} + * - items {array} + * + * @param {string} query + * @param {object} options + * @returns {object} + */ + Sifter.prototype.search = function(query, options) { + var self = this, value, score, search, calculateScore; + var fn_sort; + var fn_score; + + search = this.prepareSearch(query, options); + options = search.options; + query = search.query; + + // generate result scoring function + fn_score = options.score || self.getScoreFunction(search); + + // perform search and sort + if (query.length) { + self.iterator(self.items, function(item, id) { + score = fn_score(item); + if (options.filter === false || score > 0) { + search.items.push({'score': score, 'id': id}); + } + }); + } else { + self.iterator(self.items, function(item, id) { + search.items.push({'score': 1, 'id': id}); + }); + } + + fn_sort = self.getSortFunction(search, options); + if (fn_sort) search.items.sort(fn_sort); + + // apply limits + search.total = search.items.length; + if (typeof options.limit === 'number') { + search.items = search.items.slice(0, options.limit); + } + + return search; + }; + + // utilities + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + var cmp = function(a, b) { + if (typeof a === 'number' && typeof b === 'number') { + return a > b ? 1 : (a < b ? -1 : 0); + } + a = asciifold(String(a || '')); + b = asciifold(String(b || '')); + if (a > b) return 1; + if (b > a) return -1; + return 0; + }; + + var extend = function(a, b) { + var i, n, k, object; + for (i = 1, n = arguments.length; i < n; i++) { + object = arguments[i]; + if (!object) continue; + for (k in object) { + if (object.hasOwnProperty(k)) { + a[k] = object[k]; + } + } + } + return a; + }; + + /** + * A property getter resolving dot-notation + * @param {Object} obj The root object to fetch property on + * @param {String} name The optionally dotted property name to fetch + * @param {Boolean} nesting Handle nesting or not + * @return {Object} The resolved property value + */ + var getattr = function(obj, name, nesting) { + if (!obj || !name) return; + if (!nesting) return obj[name]; + var names = name.split("."); + while(names.length && (obj = obj[names.shift()])); + return obj; + }; + + var trim = function(str) { + return (str + '').replace(/^\s+|\s+$|/g, ''); + }; + + var escape_regex = function(str) { + return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); + }; + + var is_array = Array.isArray || (typeof $ !== 'undefined' && $.isArray) || function(object) { + return Object.prototype.toString.call(object) === '[object Array]'; + }; + + var DIACRITICS = { + 'a': '[aḀá¸Ä‚ăÂâÇǎȺⱥȦȧẠạÄäÀàÃáĀÄÃãÅåąĄÃąĄ]', + 'b': '[bâ¢Î²Î’B฿ðŒá›’]', + 'c': '[cĆćĈĉČÄÄŠÄ‹CÌ„c̄ÇçḈḉȻȼƇƈɕᴄCc]', + 'd': '[dÄŽÄḊḋá¸á¸‘Ḍá¸á¸’ḓḎá¸ÄÄ‘D̦d̦ƉɖƊɗƋƌᵭá¶á¶‘ȡᴅDdð]', + 'e': '[eÉéÈèÊêḘḙĚěĔĕẼẽḚḛẺẻĖėËëĒēȨȩĘęᶒɆɇȄȅẾếỀá»á»„ễỂểḜá¸á¸–á¸—á¸”á¸•È†È‡áº¸áº¹á»†á»‡â±¸á´‡ï¼¥ï½…É˜ÇÆÆÎµ]', + 'f': '[fƑƒḞḟ]', + 'g': '[gɢ₲ǤǥĜÄĞğĢģƓɠĠġ]', + 'h': '[hĤĥĦħḨḩẖẖḤḥḢḣɦʰǶƕ]', + 'i': '[iÃíÌìĬĭÎîÇÇÃïḮḯĨĩĮįĪīỈỉȈȉȊȋỊịḬḭƗɨɨ̆ᵻᶖİiIıɪIi]', + 'j': '[jȷĴĵɈɉÊɟʲ]', + 'k': '[kƘƙê€êḰḱǨǩḲḳḴḵκϰ₭]', + 'l': '[lÅłĽľĻļĹĺḶḷḸḹḼḽḺḻĿŀȽƚⱠⱡⱢɫɬᶅɭȴʟLl]', + 'n': '[nŃńǸǹŇňÑñṄṅŅņṆṇṊṋṈṉN̈n̈ÆÉ²È Æžáµ°á¶‡É³ÈµÉ´ï¼®ï½ŽÅŠÅ‹]', + 'o': '[oØøÖöÓóÒòÔôǑǒÅőŎÅÈ®È¯á»Œá»ÆŸÉµÆ Æ¡á»Žá»ÅŒÅÕõǪǫȌÈÕ•Ö…]', + 'p': '[pṔṕṖṗⱣᵽƤƥᵱ]', + 'q': '[qê–ê—Ê ÉŠÉ‹ê˜ê™q̃]', + 'r': '[rŔŕɌÉŘřŖŗṘṙÈȑȒȓṚṛⱤɽ]', + 's': '[sŚśṠṡṢṣꞨꞩŜÅŠšŞşȘșS̈s̈]', + 't': '[tŤťṪṫŢţṬṭƮʈȚțṰṱṮṯƬƭ]', + 'u': '[uŬŭɄʉỤụÜüÚúÙùÛûǓǔŰűŬŭƯưỦủŪūŨũŲųȔȕ∪]', + 'v': '[vṼṽṾṿƲʋêžêŸâ±±Ê‹]', + 'w': '[wẂẃẀáºÅ´Åµáº„ẅẆẇẈẉ]', + 'x': '[xẌáºáºŠáº‹Ï‡]', + 'y': '[yÃýỲỳŶŷŸÿỸỹẎáºá»´á»µÉŽÉƳƴ]', + 'z': '[zŹźáºáº‘ŽžŻżẒẓẔẕƵƶ]' + }; + + var asciifold = (function() { + var i, n, k, chunk; + var foreignletters = ''; + var lookup = {}; + for (k in DIACRITICS) { + if (DIACRITICS.hasOwnProperty(k)) { + chunk = DIACRITICS[k].substring(2, DIACRITICS[k].length - 1); + foreignletters += chunk; + for (i = 0, n = chunk.length; i < n; i++) { + lookup[chunk.charAt(i)] = k; + } + } + } + var regexp = new RegExp('[' + foreignletters + ']', 'g'); + return function(str) { + return str.replace(regexp, function(foreignletter) { + return lookup[foreignletter]; + }).toLowerCase(); + }; + })(); + + + // export + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + return Sifter; +})); + + + +/** + * microplugin.js + * Copyright (c) 2013 Brian Reavis & contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this + * file except in compliance with the License. You may obtain a copy of the License at: + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF + * ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + * + * @author Brian Reavis + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + define('microplugin', factory); + } else if (typeof exports === 'object') { + module.exports = factory(); + } else { + root.MicroPlugin = factory(); + } +}(this, function() { + var MicroPlugin = {}; + + MicroPlugin.mixin = function(Interface) { + Interface.plugins = {}; + + /** + * Initializes the listed plugins (with options). + * Acceptable formats: + * + * List (without options): + * ['a', 'b', 'c'] + * + * List (with options): + * [{'name': 'a', options: {}}, {'name': 'b', options: {}}] + * + * Hash (with options): + * {'a': { ... }, 'b': { ... }, 'c': { ... }} + * + * @param {mixed} plugins + */ + Interface.prototype.initializePlugins = function(plugins) { + var i, n, key; + var self = this; + var queue = []; + + self.plugins = { + names : [], + settings : {}, + requested : {}, + loaded : {} + }; + + if (utils.isArray(plugins)) { + for (i = 0, n = plugins.length; i < n; i++) { + if (typeof plugins[i] === 'string') { + queue.push(plugins[i]); + } else { + self.plugins.settings[plugins[i].name] = plugins[i].options; + queue.push(plugins[i].name); + } + } + } else if (plugins) { + for (key in plugins) { + if (plugins.hasOwnProperty(key)) { + self.plugins.settings[key] = plugins[key]; + queue.push(key); + } + } + } + + while (queue.length) { + self.require(queue.shift()); + } + }; + + Interface.prototype.loadPlugin = function(name) { + var self = this; + var plugins = self.plugins; + var plugin = Interface.plugins[name]; + + if (!Interface.plugins.hasOwnProperty(name)) { + throw new Error('Unable to find "' + name + '" plugin'); + } + + plugins.requested[name] = true; + plugins.loaded[name] = plugin.fn.apply(self, [self.plugins.settings[name] || {}]); + plugins.names.push(name); + }; + + /** + * Initializes a plugin. + * + * @param {string} name + */ + Interface.prototype.require = function(name) { + var self = this; + var plugins = self.plugins; + + if (!self.plugins.loaded.hasOwnProperty(name)) { + if (plugins.requested[name]) { + throw new Error('Plugin has circular dependency ("' + name + '")'); + } + self.loadPlugin(name); + } + + return plugins.loaded[name]; + }; + + /** + * Registers a plugin. + * + * @param {string} name + * @param {function} fn + */ + Interface.define = function(name, fn) { + Interface.plugins[name] = { + 'name' : name, + 'fn' : fn + }; + }; + }; + + var utils = { + isArray: Array.isArray || function(vArg) { + return Object.prototype.toString.call(vArg) === '[object Array]'; + } + }; + + return MicroPlugin; +})); + +/** + * selectize.js (v0.12.6) + * Copyright (c) 2013–2015 Brian Reavis & contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this + * file except in compliance with the License. You may obtain a copy of the License at: + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF + * ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + * + * @author Brian Reavis + */ + +/*jshint curly:false */ +/*jshint browser:true */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + define('selectize', ['jquery','sifter','microplugin'], factory); + } else if (typeof exports === 'object') { + module.exports = factory(require('jquery'), require('sifter'), require('microplugin')); + } else { + root.Selectize = factory(root.jQuery, root.Sifter, root.MicroPlugin); + } +}(this, function($, Sifter, MicroPlugin) { + 'use strict'; + + var highlight = function($element, pattern) { + if (typeof pattern === 'string' && !pattern.length) return; + var regex = (typeof pattern === 'string') ? new RegExp(pattern, 'i') : pattern; + + var highlight = function(node) { + var skip = 0; + // Wrap matching part of text node with highlighting , e.g. + // Soccer -> Soccer for regex = /soc/i + if (node.nodeType === 3) { + var pos = node.data.search(regex); + if (pos >= 0 && node.data.length > 0) { + var match = node.data.match(regex); + var spannode = document.createElement('span'); + spannode.className = 'highlight'; + var middlebit = node.splitText(pos); + var endbit = middlebit.splitText(match[0].length); + var middleclone = middlebit.cloneNode(true); + spannode.appendChild(middleclone); + middlebit.parentNode.replaceChild(spannode, middlebit); + skip = 1; + } + } + // Recurse element node, looking for child text nodes to highlight, unless element + // is childless, + + + + + + + + + + + diff --git a/hesk/theme/hesk3/customer/knowledgebase/view-article.php b/hesk/theme/hesk3/customer/knowledgebase/view-article.php new file mode 100644 index 0000000..6dd8a11 --- /dev/null +++ b/hesk/theme/hesk3/customer/knowledgebase/view-article.php @@ -0,0 +1,241 @@ + + + + + + + <?php echo $hesk_settings['tmp_title']; ?> + + + + + + + + + + + + + +
    +
    +
    +
    +
    + + +
    +
    + + $value): ?> + + +
    +
    + +
    +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +

    + +

    +
    +
    +
    :
    +
    +
    +
    +
    :
    +
    + + + +
    +
    + +
    +
    :
    +
    +
    + +
    +
    + : +
    +
    +
    + + () + + + + + +
    +
    +
    + +
    +
    + 0): ?> +
    +

    + +

    +
    +
      + $subject): ?> +
    • + + + +
    • + +
    +
    +
    + +
    +
    +
    +
    +
    + +
    +
    + + + + + + + + + + + + diff --git a/hesk/theme/hesk3/customer/knowledgebase/view-category.php b/hesk/theme/hesk3/customer/knowledgebase/view-category.php new file mode 100644 index 0000000..33e80a1 --- /dev/null +++ b/hesk/theme/hesk3/customer/knowledgebase/view-category.php @@ -0,0 +1,391 @@ + 'none', + '1' => 'success', + '2' => '', // Info has no CSS class + '3' => 'warning', + '4' => 'danger' +); +?> + + + + + + <?php echo $hesk_settings['tmp_title']; ?> + + + + + + + + + + + + + + + +
    +
    +
    +
    +
    + + +
    +
    + + $value): ?> + + +
    +
    + +
    +
    +
    + +
    +
    + + +
    +
    +
    + + + +
    +
    +

    +
    +
    + + +
    +
    +
    + + + +
    +
    +

    + +

    +
    +
    + +
    +
    +
    + + + +
    +

    +
    + + + () + + 0): + ?> +
    + +
    +
    + + + + + + + + +
    + +
    + +
    + +
    + 0): ?> + + 0 || count($latestArticles) > 0): + ?> + + +
    +
    + +
    +
    + + + + + + + + + + + + + diff --git a/hesk/theme/hesk3/customer/maintenance.php b/hesk/theme/hesk3/customer/maintenance.php new file mode 100644 index 0000000..2b5e230 --- /dev/null +++ b/hesk/theme/hesk3/customer/maintenance.php @@ -0,0 +1,78 @@ + + + + + + + <?php echo $hesk_settings['hesk_title']; ?> + + + + + + + + + + + + + +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    +

    +

    +

    +
    +
    +
    +
    + +
    +
    + + + diff --git a/hesk/theme/hesk3/customer/util/alerts.php b/hesk/theme/hesk3/customer/util/alerts.php new file mode 100644 index 0000000..b2bb829 --- /dev/null +++ b/hesk/theme/hesk3/customer/util/alerts.php @@ -0,0 +1,25 @@ + 'white', + '1' => 'green', + '2' => 'blue', // Info has no CSS class + '3' => 'orange', + '4' => 'red' + ); + foreach ($messages as $message): + ?> +
    +
    +

    + +
    +
    + +
    + + +
    + > + +
    + +
    + +
    + + +
    + +
    + + +
    + class="isError" + > + +
    + +
    + +
    + + +
    + +
    + +
    + + +
    +
    style="display: block"> + + + + + + +
    +
    + +
    + + + > +
    +
    + + + +
    + + > +
    + '.$customField['value'].''; + break; + case 'date': + $customField['value'] = hesk_custom_date_display_format($customField['value'], $customField['date_format']); + break; + } + + echo ' +
    + '.$customField['name:'].' + '.$customField['value'].' +
    + '; + } +} \ No newline at end of file diff --git a/hesk/theme/hesk3/customer/util/kb-search.php b/hesk/theme/hesk3/customer/util/kb-search.php new file mode 100644 index 0000000..f73e289 --- /dev/null +++ b/hesk/theme/hesk3/customer/util/kb-search.php @@ -0,0 +1,91 @@ + +
    +
    +
    + + + + + +
    + +
    +
    + + #kb_search { + width: 70%; + } + #search-button { + width: 30%; + margin-left: 10px; + height: inherit; + } + + + + + + +
    + + + +
    +
    '; +} \ No newline at end of file diff --git a/hesk/theme/hesk3/customer/view-ticket/form.php b/hesk/theme/hesk3/customer/view-ticket/form.php new file mode 100644 index 0000000..826bc92 --- /dev/null +++ b/hesk/theme/hesk3/customer/view-ticket/form.php @@ -0,0 +1,214 @@ + + + + + + + <?php echo $hesk_settings['hesk_title']; ?> + + + + + + + + + + + + + + + +
    +
    +
    +
    +
    + + +
    +
    + + $value): ?> + + +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +

    +
    + + + +
    + +

    +
    +
    +
    + + +
    +
    + +
    + + +
    +
    +
    +
    + + checked> + +
    +
    + +
    + +
    +
    +
    +
    +
    + + + +
    +
    +
    +

    +
    +
    + + +
    +
    +
    + > + +
    +
    + > + +
    +
    + + +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + + + + + + + + + + + diff --git a/hesk/theme/hesk3/customer/view-ticket/partial/add-reply.php b/hesk/theme/hesk3/customer/view-ticket/partial/add-reply.php new file mode 100644 index 0000000..61a9dea --- /dev/null +++ b/hesk/theme/hesk3/customer/view-ticket/partial/add-reply.php @@ -0,0 +1,64 @@ + +
    +
    +
    +
    + + +
    + +
    + +
    +
    '; + } + ?> + +
    +
    + +
    + + + + '; + } + if ($reopen) { + echo ''; + } + ?> +
    +
    +
    + + + + + + + <?php echo $hesk_settings['hesk_title']; ?> + + + + + + + + + + + + + +
    +
    +
    +
    +
    + + +
    +
    + + $value): ?> + + +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + + + +
    +
    +
    +

    + + + + + + + + +

    +
    +
    +
    :
    + +
    + + (: ) +
    + +
    + +
    + +
    +
    +
    :
    + '.$hesklang['open_action'].'' : ''; + } elseif ($hesk_settings['custclose']) { + $status_action = ' '.$hesklang['close_action'].''; + } else { + $status_action = ''; + } + ?> +
    +
    +
    +
    :
    +
    +
    +
    +
    :
    +
    +
    +
    +
    :
    +
    +
    +
    +
    :
    +
    +
    +
    +
    :
    +
    +
    + +
    +
    :
    + 'critical', + 1 => 'high', + 2 => 'medium', + 3 => 'low' + ); + $priorityValue = $priorities[$ticket['priority']]; + ?> +
    + +
    +
    + +
    +
    +
    +
    +
    +
    + +
    +
    + + + + + + + + + + + + + + + +
    + + + + + + +
    + + + + + <?php echo $hesk_settings['hesk_title']; ?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    :
    :
    :
    :
    :
    :
    :
    :
    :
    :
    :
    + + +

    + + + + + + + + + + + + +
    :
    :
    +

    + +
    + + + \ No newline at end of file diff --git a/hesk/ticket.php b/hesk/ticket.php new file mode 100644 index 0000000..2774b55 --- /dev/null +++ b/hesk/ticket.php @@ -0,0 +1,289 @@ +
    • '.$hesk_error_buffer[0].'
    • '.$hesk_error_buffer[1].'
    '; + hesk_process_messages($hesk_error_buffer,'NOREDIRECT'); + print_form(); + } +} +elseif ( empty($trackingID) || ( $hesk_settings['email_view_ticket'] && empty($my_email) ) ) +{ + print_form(); +} + +/* Connect to database */ +hesk_dbConnect(); + +/* Limit brute force attempts */ +hesk_limitBfAttempts(); + +// Load custom fields +require_once(HESK_PATH . 'inc/custom_fields.inc.php'); + +// Load statuses +require_once(HESK_PATH . 'inc/statuses.inc.php'); + +/* 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); + + /* If we require e-mail to view tickets check if it matches the one from merged ticket */ + if ( hesk_verifyEmailMatch($ticket['trackid'], $my_email, $ticket['email'], 0) ) + { + hesk_process_messages( sprintf($hesklang['tme'], $trackingID, $ticket['trackid']) ,'NOREDIRECT','NOTICE'); + $trackingID = $ticket['trackid']; + } + else + { + hesk_process_messages( sprintf($hesklang['tme1'], $trackingID, $ticket['trackid']) . '

    ' . sprintf($hesklang['tme2'], $ticket['trackid']) ,'NOREDIRECT','NOTICE'); + $trackingID = $ticket['trackid']; + print_form(); + } + } + 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); + + /* If we require e-mail to view tickets check if it matches the one in database */ + hesk_verifyEmailMatch($trackingID, $my_email, $ticket['email']); +} + +/* Ticket exists, clean brute force attempts */ +hesk_cleanBfAttempts(); + +/* Remember email address? */ +if ($is_form) +{ + if ($do_remember) + { + hesk_setcookie('hesk_myemail', $my_email, strtotime('+1 year')); + } + elseif ( isset($_COOKIE['hesk_myemail']) ) + { + hesk_setcookie('hesk_myemail', ''); + } +} + +/* Set last replier name */ +if ($ticket['lastreplier']) +{ + if (empty($ticket['repliername'])) + { + $ticket['repliername'] = $hesklang['staff']; + } +} +else +{ + $ticket['repliername'] = $ticket['name']; +} + +// If IP is unknown (tickets via email pipe/pop3 fetching) assume current visitor IP as customer IP +if ($ticket['ip'] == '' || $ticket['ip'] == 'Unknown' || $ticket['ip'] == $hesklang['unknown']) +{ + hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `ip` = '".hesk_dbEscape(hesk_getClientIP())."' WHERE `id`=".intval($ticket['id'])); +} + +/* Get category name and ID */ +$result = hesk_dbQuery("SELECT `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 `name` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE `id`='1' LIMIT 1"); +} + +$category = hesk_dbFetchAssoc($result); + +/* Get replies */ +$result = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` WHERE `replyto`='".intval($ticket['id'])."' ORDER BY `id` ".($hesk_settings['new_top'] ? 'DESC' : 'ASC') ); +$replies = hesk_dbNumRows($result); +$repliesArray = array(); +$unread_replies = array(); +while ($row = hesk_dbFetchAssoc($result)) { + if ($row['staffid'] && !$row['read']) + { + $unread_replies[] = $row['id']; + } + $repliesArray[] = $row; +} +/* If needed update unread replies as read for staff to know */ +if (count($unread_replies)) +{ + hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` SET `read` = '1' WHERE `id` IN ('".implode("','", $unread_replies)."')"); +} + +// Demo mode +if ( defined('HESK_DEMO') ) +{ + $ticket['email'] = 'hidden@demo.com'; +} + +$messages = hesk_get_messages(); + +$custom_fields_before_message = array(); +$custom_fields_after_message = array(); +foreach ($hesk_settings['custom_fields'] as $k=>$v) { + if ($v['use']==1 && hesk_is_custom_field_in_category($k, $ticket['category'])) + { + $custom_field = array( + 'name' => $v['name'], + 'name:' => $v['name:'], + 'value' => $ticket[$k], + 'type' => $v['type'] + ); + + if ($v['type'] == 'date') { + $custom_field['date_format'] = $v['value']['date_format']; + } + + + if ($v['place'] == 1) { + $custom_fields_after_message[] = $custom_field; + } else { + $custom_fields_before_message[] = $custom_field; + } + } +} + +$hesk_settings['render_template'](TEMPLATE_PATH . 'customer/view-ticket/view-ticket.php', array( + 'messages' => $messages, + 'ticketJustReopened' => isset($_SESSION['force_form_top']), + 'ticket' => $ticket, + 'trackingID' => $trackingID, + 'numberOfReplies' => $replies, + 'replies' => $repliesArray, + 'category' => $category, + 'email' => $my_email, + 'customFieldsBeforeMessage' => $custom_fields_before_message, + 'customFieldsAfterMessage' => $custom_fields_after_message +)); +unset($_SESSION['force_form_top']); + +/* Clear unneeded session variables */ +hesk_cleanSessionVars('ticket_message'); + +/*** START FUNCTIONS ***/ + +function print_form() +{ + global $hesk_settings, $hesklang; + global $hesk_error_buffer, $my_email, $trackingID, $do_remember, $display; + + /* Print header */ + $hesk_settings['tmp_title'] = $hesk_settings['hesk_title'] . ' - ' . $hesklang['view_ticket']; + + $messages = hesk_get_messages(); + + $hesk_settings['render_template'](TEMPLATE_PATH . 'customer/view-ticket/form.php', array( + 'messages' => $messages, + 'trackingId' => $trackingID, + 'email' => $my_email, + 'rememberEmail' => $do_remember, + 'submittedForgotTrackingIdForm' => $display === 'block' + )); + +exit(); +} // End print_form() diff --git a/vhost.conf b/vhost.conf new file mode 100644 index 0000000..3f4efb4 --- /dev/null +++ b/vhost.conf @@ -0,0 +1,12 @@ + + DocumentRoot /srv + + Options Indexes FollowSymLinks MultiViews + AllowOverride All + Require all granted + Order allow,deny + allow from all + + ErrorLog /var/log/apache2/error.log + CustomLog /var/log/apache2/access.log combined +