Example #1
0
function miscRound2OptDecim($value, $decimals = 2, $decimalSeparator = null, $thousandSeparator = null)
{
    if ($value == floor($value)) {
        $decimals = 0;
    }
    return miscRound2Decim($value, $decimals, $decimalSeparator, $thousandSeparator);
}
Example #2
0
    private function printTotals($format, $printFields, $intTotSum, $intTotVAT, $intTotSumVAT)
    {
        if (!in_array('sums', $printFields)) {
            return;
        }
        if ($format == 'pdf' || $format == 'pdfl') {
            $pdf = $this->pdf;
            if ($pdf->getY() > $pdf->getPageHeight() - 7 - 15) {
                $pdf->AddPage();
            }
            $pdf->SetFont('Helvetica', '', 8);
            $pdf->setLineWidth(0.2);
            $rowWidth = 0;
            $sumPos = 75;
            if (in_array('invoice_no', $printFields)) {
                $rowWidth += 18;
            }
            if (in_array('invoice_date', $printFields)) {
                $rowWidth += 20;
            }
            if (in_array('due_date', $printFields)) {
                $rowWidth += 20;
            }
            if (in_array('payment_date', $printFields)) {
                $rowWidth += 20;
            }
            if (in_array('company_name', $printFields)) {
                $rowWidth += 45;
            }
            if (in_array('status', $printFields)) {
                $rowWidth += 20;
            }
            if (in_array('ref_number', $printFields)) {
                $rowWidth += 25;
            }
            $sumPos = $rowWidth;
            $rowWidth += 75;
            $pdf = $this->pdf;
            $pdf->SetFont('Helvetica', 'B', 8);
            $pdf->line($pdf->getX() + $sumPos, $pdf->getY(), $pdf->getX() + $rowWidth, $pdf->getY());
            $pdf->setY($pdf->getY() + 1);
            $pdf->Cell($sumPos, 4, $GLOBALS['locTotal'], 0, 0, 'R');
            $pdf->Cell(25, 4, miscRound2Decim($intTotSum), 0, 0, 'R');
            $pdf->Cell(25, 4, miscRound2Decim($intTotVAT), 0, 0, 'R');
            $pdf->Cell(25, 4, miscRound2Decim($intTotSumVAT), 0, 1, 'R');
            return;
        }
        $colSpan = 0;
        if (in_array('invoice_no', $printFields)) {
            ++$colSpan;
        }
        if (in_array('invoice_date', $printFields)) {
            ++$colSpan;
        }
        if (in_array('due_date', $printFields)) {
            ++$colSpan;
        }
        if (in_array('payment_date', $printFields)) {
            ++$colSpan;
        }
        if (in_array('company_name', $printFields)) {
            ++$colSpan;
        }
        if (in_array('status', $printFields)) {
            ++$colSpan;
        }
        if (in_array('ref_number', $printFields)) {
            ++$colSpan;
        }
        ?>
    <tr>
    <?php 
        if ($colSpan > 0) {
            ?>
        <td class="input total_sum" colspan="<?php 
            echo $colSpan;
            ?>
" style="text-align: right">
            <?php 
            echo $GLOBALS['locTotal'];
            ?>
        </td>
    <?php 
        }
        ?>
        <td class="input total_sum" style="text-align: right">
            &nbsp;<?php 
        echo miscRound2Decim($intTotSum);
        ?>
        </td>
        <td class="input total_sum" style="text-align: right">
            &nbsp;<?php 
        echo miscRound2Decim($intTotVAT);
        ?>
        </td>
        <td class="input total_sum" style="text-align: right">
            &nbsp;<?php 
        echo miscRound2Decim($intTotSumVAT);
        ?>
        </td>
    </tr>
<?php 
    }
Example #3
0
    protected function printTotals($format, $stockValue)
    {
        if ($format == 'pdf') {
            $pdf = $this->pdf;
            if ($pdf->getY() > $pdf->getPageHeight() - 7 - 15) {
                $pdf->AddPage();
            }
            $pdf->SetFont('Helvetica', '', 8);
            $pdf->setLineWidth(0.2);
            $sumPos = 130;
            $rowWidth = 150;
            $pdf = $this->pdf;
            $pdf->SetFont('Helvetica', 'B', 8);
            $pdf->line($pdf->getX() + $sumPos, $pdf->getY(), $pdf->getX() + $rowWidth, $pdf->getY());
            $pdf->setY($pdf->getY() + 1);
            $pdf->Cell($sumPos, 4, $GLOBALS['locTotal'], 0, 0, 'R');
            $pdf->Cell(25, 4, miscRound2Decim($stockValue), 0, 1, 'R');
            return;
        }
        $colSpan = 5;
        ?>
    <tr>
    <?php 
        if ($colSpan > 0) {
            ?>
        <td class="input total_sum" colspan="<?php 
            echo $colSpan;
            ?>
"
				style="text-align: right">
            <?php 
            echo $GLOBALS['locTotal'];
            ?>
        </td>
    <?php 
        }
        ?>
        <td class="input total_sum" style="text-align: right">
            &nbsp;<?php 
        echo miscRound2Decim($stockValue);
        ?>
        </td>
		</tr>
<?php 
    }
Example #4
0
function createForm($strFunc, $strList, $strForm)
{
    require "form_switch.php";
    if (!sesAccessLevel($levelsAllowed) && !sesAdminAccess()) {
        ?>
  <div class="form_container ui-widget-content">
    <?php 
        echo $GLOBALS['locNoAccess'] . "\n";
        ?>
  </div>
<?php 
        return;
    }
    $blnNew = getPostRequest('newact', FALSE);
    $blnCopy = getPostRequest('copyact', FALSE) ? TRUE : FALSE;
    $blnDelete = getPostRequest('deleteact', FALSE) ? TRUE : FALSE;
    $intKeyValue = getPostRequest('id', FALSE);
    if (!$intKeyValue) {
        $blnNew = TRUE;
    }
    if (!sesWriteAccess() && ($blnNew || $blnCopy || $blnDelete)) {
        ?>
  <div class="form_container ui-widget-content">
    <?php 
        echo $GLOBALS['locNoAccess'] . "\n";
        ?>
  </div>
<?php 
        return;
    }
    $strMessage = '';
    if (isset($_SESSION['formMessage']) && $_SESSION['formMessage']) {
        $strMessage = $GLOBALS['loc' . $_SESSION['formMessage']];
        unset($_SESSION['formMessage']);
    }
    $strErrorMessage = '';
    if (isset($_SESSION['formErrorMessage']) && $_SESSION['formErrorMessage']) {
        $strErrorMessage = $GLOBALS['loc' . $_SESSION['formErrorMessage']];
        unset($_SESSION['formErrorMessage']);
    }
    // if NEW is clicked clear existing form data
    if ($blnNew) {
        unset($intKeyValue);
        unset($astrValues);
        unset($_POST);
        unset($_REQUEST);
        $readOnlyForm = false;
    }
    $astrValues = getPostValues($astrFormElements, isset($intKeyValue) ? $intKeyValue : FALSE);
    $redirect = getRequest('redirect', null);
    if (isset($redirect)) {
        // Redirect after save
        foreach ($astrFormElements as $elem) {
            if ($elem['name'] == $redirect) {
                if ($elem['style'] == 'redirect') {
                    $newLocation = str_replace('_ID_', $intKeyValue, $elem['listquery']);
                } elseif ($elem['style'] == 'openwindow') {
                    $openWindow = str_replace('_ID_', $intKeyValue, $elem['listquery']);
                }
            }
        }
    }
    if ($blnDelete && $intKeyValue && !$readOnlyForm) {
        deleteRecord($strTable, $intKeyValue);
        unset($intKeyValue);
        unset($astrValues);
        $blnNew = TRUE;
        if (getSetting('auto_close_after_delete')) {
            $qs = preg_replace('/&form=\\w*/', '', $_SERVER['QUERY_STRING']);
            $qs = preg_replace('/&id=\\w*/', '', $qs);
            header("Location: " . _PROTOCOL_ . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/index.php?{$qs}");
            return;
        }
        ?>
  <div class="form_container ui-widget-content">
    <?php 
        echo $GLOBALS['locRecordDeleted'] . "\n";
        ?>
  </div>
<?php 
        return;
    }
    if (isset($intKeyValue) && $intKeyValue) {
        $res = fetchRecord($strTable, $intKeyValue, $astrFormElements, $astrValues);
        if ($res === 'deleted') {
            $strMessage .= $GLOBALS['locDeletedRecord'] . '<br>';
        } elseif ($res === 'notfound') {
            echo $GLOBALS['locEntryDeleted'];
            die;
        }
    }
    if ($blnCopy) {
        unset($intKeyValue);
        unset($_POST);
        $blnNew = TRUE;
        $readOnlyForm = false;
    }
    ?>

  <div id="popup_dlg" style="display: none; width: 900px; overflow: hidden">
    <iframe id="popup_dlg_iframe" src="about:blank" style="width: 100%; height: 100%; overflow: hidden; border: 0"></iframe>
  </div>
<?php 
    if (isset($popupHTML)) {
        echo $popupHTML;
    }
    ?>

  <div class="form_container">

<?php 
    createFormButtons($blnNew, $copyLinkOverride, true, $readOnlyForm);
    ?>
    <div class="form">
      <form method="post" name="admin_form" id="admin_form">
      <input type="hidden" name="copyact" value="0">
      <input type="hidden" name="newact" value="<?php 
    echo $blnNew ? 1 : 0;
    ?>
">
      <input type="hidden" name="deleteact" value="0">
      <input type="hidden" name="redirect" id="redirect" value="">
      <input type="hidden" id="record_id" name="id" value="<?php 
    echo isset($intKeyValue) && $intKeyValue ? $intKeyValue : '';
    ?>
">
      <table>
<?php 
    $haveChildForm = false;
    $prevPosition = false;
    $prevColSpan = 1;
    $rowOpen = false;
    $formFieldMode = sesWriteAccess() && !$readOnlyForm ? 'MODIFY' : 'READONLY';
    foreach ($astrFormElements as $elem) {
        if ($elem['type'] === false) {
            continue;
        }
        $fieldMode = isset($elem['read_only']) && $elem['read_only'] ? 'READONLY' : $formFieldMode;
        if ($elem['type'] == "LABEL") {
            if ($rowOpen) {
                echo "        </tr>\n";
            }
            $rowOpen = false;
            ?>
        <tr>
          <td class="sublabel ui-widget-header ui-state-default" colspan="4">
            <?php 
            echo $elem['label'];
            ?>
          </td>
        </tr>
  <?php 
            continue;
        }
        if ($elem['position'] == 0 || $elem['position'] <= $prevPosition) {
            $prevPosition = 0;
            $prevColSpan = 1;
            echo "        </tr>\n";
            $rowOpen = false;
        }
        if ($elem['type'] != "IFORM") {
            if (!$rowOpen) {
                $rowOpen = true;
                echo "        <tr>\n";
            }
            if ($prevPosition !== FALSE && $elem['position'] > 0) {
                for ($i = $prevPosition + $prevColSpan; $i < $elem['position']; $i++) {
                    echo "          <td class=\"label\">&nbsp;</td>\n";
                }
            }
            if ($elem['position'] == 0 && !strstr($elem['type'], "HID_")) {
                $strColspan = "colspan=\"3\"";
                $intColspan = 3;
            } elseif ($elem['position'] == 1 && !strstr($elem['type'], "HID_")) {
                $strColspan = '';
                $intColspan = 2;
            } else {
                $intColspan = 2;
            }
        }
        if ($blnNew && ($elem['type'] == 'BUTTON' || $elem['type'] == 'JSBUTTON' || $elem['type'] == 'IMAGE')) {
            echo "          <td class=\"label\">&nbsp;</td>";
        } elseif ($elem['type'] == "BUTTON" || $elem['type'] == "JSBUTTON") {
            $intColspan = 1;
            ?>
          <td class="button">
            <?php 
            echo htmlFormElement($elem['name'], $elem['type'], $astrValues[$elem['name']], $elem['style'], $elem['listquery'], $fieldMode, $elem['parent_key'], $elem['label'], array(), isset($elem['elem_attributes']) ? $elem['elem_attributes'] : '', isset($elem['options']) ? $elem['options'] : null);
            ?>
          </td>
<?php 
        } elseif ($elem['type'] == "FILLER") {
            $intColspan = 1;
            ?>
          <td>
            &nbsp;
          </td>
<?php 
        } elseif ($elem['type'] == "HID_INT" || strstr($elem['type'], "HID_")) {
            ?>
          <?php 
            echo htmlFormElement($elem['name'], $elem['type'], $astrValues[$elem['name']], $elem['style'], $elem['listquery'], $fieldMode, $elem['parent_key'], $elem['label']);
        } elseif ($elem['type'] == "IMAGE") {
            ?>
          <td class="image" colspan="<?php 
            echo $intColspan;
            ?>
">
            <?php 
            echo htmlFormElement($elem['name'], $elem['type'], $astrValues[$elem['name']], $elem['style'], $elem['listquery'], $fieldMode, $elem['parent_key'], $elem['label'], array(), isset($elem['elem_attributes']) ? $elem['elem_attributes'] : '', isset($elem['options']) ? $elem['options'] : null);
            ?>
          </td>
<?php 
        } elseif ($elem['type'] == "IFORM") {
            if ($rowOpen) {
                echo "        </tr>\n";
            }
            echo "      </table>\n      </form>\n";
            $haveChildForm = true;
            createIForm($astrFormElements, $elem, isset($intKeyValue) ? $intKeyValue : 0, $blnNew, $strForm);
            break;
        } else {
            $value = $astrValues[$elem['name']];
            if ($elem['style'] == 'measurement') {
                $value = $value ? miscRound2Decim($value, 2) : '';
            }
            if ($elem['type'] == 'AREA') {
                ?>
          <td class="toplabel"><?php 
                echo $elem['label'];
                ?>
</td>
<?php 
            } else {
                ?>
          <td id="<?php 
                echo htmlentities($elem['name']) . '_label';
                ?>
" class="label"<?php 
                if (isset($elem['title'])) {
                    echo ' title="' . $elem['title'] . '"';
                }
                ?>
><?php 
                echo $elem['label'];
                ?>
</td>
<?php 
            }
            ?>
          <td class="field"<?php 
            echo $strColspan ? " {$strColspan}" : '';
            ?>
>
            <?php 
            echo htmlFormElement($elem['name'], $elem['type'], $value, $elem['style'], $elem['listquery'], $fieldMode, isset($elem['parent_key']) ? $elem['parent_key'] : '', '', array(), isset($elem['elem_attributes']) ? $elem['elem_attributes'] : '', isset($elem['options']) ? $elem['options'] : null);
            if (isset($elem['attached_elem'])) {
                echo '            ' . $elem['attached_elem'] . "\n";
            }
            ?>
          </td>
<?php 
        }
        $prevPosition = is_int($elem['position']) ? $elem['position'] : 0;
        if ($prevPosition == 0) {
            $prevPosition = 255;
        }
        $prevColSpan = $intColspan;
    }
    if (!$haveChildForm) {
        if ($rowOpen) {
            echo "        </tr>\n";
        }
        echo "      </table>\n      </form>\n";
    }
    if ($strForm == 'product') {
        // Special case for product: show stock balance change log
        ?>
      <div class="iform ui-corner-tl ui-corner-bl ui-corner-br ui-corner-tr ui-helper-clearfix" id="stock_balance_log">
        <div class="ui-corner-tl ui-corner-tr fg-toolbar ui-toolbar ui-widget-header"><?php 
        echo $GLOBALS['locStockBalanceUpdates'];
        ?>
</div>
        <table id="stock_balance_change_log">
          <tr>
            <th class="medium"><?php 
        echo $GLOBALS['locHeaderChangeLogDateTime'];
        ?>
</th>
            <th class="medium"><?php 
        echo $GLOBALS['locHeaderChangeLogUser'];
        ?>
</th>
            <th class="small"><?php 
        echo $GLOBALS['locHeaderChangeLogAmount'];
        ?>
</th>
            <th class="long"><?php 
        echo $GLOBALS['locHeaderChangeLogDescription'];
        ?>
</th>
          </tr>
        </table>
      </div>
    </div>
<?php 
    }
    ?>
  </div>

<script type="text/javascript">
/* <![CDATA[ */
var globals = {};

$(window).bind('beforeunload', function(e) {
  if ($('.save_button').hasClass('ui-state-highlight') || $('.add_row_button').hasClass('ui-state-highlight'))
  {
    e.returnValue = "<?php 
    echo $GLOBALS['locUnsavedData'];
    ?>
";
    return "<?php 
    echo $GLOBALS['locUnsavedData'];
    ?>
";
  }
});

function showmsg(msg, timeout)
{
  $.floatingMessage("<span>" + msg + "</span>", {
    position: "top-right",
    className: "ui-widget ui-state-highlight",
    show: "show",
    hide: "fade",
    stuffEaseTime: 200,
    moveEaseTime: 0,
    time: typeof(timeout) != 'undefined' ? timeout : 5000
  });
}

function errormsg(msg, timeout)
{
  $.floatingMessage("<span>" + msg + "</span>", {
    position: "top-right",
    className: "ui-widget ui-state-error",
    show: "show",
    hide: "fade",
    stuffEaseTime: 200,
    moveEaseTime: 0,
    time: typeof(timeout) != 'undefined' ? timeout : 5000
  });
}

$(document).ready(function() {
<?php 
    if ($strMessage) {
        ?>
  showmsg("<?php 
        echo $strMessage;
        ?>
");
<?php 
    }
    if ($strErrorMessage) {
        ?>
  errormsg("<?php 
        echo $strErrorMessage;
        ?>
");
<?php 
    }
    if ($strForm == 'product') {
        ?>
  update_stock_balance_log();
<?php 
    }
    if (sesWriteAccess()) {
        ?>
  $('input[class~="hasCalendar"]').datepicker();
<?php 
    }
    ?>
  $('#message').ajaxStart(function() {
    $('#spinner').css('visibility', 'visible');
  });
  $('#message').ajaxStop(function() {
    $('#spinner').css('visibility', 'hidden');
  });
  $('#errormsg').ajaxError(function(event, request, settings) {
    errormsg('Server request failed: ' + request.status + ' - ' + request.statusText);
    $('#spinner').css('visibility', 'hidden');
  });

  $('#admin_form').find('input[type="text"],input[type="hidden"],input[type="checkbox"],select,textarea').change(function() { $('.save_button').addClass('ui-state-highlight'); });
<?php 
    if ($haveChildForm && !$blnNew) {
        ?>
  init_rows();
  $('#iform').find('input[type="text"],input[type="hidden"],input[type="checkbox"],select,textarea').change(function() { $('.add_row_button').addClass('ui-state-highlight'); });
<?php 
    } elseif (isset($newLocation)) {
        echo "window.location='{$newLocation}';";
    }
    if (isset($openWindow)) {
        echo "window.open('{$openWindow}');";
    }
    ?>
});
<?php 
    if ($haveChildForm && !$blnNew) {
        ?>
function init_rows_done()
{
<?php 
        if (isset($newLocation)) {
            echo "window.location='{$newLocation}';";
        }
        ?>
}
<?php 
    }
    ?>

function save_record(redirect_url, redir_style)
{
  var form = document.getElementById('admin_form');
  var obj = new Object();

<?php 
    foreach ($astrFormElements as $elem) {
        if ($elem['name'] && !in_array($elem['type'], array('HID_INT', 'SECHID_INT', 'BUTTON', 'JSBUTTON', 'LABEL', 'IMAGE', 'NEWLINE', 'ROWSUM', 'CHECK', 'IFORM'))) {
            ?>
  obj.<?php 
            echo $elem['name'];
            ?>
 = form.<?php 
            echo $elem['name'];
            ?>
.value;
<?php 
        } elseif ($elem['type'] == 'CHECK') {
            ?>
  obj.<?php 
            echo $elem['name'];
            ?>
 = form.<?php 
            echo $elem['name'];
            ?>
.checked ? 1 : 0;
<?php 
        }
    }
    ?>
  obj.id = form.id.value;
  $.ajax({
    'url': "json.php?func=put_<?php 
    echo $strJSONType;
    ?>
",
    'type': 'POST',
    'dataType': 'json',
    'data': $.toJSON(obj),
    'contentType': 'application/json; charset=utf-8',
    'success': function(data) {
      if (data.warnings)
        alert(data.warnings);
      if (data.missing_fields)
      {
        errormsg('<?php 
    echo $GLOBALS['locErrValueMissing'];
    ?>
: ' + data.missing_fields);
      }
      else
      {
        $('.save_button').removeClass('ui-state-highlight');
        showmsg('<?php 
    echo $GLOBALS['locRecordSaved'];
    ?>
', 2000);
        if (redirect_url)
        {
          if (redir_style == 'openwindow')
            window.open(redirect_url);
          else
            window.location = redirect_url;
        }
        if (!obj.id)
        {
          obj.id = data.id;
          form.id.value = obj.id;
          if (!redirect_url || redir_style == 'openwindow')
          {
            var newloc = new String(window.location).split('#', 1)[0];
            window.location = newloc + '&id=' + obj.id;
          }
        }
      }
    },
    'error': function(XMLHTTPReq, textStatus, errorThrown) {
      if (XMLHTTPReq.status == 409) {
        errormsg(jQuery.parseJSON(XMLHTTPReq.responseText).warnings);
      }
      else if (textStatus == 'timeout')
        errormsg('Timeout trying to save data');
      else
        errormsg('Error trying to save data: ' + XMLHTTPReq.status + ' - ' + XMLHTTPReq.statusText);
      return false;
    }
  });
}

function popup_dialog(url, on_close, dialog_title, event, width, height)
{
  $("#popup_dlg").dialog({ modal: true, width: width, height: height, resizable: true,
    position: [50, 50],
    buttons: {
      "<?php 
    echo $GLOBALS['locClose'];
    ?>
": function() { $("#popup_dlg").dialog('close'); }
    },
    title: dialog_title,
    close: function(event, ui) { eval(on_close); }
  }).find("#popup_dlg_iframe").attr("src", url);

  return true;
}

/* ]]> */
</script>

<?php 
    createFormButtons($blnNew, $copyLinkOverride, false, $readOnlyForm);
    echo "  </div>\n";
    if ($addressAutocomplete && getSetting('address_autocomplete')) {
        ?>
  <script type="text/javascript">
  $(document).ready(function() {
  var s = document.createElement("script");
    s.type = "text/javascript";
    s.src  = "https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places&callback=gmapsready";
    window.gmapsready = function(){
        initAddressAutocomplete("");
        initAddressAutocomplete("quick_");
    };
    $("head").append(s);
  });
  </script>
<?php 
    }
}
Example #5
0
    protected function process_import_row($table, $row, $dupMode, $dupCheckColumns, $mode, &$addedRecordId)
    {
        if (!isset($row['date']) || !isset($row['amount']) || !isset($row['refnr'])) {
            return $GLOBALS['locImportStatementFieldMissing'];
        }
        $refnr = str_replace(' ', '', $row['refnr']);
        $refnr = ltrim($refnr, '0');
        $date = date('Ymd', DateTime::createFromFormat(getRequest('date_format', 'd.m.Y'), $row['date'])->getTimestamp());
        $amount = trim($row['amount']);
        if (substr($amount, 0, 1) == '-') {
            return;
        }
        if (substr($amount, 0, 1) == '+') {
            $amount = substr($amount, 1);
        }
        $sep = getRequest('decimal_separator', ',');
        if ($sep == ' ' || $sep == ',') {
            $amount = str_replace('.', '', $amount);
            $amount = str_replace($sep, '.', $amount);
        } elseif ($sep == '.') {
            $amount = str_replace(',', '', $amount);
        }
        $amount = floatval($amount);
        if ($row['refnr'] === '') {
            return $GLOBALS['locImportStatementFieldMissing'];
        }
        $sql = 'SELECT i.* FROM {prefix}invoice i' . ' WHERE i.Deleted=0 AND REPLACE(i.ref_number, " ", "") = ?';
        $params = [$refnr];
        $baseId = getRequest('base_id', '');
        if ($baseId) {
            $sql .= ' AND i.base_id = ?';
            $params[] = $baseId;
        }
        $intRes = mysqli_param_query($sql, $params);
        $count = mysqli_num_rows($intRes);
        if ($count == 0) {
            return str_replace('{refnr}', $refnr, $GLOBALS['locImportStatementInvoiceNotFound']);
        }
        if ($count > 1) {
            return str_replace('{refnr}', $refnr, $GLOBALS['locImportStatementMultipleInvoicesFound']);
        }
        $row = mysqli_fetch_assoc($intRes);
        if ($row['state_id'] == 3) {
            return str_replace('{refnr}', $refnr, $GLOBALS['locImportStatementInvoiceAlreadyPaid']);
        }
        $res2 = mysqli_param_query('SELECT ir.price, ir.pcs, ir.vat, ir.vat_included, ir.discount, ir.partial_payment from {prefix}invoice_row ir where ir.deleted = 0 AND ir.invoice_id = ?', [$row['id']]);
        $rowTotal = 0;
        $partialPayments = 0;
        while ($invoiceRow = mysqli_fetch_assoc($res2)) {
            if ($invoiceRow['partial_payment']) {
                $partialPayments += $invoiceRow['price'];
            }
            list($rowSum, $rowVAT, $rowSumVAT) = calculateRowSum($invoiceRow['price'], $invoiceRow['pcs'], $invoiceRow['vat'], $invoiceRow['vat_included'], $invoiceRow['discount']);
            $rowTotal += $rowSumVAT;
        }
        $totalToPay = $rowTotal + $partialPayments;
        if (miscRound2Decim($totalToPay) != miscRound2Decim($amount)) {
            if (getRequest('partial_payments', false) && miscRound2Decim($totalToPay) > miscRound2Decim($amount)) {
                if ($mode == 'import') {
                    $sql = <<<EOT
INSERT INTO {prefix}invoice_row
    (invoice_id, description, pcs, price, row_date, order_no, partial_payment)
    VALUES (?, ?, 0, ?, ?, 100000, 1)
EOT;
                    mysqli_param_query($sql, [$row['id'], $GLOBALS['locPartialPayment'], -$amount, $date]);
                }
                $msg = str_replace('{statementAmount}', miscRound2Decim($amount), $GLOBALS['locImportStatementPartialPayment']);
                $msg = str_replace('{invoiceAmount}', miscRound2Decim($totalToPay), $msg);
                $msg = str_replace('{id}', $row['id'], $msg);
                $msg = str_replace('{date}', dateConvDBDate2Date($date), $msg);
                $msg = str_replace('{refnr}', $refnr, $msg);
                return $msg;
            } else {
                $msg = str_replace('{statementAmount}', miscRound2Decim($amount), $GLOBALS['locImportStatementAmountMismatch']);
                $msg = str_replace('{invoiceAmount}', miscRound2Decim($totalToPay), $msg);
                $msg = str_replace('{refnr}', $refnr, $msg);
                return $msg;
            }
        }
        $archive = $row['interval_type'] == 0 && getRequest('archive', '');
        if ($mode == 'import') {
            $sql = 'UPDATE {prefix}invoice SET state_id=3, payment_date=?';
            if ($archive) {
                $sql .= ', archived=1';
            }
            $sql .= ' WHERE id = ?';
            mysqli_param_query($sql, [$date, $row['id']]);
        }
        $msg = str_replace('{amount}', miscRound2Decim($amount), $archive ? $GLOBALS['locImportStatementInvoiceMarkedAsPaidAndArchived'] : $GLOBALS['locImportStatementInvoiceMarkedAsPaid']);
        $msg = str_replace('{id}', $row['id'], $msg);
        $msg = str_replace('{date}', dateConvDBDate2Date($date), $msg);
        $msg = str_replace('{refnr}', $refnr, $msg);
        return $msg;
    }
Example #6
0
function fetchRecord($table, $primaryKey, &$formElements, &$values)
{
    $result = TRUE;
    $strQuery = "SELECT * FROM {$table} WHERE id=?";
    $intRes = mysqli_param_query($strQuery, [$primaryKey]);
    $row = mysqli_fetch_assoc($intRes);
    if (!$row) {
        return 'notfound';
    }
    if ($row['deleted']) {
        $result = 'deleted';
    }
    foreach ($formElements as $elem) {
        $type = $elem['type'];
        $name = $elem['name'];
        if (!$type || $type == 'LABEL' || $type == 'FILLER') {
            continue;
        }
        switch ($type) {
            case 'IFORM':
            case 'RESULT':
                $values[$name] = $primaryKey;
                break;
            case 'BUTTON':
            case 'JSBUTTON':
            case 'IMAGE':
                if (strstr($elem['listquery'], '=_ID_')) {
                    $values[$name] = $primaryKey;
                } else {
                    $tmpListQuery = $elem['listquery'];
                    $strReplName = substr($tmpListQuery, strpos($tmpListQuery, '_'));
                    $strReplName = strtolower(substr($strReplName, 1, strrpos($strReplName, '_') - 1));
                    $values[$name] = isset($values[$strReplName]) ? $values[$strReplName] : '';
                    $elem['listquery'] = str_replace(strtoupper($strReplName), 'ID', $elem['listquery']);
                }
                break;
            case 'INTDATE':
                $values[$name] = dateConvDBDate2Date($row[$name]);
                break;
            case 'INT':
                if (isset($elem['decimals'])) {
                    $values[$name] = miscRound2Decim($row[$name], $elem['decimals']);
                } else {
                    $values[$name] = $row[$name];
                }
                break;
            default:
                $values[$name] = $row[$name];
        }
    }
    return $result;
}
Example #7
0
    private function printTotals($format, $intTotSum, $intTotVAT, $intTotSumVAT)
    {
        if ($format == 'pdf') {
            $pdf = $this->pdf;
            $pdf->SetFont('Helvetica', 'B', 8);
            $pdf->setY($pdf->getY() + 3);
            $pdf->Cell(55, 3, $GLOBALS['locTotal'], 0, 0, 'L');
            $pdf->Cell(25, 3, '', 0, 0, 'L');
            $pdf->Cell(25, 3, '', 0, 0, 'L');
            $pdf->Cell(25, 3, miscRound2Decim($intTotSum), 0, 0, 'R');
            $pdf->Cell(15, 3, '', 0, 0, 'L');
            $pdf->Cell(25, 3, miscRound2Decim($intTotVAT), 0, 0, 'R');
            $pdf->Cell(25, 3, miscRound2Decim($intTotSumVAT), 0, 1, 'R');
            return;
        }
        ?>
    <tr>
			<td class="input total_sum">
            <?php 
        echo $GLOBALS['locTotal'];
        ?>
        </td>
			<td class="input total_sum" style="text-align: right">&nbsp;</td>
			<td class="input total_sum" style="text-align: right">&nbsp;</td>
			<td class="input total_sum" style="text-align: right">&nbsp;</td>
			<td class="input total_sum" style="text-align: right">
            <?php 
        echo miscRound2Decim($intTotSum);
        ?>
        </td>
			<td class="input total_sum" style="text-align: right">&nbsp;</td>
			<td class="input total_sum" style="text-align: right">
            <?php 
        echo miscRound2Decim($intTotVAT);
        ?>
        </td>
			<td class="input total_sum" style="text-align: right">
            <?php 
        echo miscRound2Decim($intTotSumVAT);
        ?>
        </td>
		</tr>
<?php 
    }
Example #8
0
function createJSONSelectList($strList, $startRow, $rowCount, $filter, $sort, $id = null)
{
    global $dblink;
    require "list_switch.php";
    if (!sesAccessLevel($levelsAllowed) && !sesAdminAccess()) {
        ?>
  <div class="form_container ui-widget-content">
    <?php 
        echo $GLOBALS['locNoAccess'] . "\n";
        ?>
  </div>
<?php 
        return;
    }
    if ($sort) {
        if (!preg_match('/^[\\w_,]+$/', $sort)) {
            header('HTTP/1.1 400 Bad Request');
            die('Invalid sort type');
        }
        $sortValid = 0;
        $sortFields = explode(',', $sort);
        foreach ($sortFields as $sortField) {
            foreach ($astrShowFields as $field) {
                if ($sortField === $field['name']) {
                    ++$sortValid;
                    break;
                }
            }
        }
        if ($sortValid != count($sortFields)) {
            header('HTTP/1.1 400 Bad Request');
            die('Invalid sort type');
        }
    } else {
        foreach ($astrShowFields as $field) {
            if ($field['name'] == 'order_no') {
                $sort = 'order_no';
            }
        }
    }
    $arrQueryParams = array();
    $strWhereClause = '';
    if (!getSetting('show_deleted_records') && empty($id)) {
        $strWhereClause = " WHERE {$strDeletedField}=0";
    }
    if ($strGroupBy) {
        $strGroupBy = " GROUP BY {$strGroupBy}";
    }
    // Add Filter
    if ($filter) {
        $strWhereClause .= ($strWhereClause ? ' AND ' : ' WHERE ') . createWhereClause($astrSearchFields, $filter, $arrQueryParams, !getSetting('dynamic_select_search_in_middle'));
    }
    // Filter out inactive companies
    if ($strList == 'company' || $strList == 'companies') {
        $strWhereClause .= ($strWhereClause ? ' AND ' : ' WHERE ') . 'inactive=0';
    }
    if ($id) {
        $strWhereClause .= ($strWhereClause ? ' AND ' : ' WHERE ') . 'id=' . mysqli_real_escape_string($dblink, $id);
    }
    // Build the final select clause
    $strSelectClause = "{$strPrimaryKey}, {$strDeletedField}";
    foreach ($astrShowFields as $field) {
        $strSelectClause .= ', ' . (isset($field['sql']) ? $field['sql'] : $field['name']);
    }
    $fullQuery = "SELECT {$strSelectClause} FROM {$strTable} {$strWhereClause}{$strGroupBy}";
    if ($sort) {
        $fullQuery .= " ORDER BY {$sort}";
    }
    if ($startRow >= 0 && $rowCount >= 0) {
        $fullQuery .= " LIMIT {$startRow}, " . ($rowCount + 1);
    }
    $res = mysqli_param_query($fullQuery, $arrQueryParams);
    $astrListValues = array();
    $i = -1;
    $moreAvailable = false;
    while ($row = mysqli_fetch_prefixed_assoc($res)) {
        ++$i;
        if ($startRow >= 0 && $rowCount >= 0 && $i >= $rowCount) {
            $moreAvailable = true;
            break;
        }
        $astrPrimaryKeys[$i] = $row[$strPrimaryKey];
        $aboolDeleted[$i] = $row[$strDeletedField];
        foreach ($astrShowFields as $field) {
            $name = $field['name'];
            if ($field['type'] == 'TEXT' || $field['type'] == 'INT') {
                $value = $row[$name];
                if (isset($field['mappings']) && isset($field['mappings'][$value])) {
                    $value = $field['mappings'][$value];
                }
                $astrListValues[$i][$name] = $value;
            } elseif ($field['type'] == 'CURRENCY') {
                $value = $row[$name];
                $value = miscRound2Decim($value, isset($field['decimals']) ? $field['decimals'] : 2);
                $astrListValues[$i][$name] = $value;
            } elseif ($field['type'] == 'INTDATE') {
                $astrListValues[$i][$name] = dateConvDBDate2Date($row[$name]);
            }
        }
    }
    $records = array();
    for ($i = 0; $i < count($astrListValues); $i++) {
        $row = $astrListValues[$i];
        $resultValues = array();
        foreach ($astrShowFields as $field) {
            if (!isset($field['select']) || !$field['select']) {
                continue;
            }
            $name = $field['name'];
            if (isset($field['translate']) && $field['translate'] && isset($GLOBALS["loc{$row[$name]}"])) {
                $value = $GLOBALS["loc{$row[$name]}"];
            } else {
                $value = htmlspecialchars($row[$name]);
            }
            $resultValues[$name] = $value;
        }
        $records[] = array('id' => $astrPrimaryKeys[$i], 'text' => implode(' ', $resultValues));
    }
    $results = array('moreAvailable' => $moreAvailable, 'records' => $records, 'filter' => $filter);
    return json_encode($results);
}
Example #9
0
function getInvoiceListTotal($where)
{
    global $dblink;
    $strFunc = 'invoices';
    $strList = 'invoice';
    require 'list_switch.php';
    $strWhereClause = '';
    $joinOp = 'WHERE';
    $arrQueryParams = [];
    if ($where) {
        // Validate and build query parameters
        $boolean = '';
        while (extractSearchTerm($where, $field, $operator, $term, $nextBool)) {
            if (strcasecmp($operator, 'IN') === 0) {
                $strWhereClause .= "{$boolean}{$field} {$operator} " . mysqli_real_escape_string($dblink, $term);
            } else {
                $strWhereClause .= "{$boolean}{$field} {$operator} ?";
                $arrQueryParams[] = str_replace('%-', '%', $term);
            }
            if (!$nextBool) {
                break;
            }
            $boolean = " {$nextBool}";
        }
        if ($strWhereClause) {
            $strWhereClause = "WHERE ({$strWhereClause})";
            $joinOp = ' AND';
        }
    }
    if (!getSetting('show_deleted_records')) {
        $strWhereClause .= "{$joinOp} {$strDeletedField}=0";
        $joinOp = ' AND';
    }
    $sql = "SELECT sum(it.row_total) as total_sum from {$strTable} {$strJoin} {$strWhereClause}";
    $sum = 0;
    $res = mysqli_param_query($sql, $arrQueryParams);
    if ($row = mysqli_fetch_assoc($res)) {
        $sum = $row['total_sum'];
    }
    $result = ['sum' => $sum, 'sum_str' => sprintf($GLOBALS['locInvoicesTotal'], miscRound2Decim($sum))];
    echo json_encode($result);
}
Example #10
0
 protected function _formatNumber($value, $decimals = 2, $decimalsOptional = false)
 {
     if ($decimalsOptional) {
         return miscRound2OptDecim($value, $decimals, $GLOBALS['locPDFDecimalSeparator'], $GLOBALS['locPDFThousandSeparator']);
     }
     return miscRound2Decim($value, $decimals, $GLOBALS['locPDFDecimalSeparator'], $GLOBALS['locPDFThousandSeparator']);
 }
Example #11
0
 protected function process_import_row($table, $row, $dupMode, $dupCheckColumns, $mode, &$addedRecordId)
 {
     if (!isset($row['date']) || !isset($row['amount']) || !isset($row['refnr'])) {
         return $GLOBALS['locImportStatementFieldMissing'];
     }
     $refnr = str_replace(' ', '', $row['refnr']);
     $refnr = ltrim($refnr, '0');
     $date = date('Ymd', DateTime::createFromFormat(getRequest('date_format', 'd.m.Y'), $row['date'])->getTimestamp());
     $amount = trim($row['amount']);
     if (substr($amount, 0, 1) == '-') {
         return;
     }
     if (substr($amount, 0, 1) == '+') {
         $amount = substr($amount, 1);
     }
     $sep = getRequest('decimal_separator', ',');
     if ($sep == ' ' || $sep == ',') {
         $amount = str_replace('.', '', $amount);
         $amount = str_replace($sep, '.', $amount);
     } elseif ($sep == '.') {
         $amount = str_replace(',', '', $amount);
     }
     $amount = floatval($amount);
     if ($row['refnr'] === '') {
         return $GLOBALS['locImportStatementFieldMissing'];
     }
     $intRes = mysqli_param_query('SELECT i.* FROM {prefix}invoice i' . ' WHERE i.Deleted=0 AND REPLACE(i.ref_number, " ", "") = ?', array($refnr));
     $count = mysqli_num_rows($intRes);
     if ($count == 0) {
         return str_replace('{refnr}', $refnr, $GLOBALS['locImportStatementInvoiceNotFound']);
     }
     if ($count > 1) {
         return str_replace('{refnr}', $refnr, $GLOBALS['locImportStatementMultipleInvoicesFound']);
     }
     $row = mysqli_fetch_assoc($intRes);
     if ($row['state_id'] == 3) {
         return str_replace('{refnr}', $refnr, $GLOBALS['locImportStatementInvoiceAlreadyPaid']);
     }
     $res2 = mysqli_param_query('SELECT ir.price, ir.pcs, ir.vat, ir.vat_included, ir.discount from {prefix}invoice_row ir where ir.deleted = 0 AND ir.invoice_id = ?', array($row['id']));
     $rowTotal = 0;
     while ($invoiceRow = mysqli_fetch_assoc($res2)) {
         list($rowSum, $rowVAT, $rowSumVAT) = calculateRowSum($invoiceRow['price'], $invoiceRow['pcs'], $invoiceRow['vat'], $invoiceRow['vat_included'], $invoiceRow['discount']);
         $rowTotal += $rowSumVAT;
     }
     if (miscRound2Decim($rowTotal) != miscRound2Decim($amount)) {
         $msg = str_replace('{statementAmount}', miscRound2Decim($amount), $GLOBALS['locImportStatementAmountMismatch']);
         $msg = str_replace('{invoiceAmount}', miscRound2Decim($rowTotal), $msg);
         $msg = str_replace('{refnr}', $refnr, $msg);
         return $msg;
     }
     if ($mode == 'import') {
         $sql = 'UPDATE {prefix}invoice SET state_id=3, payment_date=?';
         if (getSetting('invoice_auto_archive')) {
             $sql .= ', archived=1';
         }
         $sql .= ' WHERE id = ?';
         mysqli_param_query($sql, array($date, $row['id']));
     }
     $msg = str_replace('{amount}', miscRound2Decim($amount), $GLOBALS['locImportStatementInvoiceMarkedAsPaid']);
     $msg = str_replace('{id}', $row['id'], $msg);
     $msg = str_replace('{date}', dateConvDBDate2Date($date), $msg);
     $msg = str_replace('{refnr}', $refnr, $msg);
     return $msg;
 }
Example #12
0
    private function printTotals($format, $printFields, $intTotSum, $intTotVAT, $intTotSumVAT, $totalToPay, $totalsPerVAT)
    {
        if (!in_array('sums', $printFields)) {
            return;
        }
        if ($format == 'pdf' || $format == 'pdfl') {
            $pdf = $this->pdf;
            if ($pdf->getY() > $pdf->getPageHeight() - 7 - 15) {
                $pdf->AddPage();
            }
            $pdf->SetFont('Helvetica', '', 8);
            $pdf->setLineWidth(0.2);
            $rowWidth = 0;
            $sumPos = 75;
            if (in_array('invoice_no', $printFields)) {
                $rowWidth += 18;
            }
            if (in_array('invoice_date', $printFields)) {
                $rowWidth += 20;
            }
            if (in_array('due_date', $printFields)) {
                $rowWidth += 20;
            }
            if (in_array('payment_date', $printFields)) {
                $rowWidth += 20;
            }
            if (in_array('company_name', $printFields)) {
                $rowWidth += 40;
            }
            if (in_array('status', $printFields)) {
                $rowWidth += 15;
            }
            if (in_array('ref_number', $printFields)) {
                $rowWidth += 25;
            }
            $sumPos = $rowWidth;
            $rowWidth += 80;
            $pdf = $this->pdf;
            $pdf->SetFont('Helvetica', 'B', 8);
            $pdf->line($pdf->getX() + $sumPos, $pdf->getY(), $pdf->getX() + $rowWidth, $pdf->getY());
            $pdf->setY($pdf->getY() + 1);
            $pdf->Cell($sumPos, 4, $GLOBALS['locTotal'], 0, 0, 'R');
            $pdf->Cell(20, 4, miscRound2Decim($intTotSum), 0, 0, 'R');
            $pdf->Cell(20, 4, miscRound2Decim($intTotVAT), 0, 0, 'R');
            $pdf->Cell(20, 4, miscRound2Decim($intTotSumVAT), 0, 0, 'R');
            $pdf->Cell(20, 4, miscRound2Decim($totalToPay), 0, 1, 'R');
            if (in_array('vat_breakdown', $printFields)) {
                if ($pdf->getY() > $pdf->getPageHeight() - 30) {
                    $pdf->AddPage();
                } else {
                    $pdf->setY($pdf->getY() + 4);
                }
                $pdf->setY($pdf->getY() + 4);
                $pdf->Cell(15, 4, $GLOBALS['locVATBreakdown'], 0, 0, 'R');
                $pdf->Cell(25, 4, $GLOBALS['locVATLess'], 0, 0, 'R');
                $pdf->Cell(25, 4, $GLOBALS['locVATPart'], 0, 0, 'R');
                $pdf->Cell(25, 4, $GLOBALS['locWithVAT'], 0, 1, 'R');
                $pdf->SetFont('Helvetica', '', 8);
                foreach ($totalsPerVAT as $vat => $sums) {
                    $pdf->Cell(15, 4, miscRound2OptDecim($vat) . '%', 0, 0, 'R');
                    $pdf->Cell(25, 4, miscRound2Decim($sums['sum']), 0, 0, 'R');
                    $pdf->Cell(25, 4, miscRound2Decim($sums['VAT']), 0, 0, 'R');
                    $pdf->Cell(25, 4, miscRound2Decim($sums['sumVAT']), 0, 1, 'R');
                }
            }
            return;
        }
        $colSpan = 0;
        if (in_array('invoice_no', $printFields)) {
            ++$colSpan;
        }
        if (in_array('invoice_date', $printFields)) {
            ++$colSpan;
        }
        if (in_array('due_date', $printFields)) {
            ++$colSpan;
        }
        if (in_array('payment_date', $printFields)) {
            ++$colSpan;
        }
        if (in_array('company_name', $printFields)) {
            ++$colSpan;
        }
        if (in_array('status', $printFields)) {
            ++$colSpan;
        }
        if (in_array('ref_number', $printFields)) {
            ++$colSpan;
        }
        ?>
    <tr>
    <?php 
        if ($colSpan > 0) {
            ?>
        <td class="input total_sum" colspan="<?php 
            echo $colSpan;
            ?>
"
				style="text-align: right">
            <?php 
            echo $GLOBALS['locTotal'];
            ?>
        </td>
    <?php 
        }
        ?>
        <td class="input total_sum" style="text-align: right">
            &nbsp;<?php 
        echo miscRound2Decim($intTotSum);
        ?>
        </td>
        <td class="input total_sum" style="text-align: right">
            &nbsp;<?php 
        echo miscRound2Decim($intTotVAT);
        ?>
        </td>
        <td class="input total_sum" style="text-align: right">
            &nbsp;<?php 
        echo miscRound2Decim($intTotSumVAT);
        ?>
        </td>
        <td class="input total_sum" style="text-align: right">
            &nbsp;<?php 
        echo miscRound2Decim($totalToPay);
        ?>
        </td>
    </tr>
<?php 
        if (in_array('vat_breakdown', $printFields)) {
            ?>
    </table>
    <table>
        <tr>
            <th class="label" style="text-align: right"><?php 
            echo $GLOBALS['locVATBreakdown'];
            ?>
</th>
            <th class="label" style="text-align: right"><?php 
            echo $GLOBALS['locVATLess'];
            ?>
</th>
            <th class="label" style="text-align: right"><?php 
            echo $GLOBALS['locVATPart'];
            ?>
</th>
            <th class="label" style="text-align: right"><?php 
            echo $GLOBALS['locWithVAT'];
            ?>
</th>
        </tr>
<?php 
            foreach ($totalsPerVAT as $vat => $sums) {
                ?>
        <tr>
            <td class="input" style="text-align: right"><?php 
                echo miscRound2OptDecim($vat);
                ?>
%</td>
            <td class="input" style="text-align: right"><?php 
                echo miscRound2Decim($sums['sum']);
                ?>
</td>
            <td class="input" style="text-align: right"><?php 
                echo miscRound2Decim($sums['VAT']);
                ?>
</td>
            <td class="input" style="text-align: right"><?php 
                echo miscRound2Decim($sums['sumVAT']);
                ?>
</td>
        </tr>
<?php 
            }
        }
    }
Example #13
0
function createSettingsList()
{
    if (!sesAdminAccess()) {
        ?>
  <div class="form_container ui-widget-content">
    <?php 
        echo $GLOBALS['locNoAccess'] . "\n";
        ?>
  </div>
<?php 
        return;
    }
    require 'settings_def.php';
    $messages = '';
    $blnSave = getPostRequest('saveact', FALSE) ? TRUE : FALSE;
    if ($blnSave) {
        foreach ($arrSettings as $name => $elem) {
            $type = $elem['type'];
            $label = $elem['label'];
            if ($type == 'LABEL') {
                continue;
            }
            $newValue = getPost($name, NULL);
            if (!isset($newValue) || $newValue === '') {
                if (!$elem['allow_null']) {
                    $messages .= $GLOBALS['locErrValueMissing'] . ": '{$label}'<br>\n";
                    continue;
                } else {
                    $newValue = '';
                }
            }
            if (in_array($type, array('CURRENCY', 'PERCENT'))) {
                $newValue = str_replace($GLOBALS['locDecimalSeparator'], '.', $newValue);
            }
            if (in_array($type, array('CURRENCY', 'PERCENT', 'INT'))) {
                $newValue = trim($newValue);
                if (!is_numeric($newValue)) {
                    $messages .= $GLOBALS['locErrInvalidValue'] . " '{$label}'<br>\n";
                    continue;
                }
            }
            if (isset($elem['session']) && $elem['session']) {
                $_SESSION[$name] = $newValue;
            }
            mysqli_param_query('DELETE from {prefix}settings WHERE name=?', array($name));
            mysqli_param_query('INSERT INTO {prefix}settings (name, value) VALUES (?, ?)', array($name, $newValue));
        }
    }
    ?>
  <div class="form_container ui-widget-content">
<?php 
    if ($messages) {
        ?>
    <div class="ui-widget ui-state-error"><?php 
        echo $messages;
        ?>
</div>
<?php 
    }
    ?>

    <script type="text/javascript">
    <!--
    $(document).ready(function() {
      $('input[class~="hasCalendar"]').datepicker();
      $('iframe[class~="resizable"]').load(function() {
        var iframe = $(this);
        var body = iframe.contents().find("body");
        var newHeight = body.outerHeight(true) + 10;
        // Leave room for calendar popup
        if (newHeight < 250)
          newHeight = 250;
        iframe.css("height", newHeight + 'px');
        body.css("overflow", "hidden");
      });
      $('#admin_form').find('input[type="text"],input[type="checkbox"],select,textarea').change(function() { $('.save_button').addClass('unsaved'); });
    });
    -->
    </script>

    <?php 
    createSettingsListButtons();
    ?>
    <div class="form">
    <form method="post" name="admin_form" id="admin_form">
<?php 
    foreach ($arrSettings as $name => $elem) {
        $elemType = $elem['type'];
        if ($elemType == 'LABEL') {
            ?>
        <div class="sublabel ui-widget-header ui-state-default"><?php 
            echo $elem['label'];
            ?>
</div>
<?php 
            continue;
        }
        $value = getPost($name, NULL);
        if (!isset($value)) {
            if (isset($elem['session']) && $elem['session']) {
                $value = isset($_SESSION[$name]) ? $_SESSION[$name] : (isset($elem['default']) ? cond_utf8_decode($elem['default']) : '');
            } else {
                $res = mysqli_param_query('SELECT value from {prefix}settings WHERE name=?', array($name));
                if ($row = mysqli_fetch_assoc($res)) {
                    $value = $row['value'];
                } else {
                    $value = isset($elem['default']) ? cond_utf8_decode($elem['default']) : '';
                }
            }
            if ($elemType == 'CURRENCY') {
                $value = miscRound2Decim($value);
            } elseif ($elemType == 'PERCENT') {
                $value = miscRound2Decim($value, 1);
            }
        }
        if ($elemType == 'CURRENCY' || $elemType == 'PERCENT') {
            $elemType = 'INT';
        }
        if ($elemType == 'CHECK') {
            ?>
      <div class="field" style="clear: both">
        <?php 
            echo htmlFormElement($name, $elemType, $value, $elem['style'], '', "MODIFY", '', '', array(), isset($elem['elem_attributes']) ? $elem['elem_attributes'] : '', isset($elem['options']) ? $elem['options'] : null);
            ?>
        <label for="<?php 
            echo $name;
            ?>
"><?php 
            echo $elem['label'];
            ?>
</label>
      </div>
<?php 
        } else {
            ?>
      <div class="label" style="clear: both"><label for="<?php 
            echo $name;
            ?>
"><?php 
            echo $elem['label'];
            ?>
</label></div>
      <div class="field" style="clear: both">
        <?php 
            echo htmlFormElement($name, $elemType, $value, $elem['style'], '', "MODIFY", '', '', array(), isset($elem['elem_attributes']) ? $elem['elem_attributes'] : '', isset($elem['options']) ? $elem['options'] : null);
            ?>
      </div>
<?php 
        }
    }
    ?>
    <input type="hidden" name="saveact" value="0">
    <?php 
    createSettingsListButtons();
    ?>
    </form>
    </div>
  </div>
<?php 
}