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