NAME
LedgerSMB::Form - Provides general legacy support functions and the central object.
SYNOPSIS
This module provides general legacy support functions and the central object
STATUS
Deprecated
COPYRIGHT
#====================================================================# LedgerSMB# Small Medium Business Accounting software# http://www.ledgersmb.org/## Copyright (C) 2006# This work contains copyrighted information from a number of sources# all used with permission.## This file contains source code included with or based on SQL-Ledger# which is Copyright Dieter Simader and DWS Systems Inc. 2000-2005# and licensed under the GNU General Public License version 2 or, at# your option, any later version. For a full list including contact# information of contributors, maintainers, and copyright holders,# see the CONTRIBUTORS file.## Original Copyright Notice from SQL-Ledger 2.6.17 (before the fork):# Copyright (C) 2000## Author: DWS Systems Inc.# Web: http://www.sql-ledger.org## Contributors: Thomas Bayen <[email protected]># Antti Kaihola <[email protected]># Moritz Bunkus (tex)# Jim Rawlings <[email protected]> (DB2)#====================================================================## This file has undergone whitespace cleanup.##====================================================================## main package##====================================================================
METHODS
- new Form([$argstr])
-
Returns a reference to new Form object. The initial set of attributes is obtained from
$argstr, a CGI query string, or$ARGV[0]. All the values are run through unescape to undo any URI encoding.The version and dbversion attributes are set to hardcoded values; action, nextsub, path, script, and login are filtered to remove some dangerous values. Both menubar and lynx are set if path matches lynx.
$form->error may be called to deny access on some attribute values.
- open_form()
-
This sets a
$self->{form_id} to be used in later form validation (anti-XSRF measure).
- check_form()
-
This returns true if the form_id was associated with the session, and false if not. Use this if the form may be re-used (back-button actions are valid).
- close_form()
-
Identical with check_form() above, but also removes the form_id from the session. This should be used when back-button actions are not valid.
- $form->debug([$file]);
-
Outputs the sorted contents of
$form. If a filename is specified, log to it, otherwise output to STDOUT.
- $form->encode_all();
-
Does nothing and is unused. Contains merely the comment # TODO;
- $form->decode_all();
-
Does nothing and is unused. Contains merely the comment # TODO
- $form->escape($str[, $beenthere]);
-
Returns the URI-encoded
$str.$beenthereis a boolean that when true forces a single encoding run. When false, it escapes the string twice if it detects that it is running on a version of Apache 2.0 earlier than 2.0.44.Note that recurring transaction support depends on this function escaping ','.
- $form->unescape($str);
-
Returns the unencoded form of the URI-encoded
$str.
- $form->quote($str);
-
Replaces all double quotes in
$strwith '"'. Does nothing if$stris a reference.
- $form->unquote($str);
-
Replaces all '"' in
$strwith double quotes. Does nothing if$stris a reference.
- $form->hide_form([...]);
-
Outputs hidden HTML form fields to STDOUT. If values are passed into this function, only those
$formvalues are output. If no values are passed in, all$formvalues are output as well as deleting$form->{header}. Values from the$formobject are run through$form->quote, whereas keys/names are not.Sample output:
<input type="hidden" name="login" value="testuser" />
- $form->error($msg);
-
Output an error message,
$msg. If a CGI environment is detected, this outputs an HTTP and HTML header section if required, and displays the message after running it through$form->format_string. If it is not a CGI environment and$ENV{error_function} is set, call the specified function with$msgas the sole argument. Otherwise, this function simply dies with$msg.This function does not return. Execution is terminated at the end of the appropriate path.
- $form->finalize_request();
-
Stops further processing, allowing post-request cleanup on intermediate levels by throwing an exception.
This function replaces explicit 'exit()' calls.
- $form->info($msg);
-
Output an informational message,
$msg. If a CGI environment is detected, this outputs an HTTP and HTML header section if required, and displays the message in bold tags without escaping. If it is not a CGI environment and$ENV{info_function} is set, call the specified function with$msgas the sole argument. Otherwise, this function simply prints$msgto STDOUT.
- $form->numtextrows($str, $cols[, $maxrows]);
-
Returns the number of rows of
$colscolumns can be formed by$str. If$maxrowsis set and the number of rows is greater than$maxrows, this returns$maxrows. In the determination of rowcount, newline characters, "\n", are taken into account while spaces are not.
- $form->dberror($msg);
-
Outputs a message as in
$form->error but with$DBI::errstrautomatically appended to$msg.
- $form->isblank($name, $msg);
-
Calls
$form->error($msg) if the value of$form->{$name} matches /^\s*$/.
- $form->header([$init, $headeradd]);
-
Outputs HTML and HTTP headers and sets
$form->{header} to indicate that headers have been output. If called with$form->{header} set or in a non-CGI environment, does not output anything.$initis ignored.$headeraddis data to be added to the <head> portion of the output headers.$form->{stylesheet},$form->{title},$form->{titlebar}, and$form->{pre} all affect the output of this function.If the stylesheet indicated by
$form->{stylesheet} exists, output a link tag to reference it. If$form->{title} is false, the title text is the value of$form->{titlebar}. If$form->{title} is true, the title text takes the form of "$form->{title} -$form->{titlebar}". The value of$form->{pre} is output immediately after the closing of <head>.
- $form->open_status_div
-
Returns a div tag with an id of statusdiv.
If
$form->{id} is set and$form->{approved} the class is set to "posted" and if id is set but not approved, this is set to "saved." If neither applies, we set to "new."
- $form->close_status_div
-
Simply returns a </div> tag. This is included for clarity of code.
- $form->redirect([$msg]);
-
If
$form->{callback} is set or$msgis not set, call the redirect function in common.pl. If main::redirect returns, exit.Otherwise, output
$msgas an informational message with$form->info($msg).
- $form->sort_columns(@columns);
-
Sorts the list
@columns. If$form->{sort} is unset, do nothing. If the value of$form->{sort} does not exist in@columns, returns the list formed by the value of$form->{sort} followed by the values of@columns. If the value of$form->{sort} is in@columns, return the list formed by@columnswith the value of$form->{sort} moved to the head of the list.
- $form->sort_order($columns[, $ordinal]);
-
Returns a string that contains ordering details for the columns in SQL form.
$columnsis a reference to a list of columns,$ordinalis a reference to a hash that maps column names to ordinal positions. This function depends upon the values of$form->{direction},$form->{sort}, and$form->{oldsort}.If
$form->{direction} is false, it becomes 'ASC'. If$form->{direction} is true and$form->{sort} and$form->{oldsort} are equal, reverse the order specified by$form->{direction}.$form->{oldsort} is set to the same value as$form->{sort}The actual sorting of
$columnshappens as in$form->sort_columns(@$columns).If
$ordinalis set, the positions given by it are substituted for the names of columns returned.
- $form->convert_date($date, $myconfig)
-
This takes a date in YYYY-MM-DD format and returns it in the format of the user.
- $form->format_amount($myconfig, $amount, $places, $dash);
-
Returns
$amountas formatted in the form specified by$form->{numberformat}.$placesis the number of decimal places to have in the output.$dashindicates how to represent conditions surrounding values.+-------+----------+---------+------+| $dash | -1.00 | 1.00 | 0.00 |+-------+----------+---------+------+| - | (1.00) | 1.00 | - || DRCR | 1.00 DR | 1.00 CR | DRCR || 0 | -1.00 | 1.00 | 0.00 || x | -1.00 | 1.00 | x || undef | -1.00 | 1.00 | |+-------+----------+---------+------+Sample behaviour of the formatted output of various numbers for select
$dashvalues.
- $form->parse_amount($myconfig, $amount);
-
Return a Math::BigFloat containing the value of
$amountwhere$amountis formatted as$myconfig->{numberformat}. If$amountis '' or undefined, it is treated as zero. DRCR and parenthesis notation is accepted in addition to negative sign notation.Calls
$form->error if the value is NaN.
- $form->round_amount($amount, $places);
-
Rounds the provided
$amountto$placesdecimal places.
- $form->db_parse_numeric('sth' => $sth, ['arrayref' => $arrayref, 'hashref' => $hashref])
-
Converts numeric values in the result set
$arrayrefor$hashrefto Math::BigFloat using$sthto determine which fields are numeric.
- $form->get_my_emp_num($myconfig);
-
Function to get the employee number of the user
$form->{login}.$myconfigis only used to create%myconfig.$form->{emp_num} is set to the retrieved value.This function is currently (2007-08-02) only used by pos.conf.pl.
- $form->format_string(@fields);
-
Escape the values of
$formselected by@fieldsfor the format specified by$form->{format}.
- $form->datetonum($myconfig, $date[, $picture]);
-
Converts
$datefrom the format$myconfig->{dateformat} to the format 'yyyymmdd'. If the year extracted is only two-digits, the year given is assumed to be in the range 2000-2099.If
$datedoes not contain any non-digits, datetonum does nothing.$pictureis ignored.
- $form->add_date($myconfig, $date, $repeat, $unit);
-
Returns the date
$repeat$unitsfrom$datein the input format.$datecan either be in$myconfig->{dateformat} or 'yyyymmdd' (four digit year required for this option). The valid values for$unitare 'days', 'weeks', 'months', and 'years'.This function is unreliable for
$unitvalues other than 'days' or 'weeks' and can die horribly.
- $form->print_button($button, $name);
-
Outputs a submit button to STDOUT.
$buttonis a hashref that contains data about buttons,$nameis the key for the element in$buttonto output. Each value in$buttonis a reference to a hash of two elements, 'key' and 'value'.$nameis the value of the button that gets sent to the server when clicked,$button->{$name}{key} is the accesskey, and$button->{$name}{value} is the label for the button.
- test_should_get_images
-
Returns true if images should get be retrieved for embedding in templates
- $form->db_init($myconfig);
-
Connect to the database that
$myconfigis set to use and initialise the base parameters. The connection handle becomes$form->{dbh} and$form->{custom_db_fields} is populated. The connection initiated has autocommit disabled.
- $form->run_custom_queries($tablename, $query_type[, $linenum]);
-
Runs queries against custom fields for the specified
$query_typeagainst$tablename.Valid values for
$query_typeare any casing of 'SELECT', 'INSERT', and 'UPDATE'.
- $form->dbconnect($myconfig);
-
Returns an autocommit connection to the database specified in
$myconfig.
- $form->dbconnect_noauto($myconfig);
-
Returns a non-autocommit connection to the database specified in
$myconfig.
- $form->dbquote($var);
-
If
$varis an empty string, return NULL, otherwise return$varas quoted by$form->{dbh}->quote($var).
- $form->update_balance($dbh, $table, $field, $where, $value);
-
WARNING: This is a dangerous private function. All apps calling it must be careful to avoid SQL injection issues.
If
$valueis set, sets the value of$fieldin$tableto the sum of the current stored value and$value. In order to not annihilate the values in$table,$wheremust contain a WHERE clause that limits the UPDATE to a single row.
- $form->update_exchangerate($dbh, $curr, $transdate, $buy, $sell);
-
Updates the exchange rates
$buyand$sellfor the given$currencyon$transdate. If there is not yet an exchange rate for$currencyon$transdate, an entry is inserted. This returns without doing anything if$curreq ''.$dbhis not used, favouring$self->{dbh}.
- $form->save_exchangerate($myconfig, $currency, $transdate, $rate, $fld);
-
Saves the exchange rate
$ratefor the given$currencyon$transdatefor the provided purpose in$fld.$fldcan be either 'buy' or 'sell'.$myconfigis not used.$self->update_exchangerate is used for the majority of the work.
- $form->get_exchangerate($dbh, $curr, $transdate, $fld);
-
Returns the exchange rate in relation to the default currency for
$currencyon$transdatefor the purpose indicated by$fld.$fldcan be either 'buy' or 'sell' to get usable results.$dbhis not used, favouring$self->{dbh}.
- $form->check_exchangerate($myconfig, $currency, $transdate, $fld);
-
Returns some true value when an entry for
$currencyon$transdateis true for the purpose indicated by$fld.$fldcan be either 'buy' or 'sell' to get usable results. Returns false if$transdateis not set.$myconfigis not used.
- $form->add_shipto($dbh, $id);
-
Inserts a new address into the table shipto if the value of any of the shipto address components in
$formdiffers to the regular attribute in$form. The inserted value of trans_id is$id, the other fields correspond with the shipto address components of$form.$dbhis unused.
- $form->get_shipto ($location_id)
-
Returns the shipto record of the corresponding location, and attaches the info as expected for the templates
- $form->get_employee($dbh);
-
Returns a list containing the name and id of the employee
$form->{login}. Any portion of$form->{login} including and past '@' are ignored.$dbhis unused.
- $form->get_name($myconfig, $table[, $transdate])
-
Sets
$form->{name_list} to refer to a list of customers or vendors whose names or numbers match the value found in$form->{$table} and returns the number of matches.$tablecan be 'vendor', 'customer', or 'employee'; if the optional field$transdateis provided, the result set is further limited to$tableentries which were active on the provided date as determined by the start and end dates. The elements of$form->{name_list} are references returned rows in hashref form and are sorted by the name field. The fields of the hash are those of the view$tableand the table entity.$myconfigis unused.
- $form->all_vc($myconfig, $vc, $module, $dbh, $transdate, $job);
-
Populates the list referred to by
$form->{all_${vc}} with hashes of either vendor or customer id and name, ordered by the name. This will be vendor details unless$vcis set to 'customer'. This list can be limited to only vendors or customers which are usable on a given day by specifying$transdate. As a further restriction,$form->{all_${vc}} will not be populated if the number of vendors or customers that would be present in that list exceeds, or is equal to,$myconfig->{vclimit}.In addition to the possible population of
$form->{all_${vc}},$form->{employee_id} is looked up if not already set, the list$form->{all_language} is populated using the language table and is sorted by the description, and$form->all_employees,$form->all_departments,$form->all_projects, and$form->all_taxaccounts are all run.$moduleand$dbhare unused.
- $form->get_regular_metadata($myconfig, $vc, $module, $dbh, $transdate, $job)
-
This is API-compatible with all_vc. It is a handy wrapper function that calls the following functions: all_employees all_departments all_projects all_taxaccounts
It is preferable to using all_vc where the latter does not work properly due to variable collisions, etc.
$form->{employee_id} is looked up if not already set, the list$form->{all_language} is populated using the language table and is sorted by the description, and$form->all_employees,$form->all_departments,$form->all_projects, and$form->all_taxaccounts are all run.$moduleand$dbhare unused.
- $form->all_accounts()
-
Sets
$form->{accounts} to all accounts. Returns the list as well. Example: my@account_list=$form->all_accounts();
- $form->all_taxaccounts($myconfig, $dbh2[, $transdate]);
-
Get the tax rates and numbers for all the taxes in
$form->{taxaccounts}. Does nothing if$form->{taxaccounts} is false. Taxes are listed as a space separated list of account numbers from the chart. The retrieved values are placed within$form->{${accno}_rate} and$form->{${accno}_taxnumber}. If$transdateis set, then only process taxes that were valid on$transdate.$myconfigand$dbh2are unused.
- $form->all_employees($myconfig, $dbh2, $transdate, $sales);
-
Sets
$form->{all_employee} to be a reference to an array referencing hashes of employee information. The hashes are of the form {'id' => id, 'name' => name}. If$transdateis set, the query is limited to employees who are active on that day. If$salesis true, only employees with the sales flag set are added.$dbh2is unused.
- $form->all_projects($myconfig, $dbh2[, $transdate, $job]);
-
Populates the list referred to as
$form->{all_project} with hashes detailing all projects. If$jobis true, limit the projects to those whose ids are not also present in parts with a project_id > 0. If$transdateis set, the projects are limited to those valid on$transdate. If$form->{language_code} is set, include the translation description in the project list and limit to translations with a matching language_code. The result list,$form->{all_project}, is sorted by projectnumber.$myconfigand$dbh2are unused.$jobappears to be part of attempted job- costing support.
- $form->all_departments($myconfig, $dbh2, $vc);
-
Set
$form->{all_department} to be a reference to a list of hashrefs describing departments of the form {'id' => id, 'description' => description}. If$vcis 'customer', further limit the results to those whose role is 'P' (Profit Center).This procedure is internally followed by a call to
$form->all_years($myconfig).$dbh2is not used.
- $form->all_languages($myconfig);
-
Set
$form->{all_language} to be a reference to a list of hashrefs describing languages using the form {'code' => code, 'description' => description}.
- $form->all_years($myconfig[, $dbh2]);
-
Populates the hash
$form->{all_month} with a mapping between a two-digit month number and the English month name. Populates the list$form->{all_years} with all years which contain transactions.$dbh2is unused.
- $form->create_links( { module => $module, myconfig => $myconfig, vc => $vc, billing => $billing [, job => $job ] });
-
Populates the hash referred to as
$form->{${module}_links} details about accounts that have$modulein their link field. The hash is keyed upon link elements such as 'AP_amount' and 'AR_tax' and they refer to lists of hashes containing accno and description for the appropriate accounts. If the key does not contain 'tax', the account number is appended to the space separated list$form->{accounts}.$moduleis typically 'AR' or 'AP' and is the base type of the accounts looked up.If
$form->{id} is not set, check$form->{"$form->{vc}_id"}. If neither is set, use$form->lastname_used to populate the details. If$form->{id} is set, populate the invnumber, transdate, ${vc}_id, datepaid, duedate, ordnumber, taxincluded, currency, notes, intnotes, ${vc}, department_id, department, oldinvtotal, oldtotalpaid, employee_id, employee, language_code, ponumber, reverse, printed, emailed, queued, recurring, exchangerate, and acc_trans attributes of$formwith details about the transaction$form->{id}. All of these attributes, save for acc_trans, are scalar;$form->{acc_trans} refers to a hash keyed by link elements whose values are lists of references to hashes describing acc_trans table entries corresponding to the transaction$form->{id}. The elements in the acc_trans entry hashes are accno, description, source, amount, memo, transdate, cleared, project_id, projectnumber, and exchangerate.The closedto, separate_duties, revtrans, and currencies
$formattributes are filled with values from the defaults table, while$form->{current_date} is populated with the current date. If$form->{id} is not set, then$form->{transdate} also takes on the current date.When
$billingis provided and true, the email addresses are selected from the billing contact classes, when available, falling back to the normal email classes when not.After all this, it calls
$form->all_vc to conclude.
- $form->lastname_used($myconfig, $dbh2, $vc, $module);
-
Fills the name, currency, ${vc}_id, duedate, and possibly invoice_notes attributes of
$formwith the last used values for the transaction type specified by both$vcand$form->{type}.$vccan be either 'vendor' or 'customer' and if unspecified will take on the value given in$form->{vc}, defaulting to 'vendor'. If$form->{type} matches /_order/, the transaction type used is order, if it matches /_quotation/, quotations are looked through. If$form->{type} does not match either of the above, then ar or ap transactions are used.$myconfig,$dbh2, and$moduleare unused.
- $form->current_date($myconfig[, $thisdate, $days]);
-
If
$thisdateis false, get the current date from the database.If
$thisdateis true, get the date$daysdays from$thisdatein the date format specified by$myconfig->{dateformat} from the database.
- $form->like($str);
-
Returns '%$str%'
- $form->redo_rows($flds, $new, $count, $numrows);
-
$fldsrefers to a list of field names and$newrefers to a list of row detail hashes with the elements of$fldsas keys as well as runningnumber for an order or another multi-row item that normally expresses elements in the form$form->{${fieldname}_${index}}.For every
$fieldin @{$flds} populates$form->{${field}_$i} with an appropriate value from a$newdetail hash where$iis an index between 1 and$count. The ordering of the details is done in terms of the runningnumber element of the row detail hashes in$new.All
$formattributes with names of the form ${field}_$i where the index$iis between$count+ 1 and$numrowsis deleted.
- $form->get_partsgroup($myconfig[, $p]);
-
Populates the list referred to as
$form->{all_partsgroup}.$prefers to a hash that describes which partsgroups to retrieve.$p->{searchitems} can be 'part', 'service', 'assembly', 'labor', or 'nolabor' and will limit the groups to those that contain the item type described.$p->{searchitems} and$p->{all} conflict. If$p->{all} is set and$p->{language_code} is not, all partsgroups are retrieved. If$p->{language_code} is set, also include the translation description specified by$p->{language_code} for the partsgroup.The results in
$form->{all_partsgroup} are normally sorted by partsgroup name. If a language_code is specified, the results are then sorted by the translated description.$myconfigis unused.
- $form->update_status($myconfig);
-
DELETEs all status rows which have a formname of
$form->{formname} and a trans_id of$form->{id}. INSERTs a new row into status where trans_id is$form->{id}, formname is$form->{formname}, printed and emailed are true if their respective$formattributes match /$form->{formname}/, and spoolfile is the file extracted from the string$form->{queued} or NULL if there is no entry for$form->{formname}.$myconfigis unused.
- $form->save_status();
-
Clears out any old status entries for
$form->{id} and saves new status entries. Queued form names are extracted from$form->{queued}. Printed and emailed form names are extracted from$form->{printed} and$form->{emailed}. The queued, printed, and emailed fields are space separated lists.
- $form->get_recurring();
-
Sets
$form->{recurring} to contain info about the recurrence schedule for the action$form->{id}.$form->{recurring} is of the same form used by$form->save_recurring($dbh2,$myconfig).reference,startdate,repeat,unit,howmany,payment,print,email,messagetext date int text int int text text text
- $form->save_recurring($dbh2, $myconfig);
-
Saves or deletes recurring transaction scheduling.
$form->{id} is used to determine the id used in the various recurring tables. A recurring transaction schedule is deleted by having$form->{recurring} be false. For adding or updating a schedule,$form->{recurring} is a comma separated field with partial subfield quoting of the form:reference,startdate,repeat,unit,howmany,payment,print,email,messagetext date int text int int text text text- reference
-
A URI-encoded reference string for the recurrence set.
- startdate
-
The index date for the recurrence.
- repeat
-
The unitless repetition frequency.
- unit
-
The interval unit used. Can be 'days', 'weeks', 'months', or 'years', capitalisation and pluralisation ignored.
- howmany
-
The number of recurrences for the transaction.
- payment
-
Flag to indicate if a payment is included in the transaction.
-
A colon separated list of formname:format:printer triplets.
-
A colon separated list of formname:format pairs.
- message
-
A URI-encoded message for the emails to be sent.
Values for the nextdate and enddate columns of the recurring table are calculated using startdate, repeat, unit, howmany, and the current database date. All other fields of the recurring, recurringemail, and recurringprint are obtained directly from
$form->{recurring}.WARNING: This function does not check the validity of most subfields of
$form->{recurring}.$dbh2is not used.
- $form->save_intnotes($myconfig, $vc);
-
Sets the intnotes field of the entry in the table
$vcthat has the id$form->{id} to the value of$form->{intnotes}.Does nothing if
$form->{id} is not set.
- $form->update_defaults($myconfig, $fld[, $dbh [, $nocommit]);
-
Updates the defaults entry for the setting
$fldfollowing rules specified by the existing value and returns the processed value that results. If$formis false, such as the case when invoked as "Form::update_defaults('',...)",$dbhis used as the handle. When$formis set, it uses$form->{dbh}, initialising the connection if it does not yet exist. The entry$fldmust exist prior to executing this function and this update function does not handle the general case of updating the defaults table.Note that nocommit prevents the db from committing in this function.
NOTE: rules handling is currently broken.
Rules followed by this function's processing:
- •
-
If digits are found in the field, increment the left-most set. This change, unlike the others is reflected in the UPDATE.
- •
-
Replace <?lsmb date ?> with the date specified in
$form->{transdate} formatted as$myconfig->{dateformat}.
- •
-
Replace <?lsmb curr ?> with the value of
$form->{currency}
- $form->db_prepare_vars(var1, var2, ..., varn)
-
Undefines
$form->{varm}, 1 <= m <= n, iff$form-<{varm is both false and not "0".
- $form->split_date($dateformat[, $date]);
-
Returns ($rv,
$yy,$mm,$dd) for the provided$date, or the current date if no date is provided.$rvis a seperator-free merging of the fields$yy,$mm, and$ddin the ordering supplied by$dateformat. If the supplied$datedoes not contain non-digit characters,$rvis$dateand the other return values are undefined.$yyis two digits.
- $form->format_date($date);
-
Returns
$dateconverted from 'yyyy-mm-dd' format to the format specified by$form->{db_dateformat}. If the supplied date does not match /^\d{4}\D/, return the supplied date.This function takes a four digit year and returns the date with a four digit year.
- $form->from_to($yyyy, $mm[, $interval]);
-
Returns the date
$yyyy-$mm-01 and the the last day of the month interval - 1 months from then in the form ($form->format_date(fromdate),$form->format_date(later)). If$intervalis false but defined, the later date is the current date.This function dies horribly when
$mm+$interval> 24
- $form->audittrail($dbh, $myconfig, $audittrail);
-
Audit trail has been replaced by triggers which work on a very similar manner.