Search code examples
phphtmlosticket

How can I use a HTML form to replace presets in a PHP script to submit a ticket to osTicket?


At the moment I am trying embed an osTicket form into my website so that users can submit a ticket that is integrated into my website.

I found a PHP script online and with the help of users from another thread, I have got it working so that when I run the script on the server it opens a ticket with all the information that was written in the PHP script. I want to be able to have a HTML page which submits the information from a form on the HTML page to replace the preset information in the PHP script.

My first thoughts to complete this was to simply copy the relevant files from the default 'submit ticket' page that came as part of osTicket. I viewed the source in my web browser and saw different code than if I downloaded the file and viewed it in a text editor.

So the PHP script that I am using is:

<?php

# //Configuration: Enter the url and key. 
# url => URL to api/tickets.json # e.g http://yourdomain.com/s#upport/api/tickets.json
# key => API's Key (see admin panel o#n how to generate a key)
#


$config = array(
'url'=>'support.sinergycraft.net/tickets/api/tickets.json',
'key'=>'C2621CFA3E5F94B5396003218952DA0D'
);

#pre-checks
function_exists('curl_version') or die('CURL support required');

#set timeout
set_time_limit(30);

#Sample data for the ticket
# See https://github.com/osTicket/osTicket-1.7/blob/develop/setup/doc/api/tickets.md for full list of variables and options that you can pass.
$data = array("alert" => "true",
       "autorespond" => "true",
       "source" => "API",
       "name" => "Angry User",
       "email" => "api@osticket.com",
       "subject" => "Testing API 3",
       "message" => "MESSAGE HERE"
);
#Convert the above array into json to POST to the API with curl below.
$data_string = json_encode($data);

#curl post
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $config['url']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_USERAGENT, 'osTicket API Client v1.7');
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Expect:', 'X-API-Key: '.$config['key']));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result=curl_exec($ch);
curl_close($ch);

if(preg_match('/HTTP\/.* ([0-9]+) .*/', $result, $status) && $status[1] == 200)
exit(0);

echo $result;
exit(1);
?>

If I link a form to this like I have done in this code:

<form id="ticketForm" method="post" action="new_ticket.php" enctype="multipart/form-data">

The PHP script is called new_ticket.php. This opens a ticket with the prefilled options in the PHP but not what the uswer enters in the form.

Next I thought that I should try using the file that I downloaded off the server and not the code that I got from view source.

The file that is opened in the browser when you click the link to make a new ticket is called open.php and its content is bellow:

<?php

    open.php


require('client.inc.php');
define('SOURCE','Web'); //Ticket source.
$ticket = null;
$errors=array();
if ($_POST) {
    $vars = $_POST;
    $vars['deptId']=$vars['emailId']=0; //Just Making sure we don't accept crap...only topicId is expected.
    if ($thisclient) {
        $vars['uid']=$thisclient->getId();
    } elseif($cfg->isCaptchaEnabled()) {
        if(!$_POST['captcha'])
            $errors['captcha']=__('Enter text shown on the image');
        elseif(strcmp($_SESSION['captcha'], md5(strtoupper($_POST['captcha']))))
            $errors['captcha']=__('Invalid - try again!');
    }

    $tform = TicketForm::objects()->one()->getForm($vars);
    $messageField = $tform->getField('message');
    $attachments = $messageField->getWidget()->getAttachments();
    if (!$errors && $messageField->isAttachmentsEnabled())
        $vars['cannedattachments'] = $attachments->getClean();

    // Drop the draft.. If there are validation errors, the content
    // submitted will be displayed back to the user
    Draft::deleteForNamespace('ticket.client.'.substr(session_id(), -12));
    //Ticket::create...checks for errors..
    if(($ticket=Ticket::create($vars, $errors, SOURCE))){
        $msg=__('Support ticket request created');
        // Drop session-backed form data
        unset($_SESSION[':form-data']);
        //Logged in...simply view the newly created ticket.
        if($thisclient && $thisclient->isValid()) {
            session_write_close();
            session_regenerate_id();
            @header('Location: tickets.php?id='.$ticket->getId());
        }
    }else{
        $errors['err']=$errors['err']?$errors['err']:__('Unable to create a ticket. Please correct errors below and try again!');
    }
}

//page
$nav->setActiveNav('new');
if ($cfg->isClientLoginRequired()) {
    if (!$thisclient) {
        require_once 'secure.inc.php';
    }
    elseif ($thisclient->isGuest()) {
        require_once 'login.php';
        exit();
    }
}

require(CLIENTINC_DIR.'header.inc.php');
if($ticket
        && (
            (($topic = $ticket->getTopic()) && ($page = $topic->getPage()))
            || ($page = $cfg->getThankYouPage())
        )) {
    // Thank the user and promise speedy resolution!
    echo Format::viewableImages($ticket->replaceVars($page->getBody()));
}
else {
    require(CLIENTINC_DIR.'open.inc.php');
}
require(CLIENTINC_DIR.'footer.inc.php');
?>

I tried substituting this as the action in my HTML code instead of new_ticket.php but I still had no luck.

So basically what I am looking to do is be able to submit informaiton in the HTML form and for it to substitute the pre-written text in the PHP script for what the user entered.

Finally, bellow I have provided what the open.php file shows in view shource when I open it in the web browser. This is the file which I coppied the form off for my HTML document which I was hoping would submit the data to the PHP script.

<!DOCTYPE html>
<html >
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>SinergyCraft.net Support</title>
    <meta name="description" content="customer support platform">
    <meta name="keywords" content="osTicket, Customer support system, support ticket system">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" href="/tickets/css/osticket.css?ecb4f89" media="screen">
    <link rel="stylesheet" href="/tickets/assets/default/css/theme.css?ecb4f89" media="screen">
    <link rel="stylesheet" href="/tickets/assets/default/css/print.css?ecb4f89" media="print">
    <link rel="stylesheet" href="/tickets/scp/css/typeahead.css"
         media="screen" />
    <link type="text/css" href="/tickets/css/ui-lightness/jquery-ui-1.10.3.custom.min.css"
        rel="stylesheet" media="screen" />
    <link rel="stylesheet" href="/tickets/css/thread.css?ecb4f89" media="screen">
    <link rel="stylesheet" href="/tickets/css/redactor.css?ecb4f89" media="screen">
    <link type="text/css" rel="stylesheet" href="/tickets/css/font-awesome.min.css?ecb4f89">
    <link type="text/css" rel="stylesheet" href="/tickets/css/flags.css?ecb4f89">
    <link type="text/css" rel="stylesheet" href="/tickets/css/rtl.css?ecb4f89"/>
    <script type="text/javascript" src="/tickets/js/jquery-1.8.3.min.js?ecb4f89"></script>
    <script type="text/javascript" src="/tickets/js/jquery-ui-1.10.3.custom.min.js?ecb4f89"></script>
    <script src="/tickets/js/osticket.js?ecb4f89"></script>
    <script type="text/javascript" src="/tickets/js/filedrop.field.js?ecb4f89"></script>
    <script type="text/javascript" src="/tickets/js/jquery.multiselect.min.js?ecb4f89"></script>
    <script src="/tickets/scp/js/bootstrap-typeahead.js?ecb4f89"></script>
    <script type="text/javascript" src="/tickets/js/redactor.min.js?ecb4f89"></script>
    <script type="text/javascript" src="/tickets/js/redactor-osticket.js?ecb4f89"></script>
    <script type="text/javascript" src="/tickets/js/redactor-fonts.js?ecb4f89"></script>

    <meta name="csrf_token" content="4f5df4c017ca804903b7b513210231cd8fd6d714" />
</head>
<body>
    <div id="container">
        <div id="header">
            <a class="pull-left" id="logo" href="/tickets/index.php"
            title="Support Center"><img src="/tickets/logo.php" border=0 alt="SinergyCraft.net Support"
                style="height: 5em"></a>
            <div class="pull-right flush-right">
            <p>
                         </p>
            <p>
            </p>
            </div>
        </div>
        <div class="clear"></div>
                <ul id="nav" class="flush-left">
            <li><a class=" home" href="/tickets/index.php">Support Center Home</a></li>
<li><a class="active new" href="/tickets/open.php">Open a New Ticket</a></li>
<li><a class=" status" href="/tickets/view.php">Check Ticket Status</a></li>
        </ul>
                <div id="content">

         <h1>Open a New Ticket</h1>
<p>Please fill in the form below to open a new ticket.</p>
<form id="ticketForm" method="post" action="open.php" enctype="multipart/form-data">
  <input type="hidden" name="__CSRFToken__" value="4f5df4c017ca804903b7b513210231cd8fd6d714" />  <input type="hidden" name="a" value="open">
  <table width="800" cellpadding="1" cellspacing="0" border="0">
    <tbody>
    <tr>
        <td class="required">Help Topic:</td>
        <td>
            <select id="topicId" name="topicId" onchange="javascript:
                    var data = $(':input[name]', '#dynamic-form').serialize();
                    $.ajax(
                      'ajax.php/form/help-topic/' + this.value,
                      {
                        data: data,
                        dataType: 'json',
                        success: function(json) {
                          $('#dynamic-form').empty().append(json.html);
                          $(document.head).append(json.media);
                        }
                      });">
                <option value="" selected="selected">&mdash; Select a Help Topic &mdash;</option>
                <option value="12" >Ban Site/Server</option><option value="1" >General Inquiry</option><option value="2" >Recruitment</option><option value="10" >Report a Problem</option><option value="11" >White List Me</option>            </select>
            <font class="error">*&nbsp;</font>
        </td>
    </tr>
    <tr><td colspan="2"><hr />
    <div class="form-header" style="margin-bottom:0.5em">
        <h3>Contact Information</h3>
    <em></em>
    </div>
    </td></tr>
            <tr>
                            <td><label for="b695be87472f918f" class="required">
                Email Address:</label></td><td>
                    <span style="display:inline-block">
        <input type="text"
            id="_b695be87472f918f"
            size="40" maxlength="64" placeholder=""            name="b695be87472f918f"
            value=""/>
        </span>
                                    <font class="error">*</font>
                        </td>
        </tr>
                <tr>
                            <td><label for="e6ac2c5b0fbeba20" class="required">
                Full Name:</label></td><td>
                    <span style="display:inline-block">
        <input type="text"
            id="_e6ac2c5b0fbeba20"
            size="40" maxlength="64" placeholder=""            name="e6ac2c5b0fbeba20"
            value=""/>
        </span>
                                    <font class="error">*</font>
                        </td>
        </tr>
            </tbody>
    <tbody id="dynamic-form">
            </tbody>
    <tbody>    <tr><td colspan="2"><hr />
    <div class="form-header" style="margin-bottom:0.5em">
            <link rel="stylesheet" type="text/css" href="/tickets/css/jquery.multiselect.css"/>    <h3>Ticket Details</h3>
    <em>Please Describe Your Issue</em>
    </div>
    </td></tr>
            <tr>
                            <td><label for="48b638e54863b978" class="required">
                Issue Summary:</label></td><td>
                    <span style="display:inline-block">
        <input type="text"
            id="_48b638e54863b978"
            size="40" maxlength="50" placeholder=""            name="48b638e54863b978"
            value=""/>
        </span>
                                    <font class="error">*</font>
                        </td>
        </tr>
                <tr>
                            <td colspan="2">
            <div style="margin-bottom:0.5em;margin-top:0.5em"><strong>Issue Details</strong>:</div>
        <textarea style="width:100%;" name="message"
            placeholder="Details on the reason(s) for opening the ticket."
                            data-draft-namespace="ticket.client"
                data-draft-object-id="ea999hv0kkq1"
                        class="richtext draft draft-delete ifhtml"
            cols="21" rows="8" style="width:80%;"></textarea>
    <div id="b6d716e83936ea511681b5" class="filedrop"><div class="files"></div>
            <div class="dropzone"><i class="icon-upload"></i>
            Drop files here or <a href="#" class="manual"> choose them </a>        <input type="file" multiple="multiple"
            id="file-b6d716e83936ea511681b5" style="display:none;"
            accept=""/>
        </div></div>
        <script type="text/javascript">
        $(function(){$('#b6d716e83936ea511681b5 .dropzone').filedropbox({
          url: 'ajax.php/form/upload/attach',
          link: $('#b6d716e83936ea511681b5').find('a.manual'),
          paramname: 'upload[]',
          fallback_id: 'file-b6d716e83936ea511681b5',
          allowedfileextensions: [],
          allowedfiletypes: [],
          maxfiles: 20,
          maxfilesize: 32,
          name: 'attach:21[]',
          files: []        });});
        </script>
        <link rel="stylesheet" type="text/css" href="/tickets/css/filedrop.css"/>                            <font class="error">*</font>
                        </td>
        </tr>
            </tbody>
    <tbody>
        <tr><td colspan=2>&nbsp;</td></tr>
    </tbody>
  </table>
<hr/>
  <p style="text-align:center;">
        <input type="submit" value="Create Ticket">
        <input type="reset" name="reset" value="Reset">
        <input type="button" name="cancel" value="Cancel" onclick="javascript:
            $('.richtext').each(function() {
                var redactor = $(this).data('redactor');
                if (redactor && redactor.opts.draftDelete)
                    redactor.deleteDraft();
            });
            window.location.href='index.php';">
  </p>
</form>
        </div>
    </div>
    <div id="footer">
        <p>Copyright &copy; 2015 SinergyCraft.net Support - All rights reserved.</p>
        <a id="poweredBy" href="http://osticket.com" target="_blank">Helpdesk software - powered by osTicket</a>
    </div>
<div id="overlay"></div>
<div id="loading">
    <h4>Please Wait!</h4>
    <p>Please wait... it will take a second!</p>
</div>
</body>
</html>

Thanks


Solution

  • I may be missing something in your question, but I think you just need to put more into your form and then extract the variables in your PHP:

    HTML:

    <form id="ticketForm" method="post" action="new_ticket.php" >
    <input type="text" name="name" />
    <input type="text" name="email" />
    <input type="text" name="subject" />
    <textarea name="message"></textarea>
    <input type="submit" name="submit" value="send" />
    

    (I think I can see some of these input fields in your page source dump, but the name fields appear to be generated e.g. name="b695be87472f918f" whichever you use the html name='name' and the $_POST['name'] need to match).

    Then in your PHP code:

    $data = array("alert" => "true",
       "autorespond" => "true",
       "source" => "API",
       "name" => $_POST['name'],
       "email" => $_POST['email'],
       "subject" => $_POST['subject'],
       "message" => $_POST['message']
     );
    

    Probably wise to carry out some validation on the values before actually using them.