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