Merged changes form main trunk up to 2.2.4
[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_path, $comp_subdirs;
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         }
143         $error = write_config_db($new);
144         if ($error == -1)
145                 display_error(_("Cannot open the configuration file - ") . $path_to_root . "/config_db.php");
146         else if ($error == -2)
147                 display_error(_("Cannot write to the configuration file - ") . $path_to_root . "/config_db.php");
148         else if ($error == -3)
149                 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."));
150         if ($error != 0)
151         {
152                 return false;
153         }
154
155         if ($new)
156         {
157                 create_comp_dirs("$comp_path/$id", $comp_subdirs);
158         }
159         $exts = get_company_extensions();
160         write_extensions($exts, $id);
161         display_notification($new ? _('New company has been created.') : _('Company has been updated.'));
162         return true;
163 }
164
165 //---------------------------------------------------------------------------------------------
166
167 function handle_delete()
168 {
169         global $comp_path, $def_coy, $db_connections, $comp_subdirs, $path_to_root;
170
171         $id = $_GET['id'];
172
173         // First make sure all company directories from the one under removal are writable. 
174         // Without this after operation we end up with changed per-company owners!
175         for($i = $id; $i < count($db_connections); $i++) {
176                 if (!is_dir($comp_path.'/'.$i) || !is_writable($comp_path.'/'.$i)) {
177                         display_error(_('Broken company subdirectories system. You have to remove this company manually.'));
178                         return;
179                 }
180         }
181         // make sure config file is writable
182         if (!is_writeable($path_to_root . "/config_db.php"))
183         {
184                 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."));
185                 return;
186         }
187         // rename directory to temporary name to ensure all
188         // other subdirectories will have right owners even after
189         // unsuccessfull removal.
190         $cdir = $comp_path.'/'.$id;
191         $tmpname  = $comp_path.'/old_'.$id;
192         if (!@rename($cdir, $tmpname)) {
193                 display_error(_('Cannot rename subdirectory to temporary name.'));
194                 return;
195         }
196         // 'shift' company directories names
197         for ($i = $id+1; $i < count($db_connections); $i++) {
198                 if (!rename($comp_path.'/'.$i, $comp_path.'/'.($i-1))) {
199                         display_error(_("Cannot rename company subdirectory"));
200                         return;
201                 }
202         }
203         $err = remove_connection($id);
204         if ($err == 0)
205                 display_error(_("Error removing Database: ") . $dbase . _(", please remove it manually"));
206
207         if ($def_coy == $id)
208                 $def_coy = 0;
209         $error = write_config_db();
210         if ($error == -1)
211                 display_error(_("Cannot open the configuration file - ") . $path_to_root . "/config_db.php");
212         else if ($error == -2)
213                 display_error(_("Cannot write to the configuration file - ") . $path_to_root . "/config_db.php");
214         else if ($error == -3)
215                 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."));
216         if ($error != 0) {
217                 @rename($tmpname, $cdir);
218                 return;
219         }
220         // finally remove renamed company directory
221         @flush_dir($tmpname, true);
222         if (!@rmdir($tmpname))
223         {
224                 display_error(_("Cannot remove temporary renamed company data directory ") . $tmpname);
225                 return;
226         }
227         display_notification(_("Selected company as been deleted"));
228 }
229
230 //---------------------------------------------------------------------------------------------
231
232 function display_companies()
233 {
234         global $table_style, $def_coy, $db_connections;
235
236         $coyno = $_SESSION["wa_current_user"]->company;
237
238         echo "
239                 <script language='javascript'>
240                 function deleteCompany(id) {
241                         if (!confirm('" . _("Are you sure you want to delete company no. ") . "'+id))
242                                 return
243                         document.location.replace('create_coy.php?c=df&id='+id)
244                 }
245                 </script>";
246         start_table($table_style);
247
248         $th = array(_("Company"), _("Database Host"), _("Database User"),
249                 _("Database Name"), _("Table Pref"), _("Default"), "", "");
250         table_header($th);
251
252         $k=0;
253         $conn = $db_connections;
254         $n = count($conn);
255         for ($i = 0; $i < $n; $i++)
256         {
257                 if ($i == $def_coy)
258                         $what = _("Yes");
259                 else
260                         $what = _("No");
261                 if ($i == $coyno)
262                 start_row("class='stockmankobg'");
263         else
264                 alt_table_row_color($k);
265
266                 label_cell($conn[$i]['name']);
267                 label_cell($conn[$i]['host']);
268                 label_cell($conn[$i]['dbuser']);
269                 label_cell($conn[$i]['dbname']);
270                 label_cell($conn[$i]['tbpref']);
271                 label_cell($what);
272                 $edit = _("Edit");
273                 $delete = _("Delete");
274                 if (user_graphic_links())
275                 {
276                         $edit = set_icon(ICON_EDIT, $edit);
277                         $delete = set_icon(ICON_DELETE, $delete);
278                 }
279         label_cell("<a href='" . $_SERVER['PHP_SELF']. "?selected_id=$i'>$edit</a>");
280                 label_cell( $i == $coyno ? '' :
281                         "<a href='javascript:deleteCompany(" . $i . ")'>$delete</a>");
282                 end_row();
283         }
284
285         end_table();
286     display_note(_("The marked company is the current company which cannot be deleted."), 0, 0, "class='currentfg'");
287 }
288
289 //---------------------------------------------------------------------------------------------
290
291 function display_company_edit($selected_id)
292 {
293         global $def_coy, $db_connections, $tb_pref_counter, $table_style2;
294
295         if ($selected_id != -1)
296                 $n = $selected_id;
297         else
298                 $n = count($db_connections);
299
300         start_form(true);
301
302         echo "
303                 <script language='javascript'>
304                 function updateCompany() {
305                         if (document.forms[0].uploadfile.value!='' && document.forms[0].dbname.value!='') {
306                                 document.forms[0].action='create_coy.php?c=u&ul=1&id=" . $n . "&fn=' + document.forms[0].uploadfile.value
307                         }
308                         else {
309                                 document.forms[0].action='create_coy.php?c=u&id=" . $n . "&fn=' + document.forms[0].uploadfile.value
310                         }
311                         document.forms[0].submit()
312                 }
313                 </script>";
314
315         start_table($table_style2);
316
317         if ($selected_id != -1)
318         {
319                 $conn = $db_connections[$selected_id];
320                 $_POST['name'] = $conn['name'];
321                 $_POST['host']  = $conn['host'];
322                 $_POST['dbuser']  = $conn['dbuser'];
323                 $_POST['dbpassword']  = $conn['dbpassword'];
324                 $_POST['dbname']  = $conn['dbname'];
325                 $_POST['tbpref']  = $conn['tbpref'];
326                 if ($selected_id == $def_coy)
327                         $_POST['def'] = true;
328                 else
329                         $_POST['def'] = false;
330                 $_POST['dbcreate']  = false;
331                 hidden('selected_id', $selected_id);
332                 hidden('tbpref', $_POST['tbpref']);
333                 hidden('dbpassword', $_POST['dbpassword']);
334         }
335         else
336                 $_POST['tbpref'] = $tb_pref_counter."_";
337         text_row_ex(_("Company"), 'name', 30);
338         text_row_ex(_("Host"), 'host', 30);
339         text_row_ex(_("Database User"), 'dbuser', 30);
340         if ($selected_id == -1)
341                 text_row_ex(_("Database Password"), 'dbpassword', 30);
342         text_row_ex(_("Database Name"), 'dbname', 30);
343         if ($selected_id == -1)
344                 yesno_list_row(_("Table Pref"), 'tbpref', 1, $_POST['tbpref'], _("None"), false);
345         else
346                 label_row(_("Table Pref"), $_POST['tbpref']);
347         yesno_list_row(_("Default"), 'def', null, "", "", false);
348
349         start_row();
350         label_cell(_("Database Script"));
351         label_cell("<input name='uploadfile' type='file'>");
352         end_row();
353
354         text_row_ex(_("New script Admin Password"), 'admpassword', 20);
355
356         end_table();
357         display_note(_("Choose from Database scripts in SQL folder. No Database is created without a script."), 0, 1);
358         echo "<center><input onclick='javascript:updateCompany()' type='button' style='width:150px' value='". _("Save"). "'></center>";
359
360
361         end_form();
362 }
363
364
365 //---------------------------------------------------------------------------------------------
366
367 if (isset($_GET['c']) && $_GET['c'] == 'df') {
368         handle_delete();
369         $selected_id = -1;
370 }
371
372 if (isset($_GET['c']) && $_GET['c'] == 'u')
373         if (handle_submit())
374                 $selected_id = -1;
375
376
377 //---------------------------------------------------------------------------------------------
378
379 display_companies();
380
381 hyperlink_no_params($_SERVER['PHP_SELF'], _("Create a new company"));
382
383 display_company_edit($selected_id);
384
385 //---------------------------------------------------------------------------------------------
386 end_page();
387
388 ?>