function request($frm)
{
    if (isset($_POST["btn_back"])) {
        return enter($frm);
    }
    if ($frm->validate("request")) {
        return confirm($frm);
    }
    $newkey = genkey();
    if (isset($_REQUEST["suppid"])) {
        $suppid = $_REQUEST["suppid"];
        $custid = "0";
    } else {
        $custid = $_REQUEST["custid"];
        $suppid = "0";
    }
    $cols = grp(m("introtime", raw("CURRENT_TIMESTAMP")), m("introip", "0.0.0.0"), m("email", $_REQUEST["email"]), m("custid", $custid), m("suppid", $suppid), m("key", dbrow("0.0.0.0/0", "", $newkey)), m("userid", USER_ID));
    $upd = new dbUpdate("keys", "trh", $cols);
    $upd->run(DB_INSERT);
    if ($upd->affected() > 0) {
        if (isset($_REQUEST["suppid"])) {
            if (($r = send_trhmsg("supp", $_REQUEST["suppid"], $_REQUEST["email"], "reqkey", $newkey)) === true) {
                $OUT = "Sent request for communication to supplier. On response you will be notified.";
            } else {
                $OUT = "Error sending request for communication: {$r}";
            }
        } else {
            if (($r = send_trhmsg("cust", $_REQUEST["custid"], $_REQUEST["email"], "reqkey", $newkey)) === true) {
                $OUT = "Sent request for communication to customer. On response you will be notified.";
            } else {
                $OUT = "Error sending request for communication: {$r}";
            }
        }
    } else {
        $OUT = "Error sending request for communication: Error updating database.";
    }
    return $OUT;
}
function deny()
{
    extract($_REQUEST);
    /* order info */
    $qry = new dbSelect("recvpurch", "trh", grp(m("where", wgrp(m("id", $id)))));
    $qry->run();
    if ($qry->num_rows() <= 0) {
        invalid_use("<li class='err'>Invalid Sales Order Id (TRHAPP).</li>");
    }
    $soi = $qry->fetch_array();
    /* set approve status */
    $cols = grp(m("approved", "d"));
    $upd = new dbUpdate("recvpurch", "trh", $cols, "id='{$id}'");
    $upd->run(DB_UPDATE);
    /* get customer trh config */
    $keyinfo = trhKeyCust($soi["custid"]);
    $email = $keyinfo["email"];
    /* send trh response message */
    $purinfo = array("purid" => $soi["purid"], "status" => "d");
    $ret = send_trhmsg("cust", $soi["custid"], $email, "rsppur", $purinfo);
    $OUT = listorders("<li class='err'>Successfully denied sales order.</li>");
    return $OUT;
}
function deny(&$frm)
{
    /* @var $frm cForm */
    if (($e = $frm->validateValue($_GET["id"], "num", 1, 10)) !== false) {
        return view($frm, "<li class='err'>Error reading key: {$e}.</li>");
    }
    $qry = new dbSelect("keys", "trh", grp(m("cols", "*, (key).*"), m("where", "id='{$_GET['id']}'")));
    $qry->run();
    if ($qry->num_rows() <= 0) {
        return view($frm, "<li class='err'>Invalid key selected.</li>");
    }
    $ki = $qry->fetch_array();
    if ($ki["custid"] == "-1") {
        $fromwho = "cust";
    } else {
        if ($ki["suppid"] == "-1") {
            $fromwho = "supp";
        } else {
            return view($frm, "<li class='err'>Key already approved.</li>");
        }
    }
    if (send_trhmsg($fromwho, "-1", $ki["email"], "rspkey", str_pad("denied", 32, 'A', STR_PAD_RIGHT))) {
        $upd = new dbDelete("keys", "trh", "id='{$_GET['id']}'");
        $upd->run();
        return view($frm, "<li class='err'>Successfully denied request.</li>");
    } else {
        /* set the id back to -1, because there was an error */
        $cols = grp(m("{$fromwho}id", "-1"));
        $upd = new dbUpdate("keys", "trh", $cols, "id='{$_POST['id']}'");
        $upd->run(DB_UPDATE);
        return view($frm, "<li class='err'>Error denying request.</li>");
    }
}
function send()
{
    if (!isset($_REQUEST["id"])) {
        invalid_use();
    }
    /* fetch purchase information */
    $purchase = new dbSelect("purchases", "cubit", grp(m("where", "purid='{$_REQUEST['id']}'")));
    $purchase->run();
    if ($purchase->num_rows() <= 0) {
        invalid_use("Invalid purchase.");
    }
    $purdata = $purchase->fetch_array();
    /* fetch the transheks email address of this supplier */
    $qry = new dbSelect("keys", "trh", grp(m("cols", "email, (key).send_key AS send_key"), m("where", "suppid='{$purdata['supid']}'")));
    $qry->run();
    if ($qry->num_rows() <= 0) {
        invalid_use("This supplier isn't configured for Transheks transactioning.");
    }
    $keyinfo = trhKeySupp($purdata["supid"]);
    $email = $keyinfo["email"];
    $send_key = $keyinfo["send_key"];
    if (empty($send_key)) {
        invalid_use("This supplier hasn't confirmed the Transactioning request sent.");
    }
    /* fetch purchase item information */
    $puritems = array();
    $purchase->setTable("pur_items", "cubit");
    $purchase->run();
    if ($purchase->num_rows() <= 0) {
        invalid_use("Invalid purchase, purchase has no items.");
    }
    while ($row = $purchase->fetch_array()) {
        $puritems[] = $row;
    }
    /* build xml data */
    $XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    $attrs = array();
    foreach ($purdata as $k => $v) {
        $attrs[] = "{$k}=\"{$v}\"";
    }
    $XML .= "<purdata " . implode(" ", $attrs) . ">\n";
    foreach ($puritems as $puritem_data) {
        $attrs = array();
        foreach ($puritem_data as $k => $v) {
            $attrs[] = "{$k}=\"{$v}\"";
        }
        $XML .= "\t<puritem " . implode(" ", $attrs) . " />\n";
    }
    $XML .= "</purdata>\n";
    $OUT = "<h3>Send Supplier Order</h3>";
    if (($ret = send_trhmsg("supp", $purdata["supid"], $email, "reqpur", $XML)) !== true) {
        if ($ret === false) {
            $OUT .= "<li class='err'>There was an unknown error sending order to supplier.</li>";
        } else {
            $OUT .= "<li class='err'>Error sending order to supplier: {$ret}.</li>";
        }
    } else {
        $OUT .= "Successfully sent order to supplier.";
    }
    return $OUT;
}
/**
 * handles a new request
 *
 * @param string $key
 * @param clsMailMsg $oMSG
 * @param array $config
 * @return bool
 */
function request_new($key, $oMSG, $config)
{
    if (($stds = msg_std($oMSG)) === false) {
        return false;
    }
    list($compname, $ipaddr, $bustel, $fromwho, $email) = $stds;
    /* locate customer/supplier */
    if ($fromwho == "supp") {
        $suppid = locateSupplier($compname);
        $custid = 0;
    } else {
        // $fromwho == "cust"
        $custid = locateCustomer($compname);
        $suppid = 0;
    }
    print "name: {$compname}\n";
    print "ipaddr: {$ipaddr}\n";
    print "bustel: {$bustel}\n";
    print "fromwho: {$fromwho}\n";
    print "custid: {$custid}\n";
    print "suppid: {$suppid}\n";
    /* check if company name and key is in list */
    $qry = new dbSelect("keys", "trh", grp(m("cols", "1"), m("where", "{$fromwho}id='" . ${"{$fromwho}id"} . "' AND (key).send_key='{$key}'")));
    $qry->run();
    if ($qry->num_rows() > 0) {
        print "---> KEY EXISTS, ignoring\n";
        return false;
    }
    $qry->free();
    print "from email: {$email}\n";
    /* generate a key for receiving for client */
    $newkey = genkey();
    /* add new key to system */
    $cols = grp(m("userid", $config["MANAGEUSER"]), m("introtime", raw("CURRENT_TIMESTAMP")), m("introip", $ipaddr), m("email", $email), m("compname", $compname), m("bustel", $bustel), m("custid", $custid), m("suppid", $suppid), m("key", dbrow("0.0.0.0/0", $key, $newkey)));
    $upd = new dbUpdate("keys", "trh", $cols);
    $upd->run(DB_INSERT);
    $upd->free();
    if ($custid == -1 && $suppid == -1) {
        $desc = $fromwho == "supp" ? "supplier" : "customer";
        $userinfo = qryUsers($config["MANAGEUSER"]);
        msgSend($userinfo["username"], "Unknown {$desc} requested Transheks communication. \n\t\t\tClick <a target='mainframe' href=\"../transheks/commapprove.php\">here</a> to view.");
        return false;
    } else {
        /* send response */
        return send_trhmsg($fromwho, ${"{$fromwho}id"}, $email, "rspkey", "{$newkey}", $config);
    }
}