2 // +----------------------------------------------------------------------+
3 // | Anuko Time Tracker
4 // +----------------------------------------------------------------------+
5 // | Copyright (c) Anuko International Ltd. (https://www.anuko.com)
6 // +----------------------------------------------------------------------+
7 // | LIBERAL FREEWARE LICENSE: This source code document may be used
8 // | by anyone for any purpose, and freely redistributed alone or in
9 // | combination with other software, provided that the license is obeyed.
11 // | There are only two ways to violate the license:
13 // | 1. To redistribute this code in source form, with the copyright
14 // | notice or license removed or altered. (Distributing in compiled
15 // | forms without embedded copyright notices is permitted).
17 // | 2. To redistribute modified versions of this code in *any* form
18 // | that bears insufficient indications that the modifications are
19 // | not the work of the original author(s).
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
24 // +----------------------------------------------------------------------+
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
29 import('ttUserHelper');
30 import('ttRoleHelper');
31 import('ttTaskHelper');
32 import('ttClientHelper');
33 import('ttInvoiceHelper');
34 import('ttTimeHelper');
35 import('ttExpenseHelper');
36 import('ttFavReportHelper');
38 // ttOrgImportHelper class is used to import organization data from an XML file
39 // prepared by ttOrgExportHelper and consisting of nested groups with their info.
40 class ttOrgImportHelper {
41 var $errors = null; // Errors go here. Set in constructor by reference.
42 var $schema_version = null; // Database schema version from XML file we import from.
43 var $conflicting_logins = null; // A comma-separated list of logins we cannot import.
44 var $canImport = true; // False if we cannot import data due to a conflict such as login collision.
45 var $firstPass = true; // True during first pass through the file.
46 var $org_id = null; // Organization id (same as top group_id).
47 var $current_group_id = null; // Current group id during parsing.
48 var $parents = array(); // A stack of parent group ids for current group all the way to the root including self.
49 var $top_role_id = 0; // Top role id.
51 // Entity maps for current group. They map XML ids with database ids.
52 var $currentGroupRoleMap = array();
53 var $currentGroupTaskMap = array();
54 var $currentGroupProjectMap = array();
55 var $currentGroupClientMap = array();
56 var $currentGroupUserMap = array();
57 var $currentGroupInvoiceMap = array();
58 var $currentGroupLogMap = array();
59 var $currentGroupCustomFieldMap = array();
60 var $currentGroupCustomFieldOptionMap = array();
61 var $currentGroupFavReportMap = array();
64 function __construct(&$errors) {
65 $this->errors = &$errors;
66 $this->top_role_id = ttRoleHelper::getRoleByRank(512, 0);
69 // startElement - callback handler for opening tags in XML.
70 function startElement($parser, $name, $attrs) {
73 // First pass through the file determines if we can import data.
74 // We require 2 things:
75 // 1) Database schema version must be set. This ensures we have a compatible file.
76 // 2) No login coillisions are allowed.
77 if ($this->firstPass) {
78 if ($name == 'ORG' && $this->canImport) {
79 if ($attrs['SCHEMA'] == null) {
80 // We need (database) schema attribute to be available for import to work.
81 // Old Time Tracker export files don't have this.
82 // Current import code does not work with old format because we had to
83 // restructure data in export files for subgroup support.
84 $this->canImport = false;
85 $this->errors->add($i18n->get('error.format'));
90 // In first pass we check user logins for potential collisions with existing.
91 if ($name == 'USER' && $this->canImport) {
92 $login = $attrs['LOGIN'];
93 if ('' != $attrs['STATUS'] && ttUserHelper::getUserByLogin($login)) {
94 // We have a login collision. Append colliding login to a list of things we cannot import.
95 $this->conflicting_logins .= ($this->conflicting_logins ? ", $login" : $login);
96 // The above is printed in error message with all found colliding logins.
101 // Second pass processing. We import data here, one tag at a time.
102 if (!$this->firstPass && $this->canImport && $this->errors->no()) {
103 $mdb2 = getConnection();
105 // We are in second pass and can import data.
106 if ($name == 'GROUP') {
107 // Create a new group.
108 $this->current_group_id = $this->createGroup(array(
109 'parent_id' => $this->current_group_id, // Note: after insert current_group_id changes.
110 'org_id' => $this->org_id,
111 'name' => $attrs['NAME'],
112 'description' => $attrs['DESCRIPTION'],
113 'currency' => $attrs['CURRENCY'],
114 'decimal_mark' => $attrs['DECIMAL_MARK'],
115 'lang' => $attrs['LANG'],
116 'date_format' => $attrs['DATE_FORMAT'],
117 'time_format' => $attrs['TIME_FORMAT'],
118 'week_start' => $attrs['WEEK_START'],
119 'tracking_mode' => $attrs['TRACKING_MODE'],
120 'project_required' => $attrs['PROJECT_REQUIRED'],
121 'task_required' => $attrs['TASK_REQUIRED'],
122 'record_type' => $attrs['RECORD_TYPE'],
123 'bcc_email' => $attrs['BCC_EMAIL'],
124 'allow_ip' => $attrs['ALLOW_IP'],
125 'password_complexity' => $attrs['PASSWORD_COMPLEXITY'],
126 'plugins' => $attrs['PLUGINS'],
127 'lock_spec' => $attrs['LOCK_SPEC'],
128 'workday_minutes' => $attrs['WORKDAY_MINUTES'],
129 'custom_logo' => $attrs['CUSTOM_LOGO'],
130 'config' => $attrs['CONFIG']));
132 // Special handling for top group.
133 if (!$this->org_id && $this->current_group_id) {
134 $this->org_id = $this->current_group_id;
135 $sql = "update tt_groups set org_id = $this->current_group_id where org_id is NULL and id = $this->current_group_id";
136 $affected = $mdb2->exec($sql);
138 // Add self to parent stack.
139 array_push($this->parents, $this->current_group_id);
141 // Recycle all maps as we are starting to work on new group.
142 // Note that for this to work properly all nested groups must be last entries in xml for each group.
143 unset($this->currentGroupRoleMap); $this->currentGroupRoleMap = array();
144 unset($this->currentGroupTaskMap); $this->currentGroupTaskMap = array();
145 unset($this->currentGroupProjectMap); $this->currentGroupProjectMap = array();
146 unset($this->currentGroupClientMap); $this->currentGroupClientMap = array();
147 unset($this->currentGroupUserMap); $this->currentGroupUserMap = array();
148 unset($this->currentGroupInvoiceMap); $this->currentGroupInvoiceMap = array();
149 unset($this->currentGroupLogMap); $this->currentGroupLogMap = array();
150 unset($this->currentGroupCustomFieldMap); $this->currentGroupCustomFieldMap = array();
151 unset($this->currentGroupCustomFieldOptionMap); $this->currentGroupCustomFieldOptionMap = array();
152 unset($this->currentGroupFavReportMap); $this->currentGroupCustomFavReportMap = array();
156 if ($name == 'ROLE') {
157 // We get here when processing <role> tags for the current group.
158 $role_id = $this->insertRole(array(
159 'group_id' => $this->current_group_id,
160 'org_id' => $this->org_id,
161 'name' => $attrs['NAME'],
162 'description' => $attrs['DESCRIPTION'],
163 'rank' => $attrs['RANK'],
164 'rights' => $attrs['RIGHTS'],
165 'status' => $attrs['STATUS']));
168 $this->currentGroupRoleMap[$attrs['ID']] = $role_id;
169 } else $this->errors->add($i18n->get('error.db'));
173 if ($name == 'TASK') {
174 // We get here when processing <task> tags for the current group.
175 $task_id = ttTaskHelper::insert(array(
176 'group_id' => $this->current_group_id,
177 'org_id' => $this->org_id,
178 'name' => $attrs['NAME'],
179 'description' => $attrs['DESCRIPTION'],
180 'status' => $attrs['STATUS']));
183 $this->currentGroupTaskMap[$attrs['ID']] = $task_id;
185 $this->errors->add($i18n->get('error.db'));
190 if ($name == 'PROJECT') {
191 // We get here when processing <project> tags for the current group.
193 // Prepare a list of task ids.
194 if ($attrs['TASKS']) {
195 $tasks = explode(',', $attrs['TASKS']);
196 foreach ($tasks as $id)
197 $mapped_tasks[] = $this->currentGroupTaskMap[$id];
200 $project_id = $this->insertProject(array(
201 'group_id' => $this->current_group_id,
202 'org_id' => $this->org_id,
203 'name' => $attrs['NAME'],
204 'description' => $attrs['DESCRIPTION'],
205 'tasks' => $mapped_tasks,
206 'status' => $attrs['STATUS']));
209 $this->currentGroupProjectMap[$attrs['ID']] = $project_id;
211 $this->errors->add($i18n->get('error.db'));
216 if ($name == 'CLIENT') {
217 // We get here when processing <client> tags for the current group.
219 // Prepare a list of project ids.
220 if ($attrs['PROJECTS']) {
221 $projects = explode(',', $attrs['PROJECTS']);
222 foreach ($projects as $id)
223 $mapped_projects[] = $this->currentGroupProjectMap[$id];
226 $client_id = $this->insertClient(array(
227 'group_id' => $this->current_group_id,
228 'org_id' => $this->org_id,
229 'name' => $attrs['NAME'],
230 'address' => $attrs['ADDRESS'],
231 'tax' => $attrs['TAX'],
232 'projects' => $mapped_projects,
233 'status' => $attrs['STATUS']));
236 $this->currentGroupClientMap[$attrs['ID']] = $client_id;
237 } else $this->errors->add($i18n->get('error.db'));
241 if ($name == 'USER') {
242 // We get here when processing <user> tags for the current group.
244 $role_id = $attrs['ROLE_ID'] === '0' ? $this->top_role_id : $this->currentGroupRoleMap[$attrs['ROLE_ID']]; // 0 (not null) means top manager role.
246 $user_id = ttUserHelper::insert(array(
247 'group_id' => $this->current_group_id,
248 'org_id' => $this->org_id,
249 'role_id' => $role_id,
250 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
251 'name' => $attrs['NAME'],
252 'login' => $attrs['LOGIN'],
253 'password' => $attrs['PASSWORD'],
254 'rate' => $attrs['RATE'],
255 'email' => $attrs['EMAIL'],
256 'status' => $attrs['STATUS']), false);
259 $this->currentGroupUserMap[$attrs['ID']] = $user_id;
260 } else $this->errors->add($i18n->get('error.db'));
264 if ($name == 'USER_PROJECT_BIND') {
265 if (!ttUserHelper::insertBind(array(
266 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
267 'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
268 'group_id' => $this->current_group_id,
269 'org_id' => $this->org_id,
270 'rate' => $attrs['RATE'],
271 'status' => $attrs['STATUS']))) {
272 $this->errors->add($i18n->get('error.db'));
277 if ($name == 'INVOICE') {
278 // We get here when processing <invoice> tags for the current group.
279 $invoice_id = ttInvoiceHelper::insert(array(
280 'group_id' => $this->current_group_id,
281 'org_id' => $this->org_id,
282 'name' => $attrs['NAME'],
283 'date' => $attrs['DATE'],
284 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
285 'status' => $attrs['STATUS']));
288 $this->currentGroupInvoiceMap[$attrs['ID']] = $invoice_id;
289 } else $this->errors->add($i18n->get('error.db'));
293 if ($name == 'LOG_ITEM') {
294 // We get here when processing <log_item> tags for the current group.
295 $log_item_id = $this->insertLogEntry(array(
296 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
297 'group_id' => $this->current_group_id,
298 'org_id' => $this->org_id,
299 'date' => $attrs['DATE'],
300 'start' => $attrs['START'],
301 'finish' => $attrs['FINISH'],
302 'duration' => $attrs['DURATION'],
303 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
304 'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
305 'task_id' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
306 'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
307 'comment' => (isset($attrs['COMMENT']) ? $attrs['COMMENT'] : ''),
308 'billable' => $attrs['BILLABLE'],
309 'paid' => $attrs['PAID'],
310 'status' => $attrs['STATUS']));
313 $this->currentGroupLogMap[$attrs['ID']] = $log_item_id;
314 } else $this->errors->add($i18n->get('error.db'));
318 if ($name == 'CUSTOM_FIELD') {
319 // We get here when processing <custom_field> tags for the current group.
320 $custom_field_id = $this->insertCustomField(array(
321 'group_id' => $this->current_group_id,
322 'org_id' => $this->org_id,
323 'type' => $attrs['TYPE'],
324 'label' => $attrs['LABEL'],
325 'required' => $attrs['REQUIRED'],
326 'status' => $attrs['STATUS']));
327 if ($custom_field_id) {
329 $this->currentGroupCustomFieldMap[$attrs['ID']] = $custom_field_id;
330 } else $this->errors->add($i18n->get('error.db'));
334 if ($name == 'CUSTOM_FIELD_OPTION') {
335 // We get here when processing <custom_field_option> tags for the current group.
336 $custom_field_option_id = $this->insertCustomFieldOption(array(
337 'group_id' => $this->current_group_id,
338 'org_id' => $this->org_id,
339 'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
340 'value' => $attrs['VALUE']));
341 if ($custom_field_option_id) {
343 $this->currentGroupCustomFieldOptionMap[$attrs['ID']] = $custom_field_option_id;
344 } else $this->errors->add($i18n->get('error.db'));
348 if ($name == 'CUSTOM_FIELD_LOG_ENTRY') {
349 // We get here when processing <custom_field_log_entry> tags for the current group.
350 if (!$this->insertCustomFieldLogEntry(array(
351 'group_id' => $this->current_group_id,
352 'org_id' => $this->org_id,
353 'log_id' => $this->currentGroupLogMap[$attrs['LOG_ID']],
354 'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
355 'option_id' => $this->currentGroupCustomFieldOptionMap[$attrs['OPTION_ID']],
356 'value' => $attrs['VALUE'],
357 'status' => $attrs['STATUS']))) {
358 $this->errors->add($i18n->get('error.db'));
363 if ($name == 'EXPENSE_ITEM') {
364 // We get here when processing <expense_item> tags for the current group.
365 $expense_item_id = $this->insertExpense(array(
366 'date' => $attrs['DATE'],
367 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
368 'group_id' => $this->current_group_id,
369 'org_id' => $this->org_id,
370 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
371 'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
372 'name' => $attrs['NAME'],
373 'cost' => $attrs['COST'],
374 'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
375 'paid' => $attrs['PAID'],
376 'status' => $attrs['STATUS']));
377 if (!$expense_item_id) $this->errors->add($i18n->get('error.db'));
381 if ($name == 'PREDEFINED_EXPENSE') {
382 if (!$this->insertPredefinedExpense(array(
383 'group_id' => $this->current_group_id,
384 'org_id' => $this->org_id,
385 'name' => $attrs['NAME'],
386 'cost' => $attrs['COST']))) {
387 $this->errors->add($i18n->get('error.db'));
392 if ($name == 'MONTHLY_QUOTA') {
393 if (!$this->insertMonthlyQuota(array(
394 'group_id' => $this->current_group_id,
395 'org_id' => $this->org_id,
396 'year' => $attrs['YEAR'],
397 'month' => $attrs['MONTH'],
398 'minutes' => $attrs['MINUTES']))) {
399 $this->errors->add($i18n->get('error.db'));
404 if ($name == 'FAV_REPORT') {
406 if (strlen($attrs['USERS']) > 0) {
407 $arr = explode(',', $attrs['USERS']);
409 $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->currentGroupUserMap[$v];
411 $fav_report_id = $this->insertFavReport(array(
412 'name' => $attrs['NAME'],
413 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
414 'group_id' => $this->current_group_id,
415 'org_id' => $this->org_id,
416 'client' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
417 'option' => $this->currentGroupCustomFieldOptionMap[$attrs['CF_1_OPTION_ID']],
418 'project' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
419 'task' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
420 'billable' => $attrs['BILLABLE'],
421 'users' => $user_list,
422 'period' => $attrs['PERIOD'],
423 'from' => $attrs['PERIOD_START'],
424 'to' => $attrs['PERIOD_END'],
425 'chclient' => (int) $attrs['SHOW_CLIENT'],
426 'chinvoice' => (int) $attrs['SHOW_INVOICE'],
427 'chpaid' => (int) $attrs['SHOW_PAID'],
428 'chip' => (int) $attrs['SHOW_IP'],
429 'chproject' => (int) $attrs['SHOW_PROJECT'],
430 'chstart' => (int) $attrs['SHOW_START'],
431 'chduration' => (int) $attrs['SHOW_DURATION'],
432 'chcost' => (int) $attrs['SHOW_COST'],
433 'chtask' => (int) $attrs['SHOW_TASK'],
434 'chfinish' => (int) $attrs['SHOW_END'],
435 'chnote' => (int) $attrs['SHOW_NOTE'],
436 'chcf_1' => (int) $attrs['SHOW_CUSTOM_FIELD_1'],
437 'chunits' => (int) $attrs['SHOW_WORK_UNITS'],
438 'group_by1' => $attrs['GROUP_BY1'],
439 'group_by2' => $attrs['GROUP_BY2'],
440 'group_by3' => $attrs['GROUP_BY3'],
441 'chtotalsonly' => (int) $attrs['SHOW_TOTALS_ONLY']));
442 if ($fav_report_id) {
444 $this->currentGroupFavReportMap[$attrs['ID']] = $fav_report_id;
445 } else $this->errors->add($i18n->get('error.db'));
449 if ($name == 'NOTIFICATION') {
450 if (!$this->insertNotification(array(
451 'group_id' => $this->current_group_id,
452 'org_id' => $this->org_id,
453 'cron_spec' => $attrs['CRON_SPEC'],
454 'last' => $attrs['LAST'],
455 'next' => $attrs['NEXT'],
456 'report_id' => $this->currentGroupFavReportMap[$attrs['REPORT_ID']],
457 'email' => $attrs['EMAIL'],
458 'cc' => $attrs['CC'],
459 'subject' => $attrs['SUBJECT'],
460 'report_condition' => $attrs['REPORT_CONDITION'],
461 'status' => $attrs['STATUS']))) {
462 $this->errors->add($i18n->get('error.db'));
467 if ($name == 'USER_PARAM') {
468 if (!$this->insertUserParam(array(
469 'group_id' => $this->current_group_id,
470 'org_id' => $this->org_id,
471 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
472 'param_name' => $attrs['PARAM_NAME'],
473 'param_value' => $attrs['PARAM_VALUE']))) {
474 $this->errors->add($i18n->get('error.db'));
481 // endElement - callback handler for ending tags in XML.
482 // We use this only for process </group> element endings and
483 // set current_group_id to an immediate parent.
484 // This is required to import group hierarchy correctly.
485 function endElement($parser, $name) {
486 // No need to care about first or second pass, as this is used only in second pass.
487 // See 2nd xml_set_element_handler, where this handler is set.
488 if ($name == 'GROUP') {
489 // Remove self from the parent stack.
490 $self = array_pop($this->parents);
491 // Set current group id to an immediate parent.
492 $len = count($this->parents);
493 $this->current_group_id = $len ? $this->parents[$len-1] : null;
497 // importXml - uncompresses the file, reads and parses its content. During parsing,
498 // startElement, endElement, and dataElement functions are called as many times as necessary.
499 // Actual import occurs in the endElement handler.
500 function importXml() {
503 // Do we have a compressed file?
505 $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
506 if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
510 // Create a temporary file.
511 $dirName = dirname(TEMPLATE_DIR . '_c/.');
512 $filename = tempnam($dirName, 'import_');
514 // If the file is compressed - uncompress it.
516 if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
517 $this->errors->add($i18n->get('error.sys'));
520 unlink($_FILES['xmlfile']['tmp_name']);
522 if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
523 $this->errors->add($i18n->get('error.upload'));
528 // Initialize XML parser.
529 $parser = xml_parser_create();
530 xml_set_object($parser, $this);
531 xml_set_element_handler($parser, 'startElement', false); // No need to process end tags in 1st pass.
533 // We need to parse the file 2 times:
534 // 1) First pass: determine if import is possible.
535 // 2) Second pass: import data, one tag at a time.
537 // Read and parse the content of the file. During parsing, startElement is called back for each tag.
538 $file = fopen($filename, 'r');
539 while (($data = fread($file, 4096)) && $this->errors->no()) {
540 if (!xml_parse($parser, $data, feof($file))) {
541 $this->errors->add(sprintf($i18n->get('error.xml'),
542 xml_get_current_line_number($parser),
543 xml_error_string(xml_get_error_code($parser))));
546 if ($this->conflicting_logins) {
547 $this->canImport = false;
548 $this->errors->add($i18n->get('error.user_exists'));
549 $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_logins));
552 $this->firstPass = false; // We are done with 1st pass.
553 xml_parser_free($parser);
554 if ($file) fclose($file);
555 if (!$this->canImport) {
559 if ($this->errors->yes()) return; // Exit if we have errors.
561 // Now we can do a second pass, where real work is done.
562 $parser = xml_parser_create();
563 xml_set_object($parser, $this);
564 xml_set_element_handler($parser, 'startElement', 'endElement'); // Need to process ending tags too.
566 // Read and parse the content of the file. During parsing, startElement and endElement are called back for each tag.
567 $file = fopen($filename, 'r');
568 while (($data = fread($file, 4096)) && $this->errors->no()) {
569 if (!xml_parse($parser, $data, feof($file))) {
570 $this->errors->add(sprintf($i18n->get('error.xml'),
571 xml_get_current_line_number($parser),
572 xml_error_string(xml_get_error_code($parser))));
575 xml_parser_free($parser);
576 if ($file) fclose($file);
580 // uncompress - uncompresses the content of the $in file into the $out file.
581 function uncompress($in, $out) {
582 // Do we have the uncompress function?
583 if (!function_exists('bzopen'))
586 // Initial checks of file names and permissions.
587 if (!file_exists($in) || !is_readable ($in))
589 if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
592 if (!$out_file = fopen($out, 'wb'))
594 if (!$in_file = bzopen ($in, 'r'))
597 while (!feof($in_file)) {
598 $buffer = bzread($in_file, 4096);
599 fwrite($out_file, $buffer, 4096);
606 // createGroup function creates a new group.
607 private function createGroup($fields) {
610 $mdb2 = getConnection();
612 $columns = '(parent_id, org_id, name, description, currency, decimal_mark, lang, date_format, time_format'.
613 ', week_start, tracking_mode, project_required, task_required, record_type, bcc_email'.
614 ', allow_ip, password_complexity, plugins, lock_spec'.
615 ', workday_minutes, config, created, created_ip, created_by)';
617 $values = ' values (';
618 $values .= $mdb2->quote($fields['parent_id']);
619 $values .= ', '.$mdb2->quote($fields['org_id']);
620 $values .= ', '.$mdb2->quote(trim($fields['name']));
621 $values .= ', '.$mdb2->quote(trim($fields['description']));
622 $values .= ', '.$mdb2->quote(trim($fields['currency']));
623 $values .= ', '.$mdb2->quote($fields['decimal_mark']);
624 $values .= ', '.$mdb2->quote($fields['lang']);
625 $values .= ', '.$mdb2->quote($fields['date_format']);
626 $values .= ', '.$mdb2->quote($fields['time_format']);
627 $values .= ', '.(int)$fields['week_start'];
628 $values .= ', '.(int)$fields['tracking_mode'];
629 $values .= ', '.(int)$fields['project_required'];
630 $values .= ', '.(int)$fields['task_required'];
631 $values .= ', '.(int)$fields['record_type'];
632 $values .= ', '.$mdb2->quote($fields['bcc_email']);
633 $values .= ', '.$mdb2->quote($fields['allow_ip']);
634 $values .= ', '.$mdb2->quote($fields['password_complexity']);
635 $values .= ', '.$mdb2->quote($fields['plugins']);
636 $values .= ', '.$mdb2->quote($fields['lock_spec']);
637 $values .= ', '.(int)$fields['workday_minutes'];
638 $values .= ', '.$mdb2->quote($fields['config']);
639 $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
642 $sql = 'insert into tt_groups '.$columns.$values;
643 $affected = $mdb2->exec($sql);
644 if (is_a($affected, 'PEAR_Error')) {
645 $this->errors->add($i18n->get('error.db'));
649 $group_id = $mdb2->lastInsertID('tt_groups', 'id');
653 // insertMonthlyQuota - a helper function to insert a monthly quota.
654 private function insertMonthlyQuota($fields) {
655 $mdb2 = getConnection();
656 $group_id = (int) $fields['group_id'];
657 $org_id = (int) $fields['org_id'];
658 $year = (int) $fields['year'];
659 $month = (int) $fields['month'];
660 $minutes = (int) $fields['minutes'];
662 $sql = "INSERT INTO tt_monthly_quotas (group_id, org_id, year, month, minutes)".
663 " values ($group_id, $org_id, $year, $month, $minutes)";
664 $affected = $mdb2->exec($sql);
665 return (!is_a($affected, 'PEAR_Error'));
668 // insertPredefinedExpense - a helper function to insert a predefined expense.
669 private function insertPredefinedExpense($fields) {
670 $mdb2 = getConnection();
671 $group_id = (int) $fields['group_id'];
672 $org_id = (int) $fields['org_id'];
673 $name = $mdb2->quote($fields['name']);
674 $cost = $mdb2->quote($fields['cost']);
676 $sql = "INSERT INTO tt_predefined_expenses (group_id, org_id, name, cost)".
677 " values ($group_id, $org_id, $name, $cost)";
678 $affected = $mdb2->exec($sql);
679 return (!is_a($affected, 'PEAR_Error'));
682 // insertExpense - a helper function to insert an expense item.
683 private function insertExpense($fields) {
685 $mdb2 = getConnection();
687 $group_id = (int) $fields['group_id'];
688 $org_id = (int) $fields['org_id'];
689 $date = $fields['date'];
690 $user_id = (int) $fields['user_id'];
691 $client_id = $fields['client_id'];
692 $project_id = $fields['project_id'];
693 $name = $fields['name'];
694 $cost = str_replace(',', '.', $fields['cost']);
695 $invoice_id = $fields['invoice_id'];
696 $status = $fields['status'];
697 $paid = (int) $fields['paid'];
698 $created = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
700 $sql = "insert into tt_expense_items".
701 " (date, user_id, group_id, org_id, client_id, project_id, name, cost, invoice_id, paid, created, created_ip, created_by, status)".
702 " values (".$mdb2->quote($date).", $user_id, $group_id, $org_id, ".$mdb2->quote($client_id).", ".$mdb2->quote($project_id).
703 ", ".$mdb2->quote($name).", ".$mdb2->quote($cost).", ".$mdb2->quote($invoice_id).", $paid $created, ".$mdb2->quote($status).")";
704 $affected = $mdb2->exec($sql);
705 return (!is_a($affected, 'PEAR_Error'));
708 // insertProject - a helper function to insert a project as well as project to task binds.
709 private function insertProject($fields)
711 $mdb2 = getConnection();
713 $group_id = (int) $fields['group_id'];
714 $org_id = (int) $fields['org_id'];
716 $name = $fields['name'];
717 $description = $fields['description'];
718 $tasks = $fields['tasks'];
719 $comma_separated = implode(',', $tasks); // This is a comma-separated list of associated task ids.
720 $status = $fields['status'];
722 $sql = "insert into tt_projects (group_id, org_id, name, description, tasks, status)
723 values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
724 $affected = $mdb2->exec($sql);
725 if (is_a($affected, 'PEAR_Error'))
728 $last_id = $mdb2->lastInsertID('tt_projects', 'id');
730 // Insert binds into tt_project_task_binds table.
731 if (is_array($tasks)) {
732 foreach ($tasks as $task_id) {
733 $sql = "insert into tt_project_task_binds (project_id, task_id, group_id, org_id)".
734 " values($last_id, $task_id, $group_id, $org_id)";
735 $affected = $mdb2->exec($sql);
736 if (is_a($affected, 'PEAR_Error'))
744 // insertRole - inserts a role into tt_roles table.
745 private function insertRole($fields)
747 $mdb2 = getConnection();
749 $group_id = (int) $fields['group_id'];
750 $org_id = (int) $fields['org_id'];
751 $name = $fields['name'];
752 $rank = (int) $fields['rank'];
753 $description = $fields['description'];
754 $rights = $fields['rights'];
755 $status = $fields['status'];
757 $sql = "insert into tt_roles (group_id, org_id, name, rank, description, rights, status)
758 values ($group_id, $org_id, ".$mdb2->quote($name).", $rank, ".$mdb2->quote($description).", ".$mdb2->quote($rights).", ".$mdb2->quote($status).")";
759 $affected = $mdb2->exec($sql);
760 if (is_a($affected, 'PEAR_Error'))
763 $last_id = $mdb2->lastInsertID('tt_roles', 'id');
767 // The insertClient function inserts a new client as well as client to project binds.
768 private function insertClient($fields)
770 $mdb2 = getConnection();
772 $group_id = (int) $fields['group_id'];
773 $org_id = (int) $fields['org_id'];
774 $name = $fields['name'];
775 $address = $fields['address'];
776 $tax = $fields['tax'];
777 $projects = $fields['projects'];
779 $comma_separated = implode(',', $projects); // This is a comma-separated list of associated projects ids.
780 $status = $fields['status'];
782 $tax = str_replace(',', '.', $tax);
783 if ($tax == '') $tax = 0;
785 $sql = "insert into tt_clients (group_id, org_id, name, address, tax, projects, status)".
786 " values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($address).", $tax, ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
788 $affected = $mdb2->exec($sql);
789 if (is_a($affected, 'PEAR_Error'))
792 $last_id = $mdb2->lastInsertID('tt_clients', 'id');
794 if (count($projects) > 0)
795 foreach ($projects as $p_id) {
796 $sql = "insert into tt_client_project_binds (client_id, project_id, group_id, org_id) values($last_id, $p_id, $group_id, $org_id)";
797 $affected = $mdb2->exec($sql);
798 if (is_a($affected, 'PEAR_Error'))
805 // insertFavReport - inserts a favorite report in database.
806 private function insertFavReport($fields) {
807 $mdb2 = getConnection();
809 $group_id = (int) $fields['group_id'];
810 $org_id = (int) $fields['org_id'];
812 $sql = "insert into tt_fav_reports".
813 " (name, user_id, group_id, org_id, client_id, cf_1_option_id, project_id, task_id,".
814 " billable, invoice, paid_status, users, period, period_start, period_end,".
815 " show_client, show_invoice, show_paid, show_ip,".
816 " show_project, show_start, show_duration, show_cost,".
817 " show_task, show_end, show_note, show_custom_field_1, show_work_units,".
818 " group_by1, group_by2, group_by3, show_totals_only)".
820 $mdb2->quote($fields['name']).", ".$fields['user_id'].", $group_id, $org_id, ".
821 $mdb2->quote($fields['client']).", ".$mdb2->quote($fields['option']).", ".
822 $mdb2->quote($fields['project']).", ".$mdb2->quote($fields['task']).", ".
823 $mdb2->quote($fields['billable']).", ".$mdb2->quote($fields['invoice']).", ".
824 $mdb2->quote($fields['paid_status']).", ".
825 $mdb2->quote($fields['users']).", ".$mdb2->quote($fields['period']).", ".
826 $mdb2->quote($fields['from']).", ".$mdb2->quote($fields['to']).", ".
827 $fields['chclient'].", ".$fields['chinvoice'].", ".$fields['chpaid'].", ".$fields['chip'].", ".
828 $fields['chproject'].", ".$fields['chstart'].", ".$fields['chduration'].", ".$fields['chcost'].", ".
829 $fields['chtask'].", ".$fields['chfinish'].", ".$fields['chnote'].", ".$fields['chcf_1'].", ".$fields['chunits'].", ".
830 $mdb2->quote($fields['group_by1']).", ".$mdb2->quote($fields['group_by2']).", ".
831 $mdb2->quote($fields['group_by3']).", ".$fields['chtotalsonly'].")";
832 $affected = $mdb2->exec($sql);
833 if (is_a($affected, 'PEAR_Error'))
836 $last_id = $mdb2->lastInsertID('tt_fav_reports', 'id');
840 // insertNotification function inserts a new notification into database.
841 private function insertNotification($fields)
843 $mdb2 = getConnection();
845 $group_id = (int) $fields['group_id'];
846 $org_id = (int) $fields['org_id'];
847 $cron_spec = $fields['cron_spec'];
848 $last = (int) $fields['last'];
849 $next = (int) $fields['next'];
850 $report_id = (int) $fields['report_id'];
851 $email = $fields['email'];
853 $subject = $fields['subject'];
854 $report_condition = $fields['report_condition'];
855 $status = $fields['status'];
857 $sql = "insert into tt_cron".
858 " (group_id, org_id, cron_spec, last, next, report_id, email, cc, subject, report_condition, status)".
859 " values ($group_id, $org_id, ".$mdb2->quote($cron_spec).", $last, $next, $report_id, ".$mdb2->quote($email).", ".$mdb2->quote($cc).", ".$mdb2->quote($subject).", ".$mdb2->quote($report_condition).", ".$mdb2->quote($status).")";
860 $affected = $mdb2->exec($sql);
861 return (!is_a($affected, 'PEAR_Error'));
864 // insertUserParam - a helper function to insert a user parameter.
865 private function insertUserParam($fields) {
866 $mdb2 = getConnection();
868 $group_id = (int) $fields['group_id'];
869 $org_id = (int) $fields['org_id'];
870 $user_id = (int) $fields['user_id'];
871 $param_name = $fields['param_name'];
872 $param_value = $fields['param_value'];
874 $sql = "insert into tt_config".
875 " (user_id, group_id, org_id, param_name, param_value)".
876 " values ($user_id, $group_id, $org_id, ".$mdb2->quote($param_name).", ".$mdb2->quote($param_value).")";
877 $affected = $mdb2->exec($sql);
878 return (!is_a($affected, 'PEAR_Error'));
881 // insertCustomField - a helper function to insert a custom field.
882 private function insertCustomField($fields) {
883 $mdb2 = getConnection();
885 $group_id = (int) $fields['group_id'];
886 $org_id = (int) $fields['org_id'];
887 $type = (int) $fields['type'];
888 $label = $fields['label'];
889 $required = (int) $fields['required'];
890 $status = $fields['status'];
892 $sql = "insert into tt_custom_fields".
893 " (group_id, org_id, type, label, required, status)".
894 " values($group_id, $org_id, $type, ".$mdb2->quote($label).", $required, ".$mdb2->quote($status).")";
895 $affected = $mdb2->exec($sql);
896 if (is_a($affected, 'PEAR_Error'))
899 $last_id = $mdb2->lastInsertID('tt_custom_fields', 'id');
903 // insertCustomFieldOption - a helper function to insert a custom field option.
904 private function insertCustomFieldOption($fields) {
905 $mdb2 = getConnection();
907 $group_id = (int) $fields['group_id'];
908 $org_id = (int) $fields['org_id'];
909 $field_id = (int) $fields['field_id'];
910 $value = $fields['value'];
912 $sql = "insert into tt_custom_field_options (group_id, org_id, field_id, value)".
913 " values ($group_id, $org_id, $field_id, ".$mdb2->quote($value).")";
914 $affected = $mdb2->exec($sql);
915 if (is_a($affected, 'PEAR_Error'))
918 $last_id = $mdb2->lastInsertID('tt_custom_field_options', 'id');
922 // insertLogEntry - a helper function to insert a time log entry.
923 private function insertLogEntry($fields) {
925 $mdb2 = getConnection();
927 $group_id = (int) $fields['group_id'];
928 $org_id = (int) $fields['org_id'];
929 $user_id = (int) $fields['user_id'];
930 $date = $fields['date'];
931 $start = $fields['start'];
932 $duration = $fields['duration'];
933 $client_id = $fields['client_id'];
934 $project_id = $fields['project_id'];
935 $task_id = $fields['task_id'];
936 $invoice_id = $fields['invoice_id'];
937 $comment = $fields['comment'];
938 $billable = (int) $fields['billable'];
939 $paid = (int) $fields['paid'];
940 $status = $fields['status'];
942 $sql = "insert into tt_log".
943 " (user_id, group_id, org_id, date, start, duration, client_id, project_id, task_id, invoice_id, comment".
944 ", billable, paid, created, created_ip, created_by, status)".
945 " values ($user_id, $group_id, $org_id".
946 ", ".$mdb2->quote($date).
947 ", ".$mdb2->quote($start).
948 ", ".$mdb2->quote($duration).
949 ", ".$mdb2->quote($client_id).
950 ", ".$mdb2->quote($project_id).
951 ", ".$mdb2->quote($task_id).
952 ", ".$mdb2->quote($invoice_id).
953 ", ".$mdb2->quote($comment).
954 ", $billable, $paid".
955 ", now(), ".$mdb2->quote($_SERVER['REMOTE_ADDR']).", ".$user->id.
956 ", ". $mdb2->quote($status).")";
957 $affected = $mdb2->exec($sql);
958 if (is_a($affected, 'PEAR_Error')) {
959 $this->errors->add($i18n->get('error.db')); // TODO: review whether or not to add error here in all insert calls.
963 $log_id = $mdb2->lastInsertID('tt_log', 'id');
967 // insertCustomFieldLogEntry - a helper function to insert a custom field log entry.
968 private function insertCustomFieldLogEntry($fields) {
969 $mdb2 = getConnection();
971 $group_id = (int) $fields['group_id'];
972 $org_id = (int) $fields['org_id'];
973 $log_id = (int) $fields['log_id'];
974 $field_id = (int) $fields['field_id'];
975 $option_id = $fields['option_id'];
976 $value = $fields['value'];
977 $status = $fields['status'];
979 $sql = "insert into tt_custom_field_log (group_id, org_id, log_id, field_id, option_id, value, status)".
980 " values ($group_id, $org_id, $log_id, $field_id, ".$mdb2->quote($option_id).", ".$mdb2->quote($value).", ".$mdb2->quote($status).")";
981 $affected = $mdb2->exec($sql);
982 return (!is_a($affected, 'PEAR_Error'));