Example #1
0
function createOpenInvoiceList()
{
    $currentDate = date('Ymd');
    $res = mysqli_query_check("select count(*) as cnt from {prefix}invoice i where i.deleted = 0 AND i.interval_type > 0 AND i.next_interval_date <= {$currentDate} AND i.archived = 0");
    $row = mysqli_fetch_assoc($res);
    if ($row['cnt'] > 0) {
        createList('open_invoices', 'invoice', 'resultlist_repeating_invoices', $GLOBALS['locLabelInvoicesWithIntervalDue'], "i.interval_type > 0 AND i.next_interval_date <= {$currentDate} AND i.archived = 0", true);
    }
    $open = '';
    $res = mysqli_query_check('SELECT id FROM {prefix}invoice_state WHERE invoice_open=1');
    while ($id = mysqli_fetch_value($res)) {
        if ($open) {
            $open .= ', ';
        }
        $open .= $id;
    }
    $unpaid = '';
    $res = mysqli_query_check('SELECT id FROM {prefix}invoice_state WHERE invoice_unpaid=1');
    while ($id = mysqli_fetch_value($res)) {
        if ($unpaid) {
            $unpaid .= ', ';
        }
        $unpaid .= $id;
    }
    if ($open) {
        createList('open_invoices', 'invoice', 'resultlist_open_invoices', $GLOBALS['locLabelOpenInvoices'], "i.state_id IN ({$open}) AND i.archived=0", true);
    }
    if ($unpaid) {
        createList('open_invoices', 'invoice', 'resultlist_unpaid_invoices', $GLOBALS['locLabelUnpaidInvoices'], "i.state_id IN ({$unpaid}) AND i.archived=0", true, true);
    }
}
Example #2
0
 private function printReport()
 {
     $intBaseId = getRequest('base', false);
     $intCompanyId = getRequest('company', false);
     $grouping = getRequest('grouping', '');
     $format = getRequest('format', 'html');
     $printFields = getRequest('fields', array());
     $rowTypes = getRequest('row_types', 'all');
     $dateRange = explode(' - ', getRequest('date', ''));
     $startDate = $dateRange[0];
     $endDate = isset($dateRange[1]) ? $dateRange[1] : $startDate;
     if ($startDate) {
         $startDate = dateConvDate2DBDate($startDate);
     }
     if ($endDate) {
         $endDate = dateConvDate2DBDate($endDate);
     }
     $rowDateRange = explode(' - ', getRequest('row_date', ''));
     $rowStartDate = $rowDateRange[0];
     $rowEndDate = isset($rowDateRange[1]) ? $rowDateRange[1] : $rowStartDate;
     if ($rowStartDate) {
         $rowStartDate = dateConvDate2DBDate($rowStartDate);
     }
     if ($rowEndDate) {
         $rowEndDate = dateConvDate2DBDate($rowEndDate);
     }
     $paymentDateRange = explode(' - ', getRequest('payment_date', ''));
     $paymentStartDate = $paymentDateRange[0];
     $paymentEndDate = isset($paymentDateRange[1]) ? $paymentDateRange[1] : '';
     if ($paymentStartDate) {
         $paymentStartDate = dateConvDate2DBDate($paymentStartDate);
     }
     if ($paymentEndDate) {
         $paymentEndDate = dateConvDate2DBDate($paymentEndDate);
     }
     $arrParams = array();
     $strQuery = "SELECT i.id, i.invoice_no, i.invoice_date, i.due_date, i.payment_date, i.ref_number, i.ref_number, c.company_name AS name, c.billing_address, ist.name as state " . "FROM {prefix}invoice i " . "LEFT OUTER JOIN {prefix}company c ON c.id = i.company_id " . "LEFT OUTER JOIN {prefix}invoice_state ist ON i.state_id = ist.id " . "WHERE i.deleted=0";
     if ($startDate) {
         $strQuery .= ' AND i.invoice_date >= ?';
         $arrParams[] = $startDate;
     }
     if ($endDate) {
         $strQuery .= ' AND i.invoice_date <= ?';
         $arrParams[] = $endDate;
     }
     if ($paymentStartDate) {
         $strQuery .= ' AND i.payment_date >= ?';
         $arrParams[] = $paymentStartDate;
     }
     if ($paymentEndDate) {
         $strQuery .= ' AND i.payment_date <= ?';
         $arrParams[] = $paymentEndDate;
     }
     if ($intBaseId) {
         $strQuery .= ' AND i.base_id = ?';
         $arrParams[] = $intBaseId;
     }
     if ($intCompanyId) {
         $strQuery .= ' AND i.company_id = ?';
         $arrParams[] = $intCompanyId;
     }
     $strQuery2 = '';
     $strQuery3 = "SELECT id, name " . "FROM {prefix}invoice_state WHERE deleted=0 " . "ORDER BY order_no";
     $intRes = mysqli_query_check($strQuery3);
     while ($row = mysqli_fetch_assoc($intRes)) {
         $intStateId = $row['id'];
         $strStateName = $row['name'];
         $strTemp = "stateid_{$intStateId}";
         $tmpSelected = getRequest($strTemp, false);
         if ($tmpSelected) {
             $strQuery2 .= 'i.state_id = ? OR ';
             $arrParams[] = $intStateId;
         }
     }
     if ($strQuery2) {
         $strQuery2 = ' AND (' . substr($strQuery2, 0, -4) . ')';
     }
     $strQuery .= "{$strQuery2} ORDER BY ";
     switch ($grouping) {
         case 'state':
             $strQuery .= "state_id, invoice_date, invoice_no";
             break;
         case 'client':
             $strQuery .= "name, invoice_date, invoice_no";
             break;
         default:
             $strQuery .= "invoice_date, invoice_no";
     }
     $this->printHeader($format, $printFields, $startDate, $endDate);
     $intTotSum = 0;
     $intTotVAT = 0;
     $intTotSumVAT = 0;
     $currentGroup = false;
     $groupTotSum = 0;
     $groupTotVAT = 0;
     $groupTotSumVAT = 0;
     $intRes = mysqli_param_query($strQuery, $arrParams);
     while ($row = mysqli_fetch_assoc($intRes)) {
         switch ($grouping) {
             case 'state':
                 $invoiceGroup = $row['state'];
                 break;
             case 'month':
                 $invoiceGroup = substr($row['invoice_date'], 4, 2);
                 break;
             case 'client':
                 $invoiceGroup = $row['name'];
                 break;
             default:
                 $invoiceGroup = false;
         }
         $rowParams = array($row['id']);
         $strQuery = "SELECT ir.description, ir.pcs, ir.price, ir.discount, ir.row_date, ir.vat, ir.vat_included " . "FROM {prefix}invoice_row ir " . "WHERE ir.invoice_id=? AND ir.deleted=0";
         if ($rowStartDate) {
             $strQuery .= ' AND ir.row_date >= ?';
             $rowParams[] = $rowStartDate;
         }
         if ($rowEndDate) {
             $strQuery .= ' AND ir.row_date <= ?';
             $rowParams[] = $rowEndDate;
         }
         if ($rowTypes != 'all') {
             if ($rowTypes == 'normal') {
                 $strQuery .= ' AND ir.reminder_row = 0';
             } else {
                 if ($rowTypes == 'reminder') {
                     $strQuery .= ' AND ir.reminder_row in (1, 2)';
                 }
             }
         }
         $intRes2 = mysqli_param_query($strQuery, $rowParams);
         $intRowSum = 0;
         $intRowVAT = 0;
         $intRowSumVAT = 0;
         $rows = false;
         while ($row2 = mysqli_fetch_assoc($intRes2)) {
             $rows = true;
             list($intSum, $intVAT, $intSumVAT) = calculateRowSum($row2['price'], $row2['pcs'], $row2['vat'], $row2['vat_included'], $row2['discount']);
             $intRowSum += $intSum;
             $intRowVAT += $intVAT;
             $intRowSumVAT += $intSumVAT;
             $intTotSum += $intSum;
             $intTotVAT += $intVAT;
             $intTotSumVAT += $intSumVAT;
         }
         if (!$rows) {
             continue;
         }
         if ($grouping && $currentGroup !== false && $currentGroup != $invoiceGroup) {
             $this->printGroupSums($format, $printFields, $row, $groupTotSum, $groupTotVAT, $groupTotSumVAT);
             $groupTotSum = 0;
             $groupTotVAT = 0;
             $groupTotSumVAT = 0;
         }
         $currentGroup = $invoiceGroup;
         $groupTotSum += $intRowSum;
         $groupTotVAT += $intRowVAT;
         $groupTotSumVAT += $intRowSumVAT;
         $this->printRow($format, $printFields, $row, $intRowSum, $intRowVAT, $intRowSumVAT);
     }
     if ($grouping) {
         $this->printGroupSums($format, $printFields, $row, $groupTotSum, $groupTotVAT, $groupTotSumVAT);
     }
     $this->printTotals($format, $printFields, $intTotSum, $intTotVAT, $intTotSumVAT);
     $this->printFooter($format, $printFields);
 }
Example #3
0
function createIForm($astrFormElements, $elem, $intKeyValue, $newRecord, $strForm)
{
    ?>
      <div class="iform <?php 
    echo $elem['style'];
    ?>
 ui-corner-tl ui-corner-bl ui-corner-br ui-corner-tr ui-helper-clearfix" id="<?php 
    echo $elem['name'];
    ?>
"<?php 
    echo $elem['elem_attributes'] ? ' ' . $elem['elem_attributes'] : '';
    ?>
>
        <div class="ui-corner-tl ui-corner-tr fg-toolbar ui-toolbar ui-widget-header"><?php 
    echo $elem['label'];
    ?>
</div>
<?php 
    if ($newRecord) {
        ?>
        <div id="inewmessage" class="new_message"><?php 
        echo $GLOBALS['locSaveRecordToAddRows'];
        ?>
</div>
      </div>
<?php 
        return;
    }
    ?>
<script type="text/javascript">
/* <![CDATA[ */

function format_currency(value, decimals)
{
  var s = parseFloat(value).toFixed(decimals).replace('.', '<?php 
    echo $GLOBALS['locDecimalSeparator'];
    ?>
');
<?php 
    if ($GLOBALS['locThousandSeparator']) {
        ?>
  var parts = s.split('<?php 
        echo $GLOBALS['locDecimalSeparator'];
        ?>
');
  var regexp = /(\d+)(\d{3})<?php 
        echo $GLOBALS['locDecimalSeparator'];
        ?>
?/;
	while (regexp.test(parts[0])) {
		parts[0] = parts[0].replace(regexp, '$1' + '<?php 
        echo $GLOBALS['locThousandSeparator'];
        ?>
' + '$2');
	}
	s = parts[0];
	if (parts.length > 1) {
		s += '<?php 
        echo $GLOBALS['locDecimalSeparator'];
        ?>
' + parts[1];
	}
<?php 
    }
    ?>
  return s;
}

function round_number(num, dec)
{
  return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}

function init_rows()
{
<?php 
    $subFormElements = getFormElements($elem['name']);
    $rowSumColumns = getFormRowSumColumns($elem['name']);
    $strParentKey = getFormParentKey($elem['name']);
    $clearRowValuesAfterAdd = getFormClearRowValuesAfterAdd($elem['name']);
    $onAfterRowAdded = getFormOnAfterRowAdded($elem['name']);
    $formJSONType = getFormJSONType($elem['name']);
    foreach ($subFormElements as $subElem) {
        if ($subElem['type'] != 'LIST') {
            continue;
        }
        echo '  var arr_' . $subElem['name'] . ' = {"0":"-"';
        $res = mysqli_query_check($subElem['listquery']);
        $translate = strstr($subElem['style'], ' translated');
        while ($row = mysqli_fetch_row($res)) {
            if ($translate && isset($GLOBALS["loc{$row[1]}"])) {
                $row[1] = $GLOBALS["loc{$row[1]}"];
            }
            echo ',' . $row[0] . ':"' . addcslashes($row[1], '\\"\\/') . '"';
        }
        echo "};\n";
    }
    ?>
  $.getJSON('json.php?func=get_<?php 
    echo $elem['name'];
    ?>
&parent_id=<?php 
    echo $intKeyValue;
    ?>
', function(json) {
    $('#itable > tbody > tr[id!=form_row]').remove();
    var table = document.getElementById('itable');
    for (var i = 0; i < json.records.length; i++)
    {
      var record = json.records[i];
      var tr = $('<tr/>');
<?php 
    foreach ($subFormElements as $subElem) {
        if (in_array($subElem['type'], array('HID_INT', 'SECHID_INT', 'BUTTON', 'NEWLINE'))) {
            continue;
        }
        $name = $subElem['name'];
        $class = $subElem['style'];
        if ($subElem['type'] == 'LIST' || $subElem['type'] == 'SEARCHLIST') {
            echo "      if (record.{$name} == null) record.{$name} = 0; \$('<td/>').addClass('{$class}' + (record.deleted == 1 ? ' deleted' : '')).text(record.{$name}_text).appendTo(tr);\n";
        } elseif ($subElem['type'] == 'INT') {
            if (isset($subElem['decimals'])) {
                echo "      \$('<td/>').addClass('{$class}' + (record.deleted == 1 ? ' deleted' : '')).text(record.{$name} ? format_currency(record.{$name}, {$subElem['decimals']}) : '').appendTo(tr);\n";
            } else {
                echo "      \$('<td/>').addClass('{$class}' + (record.deleted == 1 ? ' deleted' : '')).text(record.{$name} ? record.{$name}.replace('.', '{$GLOBALS['locDecimalSeparator']}') : '').appendTo(tr);\n";
            }
        } elseif ($subElem['type'] == 'INTDATE') {
            echo "      \$('<td/>').addClass('{$class}' + (record.deleted == 1 ? ' deleted' : '')).text(record.{$name}.substr(6, 2) + '.' + record.{$name}.substr(4, 2) + '.' + record.{$name}.substr(0, 4)).appendTo(tr);\n";
        } elseif ($subElem['type'] == 'CHECK') {
            echo "      \$('<td/>').addClass('{$class}' + (record.deleted == 1 ? ' deleted' : '')).text(record.{$name} == 1 ? \"" . $GLOBALS['locYesButton'] . '" : "' . $GLOBALS['locNoButton'] . "\").appendTo(tr);\n";
        } elseif ($subElem['type'] == 'ROWSUM') {
            ?>
      var items = record.<?php 
            echo $rowSumColumns['multiplier'];
            ?>
;
      var price = record.<?php 
            echo $rowSumColumns['price'];
            ?>
;
      var discount = record.<?php 
            echo $rowSumColumns['discount'];
            ?>
 || 0;
      var VATPercent = record.<?php 
            echo $rowSumColumns['vat'];
            ?>
;
      var VATIncluded = record.<?php 
            echo $rowSumColumns['vat_included'];
            ?>
;

      price *= (1 - discount / 100);
      var sum = 0;
      var sumVAT = 0;
      var VAT = 0;
      if (VATIncluded == 1)
      {
        sumVAT = round_number(items * price, 2);
        sum = round_number(sumVAT / (1 + VATPercent / 100), 2);
        VAT = sumVAT - sum;
      }
      else
      {
        sum = round_number(items * price, 2);
        VAT = round_number(sum * (VATPercent / 100), 2);
        sumVAT = sum + VAT;
      }
      sum = format_currency(sum, <?php 
            echo isset($subElem['decimals']) ? $subElem['decimals'] : 2;
            ?>
);
      VAT = format_currency(VAT, <?php 
            echo isset($subElem['decimals']) ? $subElem['decimals'] : 2;
            ?>
);
      sumVAT = format_currency(sumVAT, <?php 
            echo isset($subElem['decimals']) ? $subElem['decimals'] : 2;
            ?>
);
      var title = '<?php 
            echo $GLOBALS['locVATLess'] . ': ';
            ?>
' + sum + ' &ndash; ' + '<?php 
            echo $GLOBALS['locVATPart'] . ': ';
            ?>
' + VAT;
      $('<td/>').addClass('<?php 
            echo $class;
            ?>
' + (record.deleted == 1 ? ' deleted' : '')).append('<span title="' + title + '">' + sumVAT + '<\/span>').appendTo(tr);
<?php 
        } else {
            echo "      \$('<td/>').addClass('{$class}' + (record.deleted == 1 ? ' deleted' : '')).text(record.{$name} ? record.{$name} : '').appendTo(tr);\n";
        }
    }
    if (sesWriteAccess()) {
        ?>
      $('<td/>').addClass('button').append('<a class="tinyactionlink row_edit_button rec' + record.id + '" href="#"><?php 
        echo $GLOBALS['locEdit'];
        ?>
<\/a>').appendTo(tr);
      $('<td/>').addClass('button').append('<a class="tinyactionlink row_copy_button rec' + record.id + '" href="#"><?php 
        echo $GLOBALS['locCopy'];
        ?>
<\/a>').appendTo(tr);
<?php 
    }
    ?>
      $(table).append(tr);
    }
<?php 
    if (isset($rowSumColumns['show_summary']) && $rowSumColumns['show_summary']) {
        ?>
    var totSum = 0;
    var totVAT = 0;
    var totSumVAT = 0;
    for (var i = 0; i < json.records.length; i++)
    {
      var record = json.records[i];

      var items = record.<?php 
        echo $rowSumColumns['multiplier'];
        ?>
;
      var price = record.<?php 
        echo $rowSumColumns['price'];
        ?>
;
      var discount = record.<?php 
        echo $rowSumColumns['discount'];
        ?>
 || 0;
      var VATPercent = record.<?php 
        echo $rowSumColumns['vat'];
        ?>
;
      var VATIncluded = record.<?php 
        echo $rowSumColumns['vat_included'];
        ?>
;

      price *= (1 - discount / 100);
      var sum = 0;
      var sumVAT = 0;
      var VAT = 0;
      if (VATIncluded == 1)
      {
        sumVAT = round_number(items * price, 2);
        sum = round_number(sumVAT / (1 + VATPercent / 100), 2);
        VAT = sumVAT - sum;
      }
      else
      {
        sum = round_number(items * price, 2);
        VAT = round_number(sum * (VATPercent / 100), 2);
        sumVAT = sum + VAT;
      }

      totSum += sum;
      totVAT += VAT;
      totSumVAT += sumVAT;
    }
    var tr = $('<tr/>').addClass('summary');
    $('<td/>').addClass('input').attr('colspan', '10').attr('align', 'right').text('<?php 
        echo $GLOBALS['locTotalExcludingVAT'];
        ?>
').appendTo(tr);
    $('<td/>').addClass('input').attr('align', 'right').text(format_currency(totSum, 2)).appendTo(tr);
    $(table).append(tr);

    tr = $('<tr/>').addClass('summary');
    $('<td/>').addClass('input').attr('colspan', '10').attr('align', 'right').text('<?php 
        echo $GLOBALS['locTotalVAT'];
        ?>
').appendTo(tr);
    $('<td/>').addClass('input').attr('align', 'right').text(format_currency(totVAT, 2)).appendTo(tr);
    $(table).append(tr);

    var tr = $('<tr/>').addClass('summary');
    $('<td/>').addClass('input').attr('colspan', '10').attr('align', 'right').text('<?php 
        echo $GLOBALS['locTotalIncludingVAT'];
        ?>
').appendTo(tr);
    $('<td/>').addClass('input').attr('align', 'right').text(format_currency(totSumVAT, 2)).appendTo(tr);
    $(table).append(tr);

<?php 
    }
    ?>
    $('a[class~="row_edit_button"]').click(function(event) {
      var row_id = $(this).attr('class').match(/rec(\d+)/)[1];
      popup_editor(event, '<?php 
    echo $GLOBALS['locRowModification'];
    ?>
', row_id, false);
      return false;
    });

    $('a[class~="row_copy_button"]').click(function(event) {
      var row_id = $(this).attr('class').match(/rec(\d+)/)[1];
      popup_editor(event, '<?php 
    echo $GLOBALS['locRowCopy'];
    ?>
', row_id, true);
      return false;
    });

    $('a[class~="tinyactionlink"]').button();

    init_rows_done();
  });
}
<?php 
    if (sesWriteAccess()) {
        ?>
function save_row(form_id)
{
  var form = document.getElementById(form_id);
  var obj = new Object();
<?php 
        foreach ($subFormElements as $subElem) {
            if (!in_array($subElem['type'], array('HID_INT', 'SECHID_INT', 'BUTTON', 'NEWLINE', 'ROWSUM', 'CHECK', 'INT'))) {
                ?>
  obj.<?php 
                echo $subElem['name'];
                ?>
 = document.getElementById(form_id + '_<?php 
                echo $subElem['name'];
                ?>
').value;
<?php 
            } elseif ($subElem['type'] == 'CHECK') {
                ?>
  obj.<?php 
                echo $subElem['name'];
                ?>
 = document.getElementById(form_id + '_<?php 
                echo $subElem['name'];
                ?>
').checked ? 1 : 0;
<?php 
            } elseif ($subElem['type'] == 'INT') {
                ?>
  obj.<?php 
                echo $subElem['name'];
                ?>
 = document.getElementById(form_id + '_<?php 
                echo $subElem['name'];
                ?>
').value.replace('<?php 
                echo $GLOBALS['locDecimalSeparator'];
                ?>
', '.');
<?php 
            }
        }
        ?>
  obj.<?php 
        echo $elem['parent_key'] . " = {$intKeyValue}";
        ?>
;
  if (form.row_id)
    obj.id = form.row_id.value;
  $.ajax({
    'url': "json.php?func=put_<?php 
        echo $formJSONType;
        ?>
",
    'type': 'POST',
    'dataType': 'json',
    'data': $.toJSON(obj),
    'contentType': 'application/json; charset=utf-8',
    'success': function(data) {
      if (data.missing_fields)
      {
        errormsg('<?php 
        echo $GLOBALS['locErrValueMissing'];
        ?>
: ' + data.missing_fields);
      }
      else
      {
        if (form_id == 'iform')
          $('.add_row_button').removeClass('ui-state-highlight');
        init_rows();
        if (form_id == 'iform_popup')
          $("#popup_edit").dialog('close');
        if (!obj.id)
        {
          <?php 
        echo $onAfterRowAdded;
        foreach ($subFormElements as $subElem) {
            if (!in_array($subElem['type'], array('HID_INT', 'SECHID_INT', 'BUTTON', 'NEWLINE', 'ROWSUM'))) {
                if (isset($subElem['default']) && strstr($subElem['default'], 'ADD')) {
                    // The value is taken from whatever form was used but put into iform
                    ?>
          var fld = document.getElementById(form_id + '_<?php 
                    echo $subElem['name'];
                    ?>
');
          document.getElementById('iform_<?php 
                    echo $subElem['name'];
                    ?>
').value = parseInt(fld.value) + 5;
<?php 
                } elseif ($clearRowValuesAfterAdd && $subElem['type'] != 'INTDATE') {
                    if ($subElem['type'] == 'LIST' || $subElem['type'] == 'SEARCHLIST') {
                        ?>
          document.getElementById('iform_<?php 
                        echo $subElem['name'];
                        ?>
').selectedIndex = 0;
<?php 
                    } elseif ($subElem['type'] == 'CHECK') {
                        ?>
          document.getElementById('iform_<?php 
                        echo $subElem['name'];
                        ?>
').checked = 0;
<?php 
                    } else {
                        ?>
          document.getElementById('iform_<?php 
                        echo $subElem['name'];
                        ?>
').value = '';
<?php 
                    }
                }
            }
        }
        ?>
        }
      }
    },
    'error': function(XMLHTTPReq, textStatus, errorThrown) {
      if (textStatus == 'timeout')
        alert('Timeout trying to save row');
      else
        alert('Error trying to save row: ' + XMLHTTPReq.status + ' - ' + XMLHTTPReq.statusText);
      return false;
    }
  });
}

function update_row_dates(id)
{
  var buttons = new Object();
  buttons["<?php 
        echo $GLOBALS['locUpdateRowDates'];
        ?>
"] = function() {
    var date = $("#popup_date_edit_field").val();
    if (date == '') {
      alert('<?php 
        echo $GLOBALS['locErrValueMissing'];
        ?>
');
      return;
    }
    var params = {
      func: 'update_invoice_row_dates',
      id: <?php 
        echo $intKeyValue;
        ?>
,
      date: date
    };
    $.ajax({
      'url': 'json.php',
      'data': params,
      'type': 'GET',
      'dataType': 'json',
      'contentType': 'application/json; charset=utf-8',
      'success': function(data) {
        if (data.status != 'ok') {
          alert(data.errors);
        } else {
          $("#popup_date_edit").dialog('close');
          init_rows();
        }
      },
      'error': function(XMLHTTPReq, textStatus, errorThrown) {
        if (textStatus == 'timeout')
          errormsg('Timeout trying to update row dates');
        else
          errormsg('Error trying to update row dates: ' + XMLHTTPReq.status + ' - ' + XMLHTTPReq.statusText);
        return false;
      }
    });
  };
  buttons["<?php 
        echo $GLOBALS['locClose'];
        ?>
"] = function() { $("#popup_date_edit").dialog('close'); };
  $("#popup_date_edit").dialog({ modal: true, width: 420, height: 120, resizable: false,
    buttons: buttons,
    title: '<?php 
        echo $GLOBALS['locUpdateAllRowDates'];
        ?>
'
  });

}

function delete_row(form_id)
{
  var form = document.getElementById(form_id);
  var id = form.row_id.value;
  $.ajax({
    'url': "json.php?func=delete_<?php 
        echo $formJSONType;
        ?>
&id=" + id,
    'type': 'GET',
    'dataType': 'json',
    'contentType': 'application/json; charset=utf-8',
    'success': function(data) {
      init_rows();
      if (form_id == 'iform_popup')
        $("#popup_edit").dialog('close');
    },
    'error': function(XMLHTTPReq, textStatus, errorThrown) {
      if (textStatus == 'timeout')
        errormsg('Timeout trying to save row');
      else
        errormsg('Error trying to save row: ' + XMLHTTPReq.status + ' - ' + XMLHTTPReq.statusText);
      return false;
    }
  });
}

function popup_editor(event, title, id, copy_row)
{
  $.getJSON('json.php?func=get_<?php 
        echo $formJSONType;
        ?>
&id=' + id, function(json) {
    if (!json.id) return;
    var form = document.getElementById('iform_popup');

    if (copy_row)
      form.row_id.value = '';
    else
      form.row_id.value = id;
<?php 
        foreach ($subFormElements as $subElem) {
            if (in_array($subElem['type'], array('HID_INT', 'SECHID_INT', 'BUTTON', 'NEWLINE', 'ROWSUM'))) {
                continue;
            }
            $name = $subElem['name'];
            if ($subElem['type'] == 'SEARCHLIST') {
                ?>
    var item = {
      id: json.<?php 
                echo $name;
                ?>
,
      text: json.<?php 
                echo $name;
                ?>
_text
    };
    $('#<?php 
                echo "iform_popup_{$name}";
                ?>
').select2('data', item);
<?php 
            } elseif ($subElem['type'] == 'LIST') {
                ?>
    for (var i = 0; i < form.<?php 
                echo "iform_popup_{$name}";
                ?>
.options.length; i++)
    {
      var item = form.<?php 
                echo "iform_popup_{$name}";
                ?>
.options[i];
      if (item.value == json.<?php 
                echo $name;
                ?>
)
      {
        item.selected = true;
        break;
      }
    }
<?php 
            } elseif ($subElem['type'] == 'INT') {
                if (isset($subElem['default']) && strstr($subElem['default'], 'ADD')) {
                    ?>
    var value;
    if (copy_row)
      value = document.getElementById('<?php 
                    echo "iform_{$name}";
                    ?>
').value;
    else
      value = json.<?php 
                    echo $name;
                    ?>
 ? json.<?php 
                    echo $name;
                    ?>
.replace('.', '<?php 
                    $GLOBALS['locDecimalSeparator'];
                    ?>
') : '';
    form.<?php 
                    echo "iform_popup_{$name}";
                    ?>
.value = value;
<?php 
                } else {
                    if (isset($subElem['decimals'])) {
                        ?>
    form.<?php 
                        echo "iform_popup_{$name}";
                        ?>
.value = json.<?php 
                        echo $name;
                        ?>
 ? format_currency(json.<?php 
                        echo $name;
                        ?>
, <?php 
                        echo $subElem['decimals'];
                        ?>
) : '';
<?php 
                    } else {
                        ?>
    form.<?php 
                        echo "iform_popup_{$name}";
                        ?>
.value = json.<?php 
                        echo $name;
                        ?>
 ? json.<?php 
                        echo $name;
                        ?>
.replace('.', '<?php 
                        echo $GLOBALS['locDecimalSeparator'];
                        ?>
') : '';
<?php 
                    }
                }
            } elseif ($subElem['type'] == 'INTDATE') {
                ?>
    form.<?php 
                echo "iform_popup_{$name}";
                ?>
.value = json.<?php 
                echo $name;
                ?>
 ? json.<?php 
                echo $name;
                ?>
.substr(6, 2) + '.' + json.<?php 
                echo $name;
                ?>
.substr(4, 2) + '.' + json.<?php 
                echo $name;
                ?>
.substr(0, 4) : '';
<?php 
            } elseif ($subElem['type'] == 'CHECK') {
                ?>
    form.<?php 
                echo "iform_popup_{$name}";
                ?>
.checked = json.<?php 
                echo $name;
                ?>
 != 0 ? true : false;
<?php 
            } else {
                ?>
    form.<?php 
                echo "iform_popup_{$name}";
                ?>
.value = json.<?php 
                echo $name;
                ?>
;
<?php 
            }
        }
        ?>
    var buttons = new Object();
    buttons["<?php 
        echo $GLOBALS['locSave'];
        ?>
"] = function() { save_row('iform_popup'); };
    if (!copy_row)
      buttons["<?php 
        echo $GLOBALS['locDelete'];
        ?>
"] = function() { if(confirm('<?php 
        echo $GLOBALS['locConfirmDelete'];
        ?>
')==true) { delete_row('iform_popup'); } return false; };
    buttons["<?php 
        echo $GLOBALS['locClose'];
        ?>
"] = function() { $("#popup_edit").dialog('close'); };
    $("#popup_edit").dialog({ modal: true, width: 840, height: 150, resizable: false,
      buttons: buttons,
      title: title,
    });

  });
}
<?php 
    }
    ?>
/* ]]> */
</script>
        <form method="post" name="iform" id="iform">
        <table class="iform" id="itable">
          <thead>
            <tr>
<?php 
    foreach ($subFormElements as $subElem) {
        if (!in_array($subElem['type'], array('HID_INT', 'SECHID_INT', 'BUTTON', 'NEWLINE'))) {
            ?>
              <th class="label ui-state-default <?php 
            echo strtolower($subElem['style']);
            ?>
_label"><?php 
            echo $subElem['label'];
            ?>
</th>
<?php 
        }
    }
    ?>
            </tr>
          </thead>
          <tbody>
<?php 
    if (sesWriteAccess()) {
        ?>
            <tr id="form_row">
<?php 
        foreach ($subFormElements as $subElem) {
            if (!in_array($subElem['type'], array('HID_INT', 'SECHID_INT', 'BUTTON', 'NEWLINE', 'ROWSUM'))) {
                $value = getFormDefaultValue($subElem, $intKeyValue);
                ?>
              <td class="label <?php 
                echo strtolower($subElem['style']);
                ?>
_label">
                <?php 
                echo htmlFormElement('iform_' . $subElem['name'], $subElem['type'], $value, $subElem['style'], $subElem['listquery'], 'MODIFY', 0, '', array(), $subElem['elem_attributes']);
                ?>
              </td>
<?php 
            } elseif ($subElem['type'] == 'ROWSUM') {
                ?>
              <td class="label <?php 
                echo strtolower($subElem['style']);
                ?>
_label">
                &nbsp;
              </td>
<?php 
            }
        }
        if ($strForm == 'invoice') {
            ?>
              <td class="button">
                <a class="tinyactionlink add_row_button" href="#" onclick="save_row('iform'); return false;"><?php 
            echo $GLOBALS['locAddRow'];
            ?>
</a>
              </td>
              <td class="button">
                <a class="tinyactionlink update_row_dates" href="#" onclick="update_row_dates(); return false;"><?php 
            echo $GLOBALS['locUpdateRowDates'];
            ?>
</a>
              </td>
<?php 
        } else {
            ?>
              <td class="button" colspan="2">
                <a class="tinyactionlink add_row_button" href="#" onclick="save_row('iform'); return false;"><?php 
            echo $GLOBALS['locAddRow'];
            ?>
</a>
              </td>
<?php 
        }
        ?>
            </tr>
          </tbody>
        </table>
        </form>
      </div>
      <div id="popup_edit" style="display: none; width: 900px; overflow: hidden">
        <form method="post" name="iform_popup" id="iform_popup">
        <input type="hidden" name="row_id" value="">
        <input type="hidden" name="<?php 
        echo $strParentKey;
        ?>
" value="<?php 
        echo $intKeyValue;
        ?>
">
        <table class="iform">
          <tr>
<?php 
        foreach ($subFormElements as $elem) {
            if (!in_array($elem['type'], array('HID_INT', 'SECHID_INT', 'BUTTON', 'NEWLINE', 'ROWSUM'))) {
                ?>
            <td class="label <?php 
                echo strtolower($elem['style']);
                ?>
_label">
              <?php 
                echo $elem['label'];
                ?>
<br>
              <?php 
                echo htmlFormElement('iform_popup_' . $elem['name'], $elem['type'], '', $elem['style'], $elem['listquery'], 'MODIFY', 0, '', array(), $elem['elem_attributes']);
                ?>
            </td>
<?php 
            } elseif ($elem['type'] == 'SECHID_INT') {
                ?>
            <input type="hidden" name="<?php 
                echo 'iform_popup_' . $elem['name'];
                ?>
" value="<?php 
                echo gpcStripSlashes($astrValues[$elem['name']]);
                ?>
">
<?php 
            } elseif ($elem['type'] == 'BUTTON') {
                ?>
            <td class="label">
              &nbsp;
            </td>
<?php 
            }
        }
    }
    ?>
          </tr>
        </table>
        </form>
      </div>
      <div id="popup_date_edit" style="display: none; width: 300px; overflow: hidden">
        <form method="post" name="form_date_popup" id="form_date_popup">
          <input id="popup_date_edit_field" type="text" class="medium hasCalendar">
        </form>
      </div>
<?php 
}
Example #4
0
function htmlFormElement($strName, $strType, $strValue, $strStyle, $strListQuery, $strMode = 'MODIFY', $strParentKey = NULL, $strTitle = "", $astrDefaults = array(), $astrAdditionalAttributes = '', $options = NULL)
{
    if ($astrAdditionalAttributes) {
        $astrAdditionalAttributes = " {$astrAdditionalAttributes}";
    }
    $strFormElement = '';
    $readOnly = $strMode == 'MODIFY' ? '' : ' readonly="readonly"';
    $disabled = $strMode == 'MODIFY' ? '' : ' disabled="disabled"';
    switch ($strType) {
        case 'TEXT':
            if (strstr($strStyle, 'hasDateRangePicker')) {
                $autocomplete = ' autocomplete="off"';
            } else {
                $autocomplete = '';
            }
            $strFormElement = "<input type=\"text\" class=\"{$strStyle}\"{$autocomplete} " . "id=\"{$strName}\" name=\"{$strName}\" value=\"" . htmlspecialchars($strValue) . "\"{$astrAdditionalAttributes}{$readOnly}>\n";
            break;
        case 'PASSWD':
            $strFormElement = "<input type=\"password\" class=\"{$strStyle}\" " . "id=\"{$strName}\" name=\"{$strName}\" value=\"\"{$astrAdditionalAttributes}{$readOnly}>\n";
            break;
        case 'CHECK':
            $strValue = $strValue ? 'checked' : '';
            $strFormElement = "<input type=\"checkbox\" id=\"{$strName}\" name=\"{$strName}\" value=\"1\" " . htmlspecialchars($strValue) . "{$astrAdditionalAttributes}{$disabled}>\n";
            break;
        case 'RADIO':
            $strChecked = $strValue ? 'checked' : '';
            $strFormElement = "<input type=\"radio\" id=\"{$strName}\" name=\"{$strName}\" value=\"" . htmlspecialchars($strValue) . "\"{$astrAdditionalAttributes}{$disabled}>\n";
            break;
        case 'INT':
            $hideZero = FALSE;
            if (strstr($strStyle, ' hidezerovalue')) {
                $strStyle = str_replace(' hidezerovalue', '', $strStyle);
                $hideZero = TRUE;
            }
            if ($hideZero && $strValue == 0) {
                $strValue = '';
            }
            $strFormElement = "<input type=\"text\" class=\"{$strStyle}\" " . "id=\"{$strName}\" name=\"{$strName}\" value=\"" . htmlspecialchars($strValue) . "\"{$astrAdditionalAttributes}{$readOnly}>\n";
            break;
        case 'INTDATE':
            $strFormElement = "<input type=\"text\" class=\"{$strStyle} hasCalendar\" " . "id=\"{$strName}\" name=\"{$strName}\" value=\"" . htmlspecialchars($strValue) . "\"{$astrAdditionalAttributes}{$readOnly}>\n";
            break;
        case 'HID_INT':
            $strFormElement = "<input type=\"hidden\" " . "id=\"{$strName}\" name=\"{$strName}\" value=\"" . htmlspecialchars($strValue) . "\">\n";
            break;
        case 'AREA':
            $strFormElement = "<textarea rows=\"24\" cols=\"80\" class=\"" . $strStyle . "\" " . "id=\"" . $strName . "\" name=\"" . $strName . "\"{$astrAdditionalAttributes}{$readOnly}>" . $strValue . "</textarea>\n";
            break;
        case 'RESULT':
            $strListQuery = str_replace("_ID_", $strValue, $strListQuery);
            $strFormElement = htmlspecialchars(mysqli_fetch_value(mysqli_query_check($strListQuery))) . "\n";
            break;
        case 'LIST':
            $translate = false;
            if (strstr($strStyle, ' translated')) {
                $translate = true;
                $strStyle = str_replace(' translated', '', $strStyle);
            }
            if ($strMode == "MODIFY") {
                $strFormElement = htmlSQLListBox($strName, $strListQuery, $strValue, $strStyle, false, $astrAdditionalAttributes, $translate);
            } else {
                $strFormElement = "<input type=\"text\" class=\"{$strStyle}\" " . "id=\"{$strName}\" name=\"{$strName}\" value=\"" . htmlspecialchars(getSQLListBoxSelectedValue($strListQuery, $strValue, $translate)) . "\"{$astrAdditionalAttributes}{$readOnly}>\n";
            }
            break;
        case 'SEARCHLIST':
            if ($strMode == "MODIFY") {
                $showEmpty = <<<EOT
      if (page == 1 && data.filter == '') {
        records.unshift({id: '', text: '-'});
      }

EOT;
                if (strstr($strStyle, ' noemptyvalue')) {
                    $strStyle = str_replace(' noemptyvalue', '', $strStyle);
                    $showEmpty = '';
                }
                $strValue = htmlspecialchars($strValue);
                $onchange = $astrAdditionalAttributes ? ".on(\"change\", {$astrAdditionalAttributes})" : '';
                $strFormElement = <<<EOT
<input type="hidden" class="{$strStyle}" id="{$strName}" name="{$strName}" value="{$strValue}"/>
<script type="text/javascript">
\$(document).ready(function() {
  \$("#{$strName}").select2({
    placeholder: "",
    ajax: {
      url: "json.php?func=get_selectlist&{$strListQuery}",
      dataType: 'json',
      quietMillis: 200,
      data: function (term, page) { // page is the one-based page number tracked by Select2
        return {
          q: term, //search term
          pagelen: 50, // page size
          page: page, // page number
        };
      },
      results: function (data, page) {
        var records = data.records;
  {$showEmpty}
        return {results: records, more: data.moreAvailable};
      }
    },
    initSelection: function(element, callback) {
      var id = \$(element).val();
      if (id !== "") {
        \$.ajax("json.php?func=get_selectlist&{$strListQuery}&id=" + id, {
          dataType: "json"
        }).done(function(data) { callback(data.records[0]); });
      }
    },
    dropdownCssClass: "bigdrop",
    dropdownAutoWidth: true,
    escapeMarkup: function (m) { return m; },
    width: "element"
  }){$onchange}
});
</script>
EOT;
            } else {
                $strFormElement = "<input type=\"text\" class=\"{$strStyle}\" " . "id=\"{$strName}\" name=\"{$strName}\" value=\"" . htmlspecialchars(getSQLListBoxSelectedValue($strListQuery, $strValue, $translate)) . "\"{$astrAdditionalAttributes}{$readOnly}>\n";
            }
            break;
        case 'SELECT':
            $translate = false;
            if (strstr($strStyle, ' translated')) {
                $translate = true;
                $strStyle = str_replace(' translated', '', $strStyle);
            }
            if ($strMode == "MODIFY") {
                $strFormElement = htmlListBox($strName, $options, $strValue, $strStyle, false, $astrAdditionalAttributes, $translate);
            } else {
                $strFormElement = "<input type=\"text\" class=\"{$strStyle}\" " . "id=\"{$strName}\" name=\"{$strName}\" value=\"" . htmlspecialchars(getListBoxSelectedValue($options, $strValue, $translate)) . "\"{$astrAdditionalAttributes}{$readOnly}>\n";
            }
            break;
        case 'BUTTON':
            $strListQuery = str_replace("_ID_", $strValue, $strListQuery);
            switch ($strStyle) {
                case 'custom':
                    $strListQuery = str_replace("'", "", $strListQuery);
                    $strHref = $strListQuery;
                    $strOnClick = "";
                    break;
                case 'redirect':
                    $strHref = "#";
                    $strOnClick = "onclick=\"save_record('{$strListQuery}', 'redirect'); return false;\"";
                    break;
                case 'openwindow':
                    $strHref = "#";
                    $strOnClick = "onclick=\"save_record('{$strListQuery}', 'openwindow'); return false;\"";
                    break;
                default:
                    switch ($strStyle) {
                        case 'tiny':
                            $strHW = "height=1,width=1,";
                            break;
                        case 'small':
                            $strHW = "height=200,width=200,";
                            break;
                        case 'medium':
                            $strHW = "height=400,width=400,";
                            break;
                        case 'large':
                            $strHW = "height=600,width=600,";
                            break;
                        case 'xlarge':
                            $strHW = "height=800,width=650,";
                            break;
                        case 'full':
                            $strHW = "";
                            break;
                        default:
                            $strHW = "";
                            break;
                    }
                    $strHref = "#";
                    $strOnClick = "onclick=\"window.open(" . $strListQuery . ",'" . $strHW . "menubar=no,scrollbars=no," . "status=no,toolbar=no'); return false;\"";
                    break;
            }
            $strFormElement = "<a class=\"formbuttonlink\" href=\"{$strHref}\" {$strOnClick}{$astrAdditionalAttributes}>" . htmlspecialchars($strTitle) . "</a>\n";
            break;
        case 'JSBUTTON':
            if (strstr($strListQuery, '_ID_') && !$strValue) {
                $strFormElement = $GLOBALS['locSaveFirst'];
            } else {
                if ($strValue) {
                    $strListQuery = str_replace('_ID_', $strValue, $strListQuery);
                }
                $strOnClick = "onClick=\"{$strListQuery}\"";
                $strFormElement = "<a class=\"formbuttonlink\" href=\"#\" {$strOnClick}{$astrAdditionalAttributes}>" . htmlspecialchars($strTitle) . "</a>\n";
            }
            break;
        case 'IMAGE':
            $strListQuery = str_replace("_ID_", $strValue, $strListQuery);
            $strFormElement = "<img class=\"{$strStyle}\" src=\"{$strListQuery}\" title=\"" . htmlspecialchars($strTitle) . "\"></div>\n";
            break;
        default:
            $strFormElement = "&nbsp;\n";
    }
    return $strFormElement;
}
Example #5
0
        $strQuery = 'SELECT * ' . 'FROM {prefix}invoice_row ' . 'WHERE deleted=0 AND invoice_id=?';
        $intRes = mysqli_param_query($strQuery, [$intInvoiceId], 'exception');
        while ($row = mysqli_fetch_assoc($intRes)) {
            if ($boolRefund) {
                $row['pcs'] = -$row['pcs'];
            } else {
                if ($row['reminder_row']) {
                    continue;
                }
            }
            unset($row['id']);
            $row['invoice_id'] = $intNewId;
            if (getSetting('invoice_update_row_dates_on_copy')) {
                $row['row_date'] = $newRowDate;
            }
            // Update product stock balance
            if ($row['product_id'] !== null) {
                updateProductStockBalance(null, $row['product_id'], $row['pcs']);
            }
            $strQuery = 'INSERT INTO {prefix}invoice_row(' . implode(', ', array_keys($row)) . ') ' . 'VALUES (' . str_repeat('?, ', count($row) - 1) . '?)';
            mysqli_param_query($strQuery, $row, 'exception');
        }
    } catch (Exception $e) {
        mysqli_query_check('ROLLBACK');
        mysqli_query_check('SET AUTOCOMMIT = 1');
        die($e->message);
    }
    mysqli_query_check('COMMIT');
    mysqli_query_check('SET AUTOCOMMIT = 1');
}
header('Location: ' . _PROTOCOL_ . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/index.php?func={$strFunc}&list={$strList}&form=invoice&id={$intNewId}");
Example #6
0
 private function printReport()
 {
     $intStateID = getRequest('stateid', FALSE);
     $intBaseId = getRequest('base', FALSE);
     $intCompanyId = getRequest('company', FALSE);
     $intProductId = getRequest('product', FALSE);
     $format = getRequest('format', 'html');
     $dateRange = explode(' - ', getRequest('date', ''));
     $startDate = $dateRange[0];
     $endDate = isset($dateRange[1]) ? $dateRange[1] : $startDate;
     if ($startDate) {
         $startDate = dateConvDate2DBDate($startDate);
     }
     if ($endDate) {
         $endDate = dateConvDate2DBDate($endDate);
     }
     $arrParams = [];
     $strQuery = 'SELECT i.id ' . 'FROM {prefix}invoice i ' . 'WHERE i.deleted=0';
     if ($startDate) {
         $strQuery .= ' AND i.invoice_date >= ?';
         $arrParams[] = $startDate;
     }
     if ($endDate) {
         $strQuery .= ' AND i.invoice_date <= ?';
         $arrParams[] = $endDate;
     }
     if ($intBaseId) {
         $strQuery .= ' AND i.base_id = ?';
         $arrParams[] = $intBaseId;
     }
     if ($intCompanyId) {
         $strQuery .= ' AND i.company_id = ?';
         $arrParams[] = $intCompanyId;
     }
     $strQuery2 = '';
     $strQuery3 = 'SELECT id, name ' . 'FROM {prefix}invoice_state WHERE deleted=0 ' . 'ORDER BY order_no';
     $intRes = mysqli_query_check($strQuery3);
     while ($row = mysqli_fetch_assoc($intRes)) {
         $intStateId = $row['id'];
         $strStateName = $row['name'];
         $strTemp = "stateid_{$intStateId}";
         $tmpSelected = getRequest($strTemp, FALSE) ? TRUE : FALSE;
         if ($tmpSelected) {
             $strQuery2 .= ' i.state_id = ? OR ';
             $arrParams[] = $intStateId;
         }
     }
     if ($strQuery2) {
         $strQuery2 = ' AND (' . substr($strQuery2, 0, -3) . ')';
     }
     $strQuery .= "{$strQuery2} ORDER BY invoice_no";
     if ($intProductId) {
         $strProductWhere = 'AND ir.product_id = ? ';
         $arrParams[] = $intProductId;
     } else {
         $strProductWhere = '';
     }
     $strProductQuery = 'SELECT p.id, p.product_code, p.product_name, ir.description, ' . 'ir.vat, ir.pcs, t.name as unit, ir.price, ir.vat_included, ir.discount ' . 'FROM {prefix}invoice_row ir ' . 'LEFT OUTER JOIN {prefix}product p ON p.id = ir.product_id ' . 'LEFT OUTER JOIN {prefix}row_type t ON t.id = ir.type_id ' . "WHERE ir.deleted = 0 AND ir.partial_payment = 0 AND ir.invoice_id IN ({$strQuery}) {$strProductWhere}" . 'ORDER BY p.id, ir.description, t.name, ir.vat';
     $this->printHeader($format, $startDate, $endDate);
     $totalSum = 0;
     $totalVAT = 0;
     $totalSumVAT = 0;
     $prevRow = false;
     $productCount = 0;
     $productSum = 0;
     $productVAT = 0;
     $productSumVAT = 0;
     $intRes = mysqli_param_query($strProductQuery, $arrParams);
     while ($row = mysqli_fetch_assoc($intRes)) {
         if ($prevRow !== false && ($prevRow['id'] != $row['id'] || $prevRow['description'] != $row['description'] || $prevRow['unit'] != $row['unit'] || $prevRow['vat'] != $row['vat'])) {
             $this->printRow($format, $prevRow['product_code'], $prevRow['product_name'], $prevRow['description'], $productCount, $prevRow['unit'], $productSum, $prevRow['vat'], $productVAT, $productSumVAT);
             $productCount = 0;
             $productSum = 0;
             $productVAT = 0;
             $productSumVAT = 0;
         }
         $prevRow = $row;
         $productCount += $row['pcs'];
         list($rowSum, $rowVAT, $rowSumVAT) = calculateRowSum($row['price'], $row['pcs'], $row['vat'], $row['vat_included'], $row['discount']);
         $productSum += $rowSum;
         $productVAT += $rowVAT;
         $productSumVAT += $rowSumVAT;
         $totalSum += $rowSum;
         $totalVAT += $rowVAT;
         $totalSumVAT += $rowSumVAT;
     }
     if ($prevRow !== false) {
         $this->printRow($format, $prevRow['product_code'], $prevRow['product_name'], $prevRow['description'], $productCount, $prevRow['unit'], $productSum, $prevRow['vat'], $productVAT, $productSumVAT);
     }
     $this->printTotals($format, $totalSum, $totalVAT, $totalSumVAT);
     $this->printFooter($format);
 }
Example #7
0
function saveFormData($table, &$primaryKey, &$formElements, &$values, &$warnings, $parentKeyName = '', $parentKey = FALSE)
{
    global $dblink;
    $missingValues = '';
    $strFields = '';
    $strInsert = '';
    $strUpdateFields = '';
    $arrValues = [];
    if (!isset($primaryKey) || !$primaryKey) {
        unset($values['id']);
    }
    foreach ($formElements as $elem) {
        $type = $elem['type'];
        if (in_array($type, ['', 'IFORM', 'RESULT', 'BUTTON', 'JSBUTTON', 'IMAGE', 'ROWSUM', 'NEWLINE', 'LABEL']) || isset($elem['read_only']) && $elem['read_only']) {
            continue;
        }
        $name = $elem['name'];
        if (!$elem['allow_null'] && (!isset($values[$name]) || $values[$name] === '')) {
            if ($missingValues) {
                $missingValues .= ', ';
            }
            $missingValues .= $elem['label'];
            continue;
        }
        $value = isset($values[$name]) ? $values[$name] : getFormDefaultValue($elem, $parentKey);
        if ($type == 'PASSWD' && !$value) {
            continue;
        }
        // Don't save empty password
        if (isset($elem['unique']) && $elem['unique']) {
            $query = "SELECT * FROM {$table} WHERE deleted=0 AND {$name}=?";
            $params = [$value];
            if (isset($primaryKey) && $primaryKey) {
                $query .= ' AND id!=?';
                $params[] = $primaryKey;
            }
            $res = mysqli_param_query($query, $params);
            if (mysqli_fetch_array($res)) {
                $warnings = sprintf($GLOBALS['locDuplicateValue'], $elem['label']);
                return false;
            }
        }
        if ($strFields) {
            $strFields .= ', ';
            $strInsert .= ', ';
            $strUpdateFields .= ', ';
        }
        $strFields .= $name;
        $fieldPlaceholder = '?';
        switch ($type) {
            case 'PASSWD':
                $fieldPlaceholder = 'md5(?)';
                $arrValues[] = $values[$name];
                break;
            case 'INT':
            case 'HID_INT':
            case 'SECHID_INT':
                $arrValues[] = $value !== '' && $value !== false ? str_replace(',', '.', $value) : ($elem['allow_null'] ? NULL : 0);
                break;
            case 'LIST':
            case 'SEARCHLIST':
                $arrValues[] = isset($values[$name]) ? $value !== '' ? str_replace(',', '.', $value) : NULL : NULL;
                break;
            case 'CHECK':
                $arrValues[] = $value ? 1 : 0;
                break;
            case 'INTDATE':
                $arrValues[] = $value ? dateConvDate2DBDate($value) : NULL;
                break;
            default:
                $arrValues[] = $value;
        }
        $strInsert .= $fieldPlaceholder;
        $strUpdateFields .= "{$name}={$fieldPlaceholder}";
    }
    if ($missingValues) {
        return $missingValues;
    }
    mysqli_query_check('SET AUTOCOMMIT = 0');
    mysqli_query_check('BEGIN');
    try {
        // Special case for invoice rows - update product stock balance
        if ($table == '{prefix}invoice_row') {
            updateProductStockBalance(isset($primaryKey) ? $primaryKey : null, isset($values['product_id']) ? $values['product_id'] : null, $values['pcs']);
        }
        if (!isset($primaryKey) || !$primaryKey) {
            if ($parentKeyName) {
                $strFields .= ", {$parentKeyName}";
                $strInsert .= ', ?';
                $arrValues[] = $parentKey;
            }
            $strQuery = "INSERT INTO {$table} ({$strFields}) VALUES ({$strInsert})";
            mysqli_param_query($strQuery, $arrValues, 'exception');
            $primaryKey = mysqli_insert_id($dblink);
        } else {
            // Special case for invoice - update product stock balance for all
            // invoice rows if the invoice was previously deleted
            if ($table == '{prefix}invoice') {
                $res = mysqli_param_query('SELECT deleted FROM {prefix}invoice WHERE id=?', [$primaryKey]);
                if (mysqli_fetch_value($res)) {
                    $res = mysqli_param_query('SELECT product_id, pcs FROM {prefix}invoice_row WHERE invoice_id=? AND deleted=0', [$primaryKey]);
                    while ($row = mysqli_fetch_assoc($res)) {
                        updateProductStockBalance(null, $row['product_id'], $row['pcs']);
                    }
                }
            }
            $strQuery = "UPDATE {$table} SET {$strUpdateFields}, deleted=0 WHERE id=?";
            $arrValues[] = $primaryKey;
            mysqli_param_query($strQuery, $arrValues, 'exception');
        }
    } catch (Exception $e) {
        mysqli_query_check('ROLLBACK');
        mysqli_query_check('SET AUTOCOMMIT = 1');
        die($e->getMessage());
    }
    mysqli_query_check('COMMIT');
    mysqli_query_check('SET AUTOCOMMIT = 1');
    // Special case for invoices - check for duplicate invoice numbers
    if ($table == '{prefix}invoice' && isset($values['invoice_no']) && $values['invoice_no']) {
        $query = 'SELECT ID FROM {prefix}invoice where deleted=0 AND id!=? AND invoice_no=?';
        $params = [$primaryKey, $values['invoice_no']];
        if (getSetting('invoice_numbering_per_base')) {
            $query .= ' AND base_id=?';
            $params[] = $values['base_id'];
        }
        if (getSetting('invoice_numbering_per_year')) {
            $query .= ' AND invoice_date >= ' . date('Y') . '0101';
        }
        $res = mysqli_param_query($query, $params);
        if (mysqli_fetch_assoc($res)) {
            $warnings = $GLOBALS['locInvoiceNumberAlreadyInUse'];
        }
    }
    return TRUE;
}
Example #8
0
 protected function get_field_defs($table)
 {
     if (!$this->table_valid($table)) {
         return array();
     }
     $res = mysqli_query_check("show fields from {prefix}{$table}");
     $field_defs = array();
     while ($row = mysqli_fetch_assoc($res)) {
         $field_defs[$row['Field']] = $row;
     }
     return $field_defs;
 }
Example #9
0
/**
 * Verify database status and upgrade as necessary.
 * Expects all pre-1.6.0 changes to have been already made.
 *
 * @return string status (OK|UPGRADED|FAILED)
 */
function verifyDatabase()
{
    $res = mysqli_query_check("SHOW TABLES LIKE '{prefix}state'");
    if (mysqli_num_rows($res) == 0) {
        $res = mysqli_query_check(<<<EOT
CREATE TABLE {prefix}state (
  id char(32) NOT NULL,
  data varchar(100) NULL,
  PRIMARY KEY (id)
) ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_swedish_ci;
EOT
, true);
        if ($res === false) {
            return 'FAILED';
        }
        mysqli_query_check("REPLACE INTO {prefix}state (id, data) VALUES ('version', '15')");
    }
    // Convert any MyISAM tables to InnoDB
    $res = mysqli_param_query('SELECT data FROM {prefix}state WHERE id=?', ['tableconversiondone']);
    if (mysqli_num_rows($res) == 0) {
        mysqli_query_check('SET AUTOCOMMIT = 0');
        mysqli_query_check('BEGIN');
        mysqli_query_check('SET FOREIGN_KEY_CHECKS = 0');
        $res = mysqli_query_check("SHOW TABLE STATUS WHERE ENGINE='MyISAM'");
        while ($row = mysqli_fetch_array($res)) {
            $res2 = mysqli_query_check('ALTER TABLE `' . $row['Name'] . '` ENGINE=INNODB', true);
            if ($res2 === false) {
                mysqli_query_check('ROLLBACK');
                mysqli_query_check('SET FOREIGN_KEY_CHECKS = 1');
                error_log('Database upgrade query failed. Please convert the tables using MyISAM engine to InnoDB engine manually');
                return 'FAILED';
            }
        }
        mysqli_query_check("INSERT INTO {prefix}state (id, data) VALUES ('tableconversiondone', '1')");
        mysqli_query_check('COMMIT');
        mysqli_query_check('SET AUTOCOMMIT = 1');
        mysqli_query_check('SET FOREIGN_KEY_CHECKS = 1');
    }
    $res = mysqli_param_query('SELECT data FROM {prefix}state WHERE id=?', ['version']);
    $version = mysqli_fetch_value($res);
    $updates = [];
    if ($version < 16) {
        $updates = array_merge($updates, ['ALTER TABLE {prefix}invoice ADD CONSTRAINT FOREIGN KEY (base_id) REFERENCES {prefix}base(id)', 'ALTER TABLE {prefix}invoice ADD COLUMN interval_type int(11) NOT NULL default 0', 'ALTER TABLE {prefix}invoice ADD COLUMN next_interval_date int(11) default NULL', "REPLACE INTO {prefix}state (id, data) VALUES ('version', '16')"]);
    }
    if ($version < 17) {
        $updates = array_merge($updates, ['ALTER TABLE {prefix}invoice_state CHANGE COLUMN name name varchar(255)', "UPDATE {prefix}invoice_state set name='StateOpen' where id=1", "UPDATE {prefix}invoice_state set name='StateSent' where id=2", "UPDATE {prefix}invoice_state set name='StatePaid' where id=3", "UPDATE {prefix}invoice_state set name='StateAnnulled' where id=4", "UPDATE {prefix}invoice_state set name='StateFirstReminder' where id=5", "UPDATE {prefix}invoice_state set name='StateSecondReminder' where id=6", "UPDATE {prefix}invoice_state set name='StateDebtCollection' where id=7", "UPDATE {prefix}print_template set name='PrintInvoiceFinnish' where name='Lasku'", "UPDATE {prefix}print_template set name='PrintDispatchNoteFinnish' where name='Lähetysluettelo'", "UPDATE {prefix}print_template set name='PrintReceiptFinnish' where name='Kuitti'", "UPDATE {prefix}print_template set name='PrintEmailFinnish' where name='Email'", "UPDATE {prefix}print_template set name='PrintInvoiceEnglish' where name='Invoice'", "UPDATE {prefix}print_template set name='PrintReceiptEnglish' where name='Receipt'", "UPDATE {prefix}print_template set name='PrintFinvoice' where name='Finvoice'", "UPDATE {prefix}print_template set name='PrintFinvoiceStyled' where name='Finvoice Styled'", "UPDATE {prefix}print_template set name='PrintInvoiceFinnishWithVirtualBarcode' where name='Lasku virtuaaliviivakoodilla'", "UPDATE {prefix}print_template set name='PrintInvoiceFinnishFormless' where name='Lomakkeeton lasku'", "INSERT INTO {prefix}print_template (name, filename, parameters, output_filename, type, order_no, inactive) VALUES ('PrintInvoiceEnglishWithVirtualBarcode', 'invoice_printer.php', 'invoice,en,Y', 'invoice_%d.pdf', 'invoice', 70, 1)", "INSERT INTO {prefix}print_template (name, filename, parameters, output_filename, type, order_no, inactive) VALUES ('PrintInvoiceEnglishFormless', 'invoice_printer_formless.php', 'invoice,en,N', 'invoice_%d.pdf', 'invoice', 80, 1)", 'ALTER TABLE {prefix}row_type CHANGE COLUMN name name varchar(255)', "UPDATE {prefix}row_type set name='TypeHour' where name='h'", "UPDATE {prefix}row_type set name='TypeDay' where name='pv'", "UPDATE {prefix}row_type set name='TypeMonth' where name='kk'", "UPDATE {prefix}row_type set name='TypePieces' where name='kpl'", "UPDATE {prefix}row_type set name='TypeYear' where name='vuosi'", "UPDATE {prefix}row_type set name='TypeLot' where name='erä'", "UPDATE {prefix}row_type set name='TypeKilometer' where name='km'", "UPDATE {prefix}row_type set name='TypeKilogram' where name='kg'", "REPLACE INTO {prefix}state (id, data) VALUES ('version', '17')"]);
    }
    if ($version < 18) {
        $updates = array_merge($updates, ['ALTER TABLE {prefix}base ADD COLUMN country varchar(255) default NULL', 'ALTER TABLE {prefix}company ADD COLUMN country varchar(255) default NULL', "REPLACE INTO {prefix}state (id, data) VALUES ('version', '18')"]);
    }
    if ($version < 19) {
        $updates = array_merge($updates, ["UPDATE {prefix}session_type set name='SessionTypeUser' where name='Käyttäjä'", "UPDATE {prefix}session_type set name='SessionTypeAdmin' where name='Ylläpitäjä'", "UPDATE {prefix}session_type set name='SessionTypeBackupUser' where name='Käyttäjä - varmuuskopioija'", "UPDATE {prefix}session_type set name='SessionTypeReadOnly' where name='Vain laskujen ja raporttien tarkastelu'", "REPLACE INTO {prefix}state (id, data) VALUES ('version', '19')"]);
    }
    if ($version < 20) {
        $updates = array_merge($updates, ['ALTER TABLE {prefix}product CHANGE COLUMN unit_price unit_price decimal(15,5)', 'ALTER TABLE {prefix}invoice_row CHANGE COLUMN price price decimal(15,5)', 'ALTER TABLE {prefix}product CHANGE COLUMN discount discount decimal(4,1) NULL', 'ALTER TABLE {prefix}invoice_row CHANGE COLUMN discount discount decimal(4,1) NULL', "REPLACE INTO {prefix}state (id, data) VALUES ('version', '20')"]);
    }
    if ($version < 21) {
        $updates = array_merge($updates, ["INSERT INTO {prefix}print_template (name, filename, parameters, output_filename, type, order_no, inactive) VALUES ('PrintInvoiceSwedish', 'invoice_printer.php', 'invoice,sv-FI,Y', 'faktura_%d.pdf', 'invoice', 90, 1)", "INSERT INTO {prefix}print_template (name, filename, parameters, output_filename, type, order_no, inactive) VALUES ('PrintInvoiceSwedishFormless', 'invoice_printer_formless.php', 'invoice,sv-FI,N', 'faktura_%d.pdf', 'invoice', 100, 1)", "REPLACE INTO {prefix}state (id, data) VALUES ('version', '21')"]);
    }
    if ($version < 22) {
        $updates = array_merge($updates, ["INSERT INTO {prefix}print_template (name, filename, parameters, output_filename, type, order_no, inactive) VALUES ('PrintEmailReceiptFinnish', 'invoice_printer_email.php', 'receipt', 'kuitti_%d.pdf', 'invoice', 110, 1)", "INSERT INTO {prefix}print_template (name, filename, parameters, output_filename, type, order_no, inactive) VALUES ('PrintEmailReceiptSwedish', 'invoice_printer_email.php', 'receipt,sv-FI', 'kvitto_%d.pdf', 'invoice', 120, 1)", "INSERT INTO {prefix}print_template (name, filename, parameters, output_filename, type, order_no, inactive) VALUES ('PrintEmailReceiptEnglish', 'invoice_printer_email.php', 'receipt,en', 'receipt_%d.pdf', 'invoice', 130, 1)", "REPLACE INTO {prefix}state (id, data) VALUES ('version', '22')"]);
    }
    if ($version < 23) {
        $updates = array_merge($updates, ['ALTER TABLE {prefix}product ADD COLUMN order_no int(11) default NULL', 'ALTER TABLE {prefix}users CHANGE COLUMN name name varchar(255)', 'ALTER TABLE {prefix}users CHANGE COLUMN login login varchar(255)', "REPLACE INTO {prefix}state (id, data) VALUES ('version', '23')"]);
    }
    if ($version < 24) {
        $updates = array_merge($updates, ["INSERT INTO {prefix}print_template (name, filename, parameters, output_filename, type, order_no, inactive) VALUES ('PrintOrderConfirmationFinnish', 'invoice_printer_order_confirmation.php', 'receipt', 'tilausvahvistus_%d.pdf', 'invoice', 140, 1)", "INSERT INTO {prefix}print_template (name, filename, parameters, output_filename, type, order_no, inactive) VALUES ('PrintOrderConfirmationSwedish', 'invoice_printer_order_confirmation.php', 'receipt,sv-FI', 'orderbekraftelse_%d.pdf', 'invoice', 150, 1)", "INSERT INTO {prefix}print_template (name, filename, parameters, output_filename, type, order_no, inactive) VALUES ('PrintOrderConfirmationEnglish', 'invoice_printer_order_confirmation.php', 'receipt,en', 'order_confirmation_%d.pdf', 'invoice', 160, 1)", "REPLACE INTO {prefix}state (id, data) VALUES ('version', '24')"]);
    }
    if ($version < 25) {
        $updates = array_merge($updates, [<<<EOT
CREATE TABLE {prefix}delivery_terms (
  id int(11) NOT NULL auto_increment,
  deleted tinyint NOT NULL default 0,
  name varchar(255) default NULL,
  order_no int(11) default NULL,
  PRIMARY KEY (id)
) ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_swedish_ci
EOT
, <<<EOT
CREATE TABLE {prefix}delivery_method (
  id int(11) NOT NULL auto_increment,
  deleted tinyint NOT NULL default 0,
  name varchar(255) default NULL,
  order_no int(11) default NULL,
  PRIMARY KEY (id)
) ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_swedish_ci
EOT
, 'ALTER TABLE {prefix}invoice ADD COLUMN delivery_terms_id int(11) default NULL', 'ALTER TABLE {prefix}invoice ADD CONSTRAINT FOREIGN KEY (delivery_terms_id) REFERENCES {prefix}delivery_terms(id)', 'ALTER TABLE {prefix}invoice ADD COLUMN delivery_method_id int(11) default NULL', 'ALTER TABLE {prefix}invoice ADD CONSTRAINT FOREIGN KEY (delivery_method_id) REFERENCES {prefix}delivery_method(id)', 'ALTER TABLE {prefix}company ADD COLUMN delivery_terms_id int(11) default NULL', 'ALTER TABLE {prefix}company ADD CONSTRAINT FOREIGN KEY (delivery_terms_id) REFERENCES {prefix}delivery_terms(id)', 'ALTER TABLE {prefix}company ADD COLUMN delivery_method_id int(11) default NULL', 'ALTER TABLE {prefix}company ADD CONSTRAINT FOREIGN KEY (delivery_method_id) REFERENCES {prefix}delivery_method(id)', "REPLACE INTO {prefix}state (id, data) VALUES ('version', '25')"]);
    }
    if ($version < 26) {
        $updates = array_merge($updates, ['CREATE INDEX {prefix}company_name on {prefix}company(company_name)', 'CREATE INDEX {prefix}company_id on {prefix}company(company_id)', 'CREATE INDEX {prefix}company_deleted on {prefix}company(deleted)', 'CREATE INDEX {prefix}invoice_no on {prefix}invoice(invoice_no)', 'CREATE INDEX {prefix}invoice_ref_number on {prefix}invoice(ref_number)', 'CREATE INDEX {prefix}invoice_name on {prefix}invoice(name)', 'CREATE INDEX {prefix}invoice_deleted on {prefix}invoice(deleted)', 'CREATE INDEX {prefix}base_name on {prefix}base(name)', 'CREATE INDEX {prefix}base_deleted on {prefix}base(deleted)', 'CREATE INDEX {prefix}product_name on {prefix}product(product_name)', 'CREATE INDEX {prefix}product_code on {prefix}product(product_code)', 'CREATE INDEX {prefix}product_deleted on {prefix}product(deleted)', 'CREATE INDEX {prefix}product_order_no_deleted on {prefix}product(order_no, deleted)', 'CREATE INDEX {prefix}users_name on {prefix}users(name)', 'CREATE INDEX {prefix}users_deleted on {prefix}users(deleted)', "REPLACE INTO {prefix}state (id, data) VALUES ('version', '26')"]);
    }
    if ($version < 27) {
        $updates = array_merge($updates, ["INSERT INTO {prefix}invoice_state (name, order_no) VALUES ('StatePaidInCash', 17)", "REPLACE INTO {prefix}state (id, data) VALUES ('version', '27')"]);
    }
    if ($version < 28) {
        $updates = array_merge($updates, ["INSERT INTO {prefix}print_template (name, filename, parameters, output_filename, type, order_no, inactive) VALUES ('PrintOrderConfirmationEmailFinnish', 'invoice_printer_order_confirmation_email.php', 'receipt', 'tilausvahvistus_%d.pdf', 'invoice', 170, 1)", "INSERT INTO {prefix}print_template (name, filename, parameters, output_filename, type, order_no, inactive) VALUES ('PrintOrderConfirmationEmailSwedish', 'invoice_printer_order_confirmation_email.php', 'receipt,sv-FI', 'orderbekraftelse_%d.pdf', 'invoice', 180, 1)", "INSERT INTO {prefix}print_template (name, filename, parameters, output_filename, type, order_no, inactive) VALUES ('PrintOrderConfirmationEmailEnglish', 'invoice_printer_order_confirmation_email.php', 'receipt,en', 'order_confirmation_%d.pdf', 'invoice', 190, 1)", "REPLACE INTO {prefix}state (id, data) VALUES ('version', '28')"]);
    }
    if ($version < 29) {
        $updates = array_merge($updates, ['ALTER TABLE {prefix}session CHANGE COLUMN id id varchar(255)', "REPLACE INTO {prefix}state (id, data) VALUES ('version', '29')"]);
    }
    if ($version < 30) {
        $updates = array_merge($updates, ['ALTER TABLE {prefix}base ADD COLUMN payment_intermediator varchar(100) default NULL', 'ALTER TABLE {prefix}company ADD COLUMN payment_intermediator varchar(100) default NULL', "INSERT INTO {prefix}print_template (name, filename, parameters, output_filename, type, order_no, inactive) VALUES ('PrintFinvoiceSOAP', 'invoice_printer_finvoice_soap.php', '', 'finvoice_%d.xml', 'invoice', 55, 1)", "REPLACE INTO {prefix}state (id, data) VALUES ('version', '30')"]);
    }
    if ($version < 31) {
        $updates = array_merge($updates, ['ALTER TABLE {prefix}product ADD COLUMN ean_code1 varchar(13) default NULL', 'ALTER TABLE {prefix}product ADD COLUMN ean_code2 varchar(13) default NULL', "REPLACE INTO {prefix}state (id, data) VALUES ('version', '31')"]);
    }
    if ($version < 32) {
        $updates = array_merge($updates, ['ALTER TABLE {prefix}product ADD COLUMN purchase_price decimal(15,5) NULL', 'ALTER TABLE {prefix}product ADD COLUMN stock_balance int(11) default NULL', <<<EOT
CREATE TABLE {prefix}stock_balance_log (
  id int(11) NOT NULL auto_increment,
  time timestamp NOT NULL default CURRENT_TIMESTAMP,
  user_id int(11) NOT NULL,
  product_id int(11) NOT NULL,
  stock_change int(11) NOT NULL,
  description varchar(255) NOT NULL,
  PRIMARY KEY (id),
  FOREIGN KEY (user_id) REFERENCES {prefix}users(id),
  FOREIGN KEY (product_id) REFERENCES {prefix}product(id)
) ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_swedish_ci
EOT
, "REPLACE INTO {prefix}state (id, data) VALUES ('version', '32')"]);
    }
    if ($version < 33) {
        $updates = array_merge($updates, ['ALTER TABLE {prefix}base ADD COLUMN receipt_email_subject varchar(255) NULL', 'ALTER TABLE {prefix}base ADD COLUMN receipt_email_body text NULL', "REPLACE INTO {prefix}state (id, data) VALUES ('version', '33')"]);
    }
    if ($version < 34) {
        $updates = array_merge($updates, ['ALTER TABLE {prefix}product CHANGE COLUMN stock_balance stock_balance decimal(11,2) default NULL', 'ALTER TABLE {prefix}stock_balance_log CHANGE COLUMN stock_change stock_change decimal(11,2) default NULL', "REPLACE INTO {prefix}state (id, data) VALUES ('version', '34')"]);
    }
    if ($version < 35) {
        $updates = array_merge($updates, ['ALTER TABLE {prefix}invoice_state ADD COLUMN invoice_open tinyint NOT NULL default 0', 'ALTER TABLE {prefix}invoice_state ADD COLUMN invoice_unpaid tinyint NOT NULL default 0', 'UPDATE {prefix}invoice_state SET invoice_open=1 WHERE id IN (1)', 'UPDATE {prefix}invoice_state SET invoice_unpaid=1 WHERE id IN (2, 5, 6, 7)', "REPLACE INTO {prefix}state (id, data) VALUES ('version', '35')"]);
    }
    if ($version < 36) {
        $updates = array_merge($updates, ['ALTER TABLE {prefix}product CHANGE COLUMN ean_code1 barcode1 varchar(255) default NULL', 'ALTER TABLE {prefix}product CHANGE COLUMN ean_code2 barcode2 varchar(255) default NULL', 'ALTER TABLE {prefix}product ADD COLUMN barcode1_type varchar(20) default NULL', 'ALTER TABLE {prefix}product ADD COLUMN barcode2_type varchar(20) default NULL', "UPDATE {prefix}product SET barcode1_type='EAN13' WHERE barcode1 IS NOT NULL", "UPDATE {prefix}product SET barcode2_type='EAN13' WHERE barcode2 IS NOT NULL", 'ALTER TABLE {prefix}base ADD COLUMN order_confirmation_email_subject varchar(255) NULL', 'ALTER TABLE {prefix}base ADD COLUMN order_confirmation_email_body text NULL', "REPLACE INTO {prefix}state (id, data) VALUES ('version', '36')"]);
    }
    if ($version < 37) {
        $updates = array_merge($updates, ['ALTER TABLE {prefix}company ADD COLUMN payment_days int(11) default NULL', 'ALTER TABLE {prefix}company ADD COLUMN terms_of_payment varchar(255) NULL', "REPLACE INTO {prefix}state (id, data) VALUES ('version', '37')"]);
    }
    if ($version < 38) {
        $updates = array_merge($updates, ['UPDATE {prefix}invoice_row ir SET ir.row_date=(SELECT i.invoice_date FROM {prefix}invoice i where i.id=ir.invoice_id) WHERE ir.row_date IS NULL', "REPLACE INTO {prefix}state (id, data) VALUES ('version', '38')"]);
    }
    if ($version < 39) {
        // Check for a bug in database creation script in v1.12.0 and v1.12.1
        $res = mysqli_param_query("SELECT count(*) FROM information_schema.columns WHERE table_schema = '" . _DB_NAME_ . "' AND table_name   = '{prefix}invoice_row' AND column_name = 'partial_payment'");
        $count = mysqli_fetch_value($res);
        if ($count == 0) {
            $updates = array_merge($updates, ['ALTER TABLE {prefix}invoice_row ADD COLUMN partial_payment tinyint NOT NULL default 0', "REPLACE INTO {prefix}state (id, data) VALUES ('version', '39')"]);
        }
    }
    if ($version < 40) {
        $updates = array_merge($updates, ['UPDATE {prefix}invoice_state SET invoice_unpaid=1 WHERE id=1', "REPLACE INTO {prefix}state (id, data) VALUES ('version', '40')"]);
    }
    if (!empty($updates)) {
        mysqli_query_check('SET AUTOCOMMIT = 0');
        mysqli_query_check('BEGIN');
        foreach ($updates as $update) {
            $res = mysqli_query_check($update, true);
            if ($res === false) {
                mysqli_query_check('ROLLBACK');
                mysqli_query_check('SET AUTOCOMMIT = 1');
                error_log('Database upgrade query failed. Please execute the following queries manually:');
                foreach ($updates as $s) {
                    error_log(str_replace('{prefix}', _DB_PREFIX_ . '_', $s) . ';');
                }
                return 'FAILED';
            }
        }
        mysqli_query_check('COMMIT');
        mysqli_query_check('SET AUTOCOMMIT = 1');
        return 'UPGRADED';
    }
    return 'OK';
}
Example #10
0
     }
     // account_statement is a pseudo table for account statement "import"
     if ($table == 'account_statement') {
         header('Content-Type: application/json');
         echo '{"columns":';
         echo json_encode([['id' => 'date', 'name' => $GLOBALS['locImportStatementPaymentDate']], ['id' => 'amount', 'name' => $GLOBALS['locImportStatementAmount']], ['id' => 'refnr', 'name' => $GLOBALS['locImportStatementRefNr']]]);
         echo "\n}";
         exit;
     }
     if (!table_valid($table)) {
         header('HTTP/1.1 400 Bad Request');
         die('Invalid table name');
     }
     header('Content-Type: application/json');
     echo '{"columns":[';
     $res = mysqli_query_check("select * from {prefix}{$table} where 1=2");
     $field_count = mysqli_num_fields($res);
     for ($i = 0; $i < $field_count; $i++) {
         $field_def = mysqli_fetch_field($res);
         if ($i == 0) {
             echo "\n";
         } else {
             echo ",\n";
         }
         echo json_encode(['name' => $field_def->name]);
     }
     echo "\n]}";
     break;
 case 'get_import_preview':
     if (!sesAdminAccess()) {
         header('HTTP/1.1 403 Forbidden');
Example #11
0
         }
         if ($printStyle == 'openwindow') {
             $printFunc = "window.open('invoice.php?id=_ID_&amp;template={$templateId}&amp;func={$strFunc}'); return false;";
         } else {
             $printFunc = "window.location = 'invoice.php?id=_ID_&amp;template={$templateId}&amp;func={$strFunc}'; return false;";
         }
     }
     $arr = array('name' => "print{$templateId}", 'label' => isset($GLOBALS["loc{$row['name']}"]) ? $GLOBALS["loc{$row['name']}"] : $row['name'], 'type' => 'JSBUTTON', 'style' => $printStyle, 'listquery' => $printFunc, 'position' => 3, 'allow_null' => true);
     if (++$rowNum > $templateFirstCol) {
         $arr['position'] = 4;
         $printButtons2[] = $arr;
     } else {
         $printButtons[] = $arr;
     }
 }
 $intRes = mysqli_query_check('SELECT ID from {prefix}base WHERE deleted=0');
 if (mysqli_num_rows($intRes) == 1) {
     $defaultBase = mysqli_fetch_value($intRes);
 } else {
     $defaultBase = FALSE;
 }
 $copyLinkOverride = "copy_invoice.php?func={$strFunc}&amp;list={$strList}&amp;id={$intInvoiceId}";
 $updateInvoiceNr = null;
 if (sesWriteAccess()) {
     if (!getSetting('invoice_add_number') || !getSetting('invoice_add_reference_number')) {
         $updateInvoiceNr = '<a class="formbuttonlink" href="#" onclick="' . $getInvoiceNr . '">' . $GLOBALS['locGetInvoiceNr'] . '</a>';
     }
 }
 $addReminderFees = "\$.getJSON('json.php?func=add_reminder_fees&amp;id=' + document.getElementById('record_id').value, function(json) { if (json.errors) { \$('#errormsg').text(json.errors).show() } else { showmsg('{$GLOBALS['locReminderFeesAdded']}'); } init_rows(); }); return false;";
 $intervalOptions = array('0' => $GLOBALS['locInvoiceIntervalNone'], '2' => $GLOBALS['locInvoiceIntervalMonth'], '3' => $GLOBALS['locInvoiceIntervalYear']);
 $astrFormElements = array(array('name' => 'base_id', 'label' => $GLOBALS['locBiller'], 'type' => 'LIST', 'style' => 'medium linked', 'listquery' => 'SELECT id, name FROM {prefix}base WHERE deleted=0', 'position' => 1, 'default' => $defaultBase), array('name' => 'name', 'label' => $GLOBALS['locInvName'], 'type' => 'TEXT', 'style' => 'medium', 'position' => 2, 'allow_null' => true), array('name' => 'company_id', 'label' => $GLOBALS['locPayer'], 'type' => 'SEARCHLIST', 'style' => 'medium linked', 'listquery' => "table=company&sort=company_name,company_id", 'position' => 1, 'allow_null' => true, 'attached_elem' => $addCompanyCode, 'elem_attributes' => $companyOnChange), array('name' => 'reference', 'label' => $GLOBALS['locClientsReference'], 'type' => 'TEXT', 'style' => 'medium', 'position' => 2, 'allow_null' => true), array('name' => 'invoice_no', 'label' => $GLOBALS['locInvoiceNumber'], 'type' => 'INT', 'style' => 'medium hidezerovalue', 'position' => 1, 'default' => null, 'allow_null' => true), array('name' => 'ref_number', 'label' => $GLOBALS['locReferenceNumber'], 'type' => 'TEXT', 'style' => 'medium hidezerovalue', 'position' => 2, 'default' => null, 'attached_elem' => $updateInvoiceNr, 'allow_null' => true), array('name' => 'invoice_date', 'label' => $GLOBALS['locInvDate'], 'type' => 'INTDATE', 'style' => 'date', 'position' => 1, 'default' => 'DATE_NOW'), array('name' => 'due_date', 'label' => $GLOBALS['locDueDate'], 'type' => 'INTDATE', 'style' => 'date', 'position' => 2, 'default' => 'DATE_NOW+' . getSetting('invoice_payment_days'), 'attached_elem' => $updateDates), array('name' => 'interval_type', 'label' => $GLOBALS['locInvoiceIntervalType'], 'type' => 'SELECT', 'style' => 'medium', 'position' => 1, 'options' => $intervalOptions, 'default' => '0', 'allow_null' => true), array('name' => 'next_interval_date', 'label' => $GLOBALS['locInvoiceNextIntervalDate'], 'type' => 'INTDATE', 'style' => 'date', 'position' => 2, 'default' => '', 'allow_null' => true), array('name' => 'state_id', 'label' => $GLOBALS['locStatus'], 'type' => 'LIST', 'style' => 'medium translated', 'listquery' => 'SELECT id, name FROM {prefix}invoice_state WHERE deleted=0 ORDER BY order_no', 'position' => 1, 'default' => 1), array('name' => 'payment_date', 'label' => $GLOBALS['locPayDate'], 'type' => 'INTDATE', 'style' => 'date', 'position' => 2, 'allow_null' => true, 'attached_elem' => $markPaidTodayButton, 'elem_attributes' => 'onchange="' . $markPaidTodayEvent . '"'), array('name' => 'delivery_terms_id', 'label' => $GLOBALS['locDeliveryTerms'], 'type' => 'LIST', 'style' => 'medium', 'listquery' => 'SELECT id, name FROM {prefix}delivery_terms WHERE deleted=0 ORDER BY order_no;', 'position' => 1, 'default' => null, 'allow_null' => true), array('name' => 'delivery_method_id', 'label' => $GLOBALS['locDeliveryMethod'], 'type' => 'LIST', 'style' => 'medium', 'listquery' => 'SELECT id, name FROM {prefix}delivery_method WHERE deleted=0 ORDER BY order_no;', 'position' => 2, 'default' => null, 'allow_null' => true), array('name' => 'archived', 'label' => $GLOBALS['locArchived'], 'type' => 'CHECK', 'style' => 'medium', 'position' => 1, 'default' => 0, 'allow_null' => true), array('name' => 'info', 'label' => $GLOBALS['locVisibleInfo'], 'type' => 'AREA', 'style' => 'medium', 'position' => 1, 'allow_null' => true), array('name' => 'internal_info', 'label' => $GLOBALS['locInternalInfo'], 'type' => 'AREA', 'style' => 'medium', 'position' => 2, 'allow_null' => true), !sesWriteAccess() ? array('name' => 'refundinvoice', 'label' => '', 'type' => 'FILLER', 'position' => 1) : array('name' => 'refundinvoice', 'label' => $GLOBALS['locRefundInvoice'], 'type' => 'BUTTON', 'style' => 'redirect', 'listquery' => "copy_invoice.php?func={$strFunc}&list={$strList}&id=_ID_&refund=1", 'position' => 1, 'default' => FALSE, 'allow_null' => true), $arrRefundedInvoice, isset($printButtons[0]) ? $printButtons[0] : array(), isset($printButtons2[0]) ? $printButtons2[0] : array(), !sesWriteAccess() ? array('name' => 'addreminderfees', 'label' => '', 'type' => 'FILLER', 'position' => 1) : array('name' => 'addreminderfees', 'label' => $GLOBALS['locAddReminderFees'], 'type' => 'JSBUTTON', 'style' => 'redirect', 'listquery' => $addReminderFees, 'position' => 1, 'default' => FALSE, 'allow_null' => true), $arrRefundingInvoice, isset($printButtons[1]) ? $printButtons[1] : array(), isset($printButtons2[1]) ? $printButtons2[1] : array());
Example #12
0
        }
    }
} elseif ($func == 'view') {
    $res = mysqli_param_query('SELECT logo_filename, logo_filesize, logo_filetype, logo_filedata FROM {prefix}base WHERE id=?', [$baseId]);
    if ($row = mysqli_fetch_assoc($res)) {
        if (isset($row['logo_filename']) && isset($row['logo_filesize']) && isset($row['logo_filetype']) && isset($row['logo_filedata'])) {
            header('Content-length: ' . $row['logo_filesize']);
            header('Content-type: ' . $row['logo_filetype']);
            header('Content-Disposition: inline; filename=' . $row['logo_filename']);
            echo $row['logo_filedata'];
        }
    }
    exit;
}
$maxUploadSize = getMaxUploadSize();
$row = mysqli_fetch_array(mysqli_query_check('SELECT @@max_allowed_packet'));
$maxPacket = $row[0];
if ($maxPacket < $maxUploadSize) {
    $maxFileSize = fileSizeToHumanReadable($maxPacket) . ' ' . $GLOBALS['locBaseLogoSizeDBLimited'];
} else {
    $maxFileSize = fileSizeToHumanReadable($maxUploadSize);
}
echo htmlPageStart(_PAGE_TITLE_);
?>
<div class="form">
	<div class="message"><?php 
echo $messages;
?>
</div>

	<div class="form_container ui-widget-content">
Example #13
0
 private function printReport()
 {
     $intBaseId = getRequest('base', false);
     $intCompanyId = getRequest('company', false);
     $grouping = getRequest('grouping', '');
     $format = getRequest('format', 'html');
     $printFields = getRequest('fields', []);
     $rowTypes = getRequest('row_types', 'all');
     $dateRange = explode(' - ', getRequest('date', ''));
     $startDate = $dateRange[0];
     $endDate = isset($dateRange[1]) ? $dateRange[1] : $startDate;
     if ($startDate) {
         $startDate = dateConvDate2DBDate($startDate);
     }
     if ($endDate) {
         $endDate = dateConvDate2DBDate($endDate);
     }
     $rowDateRange = explode(' - ', getRequest('row_date', ''));
     $rowStartDate = $rowDateRange[0];
     $rowEndDate = isset($rowDateRange[1]) ? $rowDateRange[1] : $rowStartDate;
     if ($rowStartDate) {
         $rowStartDate = dateConvDate2DBDate($rowStartDate);
     }
     if ($rowEndDate) {
         $rowEndDate = dateConvDate2DBDate($rowEndDate);
     }
     $paymentDateRange = explode(' - ', getRequest('payment_date', ''));
     $paymentStartDate = $paymentDateRange[0];
     $paymentEndDate = isset($paymentDateRange[1]) ? $paymentDateRange[1] : '';
     if ($paymentStartDate) {
         $paymentStartDate = dateConvDate2DBDate($paymentStartDate);
     }
     if ($paymentEndDate) {
         $paymentEndDate = dateConvDate2DBDate($paymentEndDate);
     }
     $arrParams = [];
     $strQuery = 'SELECT i.id, i.invoice_no, i.invoice_date, i.due_date, i.payment_date, i.ref_number, i.ref_number, c.company_name AS name, c.billing_address, ist.name as state, ist.invoice_unpaid as unpaid' . ($grouping == 'vat' ? ', ir.vat' : '') . ' FROM {prefix}invoice i' . ($grouping == 'vat' ? ' INNER JOIN {prefix}invoice_row ir ON ir.invoice_id = i.id' : '') . ' LEFT OUTER JOIN {prefix}company c ON c.id = i.company_id' . ' LEFT OUTER JOIN {prefix}invoice_state ist ON i.state_id = ist.id' . ' WHERE i.deleted=0';
     if ($startDate) {
         $strQuery .= ' AND i.invoice_date >= ?';
         $arrParams[] = $startDate;
     }
     if ($endDate) {
         $strQuery .= ' AND i.invoice_date <= ?';
         $arrParams[] = $endDate;
     }
     if ($paymentStartDate) {
         $strQuery .= ' AND i.payment_date >= ?';
         $arrParams[] = $paymentStartDate;
     }
     if ($paymentEndDate) {
         $strQuery .= ' AND i.payment_date <= ?';
         $arrParams[] = $paymentEndDate;
     }
     if ($intBaseId) {
         $strQuery .= ' AND i.base_id = ?';
         $arrParams[] = $intBaseId;
     }
     if ($intCompanyId) {
         $strQuery .= ' AND i.company_id = ?';
         $arrParams[] = $intCompanyId;
     }
     $strQuery2 = '';
     $strQuery3 = 'SELECT id, name ' . 'FROM {prefix}invoice_state WHERE deleted=0 ORDER BY order_no';
     $intRes = mysqli_query_check($strQuery3);
     while ($row = mysqli_fetch_assoc($intRes)) {
         $intStateId = $row['id'];
         $strStateName = $row['name'];
         $strTemp = "stateid_{$intStateId}";
         $tmpSelected = getRequest($strTemp, false);
         if ($tmpSelected) {
             $strQuery2 .= 'i.state_id = ? OR ';
             $arrParams[] = $intStateId;
         }
     }
     if ($strQuery2) {
         $strQuery2 = ' AND (' . substr($strQuery2, 0, -4) . ')';
     }
     $strQuery .= $strQuery2;
     switch ($grouping) {
         case 'state':
             $strQuery .= ' ORDER BY state_id, invoice_date, invoice_no';
             break;
         case 'client':
             $strQuery .= ' ORDER BY name, invoice_date, invoice_no';
             break;
         case 'vat':
             $strQuery .= ' GROUP BY i.id, ir.vat ORDER BY vat, invoice_date, invoice_no';
             break;
         default:
             $strQuery .= ' ORDER BY invoice_date, invoice_no';
     }
     $this->printHeader($format, $printFields, $startDate, $endDate);
     $intTotSum = 0;
     $intTotVAT = 0;
     $intTotSumVAT = 0;
     $intTotalToPay = 0;
     $currentGroup = false;
     $groupTotSum = 0;
     $groupTotVAT = 0;
     $groupTotSumVAT = 0;
     $groupTotalToPay = 0;
     $totalsPerVAT = [];
     $intRes = mysqli_param_query($strQuery, $arrParams);
     while ($row = mysqli_fetch_assoc($intRes)) {
         switch ($grouping) {
             case 'state':
                 $invoiceGroup = $row['state'];
                 break;
             case 'month':
                 $invoiceGroup = substr($row['invoice_date'], 4, 2);
                 break;
             case 'client':
                 $invoiceGroup = $row['name'];
                 break;
             case 'vat':
                 $invoiceGroup = $row['vat'];
                 break;
             default:
                 $invoiceGroup = false;
         }
         $rowParams = [$row['id']];
         $strQuery = 'SELECT ir.description, ir.pcs, ir.price, ir.discount, ir.row_date, ir.vat, ir.vat_included, ir.partial_payment ' . 'FROM {prefix}invoice_row ir ' . 'WHERE ir.invoice_id=? AND ir.deleted=0';
         if ($rowStartDate) {
             $strQuery .= ' AND ir.row_date >= ?';
             $rowParams[] = $rowStartDate;
         }
         if ($rowEndDate) {
             $strQuery .= ' AND ir.row_date <= ?';
             $rowParams[] = $rowEndDate;
         }
         if ($rowTypes != 'all') {
             if ($rowTypes == 'normal') {
                 $strQuery .= ' AND ir.reminder_row = 0';
             } else {
                 if ($rowTypes == 'reminder') {
                     $strQuery .= ' AND ir.reminder_row in (1, 2)';
                 }
             }
         }
         if ($grouping == 'vat') {
             if ($row['vat'] === null) {
                 $strQuery .= ' AND ir.vat IS NULL';
             } else {
                 $strQuery .= ' AND ir.vat = ?';
                 $rowParams[] = $row['vat'];
             }
         }
         $intRes2 = mysqli_param_query($strQuery, $rowParams);
         $intRowSum = 0;
         $intRowVAT = 0;
         $intRowSumVAT = 0;
         $rowPayments = 0;
         $rows = false;
         while ($row2 = mysqli_fetch_assoc($intRes2)) {
             $rows = true;
             if ($row2['partial_payment']) {
                 $rowPayments -= $row2['price'];
                 continue;
             }
             list($intSum, $intVAT, $intSumVAT) = calculateRowSum($row2['price'], $row2['pcs'], $row2['vat'], $row2['vat_included'], $row2['discount']);
             $intRowSum += $intSum;
             $intRowVAT += $intVAT;
             $intRowSumVAT += $intSumVAT;
             if (!isset($totalsPerVAT[$row2['vat']])) {
                 $totalsPerVAT[$row2['vat']] = ['sum' => $intSum, 'VAT' => $intVAT, 'sumVAT' => $intSumVAT];
             } else {
                 $totalsPerVAT[$row2['vat']]['sum'] += $intSum;
                 $totalsPerVAT[$row2['vat']]['VAT'] += $intVAT;
                 $totalsPerVAT[$row2['vat']]['sumVAT'] += $intSumVAT;
             }
         }
         if (!$rows) {
             continue;
         }
         $intTotSum += $intRowSum;
         $intTotVAT += $intRowVAT;
         $intTotSumVAT += $intRowSumVAT;
         if ($row['unpaid']) {
             $intTotalToPay += $intRowSumVAT - $rowPayments;
         } else {
             $rowPayments = $intRowSumVAT;
         }
         if ($grouping && $currentGroup !== false && $currentGroup != $invoiceGroup) {
             $this->printGroupSums($format, $printFields, $row, $groupTotSum, $groupTotVAT, $groupTotSumVAT, $groupTotalToPay, $grouping == 'vat' ? $GLOBALS['locVAT'] . ' ' . miscRound2Decim($currentGroup) : '');
             $groupTotSum = 0;
             $groupTotVAT = 0;
             $groupTotSumVAT = 0;
             $groupTotalToPay = 0;
         }
         $currentGroup = $invoiceGroup;
         $groupTotSum += $intRowSum;
         $groupTotVAT += $intRowVAT;
         $groupTotSumVAT += $intRowSumVAT;
         $groupTotalToPay += $intRowSumVAT - $rowPayments;
         $this->printRow($format, $printFields, $row, $intRowSum, $intRowVAT, $intRowSumVAT, $intRowSumVAT - $rowPayments);
     }
     if ($grouping) {
         $this->printGroupSums($format, $printFields, $row, $groupTotSum, $groupTotVAT, $groupTotSumVAT, $groupTotalToPay, $grouping == 'vat' ? $GLOBALS['locVAT'] . ' ' . miscRound2Decim($currentGroup) : '');
     }
     ksort($totalsPerVAT, SORT_NUMERIC);
     $this->printTotals($format, $printFields, $intTotSum, $intTotVAT, $intTotSumVAT, $intTotalToPay, $totalsPerVAT);
     $this->printFooter($format, $printFields);
 }
Example #14
0
    public function launch()
    {
        $charset = getRequest('charset', 'UTF-8');
        $table = getRequest('table', '');
        $format = getRequest('format', '');
        $fieldDelimiter = getRequest('field_delim', ',');
        $enclosureChar = getRequest('enclosure_char', '"');
        $rowDelimiter = getRequest('row_delim', "\n");
        $columns = getRequest('column', '');
        $childRows = getRequest('child_rows', '');
        $deletedRecords = getRequest('deleted', false);
        if ($table && $format && $columns) {
            if (!table_valid($table)) {
                die('Invalid table name');
            }
            $res = mysqli_query_check("show fields from {prefix}{$table}");
            $field_count = mysqli_num_rows($res);
            $field_defs = array();
            while ($row = mysqli_fetch_assoc($res)) {
                $field_defs[$row['Field']] = $row;
            }
            foreach ($columns as $key => $column) {
                if (!$column) {
                    unset($columns[$key]);
                } elseif (!isset($field_defs[$column])) {
                    die('Invalid column name');
                }
            }
            ob_clean();
            $filename = isset($GLOBALS["locTable_{$table}"]) ? $GLOBALS["locTable_{$table}"] : $table;
            switch ($format) {
                case 'csv':
                    $field_delims = $this->importer->get_field_delims();
                    $enclosure_chars = $this->importer->get_enclosure_chars();
                    $row_delims = $this->importer->get_row_delims();
                    if (!isset($field_delims[$fieldDelimiter])) {
                        die('Invalid field delimiter');
                    }
                    $fieldDelimiter = $field_delims[$fieldDelimiter]['char'];
                    if (!isset($enclosure_chars[$enclosureChar])) {
                        die('Invalid enclosure character');
                    }
                    $enclosureChar = $enclosure_chars[$enclosureChar]['char'];
                    if (!isset($row_delims[$rowDelimiter])) {
                        die('Invalid field delimiter');
                    }
                    $rowDelimiter = $row_delims[$rowDelimiter]['char'];
                    header('Content-type: text/csv');
                    header("Content-Disposition: attachment; filename=\"{$filename}.csv\"");
                    if ($charset == 'UTF-16') {
                        echo iconv($charset, 'UTF-16', '');
                    }
                    // output BOM
                    $this->output_str($this->str_putcsv($columns, $fieldDelimiter, $enclosureChar) . $rowDelimiter, $charset);
                    break;
                case 'xml':
                    header('Content-type: text/xml');
                    header("Content-Disposition: attachment; filename=\"{$filename}.xml\"");
                    if ($charset == 'UTF-16') {
                        echo iconv($charset, 'UTF-16', '');
                    }
                    // output BOM
                    $this->output_str("<?xml version=\"1.0\"?>\n<records>\n", $charset);
                    break;
                case 'json':
                    header('Content-type: application/json');
                    header("Content-Disposition: attachment; filename=\"{$filename}.json\"");
                    if ($charset == 'UTF-16') {
                        echo iconv($charset, 'UTF-16', '');
                    }
                    // output BOM
                    echo "{\"{$table}\":[\n";
                    break;
            }
            $query = "select * from {prefix}{$table}";
            if (!$deletedRecords) {
                $query .= ' where deleted=0';
                if ($table == 'company_contact') {
                    $query .= ' and company_id not in (select id from {prefix}company where deleted=1)';
                } elseif ($table == 'invoice_row') {
                    $query .= ' and invoice_id not in (select id from {prefix}invoice where deleted=1)';
                }
            }
            $res = mysqli_query_check($query);
            $first = true;
            while ($row = mysqli_fetch_assoc($res)) {
                $data = array();
                foreach ($columns as $column) {
                    $value = $row[$column];
                    if (is_null($value)) {
                        $data[$column] = '';
                    }
                    if ($value && substr($field_defs[$column]['Type'], 0, 8) == 'longblob') {
                        $data[$column] = '0x' . bin2hex($value);
                    } else {
                        $data[$column] = $value;
                    }
                }
                switch ($format) {
                    case 'csv':
                        $this->output_str($this->str_putcsv($data, $fieldDelimiter, $enclosureChar) . $rowDelimiter, $charset);
                        break;
                    case 'xml':
                        $str = "  <{$table}>\n";
                        foreach ($columns as $column) {
                            $str .= "    <{$column}>" . xml_encode($data[$column]) . "</{$column}>\n";
                        }
                        if ($childRows && ($table == 'invoice' || $table == 'company')) {
                            if ($table == 'invoice') {
                                $cres = mysqli_param_query('select * from {prefix}invoice_row where invoice_id=?', array($row['id']));
                            } else {
                                $cres = mysqli_param_query('select * from {prefix}company_contact where company_id=?', array($row['id']));
                            }
                            while ($crow = mysqli_fetch_assoc($cres)) {
                                $str .= "    <invoice_row>\n";
                                foreach ($crow as $column => $value) {
                                    $str .= "      <{$column}>" . xml_encode($value) . "</{$column}>\n";
                                }
                                $str .= "    </invoice_row>\n";
                            }
                        }
                        $str .= "  </{$table}>\n";
                        $this->output_str($str, $charset);
                        break;
                    case 'json':
                        if ($childRows && ($table == 'invoice' || $table == 'company')) {
                            if ($table == 'invoice') {
                                $childTable = 'invoice_row';
                            } else {
                                $childTable = 'company_contact';
                            }
                            $data[$childTable] = array();
                            if ($table == 'invoice') {
                                $cres = mysqli_param_query('select * from {prefix}invoice_row where invoice_id=?', array($row['id']));
                            } else {
                                $cres = mysqli_param_query('select * from {prefix}company_contact where company_id=?', array($row['id']));
                            }
                            while ($crow = mysqli_fetch_assoc($cres)) {
                                $data[$childTable][] = $crow;
                            }
                        }
                        if ($first) {
                            $first = false;
                        } else {
                            echo ",\n";
                        }
                        $this->output_str(json_encode($data), $charset);
                        break;
                }
            }
            switch ($format) {
                case 'xml':
                    $this->output_str("</records>\n");
                    break;
                case 'json':
                    echo "\n]}\n";
                    break;
            }
            exit;
        }
        ?>
  <script type="text/javascript">

  $(document).ready(function() {
    $('#imessage').ajaxStart(function() {
      $('#spinner').css('visibility', 'visible');
    });
    $('#imessage').ajaxStop(function() {
      $('#spinner').css('visibility', 'hidden');
    });
    $('#imessage').ajaxError(function(event, request, settings) {
      alert('Server request failed: ' + request.status + ' - ' + request.statusText);
      $('#spinner').css('visibility', 'hidden');
    });
    update_field_states();
    reset_columns();
  });

  var g_column_id = 0;

  function reset_columns()
  {
    $("#columns > select").remove();
    g_column_id = 0;
    add_column();
  }

  function add_column()
  {
    var table = document.getElementById("sel_table").value;
    $.getJSON("json.php?func=get_table_columns&table=" + table, function(json) {
      var index = ++g_column_id;
      var columns = document.getElementById("columns");
      var select = document.createElement("select");
      select.id = "column" + index;
      select.name = "column[]";
      select.onchange = update_columns;
      var option = document.createElement("option");
      option.value = "";
      option.text = "<?php 
        echo $GLOBALS['locImportExportColumnNone'];
        ?>
";
      select.options.add(option);
      for (var i = 0; i < json.columns.length; i++)
      {
        var option = document.createElement("option");
        option.value = json.columns[i].name;
        option.text = json.columns[i].name;
        select.options.add(option);
      }
      columns.appendChild(document.createTextNode(' '));
      columns.appendChild(select);
    });
  }

  function update_columns()
  {
    if (this.value == "" && $("#columns > select").size() > 1)
      $(this).remove();
    else if (this.id == "column" + g_column_id)
      add_column();
  }

  function update_field_states()
  {
    var type = document.getElementById('format').value;
    document.getElementById('field_delim').disabled = type != 'csv';
    document.getElementById('enclosure_char').disabled = type != 'csv';
    document.getElementById('row_delim').disabled = type != 'csv';
    document.getElementById('child_rows').disabled = type == 'csv';
  }

  function add_all_columns()
  {
    var options = document.getElementById("column" + g_column_id).options;

    $("#columns > select").remove();
    g_column_id = 0;

    var columns = document.getElementById("columns");
    for (var i = 1; i < options.length; i++)
    {
      var index = ++g_column_id;
      var select = document.createElement("select");
      select.id = "column" + index;
      select.name = "column[]";
      select.onchange = update_columns;
      var option = document.createElement("option");
      for (var opt = 0; opt < options.length; opt++)
        select.options.add(options[opt].cloneNode(true));
      select.selectedIndex = i;
      columns.appendChild(document.createTextNode(' '));
      columns.appendChild(select);
    }
  }

  </script>

    <div class="form_container">
      <h1><?php 
        echo $GLOBALS['locExport'];
        ?>
</h1>
      <span id="imessage" style="display: none"></span>
      <span id="spinner" style="visibility: hidden"><img src="images/spinner.gif" alt=""></span>
      <form id="export_form" name="export_form" method="GET">
        <input type="hidden" name="func" value="system">
        <input type="hidden" name="operation" value="export">

        <div class="medium_label"><?php 
        echo $GLOBALS['locImportExportCharacterSet'];
        ?>
</div>
        <div class="field">
          <select id="charset" name="charset">
            <option value="UTF-8">UTF-8</option>
            <option value="ISO-8859-1">ISO-8859-1</option>
            <option value="ISO-8859-15">ISO-8859-15</option>
            <option value="Windows-1251">Windows-1251</option>
            <option value="UTF-16">UTF-16</option>
            <option value="UTF-16LE">UTF-16 LE</option>
            <option value="UTF-16BE">UTF-16 BE</option>
          </select>
        </div>

        <div class="medium_label"><?php 
        echo $GLOBALS['locImportExportTable'];
        ?>
</div>
        <div class="field">
          <select id="sel_table" name="table" onchange="reset_columns()">
            <option value="company"><?php 
        echo $GLOBALS['locImportExportTableCompanies'];
        ?>
</option>
            <option value="company_contact"><?php 
        echo $GLOBALS['locImportExportTableCompanyContacts'];
        ?>
</option>
            <option value="base"><?php 
        echo $GLOBALS['locImportExportTableBases'];
        ?>
</option>
            <option value="invoice"><?php 
        echo $GLOBALS['locImportExportTableInvoices'];
        ?>
</option>
            <option value="invoice_row"><?php 
        echo $GLOBALS['locImportExportTableInvoiceRows'];
        ?>
</option>
            <option value="product"><?php 
        echo $GLOBALS['locImportExportTableProducts'];
        ?>
</option>
            <option value="row_type"><?php 
        echo $GLOBALS['locImportExportTableRowTypes'];
        ?>
</option>
            <option value="invoice_state"><?php 
        echo $GLOBALS['locImportExportTableInvoiceStates'];
        ?>
</option>
          </select>
        </div>

        <div class="medium_label"><?php 
        echo $GLOBALS['locImportExportFormat'];
        ?>
</div>
        <div class="field">
          <select id="format" name="format" onchange="update_field_states()">
            <option value="csv">CSV</option>
            <option value="xml">XML</option>
            <option value="json">JSON</option>
          </select>
        </div>

        <div class="medium_label"><?php 
        echo $GLOBALS['locImportExportFieldDelimiter'];
        ?>
</div>
        <div class="field">
          <select id="field_delim" name="field_delim">
  <?php 
        $field_delims = $this->importer->get_field_delims();
        foreach ($field_delims as $key => $delim) {
            echo "<option value=\"{$key}\">" . $delim['name'] . "</option>\n";
        }
        ?>
          </select>
        </div>

        <div class="medium_label"><?php 
        echo $GLOBALS['locImportExportEnclosureCharacter'];
        ?>
</div>
        <div class="field">
          <select id="enclosure_char" name="enclosure_char">
  <?php 
        $enclosure_chars = $this->importer->get_enclosure_chars();
        foreach ($enclosure_chars as $key => $delim) {
            echo "<option value=\"{$key}\">" . $delim['name'] . "</option>\n";
        }
        ?>
          </select>
        </div>

        <div class="medium_label"><?php 
        echo $GLOBALS['locImportExportRowDelimiter'];
        ?>
</div>
        <div class="field">
          <select id="row_delim" name="row_delim">
  <?php 
        $row_delims = $this->importer->get_row_delims();
        foreach ($row_delims as $key => $delim) {
            echo "<option value=\"{$key}\">" . $delim['name'] . "</option>\n";
        }
        ?>
          </select>
        </div>

        <div class="medium_label"><?php 
        echo $GLOBALS['locExportIncludeChildRows'];
        ?>
</div>
        <div class="field">
          <input id="child_rows" name="child_rows" type="checkbox" checked="checked">
        </div>

        <div class="medium_label"><?php 
        echo $GLOBALS['locExportIncludeDeletedRecords'];
        ?>
</div>
        <div class="field">
          <input id="deleted" name="deleted" type="checkbox">
        </div>

        <div class="medium_label"><?php 
        echo $GLOBALS['locExportColumns'];
        ?>
 <input type="button" value="<?php 
        echo $GLOBALS['locExportAddAllColumns'];
        ?>
" onclick="add_all_columns()"></div>
        <div id="columns" class="field">
        </div>

        <div class="form_buttons" style="clear: both">
          <input type="submit" value="<?php 
        echo $GLOBALS['locExportDo'];
        ?>
">
        </div>
      </form>
    </div>
  <?php 
    }