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');
31 // ttOrgImportHelper class is used to import organization data from an XML file
32 // prepared by ttOrgExportHelper and consisting of nested groups with their info.
33 class ttOrgImportHelper {
34 var $errors = null; // Errors go here. Set in constructor by reference.
35 var $schema_version = null; // Database schema version from XML file we import from.
36 var $conflicting_logins = null; // A comma-separated list of logins we cannot import.
37 var $canImport = true; // False if we cannot import data due to a conflict such as login collision.
38 var $firstPass = true; // True during first pass through the file.
39 var $org_id = null; // Organization id (same as top group_id).
40 var $current_group_id = null; // Current group id during parsing.
41 var $parents = array(); // A stack of parent group ids for current group all the way to the root including self.
42 var $top_role_id = 0; // Top role id.
44 // Entity maps for current group. They map XML ids with database ids.
45 var $currentGroupRoleMap = array();
46 var $currentGroupTaskMap = array();
47 var $currentGroupProjectMap = array();
48 var $currentGroupClientMap = array();
49 var $currentGroupUserMap = array();
50 var $currentGroupInvoiceMap = array();
51 var $currentGroupLogMap = array();
52 var $currentGroupCustomFieldMap = array();
53 var $currentGroupCustomFieldOptionMap = array();
54 var $currentGroupFavReportMap = array();
57 function __construct(&$errors) {
58 $this->errors = &$errors;
59 $this->top_role_id = $this->getTopRole();
62 // startElement - callback handler for opening tags in XML.
63 function startElement($parser, $name, $attrs) {
66 // First pass through the file determines if we can import data.
67 // We require 2 things:
68 // 1) Database schema version must be set. This ensures we have a compatible file.
69 // 2) No login coillisions are allowed.
70 if ($this->firstPass) {
71 if ($name == 'ORG' && $this->canImport) {
72 if ($attrs['SCHEMA'] == null) {
73 // We need (database) schema attribute to be available for import to work.
74 // Old Time Tracker export files don't have this.
75 // Current import code does not work with old format because we had to
76 // restructure data in export files for subgroup support.
77 $this->canImport = false;
78 $this->errors->add($i18n->get('error.format'));
83 // In first pass we check user logins for potential collisions with existing.
84 if ($name == 'USER' && $this->canImport) {
85 $login = $attrs['LOGIN'];
86 if ('' != $attrs['STATUS'] && ttUserHelper::getUserByLogin($login)) {
87 // We have a login collision. Append colliding login to a list of things we cannot import.
88 $this->conflicting_logins .= ($this->conflicting_logins ? ", $login" : $login);
89 // The above is printed in error message with all found colliding logins.
94 // Second pass processing. We import data here, one tag at a time.
95 if (!$this->firstPass && $this->canImport && $this->errors->no()) {
96 $mdb2 = getConnection();
98 // We are in second pass and can import data.
99 if ($name == 'GROUP') {
100 // Create a new group.
101 $this->current_group_id = $this->createGroup(array(
102 'parent_id' => $this->current_group_id, // Note: after insert current_group_id changes.
103 'org_id' => $this->org_id,
104 'name' => $attrs['NAME'],
105 'description' => $attrs['DESCRIPTION'],
106 'currency' => $attrs['CURRENCY'],
107 'decimal_mark' => $attrs['DECIMAL_MARK'],
108 'lang' => $attrs['LANG'],
109 'date_format' => $attrs['DATE_FORMAT'],
110 'time_format' => $attrs['TIME_FORMAT'],
111 'week_start' => $attrs['WEEK_START'],
112 'tracking_mode' => $attrs['TRACKING_MODE'],
113 'project_required' => $attrs['PROJECT_REQUIRED'],
114 'task_required' => $attrs['TASK_REQUIRED'],
115 'record_type' => $attrs['RECORD_TYPE'],
116 'bcc_email' => $attrs['BCC_EMAIL'],
117 'allow_ip' => $attrs['ALLOW_IP'],
118 'password_complexity' => $attrs['PASSWORD_COMPLEXITY'],
119 'plugins' => $attrs['PLUGINS'],
120 'lock_spec' => $attrs['LOCK_SPEC'],
121 'workday_minutes' => $attrs['WORKDAY_MINUTES'],
122 'custom_logo' => $attrs['CUSTOM_LOGO'],
123 'config' => $attrs['CONFIG']));
125 // Special handling for top group.
126 if (!$this->org_id && $this->current_group_id) {
127 $this->org_id = $this->current_group_id;
128 $sql = "update tt_groups set org_id = $this->current_group_id where org_id is NULL and id = $this->current_group_id";
129 $affected = $mdb2->exec($sql);
131 // Add self to parent stack.
132 array_push($this->parents, $this->current_group_id);
134 // Recycle all maps as we are starting to work on new group.
135 // Note that for this to work properly all nested groups must be last entries in xml for each group.
136 unset($this->currentGroupRoleMap); $this->currentGroupRoleMap = array();
137 unset($this->currentGroupTaskMap); $this->currentGroupTaskMap = array();
138 unset($this->currentGroupProjectMap); $this->currentGroupProjectMap = array();
139 unset($this->currentGroupClientMap); $this->currentGroupClientMap = array();
140 unset($this->currentGroupUserMap); $this->currentGroupUserMap = array();
141 unset($this->currentGroupInvoiceMap); $this->currentGroupInvoiceMap = array();
142 unset($this->currentGroupLogMap); $this->currentGroupLogMap = array();
143 unset($this->currentGroupCustomFieldMap); $this->currentGroupCustomFieldMap = array();
144 unset($this->currentGroupCustomFieldOptionMap); $this->currentGroupCustomFieldOptionMap = array();
145 unset($this->currentGroupFavReportMap); $this->currentGroupCustomFavReportMap = array();
149 if ($name == 'ROLE') {
150 // We get here when processing <role> tags for the current group.
151 $role_id = $this->insertRole(array(
152 'group_id' => $this->current_group_id,
153 'org_id' => $this->org_id,
154 'name' => $attrs['NAME'],
155 'description' => $attrs['DESCRIPTION'],
156 'rank' => $attrs['RANK'],
157 'rights' => $attrs['RIGHTS'],
158 'status' => $attrs['STATUS']));
161 $this->currentGroupRoleMap[$attrs['ID']] = $role_id;
163 $this->errors->add($i18n->get('error.db'));
168 if ($name == 'TASK') {
169 // We get here when processing <task> tags for the current group.
170 $task_id = $this->insertTask(array(
171 'group_id' => $this->current_group_id,
172 'org_id' => $this->org_id,
173 'name' => $attrs['NAME'],
174 'description' => $attrs['DESCRIPTION'],
175 'status' => $attrs['STATUS']));
178 $this->currentGroupTaskMap[$attrs['ID']] = $task_id;
180 $this->errors->add($i18n->get('error.db'));
185 if ($name == 'PROJECT') {
186 // We get here when processing <project> tags for the current group.
188 // Prepare a list of task ids.
189 if ($attrs['TASKS']) {
190 $tasks = explode(',', $attrs['TASKS']);
191 foreach ($tasks as $id)
192 $mapped_tasks[] = $this->currentGroupTaskMap[$id];
195 $project_id = $this->insertProject(array(
196 'group_id' => $this->current_group_id,
197 'org_id' => $this->org_id,
198 'name' => $attrs['NAME'],
199 'description' => $attrs['DESCRIPTION'],
200 'tasks' => $mapped_tasks,
201 'status' => $attrs['STATUS']));
204 $this->currentGroupProjectMap[$attrs['ID']] = $project_id;
206 $this->errors->add($i18n->get('error.db'));
211 if ($name == 'CLIENT') {
212 // We get here when processing <client> tags for the current group.
214 // Prepare a list of project ids.
215 if ($attrs['PROJECTS']) {
216 $projects = explode(',', $attrs['PROJECTS']);
217 foreach ($projects as $id)
218 $mapped_projects[] = $this->currentGroupProjectMap[$id];
221 $client_id = $this->insertClient(array(
222 'group_id' => $this->current_group_id,
223 'org_id' => $this->org_id,
224 'name' => $attrs['NAME'],
225 'address' => $attrs['ADDRESS'],
226 'tax' => $attrs['TAX'],
227 'projects' => $mapped_projects,
228 'status' => $attrs['STATUS']));
231 $this->currentGroupClientMap[$attrs['ID']] = $client_id;
233 $this->errors->add($i18n->get('error.db'));
238 if ($name == 'USER') {
239 // We get here when processing <user> tags for the current group.
241 $role_id = $attrs['ROLE_ID'] === '0' ? $this->top_role_id : $this->currentGroupRoleMap[$attrs['ROLE_ID']]; // 0 (not null) means top manager role.
243 $user_id = ttUserHelper::insert(array(
244 'group_id' => $this->current_group_id,
245 'org_id' => $this->org_id,
246 'role_id' => $role_id,
247 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
248 'name' => $attrs['NAME'],
249 'login' => $attrs['LOGIN'],
250 'password' => $attrs['PASSWORD'],
251 'rate' => $attrs['RATE'],
252 'email' => $attrs['EMAIL'],
253 'status' => $attrs['STATUS']), false);
256 $this->currentGroupUserMap[$attrs['ID']] = $user_id;
258 $this->errors->add($i18n->get('error.db'));
263 if ($name == 'USER_PROJECT_BIND') {
264 if (!ttUserHelper::insertBind(array(
265 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
266 'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
267 'group_id' => $this->current_group_id,
268 'org_id' => $this->org_id,
269 'rate' => $attrs['RATE'],
270 'status' => $attrs['STATUS']))) {
271 $this->errors->add($i18n->get('error.db'));
276 if ($name == 'INVOICE') {
277 // We get here when processing <invoice> tags for the current group.
278 $invoice_id = $this->insertInvoice(array(
279 'group_id' => $this->current_group_id,
280 'org_id' => $this->org_id,
281 'name' => $attrs['NAME'],
282 'date' => $attrs['DATE'],
283 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
284 'status' => $attrs['STATUS']));
287 $this->currentGroupInvoiceMap[$attrs['ID']] = $invoice_id;
289 $this->errors->add($i18n->get('error.db'));
294 if ($name == 'LOG_ITEM') {
295 // We get here when processing <log_item> tags for the current group.
296 $log_item_id = $this->insertLogEntry(array(
297 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
298 'group_id' => $this->current_group_id,
299 'org_id' => $this->org_id,
300 'date' => $attrs['DATE'],
301 'start' => $attrs['START'],
302 'finish' => $attrs['FINISH'],
303 'duration' => $attrs['DURATION'],
304 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
305 'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
306 'task_id' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
307 'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
308 'comment' => (isset($attrs['COMMENT']) ? $attrs['COMMENT'] : ''),
309 'billable' => $attrs['BILLABLE'],
310 'paid' => $attrs['PAID'],
311 'status' => $attrs['STATUS']));
314 $this->currentGroupLogMap[$attrs['ID']] = $log_item_id;
315 } else $this->errors->add($i18n->get('error.db'));
319 if ($name == 'CUSTOM_FIELD') {
320 // We get here when processing <custom_field> tags for the current group.
321 $custom_field_id = $this->insertCustomField(array(
322 'group_id' => $this->current_group_id,
323 'org_id' => $this->org_id,
324 'type' => $attrs['TYPE'],
325 'label' => $attrs['LABEL'],
326 'required' => $attrs['REQUIRED'],
327 'status' => $attrs['STATUS']));
328 if ($custom_field_id) {
330 $this->currentGroupCustomFieldMap[$attrs['ID']] = $custom_field_id;
331 } else $this->errors->add($i18n->get('error.db'));
335 if ($name == 'CUSTOM_FIELD_OPTION') {
336 // We get here when processing <custom_field_option> tags for the current group.
337 $custom_field_option_id = $this->insertCustomFieldOption(array(
338 'group_id' => $this->current_group_id,
339 'org_id' => $this->org_id,
340 'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
341 'value' => $attrs['VALUE']));
342 if ($custom_field_option_id) {
344 $this->currentGroupCustomFieldOptionMap[$attrs['ID']] = $custom_field_option_id;
345 } else $this->errors->add($i18n->get('error.db'));
349 if ($name == 'CUSTOM_FIELD_LOG_ENTRY') {
350 // We get here when processing <custom_field_log_entry> tags for the current group.
351 if (!$this->insertCustomFieldLogEntry(array(
352 'group_id' => $this->current_group_id,
353 'org_id' => $this->org_id,
354 'log_id' => $this->currentGroupLogMap[$attrs['LOG_ID']],
355 'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
356 'option_id' => $this->currentGroupCustomFieldOptionMap[$attrs['OPTION_ID']],
357 'value' => $attrs['VALUE'],
358 'status' => $attrs['STATUS']))) {
359 $this->errors->add($i18n->get('error.db'));
364 if ($name == 'EXPENSE_ITEM') {
365 // We get here when processing <expense_item> tags for the current group.
366 $expense_item_id = $this->insertExpense(array(
367 'date' => $attrs['DATE'],
368 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
369 'group_id' => $this->current_group_id,
370 'org_id' => $this->org_id,
371 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
372 'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
373 'name' => $attrs['NAME'],
374 'cost' => $attrs['COST'],
375 'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
376 'paid' => $attrs['PAID'],
377 'status' => $attrs['STATUS']));
378 if (!$expense_item_id) $this->errors->add($i18n->get('error.db'));
382 if ($name == 'PREDEFINED_EXPENSE') {
383 if (!$this->insertPredefinedExpense(array(
384 'group_id' => $this->current_group_id,
385 'org_id' => $this->org_id,
386 'name' => $attrs['NAME'],
387 'cost' => $attrs['COST']))) {
388 $this->errors->add($i18n->get('error.db'));
393 if ($name == 'MONTHLY_QUOTA') {
394 if (!$this->insertMonthlyQuota(array(
395 'group_id' => $this->current_group_id,
396 'org_id' => $this->org_id,
397 'year' => $attrs['YEAR'],
398 'month' => $attrs['MONTH'],
399 'minutes' => $attrs['MINUTES']))) {
400 $this->errors->add($i18n->get('error.db'));
405 if ($name == 'FAV_REPORT') {
407 if (strlen($attrs['USERS']) > 0) {
408 $arr = explode(',', $attrs['USERS']);
410 $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->currentGroupUserMap[$v];
412 $fav_report_id = $this->insertFavReport(array(
413 'name' => $attrs['NAME'],
414 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
415 'group_id' => $this->current_group_id,
416 'org_id' => $this->org_id,
417 'client' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
418 'option' => $this->currentGroupCustomFieldOptionMap[$attrs['CF_1_OPTION_ID']],
419 'project' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
420 'task' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
421 'billable' => $attrs['BILLABLE'],
422 'users' => $user_list,
423 'period' => $attrs['PERIOD'],
424 'from' => $attrs['PERIOD_START'],
425 'to' => $attrs['PERIOD_END'],
426 'chclient' => (int) $attrs['SHOW_CLIENT'],
427 'chinvoice' => (int) $attrs['SHOW_INVOICE'],
428 'chpaid' => (int) $attrs['SHOW_PAID'],
429 'chip' => (int) $attrs['SHOW_IP'],
430 'chproject' => (int) $attrs['SHOW_PROJECT'],
431 'chstart' => (int) $attrs['SHOW_START'],
432 'chduration' => (int) $attrs['SHOW_DURATION'],
433 'chcost' => (int) $attrs['SHOW_COST'],
434 'chtask' => (int) $attrs['SHOW_TASK'],
435 'chfinish' => (int) $attrs['SHOW_END'],
436 'chnote' => (int) $attrs['SHOW_NOTE'],
437 'chcf_1' => (int) $attrs['SHOW_CUSTOM_FIELD_1'],
438 'chunits' => (int) $attrs['SHOW_WORK_UNITS'],
439 'group_by1' => $attrs['GROUP_BY1'],
440 'group_by2' => $attrs['GROUP_BY2'],
441 'group_by3' => $attrs['GROUP_BY3'],
442 'chtotalsonly' => (int) $attrs['SHOW_TOTALS_ONLY']));
443 if ($fav_report_id) {
445 $this->currentGroupFavReportMap[$attrs['ID']] = $fav_report_id;
446 } else $this->errors->add($i18n->get('error.db'));
450 if ($name == 'NOTIFICATION') {
451 if (!$this->insertNotification(array(
452 'group_id' => $this->current_group_id,
453 'org_id' => $this->org_id,
454 'cron_spec' => $attrs['CRON_SPEC'],
455 'last' => $attrs['LAST'],
456 'next' => $attrs['NEXT'],
457 'report_id' => $this->currentGroupFavReportMap[$attrs['REPORT_ID']],
458 'email' => $attrs['EMAIL'],
459 'cc' => $attrs['CC'],
460 'subject' => $attrs['SUBJECT'],
461 'report_condition' => $attrs['REPORT_CONDITION'],
462 'status' => $attrs['STATUS']))) {
463 $this->errors->add($i18n->get('error.db'));
468 if ($name == 'USER_PARAM') {
469 if (!$this->insertUserParam(array(
470 'group_id' => $this->current_group_id,
471 'org_id' => $this->org_id,
472 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
473 'param_name' => $attrs['PARAM_NAME'],
474 'param_value' => $attrs['PARAM_VALUE']))) {
475 $this->errors->add($i18n->get('error.db'));
482 // endElement - callback handler for ending tags in XML.
483 // We use this only for process </group> element endings and
484 // set current_group_id to an immediate parent.
485 // This is required to import group hierarchy correctly.
486 function endElement($parser, $name) {
487 // No need to care about first or second pass, as this is used only in second pass.
488 // See 2nd xml_set_element_handler, where this handler is set.
489 if ($name == 'GROUP') {
490 // Remove self from the parent stack.
491 $self = array_pop($this->parents);
492 // Set current group id to an immediate parent.
493 $len = count($this->parents);
494 $this->current_group_id = $len ? $this->parents[$len-1] : null;
498 // importXml - uncompresses the file, reads and parses its content. During parsing,
499 // startElement, endElement, and dataElement functions are called as many times as necessary.
500 // Actual import occurs in the endElement handler.
501 function importXml() {
504 // Do we have a compressed file?
506 $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
507 if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
511 // Create a temporary file.
512 $dirName = dirname(TEMPLATE_DIR . '_c/.');
513 $filename = tempnam($dirName, 'import_');
515 // If the file is compressed - uncompress it.
517 if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
518 $this->errors->add($i18n->get('error.sys'));
521 unlink($_FILES['xmlfile']['tmp_name']);
523 if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
524 $this->errors->add($i18n->get('error.upload'));
529 // Initialize XML parser.
530 $parser = xml_parser_create();
531 xml_set_object($parser, $this);
532 xml_set_element_handler($parser, 'startElement', false); // No need to process end tags in 1st pass.
534 // We need to parse the file 2 times:
535 // 1) First pass: determine if import is possible.
536 // 2) Second pass: import data, one tag at a time.
538 // Read and parse the content of the file. During parsing, startElement is called back for each tag.
539 $file = fopen($filename, 'r');
540 while (($data = fread($file, 4096)) && $this->errors->no()) {
541 if (!xml_parse($parser, $data, feof($file))) {
542 $this->errors->add(sprintf($i18n->get('error.xml'),
543 xml_get_current_line_number($parser),
544 xml_error_string(xml_get_error_code($parser))));
547 if ($this->conflicting_logins) {
548 $this->canImport = false;
549 $this->errors->add($i18n->get('error.user_exists'));
550 $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_logins));
553 $this->firstPass = false; // We are done with 1st pass.
554 xml_parser_free($parser);
555 if ($file) fclose($file);
556 if (!$this->canImport) {
560 if ($this->errors->yes()) return; // Exit if we have errors.
562 // Now we can do a second pass, where real work is done.
563 $parser = xml_parser_create();
564 xml_set_object($parser, $this);
565 xml_set_element_handler($parser, 'startElement', 'endElement'); // Need to process ending tags too.
567 // Read and parse the content of the file. During parsing, startElement and endElement are called back for each tag.
568 $file = fopen($filename, 'r');
569 while (($data = fread($file, 4096)) && $this->errors->no()) {
570 if (!xml_parse($parser, $data, feof($file))) {
571 $this->errors->add(sprintf($i18n->get('error.xml'),
572 xml_get_current_line_number($parser),
573 xml_error_string(xml_get_error_code($parser))));
576 xml_parser_free($parser);
577 if ($file) fclose($file);
581 // uncompress - uncompresses the content of the $in file into the $out file.
582 function uncompress($in, $out) {
583 // Do we have the uncompress function?
584 if (!function_exists('bzopen'))
587 // Initial checks of file names and permissions.
588 if (!file_exists($in) || !is_readable ($in))
590 if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
593 if (!$out_file = fopen($out, 'wb'))
595 if (!$in_file = bzopen ($in, 'r'))
598 while (!feof($in_file)) {
599 $buffer = bzread($in_file, 4096);
600 fwrite($out_file, $buffer, 4096);
607 // createGroup function creates a new group.
608 private function createGroup($fields) {
611 $mdb2 = getConnection();
613 $columns = '(parent_id, org_id, name, description, currency, decimal_mark, lang, date_format, time_format'.
614 ', week_start, tracking_mode, project_required, task_required, record_type, bcc_email'.
615 ', allow_ip, password_complexity, plugins, lock_spec'.
616 ', workday_minutes, config, created, created_ip, created_by)';
618 $values = ' values (';
619 $values .= $mdb2->quote($fields['parent_id']);
620 $values .= ', '.$mdb2->quote($fields['org_id']);
621 $values .= ', '.$mdb2->quote(trim($fields['name']));
622 $values .= ', '.$mdb2->quote(trim($fields['description']));
623 $values .= ', '.$mdb2->quote(trim($fields['currency']));
624 $values .= ', '.$mdb2->quote($fields['decimal_mark']);
625 $values .= ', '.$mdb2->quote($fields['lang']);
626 $values .= ', '.$mdb2->quote($fields['date_format']);
627 $values .= ', '.$mdb2->quote($fields['time_format']);
628 $values .= ', '.(int)$fields['week_start'];
629 $values .= ', '.(int)$fields['tracking_mode'];
630 $values .= ', '.(int)$fields['project_required'];
631 $values .= ', '.(int)$fields['task_required'];
632 $values .= ', '.(int)$fields['record_type'];
633 $values .= ', '.$mdb2->quote($fields['bcc_email']);
634 $values .= ', '.$mdb2->quote($fields['allow_ip']);
635 $values .= ', '.$mdb2->quote($fields['password_complexity']);
636 $values .= ', '.$mdb2->quote($fields['plugins']);
637 $values .= ', '.$mdb2->quote($fields['lock_spec']);
638 $values .= ', '.(int)$fields['workday_minutes'];
639 $values .= ', '.$mdb2->quote($fields['config']);
640 $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
643 $sql = 'insert into tt_groups '.$columns.$values;
644 $affected = $mdb2->exec($sql);
645 if (is_a($affected, 'PEAR_Error')) {
646 $this->errors->add($i18n->get('error.db'));
650 $group_id = $mdb2->lastInsertID('tt_groups', 'id');
654 // insertMonthlyQuota - a helper function to insert a monthly quota.
655 private function insertMonthlyQuota($fields) {
656 $mdb2 = getConnection();
657 $group_id = (int) $fields['group_id'];
658 $org_id = (int) $fields['org_id'];
659 $year = (int) $fields['year'];
660 $month = (int) $fields['month'];
661 $minutes = (int) $fields['minutes'];
663 $sql = "INSERT INTO tt_monthly_quotas (group_id, org_id, year, month, minutes)".
664 " values ($group_id, $org_id, $year, $month, $minutes)";
665 $affected = $mdb2->exec($sql);
666 return (!is_a($affected, 'PEAR_Error'));
669 // insertPredefinedExpense - a helper function to insert a predefined expense.
670 private function insertPredefinedExpense($fields) {
671 $mdb2 = getConnection();
672 $group_id = (int) $fields['group_id'];
673 $org_id = (int) $fields['org_id'];
674 $name = $mdb2->quote($fields['name']);
675 $cost = $mdb2->quote($fields['cost']);
677 $sql = "INSERT INTO tt_predefined_expenses (group_id, org_id, name, cost)".
678 " values ($group_id, $org_id, $name, $cost)";
679 $affected = $mdb2->exec($sql);
680 return (!is_a($affected, 'PEAR_Error'));
683 // insertExpense - a helper function to insert an expense item.
684 private function insertExpense($fields) {
686 $mdb2 = getConnection();
688 $group_id = (int) $fields['group_id'];
689 $org_id = (int) $fields['org_id'];
690 $date = $fields['date'];
691 $user_id = (int) $fields['user_id'];
692 $client_id = $fields['client_id'];
693 $project_id = $fields['project_id'];
694 $name = $fields['name'];
695 $cost = str_replace(',', '.', $fields['cost']);
696 $invoice_id = $fields['invoice_id'];
697 $status = $fields['status'];
698 $paid = (int) $fields['paid'];
699 $created = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
701 $sql = "insert into tt_expense_items".
702 " (date, user_id, group_id, org_id, client_id, project_id, name, cost, invoice_id, paid, created, created_ip, created_by, status)".
703 " values (".$mdb2->quote($date).", $user_id, $group_id, $org_id, ".$mdb2->quote($client_id).", ".$mdb2->quote($project_id).
704 ", ".$mdb2->quote($name).", ".$mdb2->quote($cost).", ".$mdb2->quote($invoice_id).", $paid $created, ".$mdb2->quote($status).")";
705 $affected = $mdb2->exec($sql);
706 return (!is_a($affected, 'PEAR_Error'));
709 // insertTask function inserts a new task into database.
710 private function insertTask($fields)
712 $mdb2 = getConnection();
714 $group_id = (int) $fields['group_id'];
715 $org_id = (int) $fields['org_id'];
716 $name = $fields['name'];
717 $description = $fields['description'];
718 $projects = $fields['projects'];
719 $status = $fields['status'];
721 $sql = "insert into tt_tasks (group_id, org_id, name, description, status)
722 values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($status).")";
723 $affected = $mdb2->exec($sql);
725 if (is_a($affected, 'PEAR_Error'))
728 $last_id = $mdb2->lastInsertID('tt_tasks', 'id');
732 // insertProject - a helper function to insert a project as well as project to task binds.
733 private function insertProject($fields)
735 $mdb2 = getConnection();
737 $group_id = (int) $fields['group_id'];
738 $org_id = (int) $fields['org_id'];
740 $name = $fields['name'];
741 $description = $fields['description'];
742 $tasks = $fields['tasks'];
743 $comma_separated = implode(',', $tasks); // This is a comma-separated list of associated task ids.
744 $status = $fields['status'];
746 $sql = "insert into tt_projects (group_id, org_id, name, description, tasks, status)
747 values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
748 $affected = $mdb2->exec($sql);
749 if (is_a($affected, 'PEAR_Error'))
752 $last_id = $mdb2->lastInsertID('tt_projects', 'id');
754 // Insert binds into tt_project_task_binds table.
755 if (is_array($tasks)) {
756 foreach ($tasks as $task_id) {
757 $sql = "insert into tt_project_task_binds (project_id, task_id, group_id, org_id)".
758 " values($last_id, $task_id, $group_id, $org_id)";
759 $affected = $mdb2->exec($sql);
760 if (is_a($affected, 'PEAR_Error'))
768 // insertRole - inserts a role into tt_roles table.
769 private function insertRole($fields)
771 $mdb2 = getConnection();
773 $group_id = (int) $fields['group_id'];
774 $org_id = (int) $fields['org_id'];
775 $name = $fields['name'];
776 $rank = (int) $fields['rank'];
777 $description = $fields['description'];
778 $rights = $fields['rights'];
779 $status = $fields['status'];
781 $sql = "insert into tt_roles (group_id, org_id, name, rank, description, rights, status)
782 values ($group_id, $org_id, ".$mdb2->quote($name).", $rank, ".$mdb2->quote($description).", ".$mdb2->quote($rights).", ".$mdb2->quote($status).")";
783 $affected = $mdb2->exec($sql);
784 if (is_a($affected, 'PEAR_Error'))
787 $last_id = $mdb2->lastInsertID('tt_roles', 'id');
791 // insertInvoice - inserts an invoice in database.
792 private function insertInvoice($fields)
794 $mdb2 = getConnection();
796 $group_id = (int) $fields['group_id'];
797 $org_id = (int) $fields['org_id'];
798 $name = $fields['name'];
799 $client_id = (int) $fields['client_id'];
800 $date = $fields['date'];
801 $status = $fields['status'];
803 // Insert a new invoice record.
804 $sql = "insert into tt_invoices (group_id, org_id, name, date, client_id, status)".
805 " values($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id, ".$mdb2->quote($fields['status']).")";
806 $affected = $mdb2->exec($sql);
807 if (is_a($affected, 'PEAR_Error')) return false;
809 $last_id = $mdb2->lastInsertID('tt_invoices', 'id');
813 // The insertClient function inserts a new client as well as client to project binds.
814 private function insertClient($fields)
816 $mdb2 = getConnection();
818 $group_id = (int) $fields['group_id'];
819 $org_id = (int) $fields['org_id'];
820 $name = $fields['name'];
821 $address = $fields['address'];
822 $tax = $fields['tax'];
823 $projects = $fields['projects'];
825 $comma_separated = implode(',', $projects); // This is a comma-separated list of associated projects ids.
826 $status = $fields['status'];
828 $tax = str_replace(',', '.', $tax);
829 if ($tax == '') $tax = 0;
831 $sql = "insert into tt_clients (group_id, org_id, name, address, tax, projects, status)".
832 " values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($address).", $tax, ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
834 $affected = $mdb2->exec($sql);
835 if (is_a($affected, 'PEAR_Error'))
838 $last_id = $mdb2->lastInsertID('tt_clients', 'id');
840 if (count($projects) > 0)
841 foreach ($projects as $p_id) {
842 $sql = "insert into tt_client_project_binds (client_id, project_id, group_id, org_id) values($last_id, $p_id, $group_id, $org_id)";
843 $affected = $mdb2->exec($sql);
844 if (is_a($affected, 'PEAR_Error'))
851 // insertFavReport - inserts a favorite report in database.
852 private function insertFavReport($fields) {
853 $mdb2 = getConnection();
855 $group_id = (int) $fields['group_id'];
856 $org_id = (int) $fields['org_id'];
858 $sql = "insert into tt_fav_reports".
859 " (name, user_id, group_id, org_id, client_id, cf_1_option_id, project_id, task_id,".
860 " billable, invoice, paid_status, users, period, period_start, period_end,".
861 " show_client, show_invoice, show_paid, show_ip,".
862 " show_project, show_start, show_duration, show_cost,".
863 " show_task, show_end, show_note, show_custom_field_1, show_work_units,".
864 " group_by1, group_by2, group_by3, show_totals_only)".
866 $mdb2->quote($fields['name']).", ".$fields['user_id'].", $group_id, $org_id, ".
867 $mdb2->quote($fields['client']).", ".$mdb2->quote($fields['option']).", ".
868 $mdb2->quote($fields['project']).", ".$mdb2->quote($fields['task']).", ".
869 $mdb2->quote($fields['billable']).", ".$mdb2->quote($fields['invoice']).", ".
870 $mdb2->quote($fields['paid_status']).", ".
871 $mdb2->quote($fields['users']).", ".$mdb2->quote($fields['period']).", ".
872 $mdb2->quote($fields['from']).", ".$mdb2->quote($fields['to']).", ".
873 $fields['chclient'].", ".$fields['chinvoice'].", ".$fields['chpaid'].", ".$fields['chip'].", ".
874 $fields['chproject'].", ".$fields['chstart'].", ".$fields['chduration'].", ".$fields['chcost'].", ".
875 $fields['chtask'].", ".$fields['chfinish'].", ".$fields['chnote'].", ".$fields['chcf_1'].", ".$fields['chunits'].", ".
876 $mdb2->quote($fields['group_by1']).", ".$mdb2->quote($fields['group_by2']).", ".
877 $mdb2->quote($fields['group_by3']).", ".$fields['chtotalsonly'].")";
878 $affected = $mdb2->exec($sql);
879 if (is_a($affected, 'PEAR_Error'))
882 $last_id = $mdb2->lastInsertID('tt_fav_reports', 'id');
886 // insertNotification function inserts a new notification into database.
887 private function insertNotification($fields)
889 $mdb2 = getConnection();
891 $group_id = (int) $fields['group_id'];
892 $org_id = (int) $fields['org_id'];
893 $cron_spec = $fields['cron_spec'];
894 $last = (int) $fields['last'];
895 $next = (int) $fields['next'];
896 $report_id = (int) $fields['report_id'];
897 $email = $fields['email'];
899 $subject = $fields['subject'];
900 $report_condition = $fields['report_condition'];
901 $status = $fields['status'];
903 $sql = "insert into tt_cron".
904 " (group_id, org_id, cron_spec, last, next, report_id, email, cc, subject, report_condition, status)".
905 " 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).")";
906 $affected = $mdb2->exec($sql);
907 return (!is_a($affected, 'PEAR_Error'));
910 // insertUserParam - a helper function to insert a user parameter.
911 private function insertUserParam($fields) {
912 $mdb2 = getConnection();
914 $group_id = (int) $fields['group_id'];
915 $org_id = (int) $fields['org_id'];
916 $user_id = (int) $fields['user_id'];
917 $param_name = $fields['param_name'];
918 $param_value = $fields['param_value'];
920 $sql = "insert into tt_config".
921 " (user_id, group_id, org_id, param_name, param_value)".
922 " values ($user_id, $group_id, $org_id, ".$mdb2->quote($param_name).", ".$mdb2->quote($param_value).")";
923 $affected = $mdb2->exec($sql);
924 return (!is_a($affected, 'PEAR_Error'));
927 // insertCustomField - a helper function to insert a custom field.
928 private function insertCustomField($fields) {
929 $mdb2 = getConnection();
931 $group_id = (int) $fields['group_id'];
932 $org_id = (int) $fields['org_id'];
933 $type = (int) $fields['type'];
934 $label = $fields['label'];
935 $required = (int) $fields['required'];
936 $status = $fields['status'];
938 $sql = "insert into tt_custom_fields".
939 " (group_id, org_id, type, label, required, status)".
940 " values($group_id, $org_id, $type, ".$mdb2->quote($label).", $required, ".$mdb2->quote($status).")";
941 $affected = $mdb2->exec($sql);
942 if (is_a($affected, 'PEAR_Error'))
945 $last_id = $mdb2->lastInsertID('tt_custom_fields', 'id');
949 // insertCustomFieldOption - a helper function to insert a custom field option.
950 private function insertCustomFieldOption($fields) {
951 $mdb2 = getConnection();
953 $group_id = (int) $fields['group_id'];
954 $org_id = (int) $fields['org_id'];
955 $field_id = (int) $fields['field_id'];
956 $value = $fields['value'];
958 $sql = "insert into tt_custom_field_options (group_id, org_id, field_id, value)".
959 " values ($group_id, $org_id, $field_id, ".$mdb2->quote($value).")";
960 $affected = $mdb2->exec($sql);
961 if (is_a($affected, 'PEAR_Error'))
964 $last_id = $mdb2->lastInsertID('tt_custom_field_options', 'id');
968 // insertLogEntry - a helper function to insert a time log entry.
969 private function insertLogEntry($fields) {
971 $mdb2 = getConnection();
973 $group_id = (int) $fields['group_id'];
974 $org_id = (int) $fields['org_id'];
975 $user_id = (int) $fields['user_id'];
976 $date = $fields['date'];
977 $start = $fields['start'];
978 $duration = $fields['duration'];
979 $client_id = $fields['client_id'];
980 $project_id = $fields['project_id'];
981 $task_id = $fields['task_id'];
982 $invoice_id = $fields['invoice_id'];
983 $comment = $fields['comment'];
984 $billable = (int) $fields['billable'];
985 $paid = (int) $fields['paid'];
986 $status = $fields['status'];
988 $sql = "insert into tt_log".
989 " (user_id, group_id, org_id, date, start, duration, client_id, project_id, task_id, invoice_id, comment".
990 ", billable, paid, created, created_ip, created_by, status)".
991 " values ($user_id, $group_id, $org_id".
992 ", ".$mdb2->quote($date).
993 ", ".$mdb2->quote($start).
994 ", ".$mdb2->quote($duration).
995 ", ".$mdb2->quote($client_id).
996 ", ".$mdb2->quote($project_id).
997 ", ".$mdb2->quote($task_id).
998 ", ".$mdb2->quote($invoice_id).
999 ", ".$mdb2->quote($comment).
1000 ", $billable, $paid".
1001 ", now(), ".$mdb2->quote($_SERVER['REMOTE_ADDR']).", ".$user->id.
1002 ", ". $mdb2->quote($status).")";
1003 $affected = $mdb2->exec($sql);
1004 if (is_a($affected, 'PEAR_Error')) {
1005 $this->errors->add($i18n->get('error.db')); // TODO: review whether or not to add error here in all insert calls.
1009 $log_id = $mdb2->lastInsertID('tt_log', 'id');
1013 // insertCustomFieldLogEntry - a helper function to insert a custom field log entry.
1014 private function insertCustomFieldLogEntry($fields) {
1015 $mdb2 = getConnection();
1017 $group_id = (int) $fields['group_id'];
1018 $org_id = (int) $fields['org_id'];
1019 $log_id = (int) $fields['log_id'];
1020 $field_id = (int) $fields['field_id'];
1021 $option_id = $fields['option_id'];
1022 $value = $fields['value'];
1023 $status = $fields['status'];
1025 $sql = "insert into tt_custom_field_log (group_id, org_id, log_id, field_id, option_id, value, status)".
1026 " values ($group_id, $org_id, $log_id, $field_id, ".$mdb2->quote($option_id).", ".$mdb2->quote($value).", ".$mdb2->quote($status).")";
1027 $affected = $mdb2->exec($sql);
1028 return (!is_a($affected, 'PEAR_Error'));
1031 // getTopRole returns top role id.
1032 private function getTopRole() {
1033 $mdb2 = getConnection();
1035 $sql = "select id from tt_roles where group_id = 0 and rank = ".MAX_RANK." and status = 1";
1036 $res = $mdb2->query($sql);
1038 if (!is_a($res, 'PEAR_Error')) {
1039 $val = $res->fetchRow();