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