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