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 = ttRoleHelper::insert(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;
184 } else $this->errors->add($i18n->get('error.db'));
188 if ($name == 'PROJECT') {
189 // We get here when processing <project> tags for the current group.
191 // Prepare a list of task ids.
192 if ($attrs['TASKS']) {
193 $tasks = explode(',', $attrs['TASKS']);
194 foreach ($tasks as $id)
195 $mapped_tasks[] = $this->currentGroupTaskMap[$id];
198 $project_id = $this->insertProject(array(
199 'group_id' => $this->current_group_id,
200 'org_id' => $this->org_id,
201 'name' => $attrs['NAME'],
202 'description' => $attrs['DESCRIPTION'],
203 'tasks' => $mapped_tasks,
204 'status' => $attrs['STATUS']));
207 $this->currentGroupProjectMap[$attrs['ID']] = $project_id;
208 } else $this->errors->add($i18n->get('error.db'));
212 if ($name == 'CLIENT') {
213 // We get here when processing <client> tags for the current group.
215 // Prepare a list of project ids.
216 if ($attrs['PROJECTS']) {
217 $projects = explode(',', $attrs['PROJECTS']);
218 foreach ($projects as $id)
219 $mapped_projects[] = $this->currentGroupProjectMap[$id];
222 $client_id = $this->insertClient(array(
223 'group_id' => $this->current_group_id,
224 'org_id' => $this->org_id,
225 'name' => $attrs['NAME'],
226 'address' => $attrs['ADDRESS'],
227 'tax' => $attrs['TAX'],
228 'projects' => $mapped_projects,
229 'status' => $attrs['STATUS']));
232 $this->currentGroupClientMap[$attrs['ID']] = $client_id;
233 } else $this->errors->add($i18n->get('error.db'));
237 if ($name == 'USER') {
238 // We get here when processing <user> tags for the current group.
240 $role_id = $attrs['ROLE_ID'] === '0' ? $this->top_role_id : $this->currentGroupRoleMap[$attrs['ROLE_ID']]; // 0 (not null) means top manager role.
242 $user_id = ttUserHelper::insert(array(
243 'group_id' => $this->current_group_id,
244 'org_id' => $this->org_id,
245 'role_id' => $role_id,
246 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
247 'name' => $attrs['NAME'],
248 'login' => $attrs['LOGIN'],
249 'password' => $attrs['PASSWORD'],
250 'rate' => $attrs['RATE'],
251 'email' => $attrs['EMAIL'],
252 'status' => $attrs['STATUS']), false);
255 $this->currentGroupUserMap[$attrs['ID']] = $user_id;
256 } else $this->errors->add($i18n->get('error.db'));
260 if ($name == 'USER_PROJECT_BIND') {
261 if (!ttUserHelper::insertBind(array(
262 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
263 'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
264 'group_id' => $this->current_group_id,
265 'org_id' => $this->org_id,
266 'rate' => $attrs['RATE'],
267 'status' => $attrs['STATUS']))) {
268 $this->errors->add($i18n->get('error.db'));
273 if ($name == 'INVOICE') {
274 // We get here when processing <invoice> tags for the current group.
275 $invoice_id = ttInvoiceHelper::insert(array(
276 'group_id' => $this->current_group_id,
277 'org_id' => $this->org_id,
278 'name' => $attrs['NAME'],
279 'date' => $attrs['DATE'],
280 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
281 'status' => $attrs['STATUS']));
284 $this->currentGroupInvoiceMap[$attrs['ID']] = $invoice_id;
285 } else $this->errors->add($i18n->get('error.db'));
289 if ($name == 'LOG_ITEM') {
290 // We get here when processing <log_item> tags for the current group.
291 $log_item_id = $this->insertLogEntry(array(
292 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
293 'group_id' => $this->current_group_id,
294 'org_id' => $this->org_id,
295 'date' => $attrs['DATE'],
296 'start' => $attrs['START'],
297 'finish' => $attrs['FINISH'],
298 'duration' => $attrs['DURATION'],
299 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
300 'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
301 'task_id' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
302 'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
303 'comment' => (isset($attrs['COMMENT']) ? $attrs['COMMENT'] : ''),
304 'billable' => $attrs['BILLABLE'],
305 'paid' => $attrs['PAID'],
306 'status' => $attrs['STATUS']));
309 $this->currentGroupLogMap[$attrs['ID']] = $log_item_id;
310 } else $this->errors->add($i18n->get('error.db'));
314 if ($name == 'CUSTOM_FIELD') {
315 // We get here when processing <custom_field> tags for the current group.
316 $custom_field_id = $this->insertCustomField(array(
317 'group_id' => $this->current_group_id,
318 'org_id' => $this->org_id,
319 'type' => $attrs['TYPE'],
320 'label' => $attrs['LABEL'],
321 'required' => $attrs['REQUIRED'],
322 'status' => $attrs['STATUS']));
323 if ($custom_field_id) {
325 $this->currentGroupCustomFieldMap[$attrs['ID']] = $custom_field_id;
326 } else $this->errors->add($i18n->get('error.db'));
330 if ($name == 'CUSTOM_FIELD_OPTION') {
331 // We get here when processing <custom_field_option> tags for the current group.
332 $custom_field_option_id = $this->insertCustomFieldOption(array(
333 'group_id' => $this->current_group_id,
334 'org_id' => $this->org_id,
335 'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
336 'value' => $attrs['VALUE']));
337 if ($custom_field_option_id) {
339 $this->currentGroupCustomFieldOptionMap[$attrs['ID']] = $custom_field_option_id;
340 } else $this->errors->add($i18n->get('error.db'));
344 if ($name == 'CUSTOM_FIELD_LOG_ENTRY') {
345 // We get here when processing <custom_field_log_entry> tags for the current group.
346 if (!$this->insertCustomFieldLogEntry(array(
347 'group_id' => $this->current_group_id,
348 'org_id' => $this->org_id,
349 'log_id' => $this->currentGroupLogMap[$attrs['LOG_ID']],
350 'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
351 'option_id' => $this->currentGroupCustomFieldOptionMap[$attrs['OPTION_ID']],
352 'value' => $attrs['VALUE'],
353 'status' => $attrs['STATUS']))) {
354 $this->errors->add($i18n->get('error.db'));
359 if ($name == 'EXPENSE_ITEM') {
360 // We get here when processing <expense_item> tags for the current group.
361 $expense_item_id = $this->insertExpense(array(
362 'date' => $attrs['DATE'],
363 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
364 'group_id' => $this->current_group_id,
365 'org_id' => $this->org_id,
366 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
367 'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
368 'name' => $attrs['NAME'],
369 'cost' => $attrs['COST'],
370 'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
371 'paid' => $attrs['PAID'],
372 'status' => $attrs['STATUS']));
373 if (!$expense_item_id) $this->errors->add($i18n->get('error.db'));
377 if ($name == 'PREDEFINED_EXPENSE') {
378 if (!$this->insertPredefinedExpense(array(
379 'group_id' => $this->current_group_id,
380 'org_id' => $this->org_id,
381 'name' => $attrs['NAME'],
382 'cost' => $attrs['COST']))) {
383 $this->errors->add($i18n->get('error.db'));
388 if ($name == 'MONTHLY_QUOTA') {
389 if (!$this->insertMonthlyQuota(array(
390 'group_id' => $this->current_group_id,
391 'org_id' => $this->org_id,
392 'year' => $attrs['YEAR'],
393 'month' => $attrs['MONTH'],
394 'minutes' => $attrs['MINUTES']))) {
395 $this->errors->add($i18n->get('error.db'));
400 if ($name == 'FAV_REPORT') {
402 if (strlen($attrs['USERS']) > 0) {
403 $arr = explode(',', $attrs['USERS']);
405 $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->currentGroupUserMap[$v];
407 $fav_report_id = $this->insertFavReport(array(
408 'name' => $attrs['NAME'],
409 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
410 'group_id' => $this->current_group_id,
411 'org_id' => $this->org_id,
412 'client' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
413 'option' => $this->currentGroupCustomFieldOptionMap[$attrs['CF_1_OPTION_ID']],
414 'project' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
415 'task' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
416 'billable' => $attrs['BILLABLE'],
417 'users' => $user_list,
418 'period' => $attrs['PERIOD'],
419 'from' => $attrs['PERIOD_START'],
420 'to' => $attrs['PERIOD_END'],
421 'chclient' => (int) $attrs['SHOW_CLIENT'],
422 'chinvoice' => (int) $attrs['SHOW_INVOICE'],
423 'chpaid' => (int) $attrs['SHOW_PAID'],
424 'chip' => (int) $attrs['SHOW_IP'],
425 'chproject' => (int) $attrs['SHOW_PROJECT'],
426 'chstart' => (int) $attrs['SHOW_START'],
427 'chduration' => (int) $attrs['SHOW_DURATION'],
428 'chcost' => (int) $attrs['SHOW_COST'],
429 'chtask' => (int) $attrs['SHOW_TASK'],
430 'chfinish' => (int) $attrs['SHOW_END'],
431 'chnote' => (int) $attrs['SHOW_NOTE'],
432 'chcf_1' => (int) $attrs['SHOW_CUSTOM_FIELD_1'],
433 'chunits' => (int) $attrs['SHOW_WORK_UNITS'],
434 'group_by1' => $attrs['GROUP_BY1'],
435 'group_by2' => $attrs['GROUP_BY2'],
436 'group_by3' => $attrs['GROUP_BY3'],
437 'chtotalsonly' => (int) $attrs['SHOW_TOTALS_ONLY']));
438 if ($fav_report_id) {
440 $this->currentGroupFavReportMap[$attrs['ID']] = $fav_report_id;
441 } else $this->errors->add($i18n->get('error.db'));
445 if ($name == 'NOTIFICATION') {
446 if (!$this->insertNotification(array(
447 'group_id' => $this->current_group_id,
448 'org_id' => $this->org_id,
449 'cron_spec' => $attrs['CRON_SPEC'],
450 'last' => $attrs['LAST'],
451 'next' => $attrs['NEXT'],
452 'report_id' => $this->currentGroupFavReportMap[$attrs['REPORT_ID']],
453 'email' => $attrs['EMAIL'],
454 'cc' => $attrs['CC'],
455 'subject' => $attrs['SUBJECT'],
456 'report_condition' => $attrs['REPORT_CONDITION'],
457 'status' => $attrs['STATUS']))) {
458 $this->errors->add($i18n->get('error.db'));
463 if ($name == 'USER_PARAM') {
464 if (!$this->insertUserParam(array(
465 'group_id' => $this->current_group_id,
466 'org_id' => $this->org_id,
467 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
468 'param_name' => $attrs['PARAM_NAME'],
469 'param_value' => $attrs['PARAM_VALUE']))) {
470 $this->errors->add($i18n->get('error.db'));
477 // endElement - callback handler for ending tags in XML.
478 // We use this only for process </group> element endings and
479 // set current_group_id to an immediate parent.
480 // This is required to import group hierarchy correctly.
481 function endElement($parser, $name) {
482 // No need to care about first or second pass, as this is used only in second pass.
483 // See 2nd xml_set_element_handler, where this handler is set.
484 if ($name == 'GROUP') {
485 // Remove self from the parent stack.
486 $self = array_pop($this->parents);
487 // Set current group id to an immediate parent.
488 $len = count($this->parents);
489 $this->current_group_id = $len ? $this->parents[$len-1] : null;
493 // importXml - uncompresses the file, reads and parses its content. During parsing,
494 // startElement, endElement, and dataElement functions are called as many times as necessary.
495 // Actual import occurs in the endElement handler.
496 function importXml() {
499 // Do we have a compressed file?
501 $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
502 if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
506 // Create a temporary file.
507 $dirName = dirname(TEMPLATE_DIR . '_c/.');
508 $filename = tempnam($dirName, 'import_');
510 // If the file is compressed - uncompress it.
512 if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
513 $this->errors->add($i18n->get('error.sys'));
516 unlink($_FILES['xmlfile']['tmp_name']);
518 if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
519 $this->errors->add($i18n->get('error.upload'));
524 // Initialize XML parser.
525 $parser = xml_parser_create();
526 xml_set_object($parser, $this);
527 xml_set_element_handler($parser, 'startElement', false); // No need to process end tags in 1st pass.
529 // We need to parse the file 2 times:
530 // 1) First pass: determine if import is possible.
531 // 2) Second pass: import data, one tag at a time.
533 // Read and parse the content of the file. During parsing, startElement is called back for each tag.
534 $file = fopen($filename, 'r');
535 while (($data = fread($file, 4096)) && $this->errors->no()) {
536 if (!xml_parse($parser, $data, feof($file))) {
537 $this->errors->add(sprintf($i18n->get('error.xml'),
538 xml_get_current_line_number($parser),
539 xml_error_string(xml_get_error_code($parser))));
542 if ($this->conflicting_logins) {
543 $this->canImport = false;
544 $this->errors->add($i18n->get('error.user_exists'));
545 $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_logins));
548 $this->firstPass = false; // We are done with 1st pass.
549 xml_parser_free($parser);
550 if ($file) fclose($file);
551 if (!$this->canImport) {
555 if ($this->errors->yes()) return; // Exit if we have errors.
557 // Now we can do a second pass, where real work is done.
558 $parser = xml_parser_create();
559 xml_set_object($parser, $this);
560 xml_set_element_handler($parser, 'startElement', 'endElement'); // Need to process ending tags too.
562 // Read and parse the content of the file. During parsing, startElement and endElement are called back for each tag.
563 $file = fopen($filename, 'r');
564 while (($data = fread($file, 4096)) && $this->errors->no()) {
565 if (!xml_parse($parser, $data, feof($file))) {
566 $this->errors->add(sprintf($i18n->get('error.xml'),
567 xml_get_current_line_number($parser),
568 xml_error_string(xml_get_error_code($parser))));
571 xml_parser_free($parser);
572 if ($file) fclose($file);
576 // uncompress - uncompresses the content of the $in file into the $out file.
577 function uncompress($in, $out) {
578 // Do we have the uncompress function?
579 if (!function_exists('bzopen'))
582 // Initial checks of file names and permissions.
583 if (!file_exists($in) || !is_readable ($in))
585 if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
588 if (!$out_file = fopen($out, 'wb'))
590 if (!$in_file = bzopen ($in, 'r'))
593 while (!feof($in_file)) {
594 $buffer = bzread($in_file, 4096);
595 fwrite($out_file, $buffer, 4096);
602 // createGroup function creates a new group.
603 private function createGroup($fields) {
606 $mdb2 = getConnection();
608 $columns = '(parent_id, org_id, name, description, currency, decimal_mark, lang, date_format, time_format'.
609 ', week_start, tracking_mode, project_required, task_required, record_type, bcc_email'.
610 ', allow_ip, password_complexity, plugins, lock_spec'.
611 ', workday_minutes, config, created, created_ip, created_by)';
613 $values = ' values (';
614 $values .= $mdb2->quote($fields['parent_id']);
615 $values .= ', '.$mdb2->quote($fields['org_id']);
616 $values .= ', '.$mdb2->quote(trim($fields['name']));
617 $values .= ', '.$mdb2->quote(trim($fields['description']));
618 $values .= ', '.$mdb2->quote(trim($fields['currency']));
619 $values .= ', '.$mdb2->quote($fields['decimal_mark']);
620 $values .= ', '.$mdb2->quote($fields['lang']);
621 $values .= ', '.$mdb2->quote($fields['date_format']);
622 $values .= ', '.$mdb2->quote($fields['time_format']);
623 $values .= ', '.(int)$fields['week_start'];
624 $values .= ', '.(int)$fields['tracking_mode'];
625 $values .= ', '.(int)$fields['project_required'];
626 $values .= ', '.(int)$fields['task_required'];
627 $values .= ', '.(int)$fields['record_type'];
628 $values .= ', '.$mdb2->quote($fields['bcc_email']);
629 $values .= ', '.$mdb2->quote($fields['allow_ip']);
630 $values .= ', '.$mdb2->quote($fields['password_complexity']);
631 $values .= ', '.$mdb2->quote($fields['plugins']);
632 $values .= ', '.$mdb2->quote($fields['lock_spec']);
633 $values .= ', '.(int)$fields['workday_minutes'];
634 $values .= ', '.$mdb2->quote($fields['config']);
635 $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
638 $sql = 'insert into tt_groups '.$columns.$values;
639 $affected = $mdb2->exec($sql);
640 if (is_a($affected, 'PEAR_Error')) {
641 $this->errors->add($i18n->get('error.db'));
645 $group_id = $mdb2->lastInsertID('tt_groups', 'id');
649 // insertMonthlyQuota - a helper function to insert a monthly quota.
650 private function insertMonthlyQuota($fields) {
651 $mdb2 = getConnection();
652 $group_id = (int) $fields['group_id'];
653 $org_id = (int) $fields['org_id'];
654 $year = (int) $fields['year'];
655 $month = (int) $fields['month'];
656 $minutes = (int) $fields['minutes'];
658 $sql = "INSERT INTO tt_monthly_quotas (group_id, org_id, year, month, minutes)".
659 " values ($group_id, $org_id, $year, $month, $minutes)";
660 $affected = $mdb2->exec($sql);
661 return (!is_a($affected, 'PEAR_Error'));
664 // insertPredefinedExpense - a helper function to insert a predefined expense.
665 private function insertPredefinedExpense($fields) {
666 $mdb2 = getConnection();
667 $group_id = (int) $fields['group_id'];
668 $org_id = (int) $fields['org_id'];
669 $name = $mdb2->quote($fields['name']);
670 $cost = $mdb2->quote($fields['cost']);
672 $sql = "INSERT INTO tt_predefined_expenses (group_id, org_id, name, cost)".
673 " values ($group_id, $org_id, $name, $cost)";
674 $affected = $mdb2->exec($sql);
675 return (!is_a($affected, 'PEAR_Error'));
678 // insertExpense - a helper function to insert an expense item.
679 private function insertExpense($fields) {
681 $mdb2 = getConnection();
683 $group_id = (int) $fields['group_id'];
684 $org_id = (int) $fields['org_id'];
685 $date = $fields['date'];
686 $user_id = (int) $fields['user_id'];
687 $client_id = $fields['client_id'];
688 $project_id = $fields['project_id'];
689 $name = $fields['name'];
690 $cost = str_replace(',', '.', $fields['cost']);
691 $invoice_id = $fields['invoice_id'];
692 $status = $fields['status'];
693 $paid = (int) $fields['paid'];
694 $created = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
696 $sql = "insert into tt_expense_items".
697 " (date, user_id, group_id, org_id, client_id, project_id, name, cost, invoice_id, paid, created, created_ip, created_by, status)".
698 " values (".$mdb2->quote($date).", $user_id, $group_id, $org_id, ".$mdb2->quote($client_id).", ".$mdb2->quote($project_id).
699 ", ".$mdb2->quote($name).", ".$mdb2->quote($cost).", ".$mdb2->quote($invoice_id).", $paid $created, ".$mdb2->quote($status).")";
700 $affected = $mdb2->exec($sql);
701 return (!is_a($affected, 'PEAR_Error'));
704 // insertProject - a helper function to insert a project as well as project to task binds.
705 private function insertProject($fields)
707 $mdb2 = getConnection();
709 $group_id = (int) $fields['group_id'];
710 $org_id = (int) $fields['org_id'];
712 $name = $fields['name'];
713 $description = $fields['description'];
714 $tasks = $fields['tasks'];
715 $comma_separated = implode(',', $tasks); // This is a comma-separated list of associated task ids.
716 $status = $fields['status'];
718 $sql = "insert into tt_projects (group_id, org_id, name, description, tasks, status)
719 values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
720 $affected = $mdb2->exec($sql);
721 if (is_a($affected, 'PEAR_Error'))
725 $sql = "select last_insert_id() as last_insert_id";
726 $res = $mdb2->query($sql);
727 $val = $res->fetchRow();
728 $last_id = $val['last_insert_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 // The insertClient function inserts a new client as well as client to project binds.
745 private function insertClient($fields)
747 $mdb2 = getConnection();
749 $group_id = (int) $fields['group_id'];
750 $org_id = (int) $fields['org_id'];
751 $name = $fields['name'];
752 $address = $fields['address'];
753 $tax = $fields['tax'];
754 $projects = $fields['projects'];
756 $comma_separated = implode(',', $projects); // This is a comma-separated list of associated projects ids.
757 $status = $fields['status'];
759 $tax = str_replace(',', '.', $tax);
760 if ($tax == '') $tax = 0;
762 $sql = "insert into tt_clients (group_id, org_id, name, address, tax, projects, status)".
763 " values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($address).", $tax, ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
765 $affected = $mdb2->exec($sql);
766 if (is_a($affected, 'PEAR_Error'))
770 $sql = "select last_insert_id() as last_insert_id";
771 $res = $mdb2->query($sql);
772 $val = $res->fetchRow();
773 $last_id = $val['last_insert_id'];
775 if (count($projects) > 0)
776 foreach ($projects as $p_id) {
777 $sql = "insert into tt_client_project_binds (client_id, project_id, group_id, org_id) values($last_id, $p_id, $group_id, $org_id)";
778 $affected = $mdb2->exec($sql);
779 if (is_a($affected, 'PEAR_Error'))
786 // insertFavReport - inserts a favorite report in database.
787 private function insertFavReport($fields) {
788 $mdb2 = getConnection();
790 $group_id = (int) $fields['group_id'];
791 $org_id = (int) $fields['org_id'];
793 $sql = "insert into tt_fav_reports".
794 " (name, user_id, group_id, org_id, client_id, cf_1_option_id, project_id, task_id,".
795 " billable, invoice, paid_status, users, period, period_start, period_end,".
796 " show_client, show_invoice, show_paid, show_ip,".
797 " show_project, show_start, show_duration, show_cost,".
798 " show_task, show_end, show_note, show_custom_field_1, show_work_units,".
799 " group_by1, group_by2, group_by3, show_totals_only)".
801 $mdb2->quote($fields['name']).", ".$fields['user_id'].", $group_id, $org_id, ".
802 $mdb2->quote($fields['client']).", ".$mdb2->quote($fields['option']).", ".
803 $mdb2->quote($fields['project']).", ".$mdb2->quote($fields['task']).", ".
804 $mdb2->quote($fields['billable']).", ".$mdb2->quote($fields['invoice']).", ".
805 $mdb2->quote($fields['paid_status']).", ".
806 $mdb2->quote($fields['users']).", ".$mdb2->quote($fields['period']).", ".
807 $mdb2->quote($fields['from']).", ".$mdb2->quote($fields['to']).", ".
808 $fields['chclient'].", ".$fields['chinvoice'].", ".$fields['chpaid'].", ".$fields['chip'].", ".
809 $fields['chproject'].", ".$fields['chstart'].", ".$fields['chduration'].", ".$fields['chcost'].", ".
810 $fields['chtask'].", ".$fields['chfinish'].", ".$fields['chnote'].", ".$fields['chcf_1'].", ".$fields['chunits'].", ".
811 $mdb2->quote($fields['group_by1']).", ".$mdb2->quote($fields['group_by2']).", ".
812 $mdb2->quote($fields['group_by3']).", ".$fields['chtotalsonly'].")";
813 $affected = $mdb2->exec($sql);
814 if (is_a($affected, 'PEAR_Error'))
817 $sql = "select last_insert_id() as last_id";
818 $res = $mdb2->query($sql);
819 if (is_a($res, 'PEAR_Error'))
822 $val = $res->fetchRow();
823 return $val['last_id'];
826 // insertNotification function inserts a new notification into database.
827 private function insertNotification($fields)
829 $mdb2 = getConnection();
831 $group_id = (int) $fields['group_id'];
832 $org_id = (int) $fields['org_id'];
833 $cron_spec = $fields['cron_spec'];
834 $last = (int) $fields['last'];
835 $next = (int) $fields['next'];
836 $report_id = (int) $fields['report_id'];
837 $email = $fields['email'];
839 $subject = $fields['subject'];
840 $report_condition = $fields['report_condition'];
841 $status = $fields['status'];
843 $sql = "insert into tt_cron".
844 " (group_id, org_id, cron_spec, last, next, report_id, email, cc, subject, report_condition, status)".
845 " 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).")";
846 $affected = $mdb2->exec($sql);
847 return (!is_a($affected, 'PEAR_Error'));
850 // insertUserParam - a helper function to insert a user parameter.
851 private function insertUserParam($fields) {
852 $mdb2 = getConnection();
854 $group_id = (int) $fields['group_id'];
855 $org_id = (int) $fields['org_id'];
856 $user_id = (int) $fields['user_id'];
857 $param_name = $fields['param_name'];
858 $param_value = $fields['param_value'];
860 $sql = "insert into tt_config".
861 " (user_id, group_id, org_id, param_name, param_value)".
862 " values ($user_id, $group_id, $org_id, ".$mdb2->quote($param_name).", ".$mdb2->quote($param_value).")";
863 $affected = $mdb2->exec($sql);
864 return (!is_a($affected, 'PEAR_Error'));
867 // insertCustomField - a helper function to insert a custom field.
868 private function insertCustomField($fields) {
869 $mdb2 = getConnection();
871 $group_id = (int) $fields['group_id'];
872 $org_id = (int) $fields['org_id'];
873 $type = (int) $fields['type'];
874 $label = $fields['label'];
875 $required = (int) $fields['required'];
876 $status = $fields['status'];
878 $sql = "insert into tt_custom_fields".
879 " (group_id, org_id, type, label, required, status)".
880 " values($group_id, $org_id, $type, ".$mdb2->quote($label).", $required, ".$mdb2->quote($status).")";
881 $affected = $mdb2->exec($sql);
882 if (is_a($affected, 'PEAR_Error'))
886 $sql = "select last_insert_id() as last_insert_id";
887 $res = $mdb2->query($sql);
888 $val = $res->fetchRow();
889 $last_id = $val['last_insert_id'];
893 // insertCustomFieldOption - a helper function to insert a custom field option.
894 private function insertCustomFieldOption($fields) {
895 $mdb2 = getConnection();
897 $group_id = (int) $fields['group_id'];
898 $org_id = (int) $fields['org_id'];
899 $field_id = (int) $fields['field_id'];
900 $value = $fields['value'];
902 $sql = "insert into tt_custom_field_options (group_id, org_id, field_id, value)".
903 " values ($group_id, $org_id, $field_id, ".$mdb2->quote($value).")";
904 $affected = $mdb2->exec($sql);
905 if (is_a($affected, 'PEAR_Error'))
909 $sql = "select last_insert_id() as last_insert_id";
910 $res = $mdb2->query($sql);
911 $val = $res->fetchRow();
912 $last_id = $val['last_insert_id'];
916 // insertLogEntry - a helper function to insert a time log entry.
917 private function insertLogEntry($fields) {
919 $mdb2 = getConnection();
921 $group_id = (int) $fields['group_id'];
922 $org_id = (int) $fields['org_id'];
923 $user_id = (int) $fields['user_id'];
924 $date = $fields['date'];
925 $start = $fields['start'];
926 $duration = $fields['duration'];
927 $client_id = $fields['client_id'];
928 $project_id = $fields['project_id'];
929 $task_id = $fields['task_id'];
930 $invoice_id = $fields['invoice_id'];
931 $comment = $fields['comment'];
932 $billable = (int) $fields['billable'];
933 $paid = (int) $fields['paid'];
934 $status = $fields['status'];
936 $sql = "insert into tt_log".
937 " (user_id, group_id, org_id, date, start, duration, client_id, project_id, task_id, invoice_id, comment".
938 ", billable, paid, created, created_ip, created_by, status)".
939 " values ($user_id, $group_id, $org_id".
940 ", ".$mdb2->quote($date).
941 ", ".$mdb2->quote($start).
942 ", ".$mdb2->quote($duration).
943 ", ".$mdb2->quote($client_id).
944 ", ".$mdb2->quote($project_id).
945 ", ".$mdb2->quote($task_id).
946 ", ".$mdb2->quote($invoice_id).
947 ", ".$mdb2->quote($comment).
948 ", $billable, $paid".
949 ", now(), ".$mdb2->quote($_SERVER['REMOTE_ADDR']).", ".$mdb2->quote($user->id).
950 ", ". $mdb2->quote($status).")";
951 $affected = $mdb2->exec($sql);
952 if (is_a($affected, 'PEAR_Error')) {
953 $this->errors->add($i18n->get('error.db')); // TODO: review whether or not to add error here in all insert calls.
957 $log_id = $mdb2->lastInsertID('tt_log', 'id');
961 // insertCustomFieldLogEntry - a helper function to insert a custom field log entry.
962 private function insertCustomFieldLogEntry($fields) {
963 $mdb2 = getConnection();
965 $group_id = (int) $fields['group_id'];
966 $org_id = (int) $fields['org_id'];
967 $log_id = (int) $fields['log_id'];
968 $field_id = (int) $fields['field_id'];
969 $option_id = $fields['option_id'];
970 $value = $fields['value'];
971 $status = $fields['status'];
973 $sql = "insert into tt_custom_field_log (group_id, org_id, log_id, field_id, option_id, value, status)".
974 " values ($group_id, $org_id, $log_id, $field_id, ".$mdb2->quote($option_id).", ".$mdb2->quote($value).", ".$mdb2->quote($status).")";
975 $affected = $mdb2->exec($sql);
976 return (!is_a($affected, 'PEAR_Error'));