Added 'editable' field in stock_master
[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 {
14         var $version = '2.2';   // version installed
15         var $description;
16         var $sql = 'alter2.2.sql';
17         var $preconf = true;
18         var $beta = false; // upgrade from 2.1 or 2.2beta; set in pre_check
19         
20         function fa2_2() {
21                 global $security_groups;
22                 $this->beta = !isset($security_groups);
23                 $this->description = _('Upgrade from version 2.1/2.2beta to 2.2');
24                 $this->preconf = fix_extensions();
25         }
26         
27         //
28         //      Install procedure. All additional changes 
29         //      not included in sql file should go here.
30         //
31         function install($pref, $force) 
32         {
33                 global $db, $systypes_array;
34                 
35                 if (!$this->preconf)
36                         return false;
37
38                 // Until 2.2 sanitizing text input with db_escape was not
39                 // consequent enough. To avoid comparision problems we have to 
40                 // fix this now.
41                 sanitize_database($pref);
42
43                 if ($this->beta)        // nothing more to be done on upgrade from 2.2beta
44                         return true;
45
46                 // set item category dflt accounts to values from company GL setup
47                 $prefs = get_company_prefs();
48                 $sql = "UPDATE {$pref}stock_category SET "
49                         ."dflt_sales_act = '" . $prefs['default_inv_sales_act'] . "',"
50                         ."dflt_cogs_act = '". $prefs['default_cogs_act'] . "',"
51                         ."dflt_inventory_act = '" . $prefs['default_inventory_act'] . "',"
52                         ."dflt_adjustment_act = '" . $prefs['default_adj_act'] . "',"
53                         ."dflt_assembly_act = '" . $prefs['default_assembly_act']."'";
54                 if (db_query($sql)==false) {
55                         display_error("Cannot update category default GL accounts"
56                         .':<br>'. db_error_msg($db));
57                         return false;
58                 }
59                 // add all references to refs table for easy searching via journal interface
60                 foreach($systypes_array as $typeno => $typename) {
61                         $info = get_systype_db_info($typeno);
62                         if ($info == null || $info[3] == null) continue;
63                         $tbl = str_replace(TB_PREF, $pref, $info[0]);
64                         $sql = "SELECT DISTINCT {$info[2]} as id,{$info[3]} as ref FROM $tbl";
65                         if ($info[1])
66                                 $sql .= " WHERE {$info[1]}=$typeno";
67                         $result = db_query($sql);
68                         if (db_num_rows($result)) {
69                                 while ($row = db_fetch($result)) {
70                                         $res2 = db_query("INSERT INTO {$pref}refs VALUES("
71                                                 . $row['id'].",".$typeno.",'".$row['ref']."')");
72                                         if (!$res2) {
73                                                 display_error(_("Cannot copy references from $tbl")
74                                                         .':<br>'. db_error_msg($db));
75                                                 return false;
76                                         }
77                                 }
78                         }
79                 }
80
81                 if (!($ret = db_query("SELECT MAX(`order_no`) FROM `{$pref}sales_orders`")) ||
82                         !db_num_rows($ret))
83                 {
84                                 display_error(_('Cannot query max sales order number.'));
85                                 return false;
86                 } 
87                 $row = db_fetch($ret);
88                 $max_order = $row[0];
89                 $next_ref = $max_order+1;
90                 $sql = "UPDATE `{$pref}sys_types` 
91                         SET `type_no`='$max_order',`next_reference`='$next_ref'
92                         WHERE `type_id`=30";
93                 if(!db_query($sql))
94                 {
95                         display_error(_('Cannot store next sales order reference.'));
96                         return false;
97                 }
98                 return convert_roles($pref);
99         }
100         //
101         //      Checking before install
102         //
103         function pre_check($pref, $force)
104         {       
105                 global $security_groups;
106                 
107                 if ($this->beta && !$force)
108                         $this->sql = 'alter2.2rc.sql';
109                 // return ok when security groups still defined (upgrade from 2.1)
110                 // or usersonline not defined (upgrade from 2.2 beta)
111                 return isset($security_groups) || (check_table($pref, 'usersonline')!=0);
112         }
113         //
114         //      Test if patch was applied before.
115         //
116         function installed($pref) {
117                 $n = 1; // number of patches to be installed
118                 $patchcnt = 0;
119                 if (!$this->beta) {
120                         $n = 16;
121                         if (check_table($pref, 'company', 'custom1_name')) $patchcnt++;
122                         if (!check_table($pref, 'company', 'profit_loss_year_act')) $patchcnt++;
123                         if (!check_table($pref, 'company', 'login_tout')) $patchcnt++;
124                         if (!check_table($pref, 'stock_category', 'dflt_no_sale')) $patchcnt++;
125                         if (!check_table($pref, 'users', 'sticky_doc_date')) $patchcnt++;
126                         if (!check_table($pref, 'users', 'startup_tab')) $patchcnt++;
127                         if (!check_table($pref, 'cust_branch', 'inactive')) $patchcnt++;
128                         if (!check_table($pref, 'chart_class', 'ctype')) $patchcnt++;
129                         if (!check_table($pref, 'audit_trail')) $patchcnt++;
130                         if (!check_table($pref, 'currencies', 'auto_update')) $patchcnt++;
131                         if (!check_table($pref, 'stock_master','no_sale')) $patchcnt++;
132                         if (!check_table($pref, 'suppliers', 'supp_ref')) $patchcnt++;
133                         if (!check_table($pref, 'users', 'role_id')) $patchcnt++;
134                         if (!check_table($pref, 'sales_orders', 'reference')) $patchcnt++;
135                         if (!check_table($pref, 'tags')) $patchcnt++;
136                 } 
137                 if (!check_table($pref, 'useronline')) $patchcnt++;
138
139                 $n -= $patchcnt;
140                 return $n == 0 ? true : $patchcnt;
141         }
142 };
143
144 /*
145         Conversion of old security roles stored into $security_groups table
146 */
147 function convert_roles($pref) 
148 {
149                 global $security_groups, $security_headings, $security_areas, $path_to_root;
150                 include_once($path_to_root."/includes/access_levels.inc");
151
152         $trans_sec = array(
153                 1 => array('SA_CHGPASSWD', 'SA_SETUPDISPLAY', 'SA_BANKTRANSVIEW',
154                         'SA_ITEMSTRANSVIEW','SA_SUPPTRANSVIEW', 'SA_SALESORDER',
155                         'SA_SALESALLOC', 'SA_SALESTRANSVIEW'),
156                 2 => array('SA_DIMTRANSVIEW', 'SA_STANDARDCOST', 'SA_ITEMSTRANSVIEW',
157                         'SA_ITEMSSTATVIEW', 'SA_SALESPRICE', 'SA_MANUFTRANSVIEW',
158                         'SA_WORKORDERANALYTIC', 'SA_WORKORDERCOST', 'SA_SUPPTRANSVIEW',
159                         'SA_SUPPLIERALLOC', 'SA_STEMPLATE', 'SA_SALESTRANSVIEW',
160                         'SA_SALESINVOICE', 'SA_SALESDELIVERY', 'SA_CUSTPAYMREP',
161                         'SA_CUSTBULKREP', 'SA_PRICEREP', 'SA_SALESBULKREP', 'SA_SALESMANREP',
162                         'SA_SALESBULKREP', 'SA_CUSTSTATREP', 'SA_SUPPLIERANALYTIC',
163                         'SA_SUPPPAYMREP', 'SA_SUPPBULKREP', 'SA_ITEMSVALREP', 'SA_ITEMSANALYTIC',
164                         'SA_BOMREP', 'SA_MANUFBULKREP', 'SA_DIMENSIONREP', 'SA_BANKREP', 'SA_GLREP',
165                         'SA_GLANALYTIC', 'SA_TAXREP', 'SA_SALESANALYTIC', 'SA_SALESQUOTE'),
166                 3 => array('SA_GLACCOUNTGROUP', 'SA_GLACCOUNTCLASS','SA_PAYMENT', 
167                         'SA_DEPOSIT', 'SA_JOURNALENTRY', 'SA_INVENTORYMOVETYPE',
168                         'SA_LOCATIONTRANSFER', 'SA_INVENTORYADJUSTMENT', 'SA_WORKCENTRES',
169                         'SA_MANUFISSUE', 'SA_SUPPLIERALLOC', 'SA_CUSTOMER', 'SA_CRSTATUS',
170                         'SA_SALESMAN', 'SA_SALESAREA', 'SA_SALESALLOC', 'SA_SALESCREDITINV',
171                         'SA_SALESPAYMNT', 'SA_SALESCREDIT', 'SA_SALESGROUP', 'SA_SRECURRENT',
172                         'SA_TAXRATES', 'SA_ITEMTAXTYPE', 'SA_TAXGROUPS', 'SA_QUICKENTRY'),
173                 4 => array('SA_REORDER', 'SA_PURCHASEPRICING', 'SA_PURCHASEORDER'),
174                 5 => array('SA_VIEWPRINTTRANSACTION', 'SA_BANKTRANSFER', 'SA_SUPPLIER',
175                         'SA_SUPPLIERINVOICE', 'SA_SUPPLIERPAYMNT', 'SA_SUPPLIERCREDIT'),
176                 8 => array('SA_ATTACHDOCUMENT', 'SA_RECONCILE', 'SA_GLANALYTIC',
177                         'SA_TAXREP', 'SA_BANKTRANSVIEW', 'SA_GLTRANSVIEW'),
178                 9 => array('SA_FISCALYEARS', 'SA_CURRENCY', 'SA_EXCHANGERATE', 
179                         'SA_BOM'),
180                 10 => array('SA_PAYTERMS', 'SA_GLSETUP', 'SA_SETUPCOMPANY',
181                         'SA_FORMSETUP', 'SA_DIMTRANSVIEW', 'SA_DIMENSION', 'SA_BANKACCOUNT',
182                         'SA_GLACCOUNT', 'SA_BUDGETENTRY', 'SA_MANUFRECEIVE',
183                         'SA_MANUFRELEASE', 'SA_WORKORDERENTRY', 'SA_MANUFTRANSVIEW',
184                         'SA_WORKORDERCOST'),
185                 11 => array('SA_ITEMCATEGORY', 'SA_ITEM', 'SA_UOM', 'SA_INVENTORYLOCATION',
186                          'SA_GRN', 'SA_FORITEMCODE', 'SA_SALESKIT'),
187                 14 => array('SA_SHIPPING', 'SA_VOIDTRANSACTION', 'SA_SALESTYPES'),
188                 15 => array('SA_PRINTERS', 'SA_PRINTPROFILE', 'SA_BACKUP', 'SA_USERS',
189                         'SA_POSSETUP'),
190                 20 => array('SA_CREATECOMPANY', 'SA_CREATELANGUAGE', 'SA_CREATEMODULES',
191                         'SA_SOFTWAREUPGRADE', 'SA_SECROLES', 'SA_DIMTAGS', 'SA_GLACCOUNTTAGS')
192                 );
193                 $new_ids = array();
194                 foreach ($security_groups as $role_id => $areas) {
195                         $area_set = array();
196                         $sections = array();
197                         foreach ($areas as $a) {
198                          if (isset($trans_sec[$a]))
199                                 foreach ($trans_sec[$a] as $id) {
200                                  if ($security_areas[$id][0] != 0)
201 //                                      error_log('invalid area id: '.$a.':'.$id);
202                                         $area_set[] = $security_areas[$id][0];
203                                         $sections[$security_areas[$id][0]&~0xff] = 1;
204                                 }
205                         }
206                         $sections  = array_keys($sections);
207                         sort($sections); sort($area_set);
208                         import_security_role($pref, $security_headings[$role_id], $sections, $area_set);
209                         $new_ids[$role_id] = db_insert_id();
210                 }
211                 $result = get_users(true);
212                 $users = array();
213                 while($row = db_fetch($result)) { // complete old user ids and roles
214                         $users[$row['role_id']][] = $row['id'];
215                 }
216                 foreach($users as $old_id => $uids)
217                         foreach( $uids as $id) {
218                                 $sql = "UPDATE {$pref}users set role_id=".$new_ids[$old_id].
219                                         " WHERE id=$id";
220                                 $ret = db_query($sql, 'cannot update users roles');
221                                 if(!$ret) return false;
222                         }
223                 return true;
224 }
225
226 function import_security_role($pref, $name, $sections, $areas)
227 {
228         $sql = "INSERT INTO {$pref}security_roles (role, description, sections, areas)
229         VALUES (".db_escape('FA 2.1 '.$name).",".db_escape($name).","
230         .db_escape(implode(';',$sections)).",".db_escape(implode(';',$areas)).")";
231
232         db_query($sql, "could not add new security role");
233 }
234
235 /*
236         Changes in extensions system.
237         This function is executed once on first Upgrade System display.
238 */
239 function fix_extensions() {
240         global $path_to_root, $db_connections;
241
242         if (!file_exists($path_to_root.'/modules/installed_modules.php'))
243                 return true; // already converted
244         
245         if (!is_writable($path_to_root.'/modules/installed_modules.php')) {
246                 display_error(_('Cannot upgrade extensions system: file /modules/installed_modules.php is not writeable'));
247                 return false;
248         }
249         
250         $exts = array();
251         include($path_to_root.'/installed_extensions.php');
252         foreach($installed_extensions as $ext) {
253                 $ext['filename'] = $ext['app_file']; unset($ext['app_file']);
254                 $ext['tab'] = $ext['name'];
255                 $ext['name'] = access_string($ext['title'], true); 
256                 $ext['path'] = $ext['folder']; unset($ext['folder']);
257                 $ext['type'] = 'module';
258                 $ext['active'] = '1';
259                 $exts[] = $ext;
260         }
261
262         include($path_to_root.'/modules/installed_modules.php');
263         foreach($installed_modules as $mod) {
264                 $mod['title'] = $mod['name'];
265                 $mod['name'] = access_string($mod['name'], true);
266                 $mod['type'] = 'plugin';
267                 $ext['active'] = '1';
268                 $exts[] = $mod;
269         }
270         if (!write_extensions($exts))
271                 return false;
272         
273         $cnt = count($db_connections);
274         for ($i = 0; $i < $cnt; $i++)
275                 write_extensions($exts, $i);
276
277         unlink($path_to_root.'/modules/installed_modules.php');
278         return true;
279 }
280
281 /*
282         Find and update all database records with special chars in text fields 
283         to ensure all of them are changed to html entites.
284 */
285 function sanitize_database($pref, $test = false) {
286
287          if ($test)
288                 error_log('Sanitizing database ...');
289
290          $tsql = "SHOW TABLES LIKE '".($pref=='' ? '' : substr($pref,0,-1).'\\_')."%'";
291          $tresult = db_query($tsql, "Cannot select all tables with prefix '$pref'");
292          while($tbl = db_fetch($tresult)) {
293                 $table = $tbl[0];
294                 $csql = "SHOW COLUMNS FROM $table";
295                 $cresult = db_query($csql, "Cannot select column names for table '$table'");
296                 $textcols = $keys = array();
297                 while($col = db_fetch($cresult)) {
298                         if (strpos($col['Type'], 'char')!==false 
299                                         || strpos($col['Type'], 'text')!==false)
300                                 $textcols[] = '`'.$col['Field'].'`';
301                         if ($col['Key'] == 'PRI') {
302                                 $keys[] = '`'.$col['Field'].'`';
303                         }
304                 }
305
306                 if ($test)
307                         error_log("Table $table (".implode(',',$keys)."):(".implode(',',$textcols)."):");
308
309                 if (!count($textcols)) continue;
310
311                 // fetch all records containing special characters in text fields
312                 $sql = "SELECT ".implode(',', array_unique(array_merge($keys,$textcols)))
313                         ." FROM {$table} WHERE 
314                         CONCAT(".implode(',', $textcols).") REGEXP '[\\'\"><&]'";
315                 $result = db_query($sql, "Cannot select all suspicious fields in $table");
316
317                 // and fix them
318                 while($rec= db_fetch($result)) {
319                         $sql = "UPDATE {$table} SET ";
320                         $val = $key = array();
321                         foreach ($textcols as $f) {
322                                 $val[] = $f.'='.db_escape($rec[substr($f,1,-1)]);
323                         }
324                         $sql .= implode(',', $val). ' WHERE ';
325                         foreach ($keys as $k) {
326                                 $key[] = $k.'=\''.$rec[substr($k,1,-1)].'\'';
327                         }
328                         $sql .= implode( ' AND ', $key);
329                         if ($test)
330                                 error_log("\t(".implode(',',$val).") updated");
331                         else
332                                 db_query($sql, 'cannot update record');
333                 }
334         }
335          if ($test)
336                 error_log('Sanitizing done.');
337 }
338
339 $install = new fa2_2;
340 ?>