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