/**
  * does the actual validation for variables
  *
  * @param string $ifldname
  * @param string $fldopts
  * @return bool
  */
 private function validateField($ifldname, $fldopts)
 {
     $invalidated = false;
     $fldkey = $fldopts["dispkey"];
     $disp = $fldopts["disp"];
     if ($this->fldis("data", $ifldname)) {
         $fldname = base64_decode($ifldname);
         if (!ucfs::valid($fldname)) {
             $invalidated = ucfs::ferror($fldname);
         }
     } else {
         /* retrieve data from field options */
         if ($this->fields[$ifldname]["type"] == "date") {
             $value = "{$fldopts['year']}-{$fldopts['month']}-{$fldopts['day']}";
         } else {
             $value = $fldopts["value"];
         }
         $datatype = $fldopts["datatype"];
         if (!isset($fldopts["min"])) {
             $fldopts["min"] = "";
         }
         if (!isset($fldopts["max"])) {
             $fldopts["max"] = "";
         }
         $min = $fldopts["min"];
         $max = $fldopts["max"];
         /* mark field as being validated */
         $this->fields[$ifldname]["validated"] = true;
         $invalidated = cForm::validateValue($value, $datatype, $min, $max);
     }
     /* store error if any */
     if ($invalidated !== false) {
         if (!isset($this->errors[$fldkey])) {
             $this->errors[$fldkey] = array();
         }
         $this->errors[$fldkey][$ifldname] = "{$disp}. {$invalidated}";
     } else {
         return true;
     }
 }
function import($frm)
{
    /* @var $frm cForm */
    if ($frm->validate("import")) {
        return view($frm);
    }
    /* get field indexes */
    $stkcod = false;
    $price = false;
    foreach ($_REQUEST["fld"] as $fi => $ft) {
        if ($ft != "ignore") {
            ${$ft} = $fi;
        }
    }
    /* import file if all field types specified */
    if ($stkcod === false || $price === false) {
        $frm->setmsg("<li class='err'>Not all field types satisfied</li>");
    } else {
        $qry = new dbSelect("spricelist", "exten", grp(m("cols", "listid"), m("where", "suppid='{$_REQUEST['supid']}'")));
        $qry->run();
        if ($qry->num_rows() <= 0) {
            $suppinfo = qrySupplier($_REQUEST["supid"]);
            $cols = grp(m("suppid", $_REQUEST["supid"]), m("listname", $suppinfo["supname"]), m("div", USER_DIV));
            $upd = new dbUpdate("spricelist", "exten", $cols);
            $upd->run(DB_INSERT);
            $listid = $upd->lastid("listid");
        } else {
            $listid = $qry->fetch_result();
        }
        $upd = new dbDelete("splist_prices", "exten", "listid='{$listid}'");
        $upd->run();
        $upd = new dbUpdate("splist_prices", "exten");
        $invalid_fields = array();
        $nosuch_fields = array();
        $file = ucfs::file("supplist");
        foreach ($file as $rd) {
            $ri = explode(",", $rd);
            $ri[$stkcod] = trim($ri[$stkcod]);
            $ri[$price] = trim($ri[$price]);
            if (cForm::validateValue($ri[$stkcod], "string", 1, 250) || cForm::validateValue($ri[$price], "float", 1, 40)) {
                $invalid_fields[] = $ri[$stkcod];
                continue;
            }
            $stkid = suppStkid($_REQUEST["supid"], $ri[$stkcod]);
            if ($stkid === false) {
                $stkinfo = array("stkid" => "0", "catid" => "0", "prdcls" => "0");
            } else {
                $stkinfo = qryStock($stkid, "stkid, catid, prdcls");
            }
            if (!isset($_REQUEST["vatinc"])) {
                $ri[$price] += $ri[$price] * TAX_VAT / 100;
            }
            $cols = grp(m("listid", $listid), m("stkid", $stkinfo["stkid"]), m("catid", $stkinfo["catid"]), m("clasid", $stkinfo["prdcls"]), m("price", $ri[$price]), m("div", USER_DIV), m("supstkcod", $ri[$stkcod]));
            $upd->setCols($cols);
            $upd->run();
        }
        if (count($invalid_fields) > 0) {
            $msg = "<br />The following items weren't imported because they contain\n\t\t\t\tinvalid values for either the stock code or the price:<br />";
            foreach ($invalid_fields as $v) {
                $msg .= "&nbsp;&nbsp;&nbsp;&nbsp;- {$v}<br />";
            }
        } else {
            $msg = "";
        }
        $frm->setmsg("<li class='err'>Successfully imported new pricelist.{$msg}</li>");
    }
    return view($frm);
}
function importFile()
{
    global $_FILES, $_POST, $psql_exec;
    extract($_POST);
    $OUTPUT = "<h3>Import Company</h3>";
    $v =& new Validate();
    if (!$v->isOk($compname, "string", 1, 250, "")) {
        return "<li class='err'>Invalid Company Name</li>" . selectFile();
    }
    // generate code
    $code = "aaaa";
    // make sure it 4 chars long by padding with a's
    $code = str_replace(" ", "", $code);
    $code = str_pad($code, 4, 'a', STR_PAD_RIGHT);
    while (1) {
        // check if the code exists
        db_con("cubit");
        $rslt = db_exec("SELECT * FROM companies WHERE code='{$code}'");
        // not exist! YAY!!
        if (pg_numrows($rslt) < 1 && !exists_compdb($code)) {
            break;
        }
        // increase
        $code[3] = chr(ord($code[3]) + 1);
        for ($i = 3; $i >= 0; $i--) {
            if (ord($code[$i]) > ord('z')) {
                $code[$i] = 'a';
                if ($i > 0) {
                    $code[$i - 1] = chr(ord($code[$i - 1]) + 1);
                }
                if (substr($code, 0, 3) == "zzz") {
                    $code = "aaaa";
                }
            }
        }
    }
    require_lib("progress");
    displayProgress("newtemplate.php");
    # Change code to lowercase
    $code = strtolower($code);
    // parse the import file
    if (PLATFORM == "windows") {
        $importfile = cfs::tempnam("cubitimport_");
    } else {
        $importfile = cfs::tempnam("cubitimport_");
    }
    if (!ucfs::valid("compfile")) {
        return "<li class='err'>" . ucfs::ferror("compfile") . "</li>";
    }
    $fd_in = ucfs::fopen("compfile", "r");
    $fd_out = cfs::fopen($importfile, "w", true);
    if ($fd_in === false) {
        return "<li class='err'>Unable to open import file.</li>";
    }
    if ($fd_out === false) {
        return "<li class='err'>Unable to open temporary file required to import company.</li>";
    }
    $company_ver = "";
    while (!cfs::feof($fd_in)) {
        $buf = cfs::fgets($fd_in, 4096);
        // get the version of imported company if on this line
        $pos = strpos($buf, "-- V'e'r's'i'o'n:");
        if ($pos !== false && $pos == 0) {
            $company_ver = trim(substr($buf, 17));
        }
        // check if it valid platform
        $pos = strpos($buf, "-- P'l'a't'f'o'r'm:");
        if ($pos !== false && $pos == 0) {
            $comp_platform = trim(substr($buf, 19));
            if (PLATFORM != $comp_platform) {
                $OUTPUT .= "You cannot import another platform's company!<br>\n\t\t\t\t\tOnly from Windows to Windows or Linux to Linux.<br><Br>\n\t\t\t\t\tYour platform: " . PLATFORM . "<Br>\n\t\t\t\t\tProposed Imported Company Platform: {$comp_platform}<br>";
                return $OUTPUT;
            }
        }
        // parse the create database code variable if on this line
        $pos = strpos($buf, "CREATE DATABASE");
        if ($pos !== false && strpos($buf, "%c'o'd'e%") > 0) {
            $buf = str_replace("%c'o'd'e%", $code, $buf);
        }
        // parse the company code variable if on this line
        $pos = strpos($buf, "\\c ");
        if ($pos !== false && strpos($buf, "%c'o'd'e%") > 0) {
            $buf = str_replace("%c'o'd'e%", $code, $buf);
        }
        fputs($fd_out, $buf);
    }
    fclose($fd_in);
    fclose($fd_out);
    // get the version of current cubit
    db_con("cubit");
    $cubit_ver = CUBIT_VERSION;
    // check if versions are the same (TEMPORARY HACK, ai tog)
    if ($cubit_ver != $company_ver) {
        return $OUTPUT . "Versions do not match:<br>\n\t\t\tProposed Imported Company version is \"{$company_ver}\"<br>\n\t\t\tYour Cubit version is \"{$cubit_ver}\"<br>\n\t\t\t<br>\n\t\t\tCheck for updates for your Cubit to support the functionality of importing non matching versions.";
    }
    // import
    exec("{$psql_exec}/" . PSQL_EXE . " -U postgres template1 < {$importfile}");
    // insert the company
    db_con("cubit");
    db_exec("INSERT INTO companies (code,name,ver,status) VALUES('{$code}', '{$compname}', '{$company_ver}', 'active')");
    // if only one company in list, we can safely assume this was the first company
    // and forward to the login screen
    $sql = "SELECT * FROM companies";
    $rslt = db_exec($sql);
    if (!isset($_SESSION["USER_ID"]) && $rslt && pg_num_rows($rslt) > 0) {
        $_SESSION["code"] = $code;
        $_SESSION["comp"] = $compname;
        $OUTPUT = "<script>top.document.location.href='doc-index.php';</script>";
        return $OUTPUT;
        header("Location: main.php");
        exit;
    }
    $OUTPUT .= "\n\tCompany has been imported successfully.<br>\n\tCompany Name: {$compname}<br>\n\tCompany Code: {$code}<br>";
    return $OUTPUT;
}
 /**
  * returns mime type
  *
  * @param string $name fieldname
  * @return array
  */
 static function ftype($name)
 {
     if (!ucfs::valid($name)) {
         return false;
     }
     return $_FILES[$name]["type"];
 }