56b4fe215a48cd93c26bebaa41f11af09b254599
[fa-stable.git] / admin / create_coy.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 $page_security = 'SA_CREATECOMPANY';
13 $path_to_root="..";
14 include_once($path_to_root . "/includes/session.inc");
15
16 include_once($path_to_root . "/includes/date_functions.inc");
17 include_once($path_to_root . "/admin/db/company_db.inc");
18 include_once($path_to_root . "/admin/db/maintenance_db.inc");
19 include_once($path_to_root . "/includes/ui.inc");
20
21 page(_($help_context = "Create/Update Company"));
22
23 $comp_subdirs = array('images', 'pdf_files', 'backup','js_cache', 'reporting', 'attachments');
24
25 simple_page_mode(true);
26 /*
27         FIXME: tb_pref_counter should track prefix per database.
28 */
29 //---------------------------------------------------------------------------------------------
30 function check_data($selected_id)
31 {
32         global $db_connections, $tb_pref_counter;
33
34         if ($selected_id != -1) {
35                 if ($_POST['name'] == "")
36                 {
37                         display_error(_("Database settings are not specified."));
38                         return false;
39                 }
40         } else {
41                 if (!get_post('name') || !get_post('host') || !get_post('dbuser') || !get_post('dbname'))
42                 {
43                         display_error(_("Database settings are not specified."));
44                         return false;
45                 }
46                 foreach($db_connections as $id=>$con)
47                 {
48                  if($id != $selected_id && $_POST['host'] == $con['host'] 
49                         && $_POST['dbname'] == $con['dbname'])
50                         {
51                                 if ($_POST['tbpref'] == $con['tbpref'])
52                                 {
53                                         display_error(_("This database settings are already used by another company."));
54                                         return false;
55                                 }
56                                 if (($_POST['tbpref'] == 0) ^ ($con['tbpref'] == ''))
57                                 {
58                                         display_error(_("You cannot have table set without prefix together with prefixed sets in the same database."));
59                                         return false;
60                                 }
61                         }
62                 }
63         }
64         return true;
65 }
66
67 //---------------------------------------------------------------------------------------------
68
69 function remove_connection($id) {
70         global $db_connections;
71
72         $err = db_drop_db($db_connections[$id]);
73
74         unset($db_connections[$id]);
75         $conn = array_values($db_connections);
76         $db_connections = $conn;
77     return $err;
78 }
79 //---------------------------------------------------------------------------------------------
80
81 function handle_submit($selected_id)
82 {
83         global $db_connections, $def_coy, $tb_pref_counter, $db,
84             $comp_subdirs, $path_to_root, $Mode;
85
86         $error = false;
87
88         if ($selected_id==-1)
89                 $selected_id = count($db_connections);
90
91         $new = !isset($db_connections[$selected_id]);
92
93         if (check_value('def'))
94                 $def_coy = $selected_id;
95
96         $db_connections[$selected_id]['name'] = $_POST['name'];
97         if ($new) {
98                 $db_connections[$selected_id]['host'] = $_POST['host'];
99                 $db_connections[$selected_id]['dbuser'] = $_POST['dbuser'];
100                 $db_connections[$selected_id]['dbpassword'] = html_entity_decode($_POST['dbpassword'], ENT_QUOTES, 
101                         $_SESSION['language']->encoding=='iso-8859-2' ? 'ISO-8859-1' : $_SESSION['language']->encoding);
102                 $db_connections[$selected_id]['dbname'] = $_POST['dbname'];
103                 $db_connections[$selected_id]['collation'] = $_POST['collation'];
104                 if (is_numeric($_POST['tbpref']))
105                 {
106                         $db_connections[$selected_id]['tbpref'] = $_POST['tbpref'] == 1 ?
107                           $tb_pref_counter."_" : '';
108                 }
109                 else if ($_POST['tbpref'] != "")
110                         $db_connections[$selected_id]['tbpref'] = $_POST['tbpref'];
111                 else
112                         $db_connections[$selected_id]['tbpref'] = "";
113
114                 $conn = $db_connections[$selected_id];
115                 if (($db = db_create_db($conn)) === false)
116                 {
117                         display_error(_("Error creating Database: ") . $conn['dbname'] . _(", Please create it manually"));
118                         $error = true;
119                 } else {
120                         if (strncmp(db_get_version(), "5.6", 3) >= 0) 
121                                 db_query("SET sql_mode = ''");
122                         if (!db_import($path_to_root.'/sql/'.get_post('coa'), $conn, $selected_id)) {
123                                 display_error(_('Cannot create new company due to bugs in sql file.'));
124                                 $error = true;
125                         } 
126                         else
127                         {
128                                 if (!isset($_POST['admpassword']) || $_POST['admpassword'] == "")
129                                         $_POST['admpassword'] = "password";
130                                 update_admin_password($conn, md5($_POST['admpassword']));
131                         }
132                 }
133                 if ($error) {
134                         remove_connection($selected_id);
135                         return false;
136                 }
137         }
138         $error = write_config_db($new);
139
140         if ($error == -1)
141                 display_error(_("Cannot open the configuration file - ") . $path_to_root . "/config_db.php");
142         else if ($error == -2)
143                 display_error(_("Cannot write to the configuration file - ") . $path_to_root . "/config_db.php");
144         else if ($error == -3)
145                 display_error(_("The configuration file ") . $path_to_root . "/config_db.php" . _(" is not writable. Change its permissions so it is, then re-run the operation."));
146         if ($error != 0)
147         {
148                 return false;
149         }
150
151         if ($new)
152         {
153                 create_comp_dirs(company_path($selected_id), $comp_subdirs);
154                 $exts = get_company_extensions();
155                 write_extensions($exts, $selected_id);
156         }
157         display_notification($new ? _('New company has been created.') : _('Company has been updated.'));
158
159         $Mode = 'RESET';
160         return true;
161 }
162
163 //---------------------------------------------------------------------------------------------
164
165 function handle_delete($id)
166 {
167         global $Ajax, $def_coy, $db_connections, $comp_subdirs, $path_to_root, $Mode;
168
169         // First make sure all company directories from the one under removal are writable. 
170         // Without this after operation we end up with changed per-company owners!
171         for($i = $id; $i < count($db_connections); $i++) {
172                         $comp_path = company_path($i);
173                 if (!is_dir($comp_path) || !is_writable($comp_path)) {
174                         display_error(_('Broken company subdirectories system. You have to remove this company manually.'));
175                         return;
176                 }
177         }
178         // make sure config file is writable
179         if (!is_writeable($path_to_root . "/config_db.php"))
180         {
181                 display_error(_("The configuration file ") . $path_to_root . "/config_db.php" . _(" is not writable. Change its permissions so it is, then re-run the operation."));
182                 return;
183         }
184         // rename directory to temporary name to ensure all
185         // other subdirectories will have right owners even after
186         // unsuccessfull removal.
187         $cdir = company_path($id);
188         $tmpname  = company_path('/old_'.$id);
189         if (!@rename($cdir, $tmpname)) {
190                 display_error(_('Cannot rename subdirectory to temporary name.'));
191                 return;
192         }
193         // 'shift' company directories names
194         for ($i = $id+1; $i < count($db_connections); $i++) {
195                 if (!rename(company_path($i), company_path($i-1))) {
196                         display_error(_("Cannot rename company subdirectory"));
197                         return;
198                 }
199         }
200         $err = remove_connection($id);
201         if ($err == 0)
202                 display_error(_("Error removing Database: ") . $id . _(", please remove it manually"));
203
204         if ($def_coy == $id)
205                 $def_coy = 0;
206
207         $error = write_config_db();
208         if ($error == -1)
209                 display_error(_("Cannot open the configuration file - ") . $path_to_root . "/config_db.php");
210         else if ($error == -2)
211                 display_error(_("Cannot write to the configuration file - ") . $path_to_root . "/config_db.php");
212         else if ($error == -3)
213                 display_error(_("The configuration file ") . $path_to_root . "/config_db.php" . _(" is not writable. Change its permissions so it is, then re-run the operation."));
214         if ($error != 0) {
215                 @rename($tmpname, $cdir);
216                 return;
217         }
218         // finally remove renamed company directory
219         @flush_dir($tmpname, true);
220         if (!@rmdir($tmpname))
221         {
222                 display_error(_("Cannot remove temporary renamed company data directory ") . $tmpname);
223                 return;
224         }
225         display_notification(_("Selected company has been deleted"));
226         $Ajax->activate('_page_body');
227         $Mode = 'RESET';
228 }
229
230 //---------------------------------------------------------------------------------------------
231
232 function display_companies()
233 {
234         global $def_coy, $db_connections, $supported_collations;
235
236         $coyno = user_company();
237
238         start_table(TABLESTYLE);
239
240         $th = array(_("Company"), _("Database Host"), _("Database User"),
241                 _("Database Name"), _("Table Pref"), _("Charset"), _("Default"), "", "");
242         table_header($th);
243
244         $k=0;
245         $conn = $db_connections;
246         $n = count($conn);
247         for ($i = 0; $i < $n; $i++)
248         {
249                 if ($i == $coyno)
250                 start_row("class='stockmankobg'");
251         else
252                 alt_table_row_color($k);
253
254                 label_cell($conn[$i]['name']);
255                 label_cell($conn[$i]['host']);
256                 label_cell($conn[$i]['dbuser']);
257                 label_cell($conn[$i]['dbname']);
258                 label_cell($conn[$i]['tbpref']);
259                 label_cell($supported_collations[$conn[$i]['collation']]);
260                 label_cell($i == $def_coy ? _("Yes") : _("No"));
261                 edit_button_cell("Edit".$i, _("Edit"));
262                 if ($i != $coyno)
263                 {
264                         delete_button_cell("Delete".$i, _("Delete"));
265                         submit_js_confirm("Delete".$i, 
266                                 sprintf(_("You are about to remove company \'%s\'.\nDo you want to continue ?"), 
267                                         $conn[$i]['name']));
268                 } else
269                         label_cell('');
270                 end_row();
271         }
272
273         end_table();
274     display_note(_("The marked company is the current company which cannot be deleted."), 0, 0, "class='currentfg'");
275     display_note(_("If no Admin Password is entered, the new Admin Password will be '<b>password</b>' by default "));
276 }
277
278 //---------------------------------------------------------------------------------------------
279
280 function display_company_edit($selected_id)
281 {
282         global $def_coy, $db_connections, $tb_pref_counter;
283
284         start_table(TABLESTYLE2);
285
286         if ($selected_id != -1)
287         {
288                 $conn = $db_connections[$selected_id];
289                 $_POST['name'] = $conn['name'];
290                 $_POST['host']  = $conn['host'];
291                 $_POST['dbuser']  = $conn['dbuser'];
292                 $_POST['dbpassword']  = $conn['dbpassword'];
293                 $_POST['dbname']  = $conn['dbname'];
294                 $_POST['tbpref']  = $conn['tbpref'];
295                 $_POST['def'] = $selected_id == $def_coy;
296                 $_POST['dbcreate']  = false;
297                 $_POST['collation']  = $conn['collation'];
298                 hidden('tbpref', $_POST['tbpref']);
299                 hidden('dbpassword', $_POST['dbpassword']);
300         }
301         else
302         {
303                 $_POST['tbpref'] = $tb_pref_counter."_";
304
305                 // Use current settings as default
306                 $conn = $db_connections[user_company()];
307                 $_POST['name'] = '';
308                 $_POST['host']  = $conn['host'];
309                 $_POST['dbuser']  = $conn['dbuser'];
310                 $_POST['dbpassword']  = $conn['dbpassword'];
311                 $_POST['dbname']  = $conn['dbname'];
312                 $_POST['collation']  = $conn['collation'];
313                 unset($_POST['def']);
314         }
315
316         text_row_ex(_("Company"), 'name', 50);
317
318         if ($selected_id == -1)
319         {
320                 text_row_ex(_("Host"), 'host', 30, 60);
321                 text_row_ex(_("Database User"), 'dbuser', 30);
322                 text_row_ex(_("Database Password"), 'dbpassword', 30);
323                 text_row_ex(_("Database Name"), 'dbname', 30);
324                 collations_list_row(_("Database Collation:"), 'collation');
325                 yesno_list_row(_("Table Pref"), 'tbpref', 1, $_POST['tbpref'], _("None"), false);
326                 check_row(_("Default Company"), 'def');
327                 coa_list_row(_("Database Script"), 'coa');
328                 text_row_ex(_("New script Admin Password"), 'admpassword', 20);
329         } else {
330                 label_row(_("Host"), $_POST['host']);
331                 label_row(_("Database User"), $_POST['dbuser']);
332                 label_row(_("Database Name"), $_POST['dbname']);
333                 label_row(_("Table Pref"), $_POST['tbpref']);
334                 if (!get_post('def'))
335                         check_row(_("Default Company"), 'def');
336                 else
337                         label_row(_("Default Company"), _("Yes"));
338         }
339
340         end_table(1);
341         hidden('selected_id', $selected_id);
342 }
343
344 //---------------------------------------------------------------------------------------------
345
346 if (($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM') && check_data($selected_id))
347         handle_submit($selected_id);
348
349 if ($Mode == 'Delete')
350         handle_delete($selected_id);
351
352 if ($Mode == 'RESET')
353 {
354         $selected_id = -1;
355         unset($_POST);
356 }
357
358 //---------------------------------------------------------------------------------------------
359
360 start_form();
361
362         display_companies();
363         display_company_edit($selected_id);
364         submit_add_or_update_center($selected_id == -1, '', 'upgrade');
365
366 end_form();
367
368 end_page();
369