[0004212] Work Order Entry: fixed error when voided WO refence is reused.
[fa-stable.git] / sql / alter2.2.php
1 <?php
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 ***********************************************************************/
12
13 class fa2_2 extends fa_patch  {
14         var $previous = '2.1';          // applicable database version
15         var $version = '2.2rc'; // version installed
16         var $description;
17         var $sql = 'alter2.2.sql';
18         var $preconf = true;
19         var $beta = false; // upgrade from 2.1 or 2.2beta; set in prepare()
20         
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();
26         }
27         
28         //
29         //      Install procedure. All additional changes 
30         //      not included in sql file should go here.
31         //
32         function install($company, $force=false) 
33         {
34                 global $db, $systypes_array, $db_connections;
35
36                 if (!$this->preconf)
37                         return false;
38
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 
42                 // fix this now.
43                 sanitize_database($pref);
44
45                 if ($this->beta)        // nothing more to be done on upgrade from 2.2beta
46                         return true;
47
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));
59                         return false;
60                 }
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;
65                         $tbl = $info[0];
66                         $sql = "SELECT DISTINCT {$info[2]} as id,{$info[3]} as ref FROM $tbl";
67                         if ($info[1])
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']."')");
74                                         if (!$res2) {
75                                                 display_error(_("Cannot copy references from $tbl")
76                                                         .':<br>'. db_error_msg($db));
77                                                 return false;
78                                         }
79                                 }
80                         }
81                 }
82
83                 if (!($ret = db_query("SELECT MAX(`order_no`) FROM `".TB_PREF."sales_orders`")) ||
84                         !db_num_rows($ret))
85                 {
86                                 display_error(_('Cannot query max sales order number.'));
87                                 return false;
88                 } 
89                 $row = db_fetch($ret);
90                 $max_order = $row[0];
91                 $next_ref = $max_order+1;
92                 $sql = "UPDATE `".TB_PREF."sys_types` 
93                         SET `type_no`='$max_order',`next_reference`='$next_ref'
94                         WHERE `type_id`=30";
95                 if(!db_query($sql))
96                 {
97                         display_error(_('Cannot store next sales order reference.'));
98                         return false;
99                 }
100                 return convert_roles($pref);
101         }
102         //
103         //      Checking before install
104         //
105         function prepare()
106         {
107                 global $security_groups;
108
109                 if ($this->beta)
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'];
114
115                 return isset($security_groups) || (check_table($pref, 'usersonline')!=0);
116         }
117 };
118
119 /*
120         Conversion of old security roles stored into $security_groups table
121 */
122 function convert_roles($pref) 
123 {
124                 global $security_groups, $security_headings, $security_areas, $path_to_root;
125                 include_once($path_to_root."/includes/access_levels.inc");
126
127         $trans_sec = array(
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', 
154                         'SA_BOM'),
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',
159                         'SA_WORKORDERCOST'),
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',
164                         'SA_POSSETUP'),
165                 20 => array('SA_CREATECOMPANY', 'SA_CREATELANGUAGE', 'SA_CREATEMODULES',
166                         'SA_SOFTWAREUPGRADE', 'SA_SECROLES', 'SA_DIMTAGS', 'SA_GLACCOUNTTAGS')
167                 );
168                 $new_ids = array();
169                 foreach ($security_groups as $role_id => $areas) {
170                         $area_set = array();
171                         $sections = array();
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;
179                                 }
180                         }
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();
185                 }
186                 $result = get_users(true);
187                 $users = array();
188                 while($row = db_fetch($result)) { // complete old user ids and roles
189                         $users[$row['role_id']][] = $row['id'];
190                 }
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].
194                                         " WHERE id=$id";
195                                 $ret = db_query($sql, 'cannot update users roles');
196                                 if(!$ret) return false;
197                         }
198                 return true;
199 }
200
201 function import_security_role($name, $sections, $areas)
202 {
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)).")";
206
207         db_query($sql, "could not add new security role");
208 }
209
210 /*
211         Changes in extensions system.
212         This function is executed once on first Upgrade System display.
213 */
214 function fix_extensions() {
215         global $path_to_root, $db_connections;
216
217         if (!file_exists($path_to_root.'/modules/installed_modules.php'))
218                 return true; // already converted
219         
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'));
222                 return false;
223         }
224         
225         $exts = array();
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';
234                 $exts[] = $ext;
235         }
236
237         if (!write_extensions($exts))
238                 return false;
239         
240         $cnt = count($db_connections);
241         for ($i = 0; $i < $cnt; $i++)
242                 write_extensions($exts, $i);
243
244         unlink($path_to_root.'/modules/installed_modules.php');
245         return true;
246 }
247
248 /*
249         Find and update all database records with special chars in text fields 
250         to ensure all of them are changed to html entites.
251 */
252 function sanitize_database($pref, $test = false) {
253
254          if ($test)
255                 error_log('Sanitizing database ...');
256
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)) {
260                 $table = $tbl[0];
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'].'`';
270                         }
271                 }
272
273                 if (empty($keys)) { // comments table have no primary key, so give up
274                         continue;
275                 }
276                 if ($test)
277                         error_log("Table $table (".implode(',',$keys)."):(".implode(',',$textcols)."):");
278
279                 if (!count($textcols)) continue;
280
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");
286
287                 // and fix them
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)]);
293                         }
294                         $sql .= implode(',', $val). ' WHERE ';
295                         foreach ($keys as $k) {
296                                 $key[] = $k.'=\''.$rec[substr($k,1,-1)].'\'';
297                         }
298                         $sql .= implode( ' AND ', $key);
299                         if ($test)
300                                 error_log("\t(".implode(',',$val).") updated");
301                         else
302                                 db_query($sql, 'cannot update record');
303                 }
304         }
305          if ($test)
306                 error_log('Sanitizing done.');
307 }
308
309 $install = new fa2_2;