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 // ttOrgImportHelper class is used to import organization data from an XML file
30 // prepared by ttOrgExportHelper and consisting of nested groups with their info.
31 class ttOrgImportHelper {
32 var $errors = null; // Errors go here. Set in constructor by reference.
33 var $schema_version = null; // Database schema version from XML file we import from.
34 var $conflicting_logins = null; // A comma-separated list of logins we cannot import.
35 var $canImport = true; // False if we cannot import data due to a conflict such as login collision.
36 var $firstPass = true; // True during first pass through the file.
37 var $org_id = null; // Organization id (same as top group_id).
38 var $current_group_id = null; // Current group id during parsing.
39 var $parents = array(); // A stack of parent group ids for current group all the way to the root including self.
40 var $top_role_id = 0; // Top role id.
42 // Entity maps for current group. They map XML ids with database ids.
43 var $currentGroupRoleMap = array();
44 var $currentGroupTaskMap = array();
45 var $currentGroupProjectMap = array();
46 var $currentGroupClientMap = array();
47 var $currentGroupUserMap = array();
48 var $currentGroupInvoiceMap = array();
49 var $currentGroupLogMap = array();
50 var $currentGroupCustomFieldMap = array();
51 var $currentGroupCustomFieldOptionMap = array();
52 var $currentGroupFavReportMap = array();
55 function __construct(&$errors) {
56 $this->errors = &$errors;
57 $this->top_role_id = $this->getTopRole();
60 // startElement - callback handler for opening tags in XML.
61 function startElement($parser, $name, $attrs) {
64 // First pass through the file determines if we can import data.
65 // We require 2 things:
66 // 1) Database schema version must be set. This ensures we have a compatible file.
67 // 2) No login coillisions are allowed.
68 if ($this->firstPass) {
69 if ($name == 'ORG' && $this->canImport) {
70 if ($attrs['SCHEMA'] == null) {
71 // We need (database) schema attribute to be available for import to work.
72 // Old Time Tracker export files don't have this.
73 // Current import code does not work with old format because we had to
74 // restructure data in export files for subgroup support.
75 $this->canImport = false;
76 $this->errors->add($i18n->get('error.format'));
81 // In first pass we check user logins for potential collisions with existing.
82 if ($name == 'USER' && $this->canImport) {
83 $login = $attrs['LOGIN'];
84 if ('' != $attrs['STATUS'] && $this->loginExists($login)) {
85 // We have a login collision. Append colliding login to a list of things we cannot import.
86 $this->conflicting_logins .= ($this->conflicting_logins ? ", $login" : $login);
87 // The above is printed in error message with all found colliding logins.
92 // Second pass processing. We import data here, one tag at a time.
93 if (!$this->firstPass && $this->canImport && $this->errors->no()) {
94 $mdb2 = getConnection();
96 // We are in second pass and can import data.
97 if ($name == 'GROUP') {
98 // Create a new group.
99 $this->current_group_id = $this->createGroup(array(
100 'parent_id' => $this->current_group_id, // Note: after insert current_group_id changes.
101 'org_id' => $this->org_id,
102 'name' => $attrs['NAME'],
103 'description' => $attrs['DESCRIPTION'],
104 'currency' => $attrs['CURRENCY'],
105 'decimal_mark' => $attrs['DECIMAL_MARK'],
106 'lang' => $attrs['LANG'],
107 'date_format' => $attrs['DATE_FORMAT'],
108 'time_format' => $attrs['TIME_FORMAT'],
109 'week_start' => $attrs['WEEK_START'],
110 'tracking_mode' => $attrs['TRACKING_MODE'],
111 'project_required' => $attrs['PROJECT_REQUIRED'],
112 'task_required' => $attrs['TASK_REQUIRED'],
113 'record_type' => $attrs['RECORD_TYPE'],
114 'bcc_email' => $attrs['BCC_EMAIL'],
115 'allow_ip' => $attrs['ALLOW_IP'],
116 'password_complexity' => $attrs['PASSWORD_COMPLEXITY'],
117 'plugins' => $attrs['PLUGINS'],
118 'lock_spec' => $attrs['LOCK_SPEC'],
119 'workday_minutes' => $attrs['WORKDAY_MINUTES'],
120 'custom_logo' => $attrs['CUSTOM_LOGO'],
121 'config' => $attrs['CONFIG']));
123 // Special handling for top group.
124 if (!$this->org_id && $this->current_group_id) {
125 $this->org_id = $this->current_group_id;
126 $sql = "update tt_groups set org_id = $this->current_group_id where org_id is NULL and id = $this->current_group_id";
127 $affected = $mdb2->exec($sql);
129 // Add self to parent stack.
130 array_push($this->parents, $this->current_group_id);
132 // Recycle all maps as we are starting to work on new group.
133 // Note that for this to work properly all nested groups must be last entries in xml for each group.
134 unset($this->currentGroupRoleMap); $this->currentGroupRoleMap = array();
135 unset($this->currentGroupTaskMap); $this->currentGroupTaskMap = array();
136 unset($this->currentGroupProjectMap); $this->currentGroupProjectMap = array();
137 unset($this->currentGroupClientMap); $this->currentGroupClientMap = array();
138 unset($this->currentGroupUserMap); $this->currentGroupUserMap = array();
139 unset($this->currentGroupInvoiceMap); $this->currentGroupInvoiceMap = array();
140 unset($this->currentGroupLogMap); $this->currentGroupLogMap = array();
141 unset($this->currentGroupCustomFieldMap); $this->currentGroupCustomFieldMap = array();
142 unset($this->currentGroupCustomFieldOptionMap); $this->currentGroupCustomFieldOptionMap = array();
143 unset($this->currentGroupFavReportMap); $this->currentGroupCustomFavReportMap = array();
147 if ($name == 'ROLE') {
148 // We get here when processing <role> tags for the current group.
149 $role_id = $this->insertRole(array(
150 'group_id' => $this->current_group_id,
151 'org_id' => $this->org_id,
152 'name' => $attrs['NAME'],
153 'description' => $attrs['DESCRIPTION'],
154 'rank' => $attrs['RANK'],
155 'rights' => $attrs['RIGHTS'],
156 'status' => $attrs['STATUS']));
159 $this->currentGroupRoleMap[$attrs['ID']] = $role_id;
161 $this->errors->add($i18n->get('error.db'));
166 if ($name == 'TASK') {
167 // We get here when processing <task> tags for the current group.
168 $task_id = $this->insertTask(array(
169 'group_id' => $this->current_group_id,
170 'org_id' => $this->org_id,
171 'name' => $attrs['NAME'],
172 'description' => $attrs['DESCRIPTION'],
173 'status' => $attrs['STATUS']));
176 $this->currentGroupTaskMap[$attrs['ID']] = $task_id;
178 $this->errors->add($i18n->get('error.db'));
183 if ($name == 'PROJECT') {
184 // We get here when processing <project> tags for the current group.
186 // Prepare a list of task ids.
187 if ($attrs['TASKS']) {
188 $tasks = explode(',', $attrs['TASKS']);
189 foreach ($tasks as $id)
190 $mapped_tasks[] = $this->currentGroupTaskMap[$id];
193 $project_id = $this->insertProject(array(
194 'group_id' => $this->current_group_id,
195 'org_id' => $this->org_id,
196 'name' => $attrs['NAME'],
197 'description' => $attrs['DESCRIPTION'],
198 'tasks' => $mapped_tasks,
199 'status' => $attrs['STATUS']));
202 $this->currentGroupProjectMap[$attrs['ID']] = $project_id;
204 $this->errors->add($i18n->get('error.db'));
209 if ($name == 'CLIENT') {
210 // We get here when processing <client> tags for the current group.
212 // Prepare a list of project ids.
213 if ($attrs['PROJECTS']) {
214 $projects = explode(',', $attrs['PROJECTS']);
215 foreach ($projects as $id)
216 $mapped_projects[] = $this->currentGroupProjectMap[$id];
219 $client_id = $this->insertClient(array(
220 'group_id' => $this->current_group_id,
221 'org_id' => $this->org_id,
222 'name' => $attrs['NAME'],
223 'address' => $attrs['ADDRESS'],
224 'tax' => $attrs['TAX'],
225 'projects' => $mapped_projects,
226 'status' => $attrs['STATUS']));
229 $this->currentGroupClientMap[$attrs['ID']] = $client_id;
231 $this->errors->add($i18n->get('error.db'));
236 if ($name == 'USER') {
237 // We get here when processing <user> tags for the current group.
239 $role_id = $attrs['ROLE_ID'] === '0' ? $this->top_role_id : $this->currentGroupRoleMap[$attrs['ROLE_ID']]; // 0 (not null) means top manager role.
241 $user_id = $this->insertUser(array(
242 'group_id' => $this->current_group_id,
243 'org_id' => $this->org_id,
244 'role_id' => $role_id,
245 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
246 'name' => $attrs['NAME'],
247 'login' => $attrs['LOGIN'],
248 'password' => $attrs['PASSWORD'],
249 'rate' => $attrs['RATE'],
250 'email' => $attrs['EMAIL'],
251 'status' => $attrs['STATUS']), false);
254 $this->currentGroupUserMap[$attrs['ID']] = $user_id;
256 $this->errors->add($i18n->get('error.db'));
261 if ($name == 'USER_PROJECT_BIND') {
262 if (!$this->insertUserProjectBind(array(
263 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
264 'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
265 'group_id' => $this->current_group_id,
266 'org_id' => $this->org_id,
267 'rate' => $attrs['RATE'],
268 'status' => $attrs['STATUS']))) {
269 $this->errors->add($i18n->get('error.db'));
274 if ($name == 'INVOICE') {
275 // We get here when processing <invoice> tags for the current group.
276 $invoice_id = $this->insertInvoice(array(
277 'group_id' => $this->current_group_id,
278 'org_id' => $this->org_id,
279 'name' => $attrs['NAME'],
280 'date' => $attrs['DATE'],
281 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
282 'status' => $attrs['STATUS']));
285 $this->currentGroupInvoiceMap[$attrs['ID']] = $invoice_id;
287 $this->errors->add($i18n->get('error.db'));
292 if ($name == 'LOG_ITEM') {
293 // We get here when processing <log_item> tags for the current group.
294 $log_item_id = $this->insertLogEntry(array(
295 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
296 'group_id' => $this->current_group_id,
297 'org_id' => $this->org_id,
298 'date' => $attrs['DATE'],
299 'start' => $attrs['START'],
300 'finish' => $attrs['FINISH'],
301 'duration' => $attrs['DURATION'],
302 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
303 'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
304 'task_id' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
305 'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
306 'comment' => (isset($attrs['COMMENT']) ? $attrs['COMMENT'] : ''),
307 'billable' => $attrs['BILLABLE'],
308 'paid' => $attrs['PAID'],
309 'status' => $attrs['STATUS']));
312 $this->currentGroupLogMap[$attrs['ID']] = $log_item_id;
313 } else $this->errors->add($i18n->get('error.db'));
317 if ($name == 'CUSTOM_FIELD') {
318 // We get here when processing <custom_field> tags for the current group.
319 $custom_field_id = $this->insertCustomField(array(
320 'group_id' => $this->current_group_id,
321 'org_id' => $this->org_id,
322 'type' => $attrs['TYPE'],
323 'label' => $attrs['LABEL'],
324 'required' => $attrs['REQUIRED'],
325 'status' => $attrs['STATUS']));
326 if ($custom_field_id) {
328 $this->currentGroupCustomFieldMap[$attrs['ID']] = $custom_field_id;
329 } else $this->errors->add($i18n->get('error.db'));
333 if ($name == 'CUSTOM_FIELD_OPTION') {
334 // We get here when processing <custom_field_option> tags for the current group.
335 $custom_field_option_id = $this->insertCustomFieldOption(array(
336 'group_id' => $this->current_group_id,
337 'org_id' => $this->org_id,
338 'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
339 'value' => $attrs['VALUE']));
340 if ($custom_field_option_id) {
342 $this->currentGroupCustomFieldOptionMap[$attrs['ID']] = $custom_field_option_id;
343 } else $this->errors->add($i18n->get('error.db'));
347 if ($name == 'CUSTOM_FIELD_LOG_ENTRY') {
348 // We get here when processing <custom_field_log_entry> tags for the current group.
349 if (!$this->insertCustomFieldLogEntry(array(
350 'group_id' => $this->current_group_id,
351 'org_id' => $this->org_id,
352 'log_id' => $this->currentGroupLogMap[$attrs['LOG_ID']],
353 'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
354 'option_id' => $this->currentGroupCustomFieldOptionMap[$attrs['OPTION_ID']],
355 'value' => $attrs['VALUE'],
356 'status' => $attrs['STATUS']))) {
357 $this->errors->add($i18n->get('error.db'));
362 if ($name == 'EXPENSE_ITEM') {
363 // We get here when processing <expense_item> tags for the current group.
364 $expense_item_id = $this->insertExpense(array(
365 'date' => $attrs['DATE'],
366 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
367 'group_id' => $this->current_group_id,
368 'org_id' => $this->org_id,
369 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
370 'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
371 'name' => $attrs['NAME'],
372 'cost' => $attrs['COST'],
373 'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
374 'paid' => $attrs['PAID'],
375 'status' => $attrs['STATUS']));
376 if (!$expense_item_id) $this->errors->add($i18n->get('error.db'));
380 if ($name == 'PREDEFINED_EXPENSE') {
381 if (!$this->insertPredefinedExpense(array(
382 'group_id' => $this->current_group_id,
383 'org_id' => $this->org_id,
384 'name' => $attrs['NAME'],
385 'cost' => $attrs['COST']))) {
386 $this->errors->add($i18n->get('error.db'));
391 if ($name == 'MONTHLY_QUOTA') {
392 if (!$this->insertMonthlyQuota(array(
393 'group_id' => $this->current_group_id,
394 'org_id' => $this->org_id,
395 'year' => $attrs['YEAR'],
396 'month' => $attrs['MONTH'],
397 'minutes' => $attrs['MINUTES']))) {
398 $this->errors->add($i18n->get('error.db'));
403 if ($name == 'FAV_REPORT') {
405 if (strlen($attrs['USERS']) > 0) {
406 $arr = explode(',', $attrs['USERS']);
408 $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->currentGroupUserMap[$v];
410 $fav_report_id = $this->insertFavReport(array(
411 'name' => $attrs['NAME'],
412 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
413 'group_id' => $this->current_group_id,
414 'org_id' => $this->org_id,
415 'client' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
416 'option' => $this->currentGroupCustomFieldOptionMap[$attrs['CF_1_OPTION_ID']],
417 'project' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
418 'task' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
419 'billable' => $attrs['BILLABLE'],
420 'users' => $user_list,
421 'period' => $attrs['PERIOD'],
422 'from' => $attrs['PERIOD_START'],
423 'to' => $attrs['PERIOD_END'],
424 'chclient' => (int) $attrs['SHOW_CLIENT'],
425 'chinvoice' => (int) $attrs['SHOW_INVOICE'],
426 'chpaid' => (int) $attrs['SHOW_PAID'],
427 'chip' => (int) $attrs['SHOW_IP'],
428 'chproject' => (int) $attrs['SHOW_PROJECT'],
429 'chstart' => (int) $attrs['SHOW_START'],
430 'chduration' => (int) $attrs['SHOW_DURATION'],
431 'chcost' => (int) $attrs['SHOW_COST'],
432 'chtask' => (int) $attrs['SHOW_TASK'],
433 'chfinish' => (int) $attrs['SHOW_END'],
434 'chnote' => (int) $attrs['SHOW_NOTE'],
435 'chcf_1' => (int) $attrs['SHOW_CUSTOM_FIELD_1'],
436 'chunits' => (int) $attrs['SHOW_WORK_UNITS'],
437 'group_by1' => $attrs['GROUP_BY1'],
438 'group_by2' => $attrs['GROUP_BY2'],
439 'group_by3' => $attrs['GROUP_BY3'],
440 'chtotalsonly' => (int) $attrs['SHOW_TOTALS_ONLY']));
441 if ($fav_report_id) {
443 $this->currentGroupFavReportMap[$attrs['ID']] = $fav_report_id;
444 } else $this->errors->add($i18n->get('error.db'));
448 if ($name == 'NOTIFICATION') {
449 if (!$this->insertNotification(array(
450 'group_id' => $this->current_group_id,
451 'org_id' => $this->org_id,
452 'cron_spec' => $attrs['CRON_SPEC'],
453 'last' => $attrs['LAST'],
454 'next' => $attrs['NEXT'],
455 'report_id' => $this->currentGroupFavReportMap[$attrs['REPORT_ID']],
456 'email' => $attrs['EMAIL'],
457 'cc' => $attrs['CC'],
458 'subject' => $attrs['SUBJECT'],
459 'report_condition' => $attrs['REPORT_CONDITION'],
460 'status' => $attrs['STATUS']))) {
461 $this->errors->add($i18n->get('error.db'));
466 if ($name == 'USER_PARAM') {
467 if (!$this->insertUserParam(array(
468 'group_id' => $this->current_group_id,
469 'org_id' => $this->org_id,
470 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
471 'param_name' => $attrs['PARAM_NAME'],
472 'param_value' => $attrs['PARAM_VALUE']))) {
473 $this->errors->add($i18n->get('error.db'));
480 // endElement - callback handler for ending tags in XML.
481 // We use this only for process </group> element endings and
482 // set current_group_id to an immediate parent.
483 // This is required to import group hierarchy correctly.
484 function endElement($parser, $name) {
485 // No need to care about first or second pass, as this is used only in second pass.
486 // See 2nd xml_set_element_handler, where this handler is set.
487 if ($name == 'GROUP') {
488 // Remove self from the parent stack.
489 $self = array_pop($this->parents);
490 // Set current group id to an immediate parent.
491 $len = count($this->parents);
492 $this->current_group_id = $len ? $this->parents[$len-1] : null;
496 // importXml - uncompresses the file, reads and parses its content. During parsing,
497 // startElement, endElement, and dataElement functions are called as many times as necessary.
498 // Actual import occurs in the endElement handler.
499 function importXml() {
502 if (!$_FILES['xmlfile']['name']) {
503 $this->errors->add($i18n->get('error.upload'));
504 return; // There is nothing to do if we don't have a file.
507 // Do we have a compressed file?
509 $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
510 if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
514 // Create a temporary file.
515 $dirName = dirname(TEMPLATE_DIR . '_c/.');
516 $filename = tempnam($dirName, 'import_');
518 // If the file is compressed - uncompress it.
520 if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
521 $this->errors->add($i18n->get('error.sys'));
524 unlink($_FILES['xmlfile']['tmp_name']);
526 if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
527 $this->errors->add($i18n->get('error.upload'));
532 // Initialize XML parser.
533 $parser = xml_parser_create();
534 xml_set_object($parser, $this);
535 xml_set_element_handler($parser, 'startElement', false); // No need to process end tags in 1st pass.
537 // We need to parse the file 2 times:
538 // 1) First pass: determine if import is possible.
539 // 2) Second pass: import data, one tag at a time.
541 // Read and parse the content of the file. During parsing, startElement is called back for each tag.
542 $file = fopen($filename, 'r');
543 while (($data = fread($file, 4096)) && $this->errors->no()) {
544 if (!xml_parse($parser, $data, feof($file))) {
545 $this->errors->add(sprintf($i18n->get('error.xml'),
546 xml_get_current_line_number($parser),
547 xml_error_string(xml_get_error_code($parser))));
550 if ($this->conflicting_logins) {
551 $this->canImport = false;
552 $this->errors->add($i18n->get('error.user_exists'));
553 $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_logins));
556 $this->firstPass = false; // We are done with 1st pass.
557 xml_parser_free($parser);
558 if ($file) fclose($file);
559 if ($this->errors->yes()) {
560 // Remove the file and exit if we have errors.
565 // Now we can do a second pass, where real work is done.
566 $parser = xml_parser_create();
567 xml_set_object($parser, $this);
568 xml_set_element_handler($parser, 'startElement', 'endElement'); // Need to process ending tags too.
570 // Read and parse the content of the file. During parsing, startElement and endElement are called back for each tag.
571 $file = fopen($filename, 'r');
572 while (($data = fread($file, 4096)) && $this->errors->no()) {
573 if (!xml_parse($parser, $data, feof($file))) {
574 $this->errors->add(sprintf($i18n->get('error.xml'),
575 xml_get_current_line_number($parser),
576 xml_error_string(xml_get_error_code($parser))));
579 xml_parser_free($parser);
580 if ($file) fclose($file);
584 // uncompress - uncompresses the content of the $in file into the $out file.
585 function uncompress($in, $out) {
586 // Do we have the uncompress function?
587 if (!function_exists('bzopen'))
590 // Initial checks of file names and permissions.
591 if (!file_exists($in) || !is_readable ($in))
593 if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
596 if (!$out_file = fopen($out, 'wb'))
598 if (!$in_file = bzopen ($in, 'r'))
601 while (!feof($in_file)) {
602 $buffer = bzread($in_file, 4096);
603 fwrite($out_file, $buffer, 4096);
610 // createGroup function creates a new group.
611 private function createGroup($fields) {
614 $mdb2 = getConnection();
616 $columns = '(parent_id, org_id, name, description, currency, decimal_mark, lang, date_format, time_format'.
617 ', week_start, tracking_mode, project_required, task_required, record_type, bcc_email'.
618 ', allow_ip, password_complexity, plugins, lock_spec'.
619 ', workday_minutes, config, created, created_ip, created_by)';
621 $values = ' values (';
622 $values .= $mdb2->quote($fields['parent_id']);
623 $values .= ', '.$mdb2->quote($fields['org_id']);
624 $values .= ', '.$mdb2->quote(trim($fields['name']));
625 $values .= ', '.$mdb2->quote(trim($fields['description']));
626 $values .= ', '.$mdb2->quote(trim($fields['currency']));
627 $values .= ', '.$mdb2->quote($fields['decimal_mark']);
628 $values .= ', '.$mdb2->quote($fields['lang']);
629 $values .= ', '.$mdb2->quote($fields['date_format']);
630 $values .= ', '.$mdb2->quote($fields['time_format']);
631 $values .= ', '.(int)$fields['week_start'];
632 $values .= ', '.(int)$fields['tracking_mode'];
633 $values .= ', '.(int)$fields['project_required'];
634 $values .= ', '.(int)$fields['task_required'];
635 $values .= ', '.(int)$fields['record_type'];
636 $values .= ', '.$mdb2->quote($fields['bcc_email']);
637 $values .= ', '.$mdb2->quote($fields['allow_ip']);
638 $values .= ', '.$mdb2->quote($fields['password_complexity']);
639 $values .= ', '.$mdb2->quote($fields['plugins']);
640 $values .= ', '.$mdb2->quote($fields['lock_spec']);
641 $values .= ', '.(int)$fields['workday_minutes'];
642 $values .= ', '.$mdb2->quote($fields['config']);
643 $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
646 $sql = 'insert into tt_groups '.$columns.$values;
647 $affected = $mdb2->exec($sql);
648 if (is_a($affected, 'PEAR_Error')) {
649 $this->errors->add($i18n->get('error.db'));
653 $group_id = $mdb2->lastInsertID('tt_groups', 'id');
657 // insertMonthlyQuota - a helper function to insert a monthly quota.
658 private function insertMonthlyQuota($fields) {
659 $mdb2 = getConnection();
661 $group_id = (int) $fields['group_id'];
662 $org_id = (int) $fields['org_id'];
663 $year = (int) $fields['year'];
664 $month = (int) $fields['month'];
665 $minutes = (int) $fields['minutes'];
667 $sql = "INSERT INTO tt_monthly_quotas (group_id, org_id, year, month, minutes)".
668 " values ($group_id, $org_id, $year, $month, $minutes)";
669 $affected = $mdb2->exec($sql);
670 return (!is_a($affected, 'PEAR_Error'));
673 // insertPredefinedExpense - a helper function to insert a predefined expense.
674 private function insertPredefinedExpense($fields) {
675 $mdb2 = getConnection();
677 $group_id = (int) $fields['group_id'];
678 $org_id = (int) $fields['org_id'];
679 $name = $mdb2->quote($fields['name']);
680 $cost = $mdb2->quote($fields['cost']);
682 $sql = "INSERT INTO tt_predefined_expenses (group_id, org_id, name, cost)".
683 " values ($group_id, $org_id, $name, $cost)";
684 $affected = $mdb2->exec($sql);
685 return (!is_a($affected, 'PEAR_Error'));
688 // insertExpense - a helper function to insert an expense item.
689 private function insertExpense($fields) {
691 $mdb2 = getConnection();
693 $group_id = (int) $fields['group_id'];
694 $org_id = (int) $fields['org_id'];
695 $date = $fields['date'];
696 $user_id = (int) $fields['user_id'];
697 $client_id = $fields['client_id'];
698 $project_id = $fields['project_id'];
699 $name = $fields['name'];
700 $cost = str_replace(',', '.', $fields['cost']);
701 $invoice_id = $fields['invoice_id'];
702 $status = $fields['status'];
703 $paid = (int) $fields['paid'];
704 $created = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
706 $sql = "insert into tt_expense_items".
707 " (date, user_id, group_id, org_id, client_id, project_id, name, cost, invoice_id, paid, created, created_ip, created_by, status)".
708 " values (".$mdb2->quote($date).", $user_id, $group_id, $org_id, ".$mdb2->quote($client_id).", ".$mdb2->quote($project_id).
709 ", ".$mdb2->quote($name).", ".$mdb2->quote($cost).", ".$mdb2->quote($invoice_id).", $paid $created, ".$mdb2->quote($status).")";
710 $affected = $mdb2->exec($sql);
711 return (!is_a($affected, 'PEAR_Error'));
714 // insertTask function inserts a new task into database.
715 private function insertTask($fields)
717 $mdb2 = getConnection();
719 $group_id = (int) $fields['group_id'];
720 $org_id = (int) $fields['org_id'];
721 $name = $fields['name'];
722 $description = $fields['description'];
723 $projects = $fields['projects'];
724 $status = $fields['status'];
726 $sql = "insert into tt_tasks (group_id, org_id, name, description, status)
727 values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($status).")";
728 $affected = $mdb2->exec($sql);
730 if (is_a($affected, 'PEAR_Error'))
733 $last_id = $mdb2->lastInsertID('tt_tasks', 'id');
737 // insertUserProjectBind - inserts a user to project bind into tt_user_project_binds table.
738 private function insertUserProjectBind($fields) {
739 $mdb2 = getConnection();
741 $group_id = (int) $fields['group_id'];
742 $org_id = (int) $fields['org_id'];
743 $user_id = (int) $fields['user_id'];
744 $project_id = (int) $fields['project_id'];
745 $rate = $mdb2->quote($fields['rate']);
746 $status = $mdb2->quote($fields['status']);
748 $sql = "insert into tt_user_project_binds (user_id, project_id, group_id, org_id, rate, status)".
749 " values($user_id, $project_id, $group_id, $org_id, $rate, $status)";
750 $affected = $mdb2->exec($sql);
751 return (!is_a($affected, 'PEAR_Error'));
754 // insertUser - inserts a user into database.
755 private function insertUser($fields) {
757 $mdb2 = getConnection();
759 $group_id = (int) $fields['group_id'];
760 $org_id = (int) $fields['org_id'];
762 $columns = '(login, password, name, group_id, org_id, role_id, client_id, rate, email, created, created_ip, created_by, status)';
764 $values = 'values (';
765 $values .= $mdb2->quote($fields['login']);
766 $values .= ', '.$mdb2->quote($fields['password']);
767 $values .= ', '.$mdb2->quote($fields['name']);
768 $values .= ', '.$group_id;
769 $values .= ', '.$org_id;
770 $values .= ', '.(int)$fields['role_id'];
771 $values .= ', '.$mdb2->quote($fields['client_id']);
772 $values .= ', '.$mdb2->quote($fields['rate']);
773 $values .= ', '.$mdb2->quote($fields['email']);
774 $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
775 $values .= ', '.$mdb2->quote($fields['status']);
778 $sql = "insert into tt_users $columns $values";
779 $affected = $mdb2->exec($sql);
780 if (is_a($affected, 'PEAR_Error')) return false;
782 $last_id = $mdb2->lastInsertID('tt_users', 'id');
786 // insertProject - a helper function to insert a project as well as project to task binds.
787 private function insertProject($fields)
789 $mdb2 = getConnection();
791 $group_id = (int) $fields['group_id'];
792 $org_id = (int) $fields['org_id'];
793 $name = $fields['name'];
794 $description = $fields['description'];
795 $tasks = $fields['tasks'];
796 $comma_separated = implode(',', $tasks); // This is a comma-separated list of associated task ids.
797 $status = $fields['status'];
799 $sql = "insert into tt_projects (group_id, org_id, name, description, tasks, status)
800 values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
801 $affected = $mdb2->exec($sql);
802 if (is_a($affected, 'PEAR_Error'))
805 $last_id = $mdb2->lastInsertID('tt_projects', 'id');
807 // Insert binds into tt_project_task_binds table.
808 if (is_array($tasks)) {
809 foreach ($tasks as $task_id) {
810 $sql = "insert into tt_project_task_binds (project_id, task_id, group_id, org_id)".
811 " values($last_id, $task_id, $group_id, $org_id)";
812 $affected = $mdb2->exec($sql);
813 if (is_a($affected, 'PEAR_Error'))
821 // insertRole - inserts a role into tt_roles table.
822 private function insertRole($fields)
824 $mdb2 = getConnection();
826 $group_id = (int) $fields['group_id'];
827 $org_id = (int) $fields['org_id'];
828 $name = $fields['name'];
829 $rank = (int) $fields['rank'];
830 $description = $fields['description'];
831 $rights = $fields['rights'];
832 $status = $fields['status'];
834 $sql = "insert into tt_roles (group_id, org_id, name, rank, description, rights, status)
835 values ($group_id, $org_id, ".$mdb2->quote($name).", $rank, ".$mdb2->quote($description).", ".$mdb2->quote($rights).", ".$mdb2->quote($status).")";
836 $affected = $mdb2->exec($sql);
837 if (is_a($affected, 'PEAR_Error'))
840 $last_id = $mdb2->lastInsertID('tt_roles', 'id');
844 // insertInvoice - inserts an invoice in database.
845 private function insertInvoice($fields)
847 $mdb2 = getConnection();
849 $group_id = (int) $fields['group_id'];
850 $org_id = (int) $fields['org_id'];
851 $name = $fields['name'];
852 $client_id = (int) $fields['client_id'];
853 $date = $fields['date'];
854 $status = $fields['status'];
856 // Insert a new invoice record.
857 $sql = "insert into tt_invoices (group_id, org_id, name, date, client_id, status)".
858 " values($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id, ".$mdb2->quote($fields['status']).")";
859 $affected = $mdb2->exec($sql);
860 if (is_a($affected, 'PEAR_Error')) return false;
862 $last_id = $mdb2->lastInsertID('tt_invoices', 'id');
866 // The insertClient function inserts a new client as well as client to project binds.
867 private function insertClient($fields)
869 $mdb2 = getConnection();
871 $group_id = (int) $fields['group_id'];
872 $org_id = (int) $fields['org_id'];
873 $name = $fields['name'];
874 $address = $fields['address'];
875 $tax = $fields['tax'];
876 $projects = $fields['projects'];
878 $comma_separated = implode(',', $projects); // This is a comma-separated list of associated projects ids.
879 $status = $fields['status'];
881 $tax = str_replace(',', '.', $tax);
882 if ($tax == '') $tax = 0;
884 $sql = "insert into tt_clients (group_id, org_id, name, address, tax, projects, status)".
885 " values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($address).", $tax, ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
887 $affected = $mdb2->exec($sql);
888 if (is_a($affected, 'PEAR_Error'))
891 $last_id = $mdb2->lastInsertID('tt_clients', 'id');
893 if (count($projects) > 0)
894 foreach ($projects as $p_id) {
895 $sql = "insert into tt_client_project_binds (client_id, project_id, group_id, org_id) values($last_id, $p_id, $group_id, $org_id)";
896 $affected = $mdb2->exec($sql);
897 if (is_a($affected, 'PEAR_Error'))
904 // insertFavReport - inserts a favorite report in database.
905 private function insertFavReport($fields) {
906 $mdb2 = getConnection();
908 $group_id = (int) $fields['group_id'];
909 $org_id = (int) $fields['org_id'];
911 $sql = "insert into tt_fav_reports".
912 " (name, user_id, group_id, org_id, client_id, cf_1_option_id, project_id, task_id,".
913 " billable, invoice, paid_status, users, period, period_start, period_end,".
914 " show_client, show_invoice, show_paid, show_ip,".
915 " show_project, show_start, show_duration, show_cost,".
916 " show_task, show_end, show_note, show_custom_field_1, show_work_units,".
917 " group_by1, group_by2, group_by3, show_totals_only)".
919 $mdb2->quote($fields['name']).", ".$fields['user_id'].", $group_id, $org_id, ".
920 $mdb2->quote($fields['client']).", ".$mdb2->quote($fields['option']).", ".
921 $mdb2->quote($fields['project']).", ".$mdb2->quote($fields['task']).", ".
922 $mdb2->quote($fields['billable']).", ".$mdb2->quote($fields['invoice']).", ".
923 $mdb2->quote($fields['paid_status']).", ".
924 $mdb2->quote($fields['users']).", ".$mdb2->quote($fields['period']).", ".
925 $mdb2->quote($fields['from']).", ".$mdb2->quote($fields['to']).", ".
926 $fields['chclient'].", ".$fields['chinvoice'].", ".$fields['chpaid'].", ".$fields['chip'].", ".
927 $fields['chproject'].", ".$fields['chstart'].", ".$fields['chduration'].", ".$fields['chcost'].", ".
928 $fields['chtask'].", ".$fields['chfinish'].", ".$fields['chnote'].", ".$fields['chcf_1'].", ".$fields['chunits'].", ".
929 $mdb2->quote($fields['group_by1']).", ".$mdb2->quote($fields['group_by2']).", ".
930 $mdb2->quote($fields['group_by3']).", ".$fields['chtotalsonly'].")";
931 $affected = $mdb2->exec($sql);
932 if (is_a($affected, 'PEAR_Error'))
935 $last_id = $mdb2->lastInsertID('tt_fav_reports', 'id');
939 // insertNotification function inserts a new notification into database.
940 private function insertNotification($fields)
942 $mdb2 = getConnection();
944 $group_id = (int) $fields['group_id'];
945 $org_id = (int) $fields['org_id'];
946 $cron_spec = $fields['cron_spec'];
947 $last = (int) $fields['last'];
948 $next = (int) $fields['next'];
949 $report_id = (int) $fields['report_id'];
950 $email = $fields['email'];
952 $subject = $fields['subject'];
953 $report_condition = $fields['report_condition'];
954 $status = $fields['status'];
956 $sql = "insert into tt_cron".
957 " (group_id, org_id, cron_spec, last, next, report_id, email, cc, subject, report_condition, status)".
958 " 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).")";
959 $affected = $mdb2->exec($sql);
960 return (!is_a($affected, 'PEAR_Error'));
963 // insertUserParam - a helper function to insert a user parameter.
964 private function insertUserParam($fields) {
965 $mdb2 = getConnection();
967 $group_id = (int) $fields['group_id'];
968 $org_id = (int) $fields['org_id'];
969 $user_id = (int) $fields['user_id'];
970 $param_name = $fields['param_name'];
971 $param_value = $fields['param_value'];
973 $sql = "insert into tt_config".
974 " (user_id, group_id, org_id, param_name, param_value)".
975 " values ($user_id, $group_id, $org_id, ".$mdb2->quote($param_name).", ".$mdb2->quote($param_value).")";
976 $affected = $mdb2->exec($sql);
977 return (!is_a($affected, 'PEAR_Error'));
980 // insertCustomField - a helper function to insert a custom field.
981 private function insertCustomField($fields) {
982 $mdb2 = getConnection();
984 $group_id = (int) $fields['group_id'];
985 $org_id = (int) $fields['org_id'];
986 $type = (int) $fields['type'];
987 $label = $fields['label'];
988 $required = (int) $fields['required'];
989 $status = $fields['status'];
991 $sql = "insert into tt_custom_fields".
992 " (group_id, org_id, type, label, required, status)".
993 " values($group_id, $org_id, $type, ".$mdb2->quote($label).", $required, ".$mdb2->quote($status).")";
994 $affected = $mdb2->exec($sql);
995 if (is_a($affected, 'PEAR_Error'))
998 $last_id = $mdb2->lastInsertID('tt_custom_fields', 'id');
1002 // insertCustomFieldOption - a helper function to insert a custom field option.
1003 private function insertCustomFieldOption($fields) {
1004 $mdb2 = getConnection();
1006 $group_id = (int) $fields['group_id'];
1007 $org_id = (int) $fields['org_id'];
1008 $field_id = (int) $fields['field_id'];
1009 $value = $fields['value'];
1011 $sql = "insert into tt_custom_field_options (group_id, org_id, field_id, value)".
1012 " values ($group_id, $org_id, $field_id, ".$mdb2->quote($value).")";
1013 $affected = $mdb2->exec($sql);
1014 if (is_a($affected, 'PEAR_Error'))
1017 $last_id = $mdb2->lastInsertID('tt_custom_field_options', 'id');
1021 // insertLogEntry - a helper function to insert a time log entry.
1022 private function insertLogEntry($fields) {
1024 $mdb2 = getConnection();
1026 $group_id = (int) $fields['group_id'];
1027 $org_id = (int) $fields['org_id'];
1028 $user_id = (int) $fields['user_id'];
1029 $date = $fields['date'];
1030 $start = $fields['start'];
1031 $duration = $fields['duration'];
1032 $client_id = $fields['client_id'];
1033 $project_id = $fields['project_id'];
1034 $task_id = $fields['task_id'];
1035 $invoice_id = $fields['invoice_id'];
1036 $comment = $fields['comment'];
1037 $billable = (int) $fields['billable'];
1038 $paid = (int) $fields['paid'];
1039 $status = $fields['status'];
1041 $sql = "insert into tt_log".
1042 " (user_id, group_id, org_id, date, start, duration, client_id, project_id, task_id, invoice_id, comment".
1043 ", billable, paid, created, created_ip, created_by, status)".
1044 " values ($user_id, $group_id, $org_id".
1045 ", ".$mdb2->quote($date).
1046 ", ".$mdb2->quote($start).
1047 ", ".$mdb2->quote($duration).
1048 ", ".$mdb2->quote($client_id).
1049 ", ".$mdb2->quote($project_id).
1050 ", ".$mdb2->quote($task_id).
1051 ", ".$mdb2->quote($invoice_id).
1052 ", ".$mdb2->quote($comment).
1053 ", $billable, $paid".
1054 ", now(), ".$mdb2->quote($_SERVER['REMOTE_ADDR']).", ".$user->id.
1055 ", ". $mdb2->quote($status).")";
1056 $affected = $mdb2->exec($sql);
1057 if (is_a($affected, 'PEAR_Error')) {
1058 $this->errors->add($i18n->get('error.db')); // TODO: review whether or not to add error here in all insert calls.
1062 $log_id = $mdb2->lastInsertID('tt_log', 'id');
1066 // insertCustomFieldLogEntry - a helper function to insert a custom field log entry.
1067 private function insertCustomFieldLogEntry($fields) {
1068 $mdb2 = getConnection();
1070 $group_id = (int) $fields['group_id'];
1071 $org_id = (int) $fields['org_id'];
1072 $log_id = (int) $fields['log_id'];
1073 $field_id = (int) $fields['field_id'];
1074 $option_id = $fields['option_id'];
1075 $value = $fields['value'];
1076 $status = $fields['status'];
1078 $sql = "insert into tt_custom_field_log (group_id, org_id, log_id, field_id, option_id, value, status)".
1079 " values ($group_id, $org_id, $log_id, $field_id, ".$mdb2->quote($option_id).", ".$mdb2->quote($value).", ".$mdb2->quote($status).")";
1080 $affected = $mdb2->exec($sql);
1081 return (!is_a($affected, 'PEAR_Error'));
1084 // getTopRole returns top role id.
1085 private function getTopRole() {
1086 $mdb2 = getConnection();
1088 $sql = "select id from tt_roles where group_id = 0 and rank = ".MAX_RANK." and status = 1";
1089 $res = $mdb2->query($sql);
1091 if (!is_a($res, 'PEAR_Error')) {
1092 $val = $res->fetchRow();
1099 // The loginExists function detrmines if a login already exists.
1100 private function loginExists($login) {
1101 $mdb2 = getConnection();
1103 $sql = "select id from tt_users where login = ".$mdb2->quote($login)." and (status = 1 or status = 0)";
1104 $res = $mdb2->query($sql);
1105 if (!is_a($res, 'PEAR_Error')) {
1106 if ($val = $res->fetchRow()) {