runreport.php
上传用户:gzy2002
上传日期:2010-02-11
资源大小:1785k
文件大小:59k
- <?php
- // +-------------------------------------------------------------+
- // | DeskPRO v [2.0.1 Production]
- // | Copyright (C) 2001 - 2004 Headstart Solutions Limited
- // | Supplied by WTN-WDYL
- // | Nullified by WTN-WDYL
- // | Distribution via WebForum, ForumRU and associated file dumps
- // +-------------------------------------------------------------+
- // | DESKPRO IS NOT FREE SOFTWARE
- // +-------------------------------------------------------------+
- // | License ID : Full Enterprise License =) ...
- // | License Owner : WTN-WDYL Team
- // +-------------------------------------------------------------+
- // | $RCSfile: runreport.php,v $
- // | $Date: 2004/02/10 01:34:25 $
- // | $Revision: 1.128 $
- // +-------------------------------------------------------------+
- // | File Details:
- // | - Report generator (administration interface)
- // +-------------------------------------------------------------+
- error_reporting(E_ALL & ~E_NOTICE);
- require_once('./global.php');
- // License checks
- //Nullify WTN-WDYL Team
- feature_check('reports');
- // Stop JPgraph from installing an error handler here, since it causes problems.
- define('NO_GRAPHIC_HANDLER', 'true');
- // Need the calendar functions here for date slinging.
- include "./../includes/functions/calendar_functions.php";
- // default do
- $_REQUEST['do'] = trim($_REQUEST['do']);
- if (!isset($_REQUEST['do']) or $_REQUEST['do'] == "") {
- $_REQUEST['do'] = "runreport";
- }
- // globalise variables
- $global = array (
- array('id', 'number')
- );
- rg($global);
- // MODE: previewstat
- // If the administrator has requested a preview of a statistic,
- // we generate it here. The reporting engine runs 365 days into
- // the past to gather statistics to show the preview (so this
- // doesn't always look as good as it should.
- if ($_REQUEST['do'] == 'previewstat') {
- $work[] = $db->query_return("SELECT * FROM report_stat WHERE id = '$id'");
- if (!$db->num_rows()) {
- mistake('No valid statistic specified.');
- exit;
- }
- $work[0]['title'] = "Statistic Preview ({$work[0][title]})";
- $style = array('id' => 1, 'name' => 'style', 'title_colour' => '', 'description_colour' => '');
- $report = array(
- 'id' => 1,
- 'title' => "{$work[0][title]}",
- 'name' => 'None',
- 'description' => '',
- 'lastrun' => 0,
- 'format' => 'html',
- 'email' => '',
- 'repeattype' => '',
- 'value1' => '',
- 'value2' => '',
- 'style' => '1',
- 'path' => ''
- );
- $date = split('-', strtotime(date('Y-m-d').' - 1 year'));
- $_REQUEST['ydate'] = $date[0];
- $_REQUEST['mdate'] = $date[1];
- $_REQUEST['ddate'] = $date[2];
- $_REQUEST['number'] = 1;
- $_REQUEST['type'] = 'years';
- if ($work['displaytype'] == 'csv') {
- $csv = 1;
- }
- } else {
- // MODE: regular report
- // If we're *not* generating a preview, we're actually running the
- // report instead. Run through the given range of time and gather
- // statistics.
- $report = $db->query_return("SELECT * FROM report WHERE id = '$id'");
- $style = $db->query_return("SELECT * FROM report_style WHERE id = '$report[style]'");
- $db->query("
- SELECT report_stat.*
- FROM report_relations
- LEFT JOIN report_stat ON (report_stat.id = report_relations.statid)
- WHERE reportid = '$id'
- ");
- $work = array();
- while ($stat = $db->row_array()) {
- $work[] = $stat;
- if ($stat['displaytype'] == 'csv') {
- $csv = 1;
- }
- }
- }
- // CSV statistics must be standalone; if even one statistic in a report is a
- // CSV, we have to ignore the rest and just process the CSV.
- if ($csv) {
- $csv = array();
- foreach ($work as $stat) {
- if ($stat['displaytype'] == 'csv') {
- $csv[] = $stat;
- }
- }
- $work = array($csv[0]);
- $report['format'] = 'html';
- }
- // If the report's format is PDF, set up the PDF object and prepare it for
- // data.
- if ($report['format'] == 'PDF') {
- define('FPDF_FONTPATH','../includes/fpdf/font/');
- require('../includes/fpdf/fpdf.php');
- $pdf = new FPDF('P', 'mm', 'Letter');
- $pdf->Open();
- $pdf->AddPage();
- if ($report[title]) {
- $pdf->SetTitle($report['title']);
- $pdf->SetCreator('DeskPro v2.0');
- $pdf->SetFont('Times', 'B', 24);
- $pdf->Cell(0, 10, $report['title'], 0, 1, 'C');
- }
- }
- // If the report is to be mailed or saved, validate the inputs and set up if
- // needed.
- if ($report['email'] or $report['path']) { // Check for save-to-disk or e-mail options
- if (!validate_email($report['email'])) { // We've got a valid e-mail address
- $ext_error = 'The e-mail address specified, ' . htmlspecialchars_uni($report['email']) . ', is not valid. Not mailing.';
- $report['email'] = '';
- }
- if ($report['path']) { // Permissions checks for writing report to file.
- $filename = htmlspecialchars_uni($report['path']);
- if (is_dir($report['path'])) { // If it's a directory, we need to make up a name and try creating the file
- $tmpname = tempnam ($report['path'], 'report');
- if ($report['format'] == 'html') {
- $tmpname .= '.html';
- } else {
- $tmpname .= '.pdf';
- }
- $filename = htmlspecialchars_uni($tmpname);
- $handle = fopen($tmpfname, "wb");
- if (!$handle) {
- $ext_error = "Cannot create $filename.";
- $report['path'] = '';
- }
- } elseif (file_exists($report['path'])) { // Else, if it's a file, it'd best not exist yet.
- $ext_error = 'The filename you specified, ' . htmlspecialchars_uni($report['path']) . ', already exists.';
- $report['path'] = '';
- } else {
- $handle = @fopen($report['path'], 'wb');
- if (!$handle) {
- $ext_error = 'Cannot open ' . htmlspecialchars_uni($report['path']);
- $report['path'] = '';
- }
- if (!$handle) {
- $ext_error = "Cannot create $filename; make sure DeskPRO has permission to create files in this location.";
- $report['path'] = '';
- }
- }
- }
- }
- // Same check, different actions if they're still true now that we've validated some things.
- if ($report['email'] or $report['path']) { // Do we need to save this output to a buffer for later handling?
- $buffer = 1;
- ob_start();
- } elseif ($ext_error) {
- $report['format'] = 'html';
- print "<B>WARNING:</B> $ext_error Producing HTML output<BR />n";
- }
- // Each statistic is run independently of any others in a report. They are
- // processed in the order the database query returns them in. This loop runs
- // once for each statistic.
- foreach ($work as $stat) {
- unset($appendix);
- unset($data);
- unset($data2);
- unset($data_tmp);
- unset($data_tmp2);
- unset($where);
- unset($daterange);
- $interval = 0;
- // Unserialize data fields if any are present.
-
- if (isset($stat['fixed_general'])) {
- $fixed_general = unserialize($stat['fixed_general']);
- }
- if (isset($stat['fixed_user'])) {
- $fixed_user = unserialize($stat['fixed_user']);
- }
-
- if (isset($stat['fixed_ticket'])) {
- $fixed_ticket = unserialize($stat['fixed_ticket']);
- }
- // =========== Begin building the first level query ============
- $where = '1 ';
- ################# FIXED GENERAL FIELDS #################
- // open / closed
- if ($fixed_general['open_status'] == 'open') {
- $where .= " AND is_open = 1";
- } elseif ($fixed_general['open_status'] == 'closed') {
- $where .= " AND is_open = 0";
- }
- // awaiting tech / user
- if (isset($fixed_general['awaiting_status'])) {
- if ($fixed_general['awaiting_status'] == 'tech') {
- $where .= " AND awaiting_tech";
- } elseif ($fixed_general['awaiting_status'] == 'user') {
- $where .= " AND !awaiting_tech";
- }
- }
- // category
- if (isset($fixed_general['category'])) {
- if (is_array($fixed_general['category'])) {
- $where .= " AND category IN " . array2sql($fixed_general['category']);
- }
- }
- // priority
- if (isset($fixed_general['category'])) {
- if (is_array($fixed_general['priority'])) {
- $where .= " AND priority IN " . array2sql($fixed_general['priority']);
- }
- }
- ################# FIXED CUSTOM TICKET FIELDS #################
- // For each custom ticket field specified by the statistic, add the correct
- // search clause to the query.
- if (is_array($fixed_ticket)) {
- $values = array();
- $db->query("SELECT * FROM ticket_def");
- while ($result = $db->row_array()) {
- $display_name = unserialize($result['display_name']);
- $tfields_names[$result['name']] = $display_name[1];
- $tfields[$result['name']] = $result;
- $ticket_fields[$result['name']] = $result['formtype'];
- }
- foreach ($fixed_ticket AS $key => $var) {
- if (in_array($key, array_keys($ticket_fields)) AND $fixed_ticket[$key]) {
- $where .= field_search($tfields[$key],
- $fixed_ticket[$key],
- $fixed_ticket["extra$key"],
- 'ticket',
- $fixed_ticket[$key."_match"],
- $fixed_ticket[$key."_not"]);
- }
- }
- }
- ################# FIXED CUSTOM USER FIELDS #################
- // For each custom user field specified by the statistic, add the correct
- // search clause to the query. This is done by running another query to
- // find all matching users, then using those results to add to the primary
- // query.
-
- if (is_array($fixed_user)) {
- $values = array();
- $db->query("SELECT * FROM user_def");
- while ($result = $db->row_array()) {
- $display_name = unserialize($result['display_name']);
- $ufields_names[$result['name']] = $display_name[1];
- $ufields[$result['name']] = $result;
- $user_fields[$result['name']] = $result['formtype'];
- }
- $where2 = '1';
- foreach ($fixed_user AS $key => $var) {
- if (in_array($key, array_keys($user_fields)) AND $fixed_user[$key]) {
- $where2 .= field_search($ufields[$key],
- $fixed_user[$key],
- $fixed_user["extra$key"],
- 'user',
- $fixed_user[$key."_match"],
- $fixed_user[$key."_not"]);
- }
- }
- $db->query("SELECT user.id FROM user WHERE $where2");
- $techs = array();
- if ($db->num_rows()) {
- while ($result = $db->row_array()) {
- $techs[] = $result['id'];
- }
- $techs = join(',', $techs);
- $where .= " AND ticket.userid IN ($techs)";
- }
- }
- ################# DATE #################
- $startdate = formatymd("$_REQUEST[ydate]-$_REQUEST[mdate]-$_REQUEST[ddate]");
- if (validate_ymd($startdate) && $_REQUEST['number'] && $_REQUEST['type']) {
- $enddate = strtotime("$startdate + $_REQUEST[number] $_REQUEST[type]");
- $startdate = strtotime($startdate);
- $daterange = " AND date_opened >= '$startdate'
- AND date_opened < '$enddate' ";
- }
- ################# PRE PROCESSING (TO CHANGE INDEXES FROM NUMBERS TO VALUES) #################
- $change['is_open'] = array(
- 0 => 'Closed',
- 1 => 'Open'
- );
- $change['awaiting_tech'] = array(
- 0 => 'Awaiting User Response',
- 1 => 'Awaiting Technician Response'
- );
- // category
- $db->query("SELECT id, name FROM ticket_cat");
- while ($result = $db->row_array()) {
- $change['category'][$result['id']] = $result['name'];
- }
- $change['category'][0] = 'No category specified';
- // priority
- $db->query("SELECT id, name FROM ticket_pri");
- while ($result = $db->row_array()) {
- $change['priority'][$result['id']] = $result['name'];
- }
- $change['priority'][0] = 'No priority specified';
- // tech
- $db->query("SELECT id, username FROM tech");
- while ($result = $db->row_array()) {
- $change['tech'][$result['id']] = $result['username'];
- }
- $change['tech'][0] = 'Unassigned';
- // users
- $db->query("SELECT id, username FROM user");
- while ($result = $db->row_array()) {
- $change['userid'][$result['id']] = $result['username'];
- }
- $change['userid'][0] = 'Unowned';
- ################# 1ST VARIABLE PROCESSING #################
- // If this statistic has a Date Affects setting, then we're doing some
- // custom processing.
- // If it's an "interval"-style setting, the intervals make up the "first
- // variable" for this statistic, and the real "1st Variable" becomes the
- // "2nd Variable"; we gather all the first-pass query results together to
- // let 2nd Variable processing handle it from there.
- // If it's a "length"-style setting, we're just searching for tickets that
- // match some function-of-time value and so can just be added to the WHERE
- // clause; we process those here.
- if ($stat['dateaffect'] != 'none') {
- // Build the intervals list (dividing the total report range into
- // sections of time as specified by the statistic
- $intervals = explode(',', $stat['variable1times']);
- $i_years = $intervals[0];
- $i_days = $intervals[1];
- $i_hours = $intervals[2];
- $i_mins = $intervals[3];
- if (!$i_hours AND !$i_mins) {
- $dateformat = 'm/d/Y';
- } elseif (!$i_years AND !$i_days) {
- $dateformat = 'h:i:sa';
- } else {
- $dateformat = 'm/d/Y h:i:sa';
- }
- $duration = ($i_mins * 60) + ($i_hours * 3600) + ($i_days * 86400) + ($i_years * 31536000);
- $intervals = get_intervals($startdate, $enddate,
- "+ $i_years years $i_days days $i_hours hours $i_mins minutes"
- );
- }
- switch ($stat['dateaffect']) {
- default: // Regular processing
- $db->query("SELECT COUNT(*) AS totals, $stat[variable1]
- FROM ticket
- WHERE $where $daterange
- GROUP BY ticket.$stat[variable1]
- ");
- while ($result = $db->row_array()) {
- $data_tmp[$result[$stat['variable1']]] = $result['totals'];
- }
- $db->query("SELECT ticket.id
- FROM ticket
- WHERE $where $daterange
- ");
- while ($result = $db->row_array()) {
- $appendix[$result['id']] = 1;
- }
- break;
- case 'opened': // Interval: all tickets opened between start and end,
- // grouped by interval
- $stat['variable2'] = $stat['variable1'];
- $result = $db->query_return_array("SELECT ticket.id, ticket.$stat[variable1], ticket.date_opened
- FROM ticket
- WHERE $where
- AND date_opened >= '$startdate'
- AND date_opened < '$enddate'");
- foreach ($intervals as $intkey => $intval) {
- $data_tmp[date($dateformat, $intval[0])] = 0;
- foreach ($result AS $tmpdata) {
- if ($tmpdata['date_opened'] >= $intval[0] AND $tmpdata['date_opened'] < $intval[1]) {
- $data_tmp[date($dateformat, $intval[0])]++;
- $appendix[$tmpdata['id']] = 1;
- }
- }
- }
- $interval = 1;
- break;
- case 'closed': // Interval; all tickets closed between start and end,
- // grouped by interval
- $stat['variable2'] = $stat['variable1'];
- $result = $db->query_return_array("SELECT ticket.id, ticket.$stat[variable1], ticket.date_closed
- FROM ticket
- WHERE $where
- AND date_closed >= '$startdate'
- AND date_closed < '$enddate'");
- if (is_array($intervals)) {
- foreach ($intervals as $intkey => $intval) {
- $data_tmp[date($dateformat, $intval[0])] = 0;
- if (is_array($result)) {
- foreach ($result AS $tmpdata) {
- if ($tmpdata['date_closed'] >= $intval[0] AND $tmpdata['date_closed'] < $intval[1]) {
- $data_tmp[date($dateformat, $intval[0])]++;
- $appendix[$tmpdata['id']] = 1;
- }
- }
- }
- }
- }
- $interval = 1;
- break;
- case 'reply': // Interval; all tickets replied to between start and end,
- // grouped by interval
- $stat['variable2'] = $stat['variable1'];
- $result = $db->query_return_array("SELECT ticket.id, ticket.$stat[variable1], ticket_message.date
- FROM ticket, ticket_message
- WHERE $where
- AND ticket_message.date >= '$startdate'
- AND ticket_message.date < '$enddate'
- AND ticket.id = ticket_message.ticketid");
- foreach ($intervals as $intkey => $intval) {
- $data_tmp[date($dateformat, $intval[0])] = 0;
- foreach ($result AS $tmpdata) {
- if ($tmpdata['date'] >= $intval[0] AND $tmpdata['date'] < $intval[1]) {
- $data_tmp[date($dateformat, $intval[0])]++;
- $appendix[$tmpdata['id']] = 1;
- }
- }
- }
- $interval = 1;
- break;
- case '1streply_less': // Length; all tickets whose first response took less
- // than the specified amount of time.
- $db->query("SELECT COUNT(*) AS totals, ticket.$stat[variable1], ticket_message.date
- FROM ticket, ticket_message
- WHERE ticket.id = ticket_message.ticketid
- AND ((ticket.date_opened - ticket_message.date) < $duration)
- GROUP BY $stat[variable1]");
- if ($result = $db->num_rows()) {
- $data_tmp[$stat['variable1']] = $result['totals'];
- }
- $db->query("SELECT ticket.id, ticket_message.date
- FROM ticket, ticket_message
- WHERE ((ticket.date_opened - ticket_message.date) < $duration)");
- while ($result = $db->row_array()) {
- $appendix[$result['id']] = 1;
- }
- $length = 1;
- break;
- case '1streply_greater': // Length; all tickets whose first response took more
- // than the specified amount of time.
- $db->query("SELECT COUNT(*) AS totals, ticket.$stat[variable1], ticket_message.date
- FROM ticket, ticket_message
- WHERE ticket.id = ticket_message.ticketid
- AND ((ticket.date_opened - ticket_message.date) >= $duration)
- GROUP BY $stat[variable1]");
- if ($result = $db->num_rows()) {
- $data_tmp[$stat['variable1']] = $result['totals'];
- }
- $db->query("SELECT ticket.id, ticket_message.date
- FROM ticket, ticket_message
- WHERE ((ticket.date_opened - ticket_message.date) >= $duration)");
- while ($result = $db->row_array()) {
- $appendix[$result['id']] = 1;
- }
- $length = 1;
- break;
- case 'span_less': // Length; all tickets whose open-to-close duration is less
- // than the specified amount of time.
- $db->query("SELECT COUNT(ticket.id) AS totals, ticket.$stat[variable1]
- FROM ticket, ticket_def
- WHERE ((ticket.date_closed - ticket.date_opened) < $duration)
- OR ((now() - ticket.date_opened) < $duration)
- GROUP BY $stat[variable1]");
- if ($result = $db->num_rows()) {
- while ($result = $db->row_array()) {
- $data_tmp[$result[$stat['variable1']]] = $result['totals'];
- }
- }
- $db->query("SELECT ticket.id
- FROM ticket
- WHERE ((ticket.date_closed - ticket.date_opened) < $duration)
- OR ((now() - ticket.date_opened) < $duration)");
- while ($result = $db->row_array()) {
- $appendix[$result['id']] = 1;
- }
- $length = 1;
- break;
- case 'span_more': // Length; all tickets whose open-to-close duration is more
- // than the specified amount of time.
- $db->query("SELECT COUNT(ticket.id) AS totals, ticket.$stat[variable1]
- FROM ticket
- WHERE ((ticket.date_closed - ticket.date_opened) >= $duration)
- OR ((now() - ticket.date_opened) >= $duration)
- GROUP BY $stat[variable1]");
- if ($result = $db->num_rows()) {
- while ($result = $db->row_array()) {
- $data_tmp[$result[$stat['variable1']]] = $result['totals'];
- }
- }
- $db->query("SELECT ticket.id
- FROM ticket
- WHERE ((ticket.date_closed - ticket.date_opened) >= $duration)
- OR ((now() - ticket.date_opened) >= $duration)");
- while ($result = $db->row_array()) {
- $appendix[$result['id']] = 1;
- }
- $length = 1;
- break;
- }
- // If there *isn't* an interval, name translations haven't already been
- // done for us, so do them here.
- if (!$interval) {
- if (isset($data_tmp)) {
- if (is_array($data_tmp)) {
- if (stristr($stat['variable1'], 'custom')) { // If it's a custom field, we have to figure out names ourselves.
- foreach ($data_tmp AS $key => $val) {
- $items = explode('|||', $key);
- $tmptitle = array();
- foreach ($items AS $ikey => $ival) {
- if (is_array($tfields[$stat['variable1']])) {
- foreach ($tfields[$stat['variable1']] AS $tkey => $tval) {
- if ($tval[0] == $ival) {
- $tmptitle[] = $tval[2];
- }
- }
- } else {
- $tmptitle[] = $tfields_names[$stat['variable1']];
- }
- }
- $change[$stat['variable1']][$key] = join(', ', $tmptitle);
- }
- }
- $data = change_index($data_tmp, $change[$stat['variable1']]);
- }
- }
- } else {
- if (isset($data_tmp)) {
- $data = $data_tmp;
- }
- }
- ################# 2ND VARIABLE PROCESSING #################
- // The 2nd variable is processed after the first has been run; each
- // "column" of the 1st variable's series of data is used as a key for the
- // 2nd variable run.
- if ($interval) { // If we're doing an interval search, use the dates as X series data
- switch ($stat['dateaffect']) {
- case 'opened': // By date-opened
- $result = $db->query_return_array("SELECT ticket.id, ticket.$stat[variable2], ticket.date_opened
- FROM ticket
- WHERE $where
- AND date_opened >= '$startdate'
- AND date_opened < '$enddate'");
- unset($tmp);
- foreach ($intervals as $intkey => $intval) {
- $tmp[$tmpdata[$stat['variable2']]] = 0;
- foreach ($result AS $tmpdata) {
- if ($tmpdata['date_opened'] >= $intval[0] AND $tmpdata['date_opened'] < $intval[1]) {
- $tmp[$tmpdata[$stat['variable2']]]++;
- }
- }
- if (isset($tmp)) {
- $data2[date($dateformat, $intval[0])] = change_index($tmp, $change[$stat['variable2']]);
- } else {
- $data2[date($dateformat, $intval[0])] = NULL;
- }
- }
- break;
- case 'closed': // By date-closed
- $result = $db->query_return_array("SELECT ticket.id, ticket.$stat[variable2], ticket.date_closed
- FROM ticket
- WHERE $where
- AND date_closed >= '$startdate'
- AND date_closed < '$enddate'");
- unset($tmp);
- foreach ($intervals as $intkey => $intval) {
- $tmp[$tmpdata[$stat['variable2']]] = 0;
- foreach ($result AS $tmpdata) {
- if ($tmpdata['date_closed'] >= $intval[0] AND $tmpdata['date_closed'] < $intval[1]) {
- $tmp[$tmpdata[$stat['variable2']]]++;
- }
- }
- if (isset($tmp)) {
- $data2[date($dateformat, $intval[0])] = change_index($tmp, $change[$stat['variable2']]);
- } else {
- $data2[date($dateformat, $intval[0])] = NULL;
- }
- }
- break;
- case 'reply': // By date of reply.
- $result = $db->query_return_array("SELECT ticket.id, ticket.$stat[variable2], ticket_message.date
- FROM ticket, ticket_message
- WHERE $where
- AND ticket_message.date >= '$startdate'
- AND ticket_message.date < '$enddate'
- AND ticket.id = ticket_message.ticketid");
- unset($tmp);
- foreach ($intervals as $intkey => $intval) {
- $tmp[$tmpdata[$stat['variable2']]] = 0;
- foreach ($result AS $tmpdata) {
- if ($tmpdata['date'] >= $intval[0] AND $tmpdata['date'] < $intval[1]) {
- $tmp[$tmpdata[$stat['variable2']]]++;
- }
- }
- if (isset($tmp)) {
- $data2[date($dateformat, $intval[0])] = change_index($tmp, $change[$stat['variable2']]);
- } else {
- $data2[date($dateformat, $intval[0])] = NULL;
- }
- }
- break;
- }
- } else {
- // Otherwise, process normally, once for each piece of data in the 1st
- // variable series.
- if (($stat['variable2'] AND isset($data_tmp)) and
- ($stat['variable1'] != $stat['variable2'])) {
- foreach ($data_tmp AS $key => $var) {
- $db->query("
- SELECT COUNT(*) AS totals, $stat[variable2]
- FROM ticket
- WHERE $where
- AND $stat[variable1] = '" . mysql_escape_string($key) . "'
- GROUP BY $stat[variable2]
- ");
- unset($tmp);
- if ($db->num_rows()) {
- while ($result = $db->row_array()) {
- $tmp[$result[$stat['variable2']]] = $result['totals'];
- }
- }
- if (stristr($stat['variable2'], 'custom')) { // If it's a custom field, we have to figure out names ourselves.
- foreach ($data_tmp AS $key => $val) {
- $items = explode('|||', $key);
- $tmptitle = array();
- foreach ($items AS $ikey => $ival) {
- if (is_array($tfields[$stat['variable2']])) {
- foreach ($tfields[$stat['variable2']] AS $tkey => $tval) {
- if ($tval[0] == $ival) {
- $tmptitle[] = $tval[2];
- }
- }
- } else {
- $tmptitle[] = $tfields_names[$stat['variable2']];
- }
- }
- $change[$stat['variable2']][$key] = join(', ', $tmptitle);
- }
- }
- // Perform the index exchange so the table/graph rendering
- // functions can label each axis.
- $data_tmp2[$key] = change_index($tmp, $change[$stat['variable2']]);
- $db->query("
- SELECT id
- FROM ticket
- WHERE $where
- AND $stat[variable1] = '" . mysql_escape_string($key) . "'
- ");
- while ($result = $db->row_array()) {
- $appendix[$result['id']] = 1;
- }
- }
- $data2 = change_index($data_tmp2, $change[$stat['variable1']]);
- }
- }
- ################# GENERATE REPORT ENTRY #################
- // With the data array loaded, the statistic's output can be generated.
- if (isset($appendix)) { // Get the appendix ticket numbers into a list.
- $appendix = array_keys($appendix);
- }
- if (!isset($data)) {
- $data = NULL;
- }
- if (!isset($data2)) {
- $data2 = NULL;
- }
- // Now call the correct function to generate the requested output.
- switch($report['format']) {
- case 'default':
- case 'HTML': // HTML generation
- switch($stat['displaytype']) {
- case 'default':
- case 'data':
- echo make_table($data, $data2, $stat, $style);
- echo "<BR />n";
- break;
- case 'bar':
- echo make_barchart($data, $data2, $stat, $style);
- break;
- case 'databar':
- echo make_table($data, $data2, $stat, $style);
- echo make_barchart($data, $data2, $stat, $style);
- break;
- case 'pie':
- echo make_piechart($data, $data2, $stat, $style);
- break;
- case 'datapie':
- echo make_table($data, $data2, $stat, $style);
- echo make_piechart($data, $data2, $stat, $style);
- break;
- case 'csv': // If the user wants a CSV, we generate it and exit.
- header('Content-type: text/comma-separated-values');
- echo make_csv($data, $data2, $stat, $style);
- exit;
- }
- // Generate the appendix if it's been requested.
- if (($data OR $data2) AND isset($stat['appendix'])) {
- if (isset($appendix)) {
- echo make_appendix($appendix, $stat['displayfields'], $change);
- }
- }
- echo "<HR>n";
- break;
- case 'PDF': // PDF generation
- switch($stat['displaytype']) {
- case 'default':
- case 'data':
- make_pdf_table($data, $data2, $stat);
- break;
- case 'bar':
- make_barchart($data, $data2, $stat, $style, 1);
- break;
- case 'databar':
- make_pdf_table($data, $data2, $stat);
- make_barchart($data, $data2, $stat, $style, 1);
- break;
- case 'pie':
- make_piechart($data, $data2, $stat, $style, 1);
- break;
- case 'datapie':
- make_pdf_table($data, $data2, $stat);
- make_piechart($data, $data2, $stat, $style, 1);
- break;
- case 'csv':
- mistake('CSV type not supported in PDFs!');
- exit;
- break;
- }
- // Generate the appendix if it's been requested.
- if (($data OR $data2) AND $stat['appendix']) {
- echo make_pdf_appendix($appendix, $stat['displayfields'], $change);
- }
- break;
- }
- }
- // Now that all the statistics have been generated, if we have to mail or save
- // the report somewhere, gather it up and prepare it.
- if (isset($buffer)) { // We're saving or mailing this, not emitting it.
- if ($report['format'] == 'pdf') { // The attachment is a PDF
- $tmpfname = tempnam ("/tmp", "dp2_pdf");
- $pdf->Output($tmpfname);
- $handle = fopen($tmpfname, "rb");
- $output['data'] = fread($handle, filesize($tmpfname));
- fclose($handle);
- unlink($tmpfname);
- $output['name'] = 'report.pdf';
- $output['extension'] = 'pdf';
- } else { // The attachment is HTML
- $output['data'] = ob_get_contents();
- $output['name'] = 'report.html';
- $output['extension'] = 'html';
- }
- if ($report['email']) { // Send e-mail
- global $footer;
- eval(makeemaileval('message', 'TECHBODY_report', $subject));
- dp_mail($report['email'], $subject, $message, '', '', array($output));
- $msg = 'Report mailed to ' . htmlspecialchars_uni($report['email']) . '. ';
- }
- if (isset($handle)) { // Save to disk
- fwrite($handle, $output['data']);
- fclose($handle);
- if (isset($msg)) {
- $msg .= "Report saved in file $filename.";
- } else {
- $msg = "Report saved in file $filename.";
- }
- }
- ob_end_clean();
- if (!defined('CRONZONE')) {
- // If this is *NOT* being run as a cron job, generate a header and let
- // the admin know the run is complete.
- admin_header('Reports', 'Save/E-Mail Report');
- print $msg;
- }
- exit;
- } else {
- // Finally, if the report is just meant to be viewed immediately, show it
- // and exit.
- if ($report['format'] == 'PDF') {
- $pdf->Output();
- }
- }
- // All done!
- // ============================================
- // Function make_appendix
- // ============================================
- // Generates an HTML table containing a list of
- // all tickets matched during the reporting run
- // ============================================
- // Arguments:
- // appendix List of ticket numbers in
- // the appendix
- // appendix_fields
- // List of fields to show in
- // the appendix
- // change Column or row name mappings
- // to use.
- // ============================================
- // Returns:
- // The HTML to display.
- // ============================================
- function make_appendix($appendix, $appendix_fields = NULL, $change = array()) {
- global $db, $tfields, $tfields_names;
- $html = "<table cellpadding="0" cellspacing="0" width="100%"><tr><td bgcolor="#000000"><table cellspacing="1" cellpadding="3" width="100%">";
- $fields = explode(',', $appendix_fields);
- $total = count($fields);
- $count = 0;
-
- // If there weren't any tickets matched, or if the admin hasn't specified
- // anything to display, don't bother doing anything.
- if ($appendix_fields AND count($appendix)) {
- $appendix = array2sql($appendix);
- // Remap "user" fields to "userid" to match the ticket table.
- foreach ($fields as $key => $var) {
- if ($var == 'user') {
- $fields[$key] = 'userid';
- }
- }
- $appendix_fields = join(',', $fields);
- // Grab ticket data
- $db->query(
- "SELECT id, $appendix_fields
- FROM ticket
- WHERE id IN $appendix
- ");
-
- // If we don't get any rows, don't bother running through any results.
- // Otherwise, generate the table headers and run through the result set
- // showing each entry.
- if ($db->num_rows()) {
- $count++;
- $total++;
- $html .= "<tr bgcolor="#FFFF99"><td align="center" colspan="$total"><B>Found " . $db->num_rows() . " Ticket(s)</B></td></tr>";
- $html .= "<tr>n";
- // Generate the headings.
- foreach($fields as $key => $val) {
- switch ($val) {
- case 'subject': $label = 'Subject'; break;
- case 'priority' : $label = 'Priority'; break;
- case 'tech' : $label = 'Technician'; break;
- case 'is_open' : $label = 'Open/Closed'; break;
- case 'awaiting_tech' : $label = 'Awaiting...'; break;
- case 'category' : $label = 'Category'; break;
- case 'userid' : $label = 'User'; break;
- case 'id' : next; break;
- default: $label = $val;
- }
- if (stristr($val, 'custom')) {
- $label = $tfields_names[$val];
- }
- $html .= "<td bgcolor="#FFFFCC"><B>$label</B></TD>";
- }
- $html .= "<td align="center" bgcolor="#FFFFCC"><B>View</B></TD>";
- $html .= "</tr>n";
- // Run through each result and generate the row.
- while ($result = $db->row_array()) {
- $html .= "<tr>n";
-
- // Figure out what kind of field it is, and "massage" the
- // displayed data accordingly.
- foreach($fields as $key => $val) {
- switch ($val) {
- case 'id':
- next;
- break;
- case 'subject':
- if ($result[$val]) {
- $result[$val] = $result[$val];
- } else {
- $result[$val] = "<I>None</I>";
- }
- break;
- case 'category': $result[$val] = $change['category'][$result[$val]]; break;
- case 'priority': $result[$val] = $change['priority'][$result[$val]]; break;
- case 'tech':
- if (isset($result[$val])) {
- $result[$val] = $change['tech'][$result[$val]];
- } else {
- $result[$val] = "<I>None Assigned</I>";
- }
- break;
- case 'userid':
- if (isset($result[$val])) {
- $result[$val] = $change['userid'][$result[$val]];
- } else {
- $result[$val] = "<I>None</I>";
- }
- break;
- case 'is_open': $result[$val] = $change['is_open'][$result[$val]]; break;
- case 'awaiting_tech': $result[$val] = $change['awaiting_tech'][$result[$val]]; break;
- }
- // Again, for custom fields we have to calculate the
- // display name here.
- if (stristr($val, 'custom')) {
- $items = explode('|||', $result[$val]);
- $tmptitle = array();
- foreach ($items AS $ikey => $ival) {
- if (is_array($tfields[$val])) {
- foreach ($tfields[$val] AS $tkey => $tval) {
- if ($tval[0] == $ival) {
- $tmptitle[] = $tval[2];
- }
- }
- }
- }
- $result[$val] = join(', ', $tmptitle);
- }
- $html .= "<td bgcolor="#FFFFFF"><B>$result[$val]</B></TD>";
- }
- $html .= "<td align="center" bgcolor="#FFFFFF"><B><A HREF="../tech/tickets/ticketview.php?id=$result[id]">View</A></B></td>";
- $html .= "</tr>n";
- }
- } else {
- $html .= "<tr bgcolor="#FFFF99"><td align="center"><B>No Tickets Found</B></td></tr></table></td></tr></table>";
- }
- $html .= "</table></td></tr></table>";
- } else {
- $html = NULL;
- }
- return $html;
- }
- // ============================================
- // Function make_barchart
- // ============================================
- // Generates a graphical bar chart showing the
- // number of tickets matched per grouping
- // during the reporting run.
- // ============================================
- // Arguments:
- // data First series of data
- // data2 First and second series of data
- // stat Statistic definition from DB
- // style Style definition from DB
- // do_pdf If true, add the resulting
- // graph to the PDF object,
- // otherwise, generate the file
- // and output a link to it.
- // ============================================
- // Returns:
- // Nothing; directly outputs to browser or
- // adds data to the PDF object
- // ============================================
- function make_barchart($data = NULL, $data2 = NULL, $stat, $style = NULL, $do_pdf = 0) {
- global $pdf;
- $html = "<font size="+1"><B>$stat[title]</B></font><br />n<b>$stat[description]</b></font><br />n<br />n";
- $html .= "<table cellpadding="0" cellspacing="0"><tr><td bgcolor="#000000"><table cellspacing="1" cellpadding="3">";
- include_once("./../includes/graph/jpgraph.php");
- include_once ("./../includes/graph/jpgraph_bar.php");
- error_reporting(0);
- if (!($data) AND !($data2)) { // If no tickets, don't bother with a graphic
- if ($do_pdf) {
- return make_pdf_table($data, $data2, $stat);
- } else {
- return make_table($data, $data2, $stat);
- }
- }
- // If we're making a PDF, set up the headers for the stat in the PDF
- // object.
- if ($do_pdf) {
- $pdf->SetFont('Times', 'B', 20);
- $pdf->Write(8, trim($stat['title'])."n");
- $pdf->SetFontSize(12);
- $pdf->Write(6, trim($stat['description'])."n");
- }
- // Set up the graph object and set basic attributes.
- $angle = 0;
- $graph = new Graph(700,350);
- $graph->SetScale('textlin');
- $graph->img->SetMargin(45,50,40,65);
- $graph->xaxis->SetFont(FF_FONT1,FS_BOLD);
- if ($data2) { // We're generating a group bar graph
- // Set up colors, and count rows and columns.
- $colors = array('gray', 'red', 'orange', 'yellow', 'green', 'blue', 'purple', 'white', 'black');
- foreach ($data2 AS $key1 => $var1) {
- $cols[$key1] = 1;
- }
- $rowdata = 0;
- foreach ($data2 AS $key1 => $var1) {
- if (is_array($var1)) {
- foreach ($var1 AS $key2 => $var2) {
- $rows[$key2] = 1;
- $rowdata = 1;
- }
- }
- }
- // If there isn't at least one row with valid data, don't continue with
- // the graphic.
- if (!$rowdata) {
- if ($do_pdf) {
- return make_pdf_table($data, $data2, $stat);
- } else {
- return make_table($data, $data2, $stat);
- }
- }
- // Otherwise, generate the graph, one X axis entry at a time.
- foreach ($rows AS $key1 => $var1) {
- $axis_x = array();
- $names = array();
- foreach ($cols AS $key2 => $var2) {
- $names[] = $key2;
- if (strlen($key2) > 10) {
- $angle = 12;
- }
- if (isset($data2[$key2][$key1])) {
- $axis_x[] = $data2[$key2][$key1];
- } else {
- $axis_x[] = 0;
- }
- }
- $bargraph = new BarPlot($axis_x);
- if (!($color = next($colors))) {
- $color = reset($colors);
- }
- $bargraph->SetFillColor($color);
- if ($key1) {
- $bargraph->SetLegend($key1);
- } else {
- $bargraph->SetLegend('None Assigned');
- }
- $bargraphs[] = $bargraph;
- }
- $group = new GroupBarPlot($bargraphs);
- $graph->Add($group);
- } elseif ($data) {
- // Generate a single-axis graph.
- foreach ($data AS $key1 => $var1) {
- $names[] = $key1;
- if (strlen($key1) > 10) {
- $angle = 12;
- }
- if ($data[$key1]) {
- $axis_x[] = $data[$key1];
- } else {
- $axis_x[] = 0;
- }
- }
- $bargraph = new BarPlot($axis_x);
- $graph->Add($bargraph);
- }
- // Labels tend to run together if there's more than just a few of them;
- // when there's more than five, angle the labels to 25 degrees so they
- // won't run into each other unless there's hundreds of them (that's where
- // a table is most appropriate anyway)
- if (count($names) > 5) {
- $angle = 25;
- }
- // If there are more than 10 labels, we're probably running an
- // interval-based statistic with hundreds of labels, so we don't need to
- // show them all. Only show an eighth of the labels.
- if (count($names) > 10) {
- $count = 0;
- $newnames = array();
- $factor = (int)(count($names) / 8);
- foreach ($names AS $namekey => $nameval) {
- $count++;
- if ($count == $factor) {
- $newnames[] = $nameval;
- $count = 0;
- } else {
- $newnames[] = '';
- }
- }
- $names = $newnames;
- }
- // Now set up the graph axis labels and other features.
- $graph->xaxis->SetTickLabels($names);
- $graph->xaxis->SetLabelAngle($angle);
- $graph->title->Set($stat['title']);
- $graph->SetMarginColor("silver");
- $graph->legend->Pos(0.01,0.01);
- // Set up the title for the graph
- $graph->title->SetFont(FF_VERDANA,FS_NORMAL,14);
- $graph->xaxis->SetFont(FF_VERDANA,FS_NORMAL,8);
- $graph->yaxis->SetFont(FF_VERDANA,FS_NORMAL,8);
- $graph->legend->SetFont(FF_VERDANA,FS_NORMAL,8);
- // Show 0 label on Y-axis (default is not to show)
- $graph->yscale->ticks->SupressZeroLabel(false);
- // Finally write the image to the browser.
- $x = rand(1, 1000000);
- $graph->Stroke("graphs/$x.png");
- // If we're generating a PDF, write the image straight to the PDF object.
- if ($do_pdf) {
- $ix = $pdf->GetX();
- $iy = $pdf->GetY();
- $pdf->Image("graphs/$x.png", $ix, $iy, 150);
- $pdf->AddPage();
- return;
- }
- if (isset($stat['title_colour'])) {
- $tc = " color="$stat[title_colour]"";
- } else {
- $tc = NULL;
- }
- if (isset($stat['description_colour'])) {
- $dc = " color="$stat[description_colour]"";
- } else {
- $dc = NULL;
- }
- // Write the image tag to the browser.
- echo "<img src="graphs/$x.png"><br />n";
- echo "<I><FONT SIZE="-1" $dc>$stat[description]</FONT></I>n";
- }
- // ============================================
- // Function make_piechart
- // ============================================
- // Generates a graphical pie chart showing the
- // number of tickets matched per grouping
- // during the reporting run.
- // ============================================
- // Arguments:
- // data First series of data
- // data2 First and second series of data
- // stat Statistic definition from DB
- // style Style definition from DB
- // do_pdf If true, add the resulting
- // graph to the PDF object,
- // otherwise, generate the file
- // and output a link to it.
- // ============================================
- // Returns:
- // Nothing; directly outputs to browser or
- // adds data to the PDF object
- // ============================================
- // Note:
- // For two-series graphs, we generate one
- // pie graph per first-series datum since
- // pie graphs are by nature one-axis-only.
- function make_piechart($data = NULL, $data2 = NULL, $stat, $style = NULL, $do_pdf = 0) {
- global $pdf;
- $html = "<font size="+1"><B>$stat[title]</B></font><br />n<b>$stat[description]</b></font><br />n<br />n";
- include_once("./../includes/graph/jpgraph.php");
- include_once ("./../includes/graph/jpgraph_pie.php");
- include_once ("./../includes/graph/jpgraph_pie3d.php");
- error_reporting(0);
- if (!($data) AND !($data2)) { // If no tickets, don't bother with a graphic
- if ($do_pdf) {
- return make_pdf_table($data, $data2, $stat);
- } else {
- return make_table($data, $data2, $stat);
- }
- }
- $angle = 0;
- if (!$do_pdf) {
- echo $html;
- }
- // Use different sizes for PDF versus online viewing; PDF is higher
- // resolution (when printed, anyway).
- if ($do_pdf) {
- $width = 800;
- $height = 550;
- $minifont = 8;
- } else {
- $width = 450;
- $height = 300;
- $minifont = 6;
- }
- if ($data2) { // Processing for 2-axis graphs
- foreach ($data2 AS $key2 => $var2) {
- $names = array();
- $graph = new PieGraph($width,$height);
- $graph->legend->SetFont(FF_VERDANA,FS_NORMAL,7);
- $axis_x = array();
- foreach ($var2 AS $key1 => $var1) {
- if (!$key1) {
- if (!$data2[$key2][$key1]) {
- // Don't even bother putting this on the legend if it won't show up
- // on the pie graph.
- continue;
- }
- }
- if ($data2[$key2][$key1]) {
- $axis_x[] = $data2[$key2][$key1];
- } else {
- $axis_x[] = 0;
- }
- if (!$key1) {
- $key1 = '(none)';
- }
- $names[] = $key1;
- }
- if (!array_sum($axis_x)) {
- if ($do_pdf) {
- $pdf->Write(8, "No data to show for $key2.");
- }
- continue;
- }
- // Set up the graph's attributes and labels, then plot.
- $piegraph = new PiePlot3D($axis_x);
- $piegraph->title->SetFont(FF_VERDANA,FS_NORMAL,14);
- $piegraph->value->SetFont(FF_VERDANA,FS_NORMAL,$minifont);
- $piegraph->title->Set($key2);
- $piegraph->SetLegends($names);
- $piegraph->SetCenter(0.5,0.5);
- $piegraph->SetSize(0.5);
- $graph->Add($piegraph);
- $graph->legend->Pos(0.01,0.01);
- $graph->SetMarginColor("silver");
- // Finally write the graph to disk.
- $x = rand(1, 1000000);
- $graph->Stroke("graphs/$x.png");
- if ($do_pdf) { // Add to the PDF object.
- $pdf->SetFont('Times', 'B', 20);
- $pdf->Write(8, trim($stat['title'])."n");
- $pdf->SetFontSize(12);
- $pdf->Write(6, trim($stat['description'])."n");
- $ix = $pdf->GetX();
- $iy = $pdf->GetY();
- $pdf->Image("graphs/$x.png", $ix, $iy, 150);
- $pdf->AddPage();
- continue;
- }
- if ($stat['title_colour']) {
- $tc = " color="$stat[title_colour]"";
- }
- if ($stat['description_colour']) {
- $dc = " color="$stat[description_colour]"";
- }
- // Emit an image tag to the browser.
- echo "<img src="graphs/$x.png"><br /><br />n";
- }
- } elseif ($data) { // 1-axis data processing
- if ($do_pdf) {
- $pdf->SetFont('Times', 'B', 20);
- $pdf->Write(8, trim($stat['title'])."n");
- $pdf->SetFontSize(12);
- $pdf->Write(6, trim($stat['description'])."n");
- }
- $graph = new PieGraph($width,$height);
- foreach ($data AS $key1 => $var1) {
- $names[] = $key1;
- if ($data[$key1]) {
- $axis_x[] = $data[$key1];
- } else {
- $axis_x[] = 0;
- }
- }
- // Set up the graph's attributes and labels, then plot.
- $piegraph = new PiePlot3D($axis_x);
- $piegraph->title->SetFont(FF_VERDANA,FS_NORMAL,14);
- $piegraph->value->SetFont(FF_VERDANA,FS_NORMAL,$minifont);
- $piegraph->title->Set($stat['title']);
- $graph->legend->SetFont(FF_VERDANA,FS_NORMAL,8);
- $piegraph->SetLegends($names);
- $piegraph->SetCenter(0.5,0.41);
- $piegraph->SetSize(0.45);
- $graph->Add($piegraph);
-
- $graph->legend->Pos(0.01,0.01);
- $graph->SetMarginColor("silver");
- // Finally write the graph to disk.
- $x = rand(1, 1000000);
- $graph->Stroke("graphs/$x.png");
- if ($do_pdf) { // Add to the PDF object.
- $ix = $pdf->GetX();
- $iy = $pdf->GetY();
- $pdf->Image("graphs/$x.png", $ix, $iy, 150);
- $pdf->AddPage();
- return;
- }
- if (isset($stat['title_colour'])) {
- $tc = " color="$stat[title_colour]"";
- } else {
- $tc = NULL;
- }
- if (isset($stat['description_colour'])) {
- $dc = " color="$stat[description_colour]"";
- } else {
- $dc = NULL;
- }
-
- // Emit image tag to the browser.
- echo "<img src="graphs/$x.png"><br />n";
- echo "<I><FONT SIZE="-1" $dc>$stat[description]</FONT></I>n";
- }
- }
- // ============================================
- // Function make_table
- // ============================================
- // Generates an HTML table showing the
- // number of tickets matched per grouping
- // during the reporting run.
- // ============================================
- // Arguments:
- // data First series of data
- // data2 First and second series of data
- // stat Statistic definition from DB
- // ============================================
- // Returns:
- // The HTML to display.
- // ============================================
- function make_table($data = NULL, $data2 = NULL, $stat) {
- // Set up styles, if any.
- if (isset($stat['title_colour'])) {
- $tc = " color="$stat[title_colour]"";
- } else {
- $tc = NULL;
- }
- if (isset($stat['description_colour'])) {
- $dc = " color="$stat[description_colour]"";
- } else {
- $dc = NULL;
- }
- // Generate the table headings.
- $html = "<font size="+1" $tc><B>$stat[title]</B></font><br />n<font $dc><b>$stat[description]</b></font><br />n<br />n";
- $html .= "<table cellpadding="0" cellspacing="0"><tr><td bgcolor="#000000"><table cellspacing="1" cellpadding="3">";
- if ((!$data) AND (!$data2)) { // If it's an empty data set, return an empty table
- $html .= "<td bgcolor="#FFFF99">No tickets found</td></tr></table></td></tr></table>";
- return $html;
- }
- if ($data2) { // Two-axis processing
- // Draw the heading row (X axis)
- $html .= "<tr><td bgcolor="#FFFF99"> </td>n";
- foreach ($data2 AS $key1 => $var1) {
- $html .= "<td bgcolor="#FFFFCC"><b>$key1</b></td>";
- $cols[$key1] = 1;
- }
- $html .= "</tr>n";
-
- $rowdata = 0;
- // Now figure out what rows we've got
- foreach ($data2 AS $key1 => $var1) {
- if (is_array($var1)) {
- foreach ($var1 AS $key2 => $var2) {
- $rows[$key2] = 1;
- $rowdata = 1;
- }
- }
- }
- // Now render the table
- if (!$rowdata) { // Another way out, just in case there aren't any tickets matched in any row
- $html = "<font size="+1" $tc><B>$stat[title]</B></font><br />n<font $dc><b>$stat[description]</b></font><br />n<br />n";
- $html .= "<table cellpadding="0" cellspacing="0"><tr><td bgcolor="#000000"><table cellspacing="1" cellpadding="3">";
- $html .= "<td bgcolor="#FFFF99">No tickets found</td></tr></table></td></tr></table>";
- return $html;
- }
- // Generate each row of the table.
- foreach ($rows AS $key1 => $val1) {
- $html .= "<tr>";
- if (!$key1) {
- $key1 = "<I>None Assigned</I>";
- }
- $html .= "<td bgcolor="#FFFFCC" align="right"><B>$key1</B></td>n";
- foreach ($cols AS $key2 => $val2) {
- if ($data2[$key2][$key1]) {
- $html .= "<td bgcolor="#FFFFFF">" . $data2[$key2][$key1] . "</td>n";
- } else {
- $html .= "<td bgcolor="#FFFFFF"><font color="gray">0</font></td>n";
- }
- $colnum++;
- }
- $html .= "</tr>";
- }
- $html .= "</table></td></tr></table>";
- } else {
- // 1-axis processing.
- foreach ($data AS $key => $var) {
- if (!$key) {
- $key = "<I>None Assigned</I>";
- }
- $html .= "<tr><td bgcolor="#FFFFCC"><b>$key</b></td><td bgcolor="#FFFFFF">$var tickets</td></tr>";
- }
- $html .= "</table></td></tr></table>";
- }
- return $html;
- }
- // ============================================
- // Function make_csv
- // ============================================
- // Generates a CSV file containing the
- // number of tickets matched per grouping
- // during the reporting run.
- // ============================================
- // Arguments:
- // data First series of data
- // data2 First and second series of data
- // stat Statistic definition from DB
- // ============================================
- // Returns:
- // The CSV data.
- // ============================================
- function make_csv($data = NULL, $data2 = NULL, $stat) {
- if ((!$data) AND (!$data2)) { // If it's an empty data set, return an empty table
- return "No tickets found.";
- }
- if ($data2) {
- $headers = array('"Labels"');
- // Draw the heading row (X axis)
- foreach ($data2 AS $key1 => $var1) {
- $headers[] = ""$key1"";
- $cols[$key1] = 1;
- }
- $ret = join(',',$headers) . "nn";
- // Now figure out what rows we've got
- foreach ($data2 AS $key1 => $var1) {
- foreach ($var1 AS $key2 => $var2) {
- $rows[$key2] = 1;
- }
- }
-
- // Now produce the records
- foreach ($rows AS $key1 => $val1) {
- $row = array();
- $row[] = ""$key1"";
- foreach ($cols AS $key2 => $val2) {
- if ($data2[$key2][$key1]) {
- $row[] = '"' . $data2[$key2][$key1] . '"';
- } else {
- $row[] = '"0"';
- }
- $colnum++;
- }
- $ret .= join(',',$row) . "n";
- }
- } else {
- $headers = array();
- $row = array();
- foreach ($data AS $key => $var) {
- $headers[] = ""$key"";
- $row[] = ""$var"";
- }
- $ret .= join(',',$headers);
- $ret .= "nn";
- $ret .= join(',',$row);
- }
- return $ret;
- }
- // ============================================
- // Function make_pdf_table
- // ============================================
- // Generates a PDF table showing the
- // number of tickets matched per grouping
- // during the reporting run.
- // ============================================
- // Arguments:
- // data First series of data
- // data2 First and second series of data
- // stat Statistic definition from DB
- // ============================================
- // Returns:
- // Nothing; directly adds to the PDF
- // object.
- // ============================================
- function make_pdf_table($data = NULL, $data2 = NULL, $stat) {
- global $pdf;
- $pdf->SetFont('Times', 'B', 20);
- $pdf->Write(8, trim($stat['title'])."n");
- $pdf->SetFontSize(12);
- $pdf->Write(6, trim($stat['description'])."n");
- if ((!$data) AND (!$data2)) { // If it's an empty data set, return an empty table
- $pdf->SetFont('Arial', 'B', 10);
- $width = $pdf->GetStringWidth('No tickets found');
- $pdf->SetFillColor(255, 255, 200);
- $pdf->Cell($width+2, 5, 'No tickets found', 1, 1, 'C', 1);
- return;
- }
- if ($data2) { // 2-axis processing.
- $table = array();
- // Load the heading row (X axis) array
- $pdf->SetFont('Arial', 'B', 10);
- $col[] = '';
- $widths[] = $pdf->GetStringWidth('');
- foreach ($data2 AS $key1 => $var1) {
- $col[] = $key1;
- $widths[] = $pdf->GetStringWidth($key1);
- $table[0] = $col;
- }
- // Load the heading column (Y axis) helper array
- foreach ($data2 AS $key1 => $var1) {
- if (is_array($var1)) {
- foreach ($var1 AS $key2 => $var2) {
- $rows[$key2] = 1;
- }
- }
- }
- if (!is_array($rows)) { // Another way out, just in case there aren't any tickets matched in any row
- $pdf->SetFont('Arial', 'B', 10);
- $width = $pdf->GetStringWidth('No tickets found');
- $pdf->SetFillColor(255, 255, 200);
- $pdf->Cell($width+2, 5, 'No tickets found', 1, 1, 'C', 1);
- return $html;
- }
-
- // Load the table array
- foreach ($rows AS $key1 => $val1) {
- $colnum = 0;
- unset($row);
- $width = $pdf->GetStringWidth($key1);
- if ($width > $widths[0]) {
- $widths[0] = $width;
- }
- $row[] = $key1;
- array_shift($col);
- foreach ($col AS $key2 => $val2) {
- if ($data2[$val2][$key1]) {
- $val = $data2[$val2][$key1];
- } else {
- $val = 'None';
- }
- if ($colnum) { // regular cell
- $pdf->SetFont('Arial', '', 10);
- } else { // heading column
- $pdf->SetFont('Arial', 'B', 10);
- }
- $width = $pdf->GetStringWidth($val);
- if ($width > $widths[$colnum]) {
- $widths[$colnum] = $width;
- }
- $row[] = $val;
- }
- array_unshift($col, '');
- $table[] = $row;
- }
- // Render the table
-
- $maxwidth = 195;
- if (array_sum($widths) > $maxwidth) {
-
- // If the total width of all columns is greater than the page's
- // width, we have to truncate.
- $maxcol = 0;
- $totwid = 0;
- foreach ($widths AS $key => $val) {
- $totwid = $totwid + $val;
- if ($totwid <= $maxwidth) {
- $maxcol++;
- } else {
- $maxwidth = 0;
- }
- }
- }
- // Render the heading row
- $headings = array_shift($table);
- $pdf->SetFont('Arial', 'B', 10);
- $pdf->SetFillColor(255,255,200);
- $colnum = 0;
- foreach ($headings as $key => $val) {
- if ((($colnum+1) < $maxcol) OR (!$maxcol)) {
- $pdf->Cell($widths[$colnum]+2, 4.5, $val, 1, 0, 'C', 1);
- $colnum++;
- }
- }
- $pdf->Ln();
- // Render the remaining rows
- $pdf->SetFillColor(220,220,220);
- $fill = 0;
- foreach ($table as $key => $val) {
- $cell = array_shift($val);
- $pdf->SetFont('Arial', 'B', 10);
- $pdf->Cell($widths[0]+2, 4.5, $cell, 1, 0, 'R', $fill);
- $pdf->SetFont('Arial', '', 10);
- $colnum = 1;
- foreach ($val as $key => $val2) {
- if ((($colnum+1) < $maxcol) OR (!$maxcol)) {
- if ($val2) {
- $pdf->Cell($widths[$colnum]+2, 4.5, $val2, 1, 0, 'C', $fill);
- } else {
- $pdf->SetFont('Arial', 'I', 10);
- $pdf->Cell($widths[$colnum]+2, 4.5, 'None', 1, 0, 'C', $fill);
- $pdf->SetFont('Arial', '', 10);
- }
- $colnum++;
- }
- }
- $pdf->Ln();
- $fill=!$fill;
- }
- } else { // 1-axis processing.
- // Calculate widths
- $widths = array();
- foreach ($data AS $key => $val) {
- if (!$key) {
- $key = "None";
- }
- $pdf->SetFont('Arial', 'B', 10);
- $width = $pdf->GetStringWidth($key);
- if ($width > $widths[0]) {
- $widths[0] = $width;
- }
- $pdf->SetFont('Arial', '', 10);
- $width = $pdf->GetStringWidth($val);
- if ($width > $widths[1]) {
- $widths[1] = $width;
- }
- }
-
- // Render table
- $pdf->SetFillColor(255,255,200);
- foreach ($data AS $key => $val) {
- $pdf->Cell($widths[0]+2, 4.5, $key, 1, 0, 'R', 1);
- $pdf->Cell($widths[1]+2, 4.5, $val, 1, 1, 'L', 1);
- }
- }
- $pdf->Ln();
- return;
- }
- // ============================================
- // Function make_pdf_appendix
- // ============================================
- // Generates a PDF table containing a list of
- // all tickets matched during the reporting run
- // ============================================
- // Arguments:
- // appendix List of ticket numbers in
- // the appendix
- // appendix_fields
- // List of fields to show in
- // the appendix
- // change Column or row name mappings
- // to use.
- // ============================================
- // Returns:
- // Nothing; adds to the PDF object
- // ============================================
- function make_pdf_appendix($appendix, $appendix_fields = NULL, $change = array()) {
- global $db, $pdf, $tfields, $tfields_names;
- $pdf->SetFont('Arial', 'B', 10);
- $fields = explode(',', $appendix_fields);
- $total = count($fields);
- if ($appendix_fields AND count($appendix)) {
- $appendix = array2sql($appendix);
- foreach ($fields as $key => $var) {
- if ($var == 'user') {
- $fields[$key] = 'userid';
- }
- }
- $appendix_fields = join(',', $fields);
- $db->query(
- "SELECT id, $appendix_fields
- FROM ticket
- WHERE id IN $appendix
- ");
-
- // Run through the result set.
- if ($db->num_rows()) {
- $colnum = 0;
- $total++;
- $tickets = $db->num_rows();
- $row = array();
- foreach($fields as $key => $val) {
- switch ($val) {
- case 'subject': $label = 'Subject'; break;
- case 'priority' : $label = 'Priority'; break;
- case 'tech' : $label = 'Technician'; break;
- case 'is_open' : $label = 'Open/Closed'; break;
- case 'awaiting_tech' : $label = 'Awaiting...'; break;
- case 'userid' : $label = 'User'; break;
- case 'category' : $label = 'Category'; break;
- case 'id' : next; break;
- default: $label = $val;
- }
- if (stristr($val, 'custom')) {
- $label = $tfields_names[$val];
- }
- $row[] = $label;
- $widths[$colnum] = $pdf->GetStringWidth($label);
- $colnum++;
- }
- $table[] = $row;
- $row = array();
- $pdf->SetFont('Arial', '', 10);
- while ($result = $db->row_array()) {
- $row = array();
- $colnum = 0;
- foreach($fields as $key => $val) {
- switch ($val) {
- case 'id':
- next;
- break;
- case 'subject':
- if ($result[$val]) {
- $result[$val] = $result[$val];
- } else {
- $result[$val] = "None";
- }
- break;
- case 'category': $result[$val] = $change['category'][$result[$val]]; break;
- case 'priority': $result[$val] = $change['priority'][$result[$val]]; break;
- case 'tech':
- if ($result[$val]) {
- $result[$val] = $change['tech'][$result[$val]];
- } else {
- $result[$val] = "None";
- }
- break;
- case 'userid':
- if ($result[$val]) {
- $result[$val] = $change['userid'][$result[$val]];
- } else {
- $result[$val] = "<I>None</I>";
- }
- break;
- case 'is_open': $result[$val] = $change['is_open'][$result[$val]]; break;
- case 'awaiting_tech': $result[$val] = $change['awaiting_tech'][$result[$val]]; break;
- }
- if (stristr($val, 'custom')) {
- $items = explode('|||', $result[$val]);
- $tmptitle = array();
- foreach ($items AS $ikey => $ival) {
- if (is_array($tfields[$val])) {
- foreach ($tfields[$val] AS $tkey => $tval) {
- if ($tval[0] == $ival) {
- $tmptitle[] = $tval[2];
- }
- }
- }
- }
- $result[$val] = join(', ', $tmptitle);
- }
- $row[] = $result[$val];
- $width = $pdf->GetStringWidth($result[$val]);
- if ($width > $widths[$colnum]) {
- $widths[$colnum] = $width;
- }
- $colnum++;
- }
- $table[] = $row;
- }
- // "Letter" size paper is 215.9 mm wide, defaults to 10mm margins.
- $maxwidth = 195;
- if (array_sum($widths) > $maxwidth) {
-
- // If the total width of all columns is greater than the page's
- // width, we have to truncate.
- $maxcol = 0;
- $totwid = 0;
- foreach ($widths AS $key => $val) {
- $totwid = $totwid + $val;
- if ($totwid <= $maxwidth) {
- $maxcol++;
- } else {
- $maxwidth = 0;
- }
- }
- }
- $pdf->SetFont('Arial', 'B', 10);
- $colnum = 0;
- $row = array_shift($table);
- foreach ($row as $key => $val) {
- if ((($colnum+1) < $maxcol) OR (!$maxcol)) {
- $pdf->Cell($widths[$colnum]+2, 4.5, $val, 1, 0, 'C', 1);
- }
- $colnum++;
- }
- $pdf->Ln();
- $pdf->SetFillColor(220,220,220);
- $fill = 0;
- $pdf->SetFont('Arial', '', 10);
- foreach ($table as $key => $val) {
- $colnum = 0;
- foreach ($val as $key2 => $val2) {
- if ((($colnum+1) < $maxcol) OR (!$maxcol)) {
- if ($val2) {
- $pdf->Cell($widths[$colnum]+2, 4.5, $val2, 1, 0, 'C', $fill);
- } else {
- $pdf->SetFont('Arial', 'I', 10);
- $pdf->Cell($widths[$colnum]+2, 4.5, 'None', 1, 0, 'C', $fill);
- $pdf->SetFont('Arial', '', 10);
- }
- }
- $colnum++;
- }
- $pdf->Ln();
- $fill=!$fill;
- }
- $pdf->SetFont('Arial', 'I', 10);
- $width = $pdf->GetStringWidth("$tickets tickets found");
- $pdf->Cell($width, 5, "$tickets tickets found", 0, 1, 'L');
- $pdf->Ln();
- $pdf->Ln();
- } else {
- $pdf->SetFont('Arial', 'B', 10);
- $width = $pdf->GetStringWidth('No tickets found');
- $pdf->SetFillColor(255, 255, 200);
- $pdf->Cell($width+2, 5, 'No tickets found', 1, 1, 'C', 1);
- }
- }
- return;
- }