2 /**********************************************************************
3 Copyright (C) FrontAccounting, LLC.
4 Released under the terms of the GNU General Public License, GPL,
5 as published by the Free Software Foundation, either version 3
6 of the License, or (at your option) any later version.
7 This program is distributed in the hope that it will be useful,
8 but WITHOUT ANY WARRANTY; without even the implied warranty of
9 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
11 ***********************************************************************/
13 class fa2_2 extends fa_patch {
14 var $previous = '2.1'; // applicable database version
15 var $version = '2.2rc'; // version installed
17 var $sql = 'alter2.2.sql';
19 var $beta = false; // upgrade from 2.1 or 2.2beta; set in prepare()
21 function __construct() {
22 global $security_groups;
23 $this->beta = !isset($security_groups);
24 $this->description = _('Upgrade from version 2.1/2.2beta to 2.2');
25 $this->preconf = fix_extensions();
29 // Install procedure. All additional changes
30 // not included in sql file should go here.
32 function install($company, $force=false)
34 global $db, $systypes_array, $db_connections;
39 $pref = $db_connections[$company]['tbpref'];
40 // Until 2.2 sanitizing text input with db_escape was not
41 // consequent enough. To avoid comparision problems we have to
43 sanitize_database($pref);
45 if ($this->beta) // nothing more to be done on upgrade from 2.2beta
48 // set item category dflt accounts to values from company GL setup
49 $prefs = get_company_prefs();
50 $sql = "UPDATE ".TB_PREF."stock_category SET "
51 ."dflt_sales_act = '" . $prefs['default_inv_sales_act'] . "',"
52 ."dflt_cogs_act = '". $prefs['default_cogs_act'] . "',"
53 ."dflt_inventory_act = '" . $prefs['default_inventory_act'] . "',"
54 ."dflt_adjustment_act = '" . $prefs['default_adj_act'] . "',"
55 ."dflt_assembly_act = '" . $prefs['default_assembly_act']."'";
56 if (db_query($sql)==false) {
57 display_error("Cannot update category default GL accounts"
58 .':<br>'. db_error_msg($db));
61 // add all references to refs table for easy searching via journal interface
62 foreach($systypes_array as $typeno => $typename) {
63 $info = get_systype_db_info($typeno);
64 if ($info == null || $info[3] == null) continue;
66 $sql = "SELECT DISTINCT {$info[2]} as id,{$info[3]} as ref FROM $tbl";
68 $sql .= " WHERE {$info[1]}=$typeno";
69 $result = db_query($sql);
70 if (db_num_rows($result)) {
71 while ($row = db_fetch($result)) {
72 $res2 = db_query("INSERT INTO ".TB_PREF."refs VALUES("
73 . $row['id'].",".$typeno.",'".$row['ref']."')");
75 display_error(_("Cannot copy references from $tbl")
76 .':<br>'. db_error_msg($db));
83 if (!($ret = db_query("SELECT MAX(`order_no`) FROM `".TB_PREF."sales_orders`")) ||
86 display_error(_('Cannot query max sales order number.'));
89 $row = db_fetch($ret);
91 $next_ref = $max_order+1;
92 $sql = "UPDATE `".TB_PREF."sys_types`
93 SET `type_no`='$max_order',`next_reference`='$next_ref'
97 display_error(_('Cannot store next sales order reference.'));
100 return convert_roles($pref);
103 // Checking before install
107 global $security_groups;
110 $this->sql = 'alter2.2rc.sql';
111 // return ok when security groups still defined (upgrade from 2.1)
112 // or usersonline not defined (upgrade from 2.2 beta)
113 $pref = $this->companies[$company]['tbpref'];
115 return isset($security_groups) || (check_table($pref, 'usersonline')!=0);
120 Conversion of old security roles stored into $security_groups table
122 function convert_roles($pref)
124 global $security_groups, $security_headings, $security_areas, $path_to_root;
125 include_once($path_to_root."/includes/access_levels.inc");
128 1 => array('SA_CHGPASSWD', 'SA_SETUPDISPLAY', 'SA_BANKTRANSVIEW',
129 'SA_ITEMSTRANSVIEW','SA_SUPPTRANSVIEW', 'SA_SALESORDER',
130 'SA_SALESALLOC', 'SA_SALESTRANSVIEW'),
131 2 => array('SA_DIMTRANSVIEW', 'SA_STANDARDCOST', 'SA_ITEMSTRANSVIEW',
132 'SA_ITEMSSTATVIEW', 'SA_SALESPRICE', 'SA_MANUFTRANSVIEW',
133 'SA_WORKORDERANALYTIC', 'SA_WORKORDERCOST', 'SA_SUPPTRANSVIEW',
134 'SA_SUPPLIERALLOC', 'SA_STEMPLATE', 'SA_SALESTRANSVIEW',
135 'SA_SALESINVOICE', 'SA_SALESDELIVERY', 'SA_CUSTPAYMREP',
136 'SA_CUSTBULKREP', 'SA_PRICEREP', 'SA_SALESBULKREP', 'SA_SALESMANREP',
137 'SA_SALESBULKREP', 'SA_CUSTSTATREP', 'SA_SUPPLIERANALYTIC',
138 'SA_SUPPPAYMREP', 'SA_SUPPBULKREP', 'SA_ITEMSVALREP', 'SA_ITEMSANALYTIC',
139 'SA_BOMREP', 'SA_MANUFBULKREP', 'SA_DIMENSIONREP', 'SA_BANKREP', 'SA_GLREP',
140 'SA_GLANALYTIC', 'SA_TAXREP', 'SA_SALESANALYTIC', 'SA_SALESQUOTE'),
141 3 => array('SA_GLACCOUNTGROUP', 'SA_GLACCOUNTCLASS','SA_PAYMENT',
142 'SA_DEPOSIT', 'SA_JOURNALENTRY', 'SA_INVENTORYMOVETYPE',
143 'SA_LOCATIONTRANSFER', 'SA_INVENTORYADJUSTMENT', 'SA_WORKCENTRES',
144 'SA_MANUFISSUE', 'SA_SUPPLIERALLOC', 'SA_CUSTOMER', 'SA_CRSTATUS',
145 'SA_SALESMAN', 'SA_SALESAREA', 'SA_SALESALLOC', 'SA_SALESCREDITINV',
146 'SA_SALESPAYMNT', 'SA_SALESCREDIT', 'SA_SALESGROUP', 'SA_SRECURRENT',
147 'SA_TAXRATES', 'SA_ITEMTAXTYPE', 'SA_TAXGROUPS', 'SA_QUICKENTRY'),
148 4 => array('SA_REORDER', 'SA_PURCHASEPRICING', 'SA_PURCHASEORDER'),
149 5 => array('SA_VIEWPRINTTRANSACTION', 'SA_BANKTRANSFER', 'SA_SUPPLIER',
150 'SA_SUPPLIERINVOICE', 'SA_SUPPLIERPAYMNT', 'SA_SUPPLIERCREDIT'),
151 8 => array('SA_ATTACHDOCUMENT', 'SA_RECONCILE', 'SA_GLANALYTIC',
152 'SA_TAXREP', 'SA_BANKTRANSVIEW', 'SA_GLTRANSVIEW'),
153 9 => array('SA_FISCALYEARS', 'SA_CURRENCY', 'SA_EXCHANGERATE',
155 10 => array('SA_PAYTERMS', 'SA_GLSETUP', 'SA_SETUPCOMPANY',
156 'SA_FORMSETUP', 'SA_DIMTRANSVIEW', 'SA_DIMENSION', 'SA_BANKACCOUNT',
157 'SA_GLACCOUNT', 'SA_BUDGETENTRY', 'SA_MANUFRECEIVE',
158 'SA_MANUFRELEASE', 'SA_WORKORDERENTRY', 'SA_MANUFTRANSVIEW',
160 11 => array('SA_ITEMCATEGORY', 'SA_ITEM', 'SA_UOM', 'SA_INVENTORYLOCATION',
161 'SA_GRN', 'SA_FORITEMCODE', 'SA_SALESKIT'),
162 14 => array('SA_SHIPPING', 'SA_VOIDTRANSACTION', 'SA_SALESTYPES'),
163 15 => array('SA_PRINTERS', 'SA_PRINTPROFILE', 'SA_BACKUP', 'SA_USERS',
165 20 => array('SA_CREATECOMPANY', 'SA_CREATELANGUAGE', 'SA_CREATEMODULES',
166 'SA_SOFTWAREUPGRADE', 'SA_SECROLES', 'SA_DIMTAGS', 'SA_GLACCOUNTTAGS')
169 foreach ($security_groups as $role_id => $areas) {
172 foreach ($areas as $a) {
173 if (isset($trans_sec[$a]))
174 foreach ($trans_sec[$a] as $id) {
175 if ($security_areas[$id][0] != 0)
176 // error_log('invalid area id: '.$a.':'.$id);
177 $area_set[] = $security_areas[$id][0];
178 $sections[$security_areas[$id][0]&~0xff] = 1;
181 $sections = array_keys($sections);
182 sort($sections); sort($area_set);
183 import_security_role($security_headings[$role_id], $sections, $area_set);
184 $new_ids[$role_id] = db_insert_id();
186 $result = get_users(true);
188 while($row = db_fetch($result)) { // complete old user ids and roles
189 $users[$row['role_id']][] = $row['id'];
191 foreach($users as $old_id => $uids)
192 foreach( $uids as $id) {
193 $sql = "UPDATE ".TB_PREF."users set role_id=".$new_ids[$old_id].
195 $ret = db_query($sql, 'cannot update users roles');
196 if(!$ret) return false;
201 function import_security_role($name, $sections, $areas)
203 $sql = "INSERT INTO ".TB_PREF."security_roles (role, description, sections, areas)
204 VALUES (".db_escape('FA 2.1 '.$name).",".db_escape($name).","
205 .db_escape(implode(';',$sections)).",".db_escape(implode(';',$areas)).")";
207 db_query($sql, "could not add new security role");
211 Changes in extensions system.
212 This function is executed once on first Upgrade System display.
214 function fix_extensions() {
215 global $path_to_root, $db_connections;
217 if (!file_exists($path_to_root.'/modules/installed_modules.php'))
218 return true; // already converted
220 if (!is_writable($path_to_root.'/modules/installed_modules.php')) {
221 display_error(_('Cannot upgrade extensions system: file /modules/installed_modules.php is not writeable'));
226 include($path_to_root.'/installed_extensions.php');
227 foreach($installed_extensions as $ext) {
228 $ext['filename'] = $ext['app_file']; unset($ext['app_file']);
229 $ext['tab'] = $ext['name'];
230 $ext['name'] = access_string($ext['title'], true);
231 $ext['path'] = $ext['folder']; unset($ext['folder']);
232 $ext['type'] = 'extension';
233 $ext['active'] = '1';
237 if (!write_extensions($exts))
240 $cnt = count($db_connections);
241 for ($i = 0; $i < $cnt; $i++)
242 write_extensions($exts, $i);
244 unlink($path_to_root.'/modules/installed_modules.php');
249 Find and update all database records with special chars in text fields
250 to ensure all of them are changed to html entites.
252 function sanitize_database($pref, $test = false) {
255 error_log('Sanitizing database ...');
257 $tsql = "SHOW TABLES LIKE '".($pref=='' ? '' : substr($pref,0,-1).'\\_')."%'";
258 $tresult = db_query($tsql, "Cannot select all tables with prefix '$pref'");
259 while($tbl = db_fetch($tresult)) {
261 $csql = "SHOW COLUMNS FROM $table";
262 $cresult = db_query($csql, "Cannot select column names for table '$table'");
263 $textcols = $keys = array();
264 while($col = db_fetch($cresult)) {
265 if (strpos($col['Type'], 'char')!==false
266 || strpos($col['Type'], 'text')!==false)
267 $textcols[] = '`'.$col['Field'].'`';
268 if ($col['Key'] == 'PRI') {
269 $keys[] = '`'.$col['Field'].'`';
273 if (empty($keys)) { // comments table have no primary key, so give up
277 error_log("Table $table (".implode(',',$keys)."):(".implode(',',$textcols)."):");
279 if (!count($textcols)) continue;
281 // fetch all records containing special characters in text fields
282 $sql = "SELECT ".implode(',', array_unique(array_merge($keys,$textcols)))
283 ." FROM {$table} WHERE
284 CONCAT(".implode(',', $textcols).") REGEXP '[\\'\"><&]'";
285 $result = db_query($sql, "Cannot select all suspicious fields in $table");
288 while($rec= db_fetch($result)) {
289 $sql = "UPDATE {$table} SET ";
290 $val = $key = array();
291 foreach ($textcols as $f) {
292 $val[] = $f.'='.db_escape($rec[substr($f,1,-1)]);
294 $sql .= implode(',', $val). ' WHERE ';
295 foreach ($keys as $k) {
296 $key[] = $k.'=\''.$rec[substr($k,1,-1)].'\'';
298 $sql .= implode( ' AND ', $key);
300 error_log("\t(".implode(',',$val).") updated");
302 db_query($sql, 'cannot update record');
306 error_log('Sanitizing done.');
309 $install = new fa2_2;