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