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 'quota_percent' => $attrs['QUOTA_PERCENT'],
251 'email' => $attrs['EMAIL'],
252 'status' => $attrs['STATUS']), false);
255 $this->currentGroupUserMap[$attrs['ID']] = $user_id;
257 $this->errors->add($i18n->get('error.db'));
262 if ($name == 'USER_PROJECT_BIND') {
263 if (!$this->insertUserProjectBind(array(
264 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
265 'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
266 'group_id' => $this->current_group_id,
267 'org_id' => $this->org_id,
268 'rate' => $attrs['RATE'],
269 'status' => $attrs['STATUS']))) {
270 $this->errors->add($i18n->get('error.db'));
275 if ($name == 'INVOICE') {
276 // We get here when processing <invoice> tags for the current group.
277 $invoice_id = $this->insertInvoice(array(
278 'group_id' => $this->current_group_id,
279 'org_id' => $this->org_id,
280 'name' => $attrs['NAME'],
281 'date' => $attrs['DATE'],
282 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
283 'status' => $attrs['STATUS']));
286 $this->currentGroupInvoiceMap[$attrs['ID']] = $invoice_id;
288 $this->errors->add($i18n->get('error.db'));
293 if ($name == 'LOG_ITEM') {
294 // We get here when processing <log_item> tags for the current group.
295 $log_item_id = $this->insertLogEntry(array(
296 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
297 'group_id' => $this->current_group_id,
298 'org_id' => $this->org_id,
299 'date' => $attrs['DATE'],
300 'start' => $attrs['START'],
301 'finish' => $attrs['FINISH'],
302 'duration' => $attrs['DURATION'],
303 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
304 'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
305 'task_id' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
306 'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
307 'comment' => (isset($attrs['COMMENT']) ? $attrs['COMMENT'] : ''),
308 'billable' => $attrs['BILLABLE'],
309 'paid' => $attrs['PAID'],
310 'status' => $attrs['STATUS']));
313 $this->currentGroupLogMap[$attrs['ID']] = $log_item_id;
314 } else $this->errors->add($i18n->get('error.db'));
318 if ($name == 'CUSTOM_FIELD') {
319 // We get here when processing <custom_field> tags for the current group.
320 $custom_field_id = $this->insertCustomField(array(
321 'group_id' => $this->current_group_id,
322 'org_id' => $this->org_id,
323 'type' => $attrs['TYPE'],
324 'label' => $attrs['LABEL'],
325 'required' => $attrs['REQUIRED'],
326 'status' => $attrs['STATUS']));
327 if ($custom_field_id) {
329 $this->currentGroupCustomFieldMap[$attrs['ID']] = $custom_field_id;
330 } else $this->errors->add($i18n->get('error.db'));
334 if ($name == 'CUSTOM_FIELD_OPTION') {
335 // We get here when processing <custom_field_option> tags for the current group.
336 $custom_field_option_id = $this->insertCustomFieldOption(array(
337 'group_id' => $this->current_group_id,
338 'org_id' => $this->org_id,
339 'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
340 'value' => $attrs['VALUE']));
341 if ($custom_field_option_id) {
343 $this->currentGroupCustomFieldOptionMap[$attrs['ID']] = $custom_field_option_id;
344 } else $this->errors->add($i18n->get('error.db'));
348 if ($name == 'CUSTOM_FIELD_LOG_ENTRY') {
349 // We get here when processing <custom_field_log_entry> tags for the current group.
350 if (!$this->insertCustomFieldLogEntry(array(
351 'group_id' => $this->current_group_id,
352 'org_id' => $this->org_id,
353 'log_id' => $this->currentGroupLogMap[$attrs['LOG_ID']],
354 'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
355 'option_id' => $this->currentGroupCustomFieldOptionMap[$attrs['OPTION_ID']],
356 'value' => $attrs['VALUE'],
357 'status' => $attrs['STATUS']))) {
358 $this->errors->add($i18n->get('error.db'));
363 if ($name == 'EXPENSE_ITEM') {
364 // We get here when processing <expense_item> tags for the current group.
365 $expense_item_id = $this->insertExpense(array(
366 'date' => $attrs['DATE'],
367 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
368 'group_id' => $this->current_group_id,
369 'org_id' => $this->org_id,
370 'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
371 'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
372 'name' => $attrs['NAME'],
373 'cost' => $attrs['COST'],
374 'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
375 'paid' => $attrs['PAID'],
376 'status' => $attrs['STATUS']));
377 if (!$expense_item_id) $this->errors->add($i18n->get('error.db'));
381 if ($name == 'PREDEFINED_EXPENSE') {
382 if (!$this->insertPredefinedExpense(array(
383 'group_id' => $this->current_group_id,
384 'org_id' => $this->org_id,
385 'name' => $attrs['NAME'],
386 'cost' => $attrs['COST']))) {
387 $this->errors->add($i18n->get('error.db'));
392 if ($name == 'MONTHLY_QUOTA') {
393 if (!$this->insertMonthlyQuota(array(
394 'group_id' => $this->current_group_id,
395 'org_id' => $this->org_id,
396 'year' => $attrs['YEAR'],
397 'month' => $attrs['MONTH'],
398 'minutes' => $attrs['MINUTES']))) {
399 $this->errors->add($i18n->get('error.db'));
404 if ($name == 'FAV_REPORT') {
406 if (strlen($attrs['USERS']) > 0) {
407 $arr = explode(',', $attrs['USERS']);
409 $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->currentGroupUserMap[$v];
411 $fav_report_id = $this->insertFavReport(array(
412 'name' => $attrs['NAME'],
413 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
414 'group_id' => $this->current_group_id,
415 'org_id' => $this->org_id,
416 'client' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
417 'option' => $this->currentGroupCustomFieldOptionMap[$attrs['CF_1_OPTION_ID']],
418 'project' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
419 'task' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
420 'billable' => $attrs['BILLABLE'],
421 'users' => $user_list,
422 'period' => $attrs['PERIOD'],
423 'from' => $attrs['PERIOD_START'],
424 'to' => $attrs['PERIOD_END'],
425 'chclient' => (int) $attrs['SHOW_CLIENT'],
426 'chinvoice' => (int) $attrs['SHOW_INVOICE'],
427 'chpaid' => (int) $attrs['SHOW_PAID'],
428 'chip' => (int) $attrs['SHOW_IP'],
429 'chproject' => (int) $attrs['SHOW_PROJECT'],
430 'chstart' => (int) $attrs['SHOW_START'],
431 'chduration' => (int) $attrs['SHOW_DURATION'],
432 'chcost' => (int) $attrs['SHOW_COST'],
433 'chtask' => (int) $attrs['SHOW_TASK'],
434 'chfinish' => (int) $attrs['SHOW_END'],
435 'chnote' => (int) $attrs['SHOW_NOTE'],
436 'chcf_1' => (int) $attrs['SHOW_CUSTOM_FIELD_1'],
437 'chunits' => (int) $attrs['SHOW_WORK_UNITS'],
438 'group_by1' => $attrs['GROUP_BY1'],
439 'group_by2' => $attrs['GROUP_BY2'],
440 'group_by3' => $attrs['GROUP_BY3'],
441 'chtotalsonly' => (int) $attrs['SHOW_TOTALS_ONLY']));
442 if ($fav_report_id) {
444 $this->currentGroupFavReportMap[$attrs['ID']] = $fav_report_id;
445 } else $this->errors->add($i18n->get('error.db'));
449 if ($name == 'NOTIFICATION') {
450 if (!$this->insertNotification(array(
451 'group_id' => $this->current_group_id,
452 'org_id' => $this->org_id,
453 'cron_spec' => $attrs['CRON_SPEC'],
454 'last' => $attrs['LAST'],
455 'next' => $attrs['NEXT'],
456 'report_id' => $this->currentGroupFavReportMap[$attrs['REPORT_ID']],
457 'email' => $attrs['EMAIL'],
458 'cc' => $attrs['CC'],
459 'subject' => $attrs['SUBJECT'],
460 'report_condition' => $attrs['REPORT_CONDITION'],
461 'status' => $attrs['STATUS']))) {
462 $this->errors->add($i18n->get('error.db'));
467 if ($name == 'USER_PARAM') {
468 if (!$this->insertUserParam(array(
469 'group_id' => $this->current_group_id,
470 'org_id' => $this->org_id,
471 'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
472 'param_name' => $attrs['PARAM_NAME'],
473 'param_value' => $attrs['PARAM_VALUE']))) {
474 $this->errors->add($i18n->get('error.db'));
481 // endElement - callback handler for ending tags in XML.
482 // We use this only for process </group> element endings and
483 // set current_group_id to an immediate parent.
484 // This is required to import group hierarchy correctly.
485 function endElement($parser, $name) {
486 // No need to care about first or second pass, as this is used only in second pass.
487 // See 2nd xml_set_element_handler, where this handler is set.
488 if ($name == 'GROUP') {
489 // Remove self from the parent stack.
490 $self = array_pop($this->parents);
491 // Set current group id to an immediate parent.
492 $len = count($this->parents);
493 $this->current_group_id = $len ? $this->parents[$len-1] : null;
497 // importXml - uncompresses the file, reads and parses its content.
498 // It goes through the file 2 times.
500 // During 1st pass, it determines whether we can import data.
501 // In 1st pass, startElement function is called as many times as necessary.
503 // Actual import occurs during 2nd pass.
504 // In 2nd pass, startElement and endElement are called many times.
505 // We only use endElement to finish current group processing.
507 // The above allows us to export/import complex orgs with nested groups,
508 // while by design all data are in attributes of the elements (no CDATA).
510 // There is currently at least one problem with keeping all data in attributes:
511 // a vertical tab character 0xB anywhere breaks parsing, making import impossible.
512 // See https://github.com/sparklemotion/nokogiri/issues/1581 - looks like
513 // an XML standard thing. Apparently, other invalid characters break parsing too.
514 // This problem needs to be addressed at some point but how exactly without
515 // complicating export-import too much with CDATA and dataElement processing?
516 function importXml() {
519 if (!$_FILES['xmlfile']['name']) {
520 $this->errors->add($i18n->get('error.upload'));
521 return; // There is nothing to do if we don't have a file.
524 // Do we have a compressed file?
526 $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
527 if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
531 // Create a temporary file.
532 $dirName = dirname(TEMPLATE_DIR . '_c/.');
533 $filename = tempnam($dirName, 'import_');
535 // If the file is compressed - uncompress it.
537 if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
538 $this->errors->add($i18n->get('error.sys'));
541 unlink($_FILES['xmlfile']['tmp_name']);
543 if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
544 $this->errors->add($i18n->get('error.upload'));
549 // Initialize XML parser.
550 $parser = xml_parser_create();
551 xml_set_object($parser, $this);
552 xml_set_element_handler($parser, 'startElement', false); // No need to process end tags in 1st pass.
554 // We need to parse the file 2 times:
555 // 1) First pass: determine if import is possible.
556 // 2) Second pass: import data, one tag at a time.
558 // Read and parse the content of the file. During parsing, startElement is called back for each tag.
559 $file = fopen($filename, 'r');
560 while (($data = fread($file, 4096)) && $this->errors->no()) {
561 if (!xml_parse($parser, $data, feof($file))) {
562 $this->errors->add(sprintf($i18n->get('error.xml'),
563 xml_get_current_line_number($parser),
564 xml_error_string(xml_get_error_code($parser))));
567 if ($this->conflicting_logins) {
568 $this->canImport = false;
569 $this->errors->add($i18n->get('error.user_exists'));
570 $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_logins));
573 $this->firstPass = false; // We are done with 1st pass.
574 xml_parser_free($parser);
575 if ($file) fclose($file);
576 if ($this->errors->yes()) {
577 // Remove the file and exit if we have errors.
582 // Now we can do a second pass, where real work is done.
583 $parser = xml_parser_create();
584 xml_set_object($parser, $this);
585 xml_set_element_handler($parser, 'startElement', 'endElement'); // Need to process ending tags too.
587 // Read and parse the content of the file. During parsing, startElement and endElement are called back for each tag.
588 $file = fopen($filename, 'r');
589 while (($data = fread($file, 4096)) && $this->errors->no()) {
590 if (!xml_parse($parser, $data, feof($file))) {
591 $this->errors->add(sprintf($i18n->get('error.xml'),
592 xml_get_current_line_number($parser),
593 xml_error_string(xml_get_error_code($parser))));
596 xml_parser_free($parser);
597 if ($file) fclose($file);
601 // uncompress - uncompresses the content of the $in file into the $out file.
602 function uncompress($in, $out) {
603 // Do we have the uncompress function?
604 if (!function_exists('bzopen'))
607 // Initial checks of file names and permissions.
608 if (!file_exists($in) || !is_readable ($in))
610 if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
613 if (!$out_file = fopen($out, 'wb'))
615 if (!$in_file = bzopen ($in, 'r'))
618 while (!feof($in_file)) {
619 $buffer = bzread($in_file, 4096);
620 fwrite($out_file, $buffer, 4096);
627 // createGroup function creates a new group.
628 private function createGroup($fields) {
631 $mdb2 = getConnection();
633 $columns = '(parent_id, org_id, name, description, currency, decimal_mark, lang, date_format, time_format'.
634 ', week_start, tracking_mode, project_required, task_required, record_type, bcc_email'.
635 ', allow_ip, password_complexity, plugins, lock_spec'.
636 ', workday_minutes, config, created, created_ip, created_by)';
638 $values = ' values (';
639 $values .= $mdb2->quote($fields['parent_id']);
640 $values .= ', '.$mdb2->quote($fields['org_id']);
641 $values .= ', '.$mdb2->quote(trim($fields['name']));
642 $values .= ', '.$mdb2->quote(trim($fields['description']));
643 $values .= ', '.$mdb2->quote(trim($fields['currency']));
644 $values .= ', '.$mdb2->quote($fields['decimal_mark']);
645 $values .= ', '.$mdb2->quote($fields['lang']);
646 $values .= ', '.$mdb2->quote($fields['date_format']);
647 $values .= ', '.$mdb2->quote($fields['time_format']);
648 $values .= ', '.(int)$fields['week_start'];
649 $values .= ', '.(int)$fields['tracking_mode'];
650 $values .= ', '.(int)$fields['project_required'];
651 $values .= ', '.(int)$fields['task_required'];
652 $values .= ', '.(int)$fields['record_type'];
653 $values .= ', '.$mdb2->quote($fields['bcc_email']);
654 $values .= ', '.$mdb2->quote($fields['allow_ip']);
655 $values .= ', '.$mdb2->quote($fields['password_complexity']);
656 $values .= ', '.$mdb2->quote($fields['plugins']);
657 $values .= ', '.$mdb2->quote($fields['lock_spec']);
658 $values .= ', '.(int)$fields['workday_minutes'];
659 $values .= ', '.$mdb2->quote($fields['config']);
660 $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
663 $sql = 'insert into tt_groups '.$columns.$values;
664 $affected = $mdb2->exec($sql);
665 if (is_a($affected, 'PEAR_Error')) {
666 $this->errors->add($i18n->get('error.db'));
670 $group_id = $mdb2->lastInsertID('tt_groups', 'id');
674 // insertMonthlyQuota - a helper function to insert a monthly quota.
675 private function insertMonthlyQuota($fields) {
676 $mdb2 = getConnection();
678 $group_id = (int) $fields['group_id'];
679 $org_id = (int) $fields['org_id'];
680 $year = (int) $fields['year'];
681 $month = (int) $fields['month'];
682 $minutes = (int) $fields['minutes'];
684 $sql = "INSERT INTO tt_monthly_quotas (group_id, org_id, year, month, minutes)".
685 " values ($group_id, $org_id, $year, $month, $minutes)";
686 $affected = $mdb2->exec($sql);
687 return (!is_a($affected, 'PEAR_Error'));
690 // insertPredefinedExpense - a helper function to insert a predefined expense.
691 private function insertPredefinedExpense($fields) {
692 $mdb2 = getConnection();
694 $group_id = (int) $fields['group_id'];
695 $org_id = (int) $fields['org_id'];
696 $name = $mdb2->quote($fields['name']);
697 $cost = $mdb2->quote($fields['cost']);
699 $sql = "INSERT INTO tt_predefined_expenses (group_id, org_id, name, cost)".
700 " values ($group_id, $org_id, $name, $cost)";
701 $affected = $mdb2->exec($sql);
702 return (!is_a($affected, 'PEAR_Error'));
705 // insertExpense - a helper function to insert an expense item.
706 private function insertExpense($fields) {
708 $mdb2 = getConnection();
710 $group_id = (int) $fields['group_id'];
711 $org_id = (int) $fields['org_id'];
712 $date = $fields['date'];
713 $user_id = (int) $fields['user_id'];
714 $client_id = $fields['client_id'];
715 $project_id = $fields['project_id'];
716 $name = $fields['name'];
717 $cost = str_replace(',', '.', $fields['cost']);
718 $invoice_id = $fields['invoice_id'];
719 $status = $fields['status'];
720 $paid = (int) $fields['paid'];
721 $created = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
723 $sql = "insert into tt_expense_items".
724 " (date, user_id, group_id, org_id, client_id, project_id, name, cost, invoice_id, paid, created, created_ip, created_by, status)".
725 " values (".$mdb2->quote($date).", $user_id, $group_id, $org_id, ".$mdb2->quote($client_id).", ".$mdb2->quote($project_id).
726 ", ".$mdb2->quote($name).", ".$mdb2->quote($cost).", ".$mdb2->quote($invoice_id).", $paid $created, ".$mdb2->quote($status).")";
727 $affected = $mdb2->exec($sql);
728 return (!is_a($affected, 'PEAR_Error'));
731 // insertTask function inserts a new task into database.
732 private function insertTask($fields)
734 $mdb2 = getConnection();
736 $group_id = (int) $fields['group_id'];
737 $org_id = (int) $fields['org_id'];
738 $name = $fields['name'];
739 $description = $fields['description'];
740 $projects = $fields['projects'];
741 $status = $fields['status'];
743 $sql = "insert into tt_tasks (group_id, org_id, name, description, status)
744 values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($status).")";
745 $affected = $mdb2->exec($sql);
747 if (is_a($affected, 'PEAR_Error'))
750 $last_id = $mdb2->lastInsertID('tt_tasks', 'id');
754 // insertUserProjectBind - inserts a user to project bind into tt_user_project_binds table.
755 private function insertUserProjectBind($fields) {
756 $mdb2 = getConnection();
758 $group_id = (int) $fields['group_id'];
759 $org_id = (int) $fields['org_id'];
760 $user_id = (int) $fields['user_id'];
761 $project_id = (int) $fields['project_id'];
762 $rate = $mdb2->quote($fields['rate']);
763 $status = $mdb2->quote($fields['status']);
765 $sql = "insert into tt_user_project_binds (user_id, project_id, group_id, org_id, rate, status)".
766 " values($user_id, $project_id, $group_id, $org_id, $rate, $status)";
767 $affected = $mdb2->exec($sql);
768 return (!is_a($affected, 'PEAR_Error'));
771 // insertUser - inserts a user into database.
772 private function insertUser($fields) {
774 $mdb2 = getConnection();
776 $group_id = (int) $fields['group_id'];
777 $org_id = (int) $fields['org_id'];
779 $columns = '(login, password, name, group_id, org_id, role_id, client_id, rate, quota_percent, email, created, created_ip, created_by, status)';
781 $values = 'values (';
782 $values .= $mdb2->quote($fields['login']);
783 $values .= ', '.$mdb2->quote($fields['password']);
784 $values .= ', '.$mdb2->quote($fields['name']);
785 $values .= ', '.$group_id;
786 $values .= ', '.$org_id;
787 $values .= ', '.(int)$fields['role_id'];
788 $values .= ', '.$mdb2->quote($fields['client_id']);
789 $values .= ', '.$mdb2->quote($fields['rate']);
790 $values .= ', '.$mdb2->quote($fields['quota_percent']);
791 $values .= ', '.$mdb2->quote($fields['email']);
792 $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
793 $values .= ', '.$mdb2->quote($fields['status']);
796 $sql = "insert into tt_users $columns $values";
797 $affected = $mdb2->exec($sql);
798 if (is_a($affected, 'PEAR_Error')) return false;
800 $last_id = $mdb2->lastInsertID('tt_users', 'id');
804 // insertProject - a helper function to insert a project as well as project to task binds.
805 private function insertProject($fields)
807 $mdb2 = getConnection();
809 $group_id = (int) $fields['group_id'];
810 $org_id = (int) $fields['org_id'];
811 $name = $fields['name'];
812 $description = $fields['description'];
813 $tasks = $fields['tasks'];
814 $comma_separated = implode(',', $tasks); // This is a comma-separated list of associated task ids.
815 $status = $fields['status'];
817 $sql = "insert into tt_projects (group_id, org_id, name, description, tasks, status)
818 values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
819 $affected = $mdb2->exec($sql);
820 if (is_a($affected, 'PEAR_Error'))
823 $last_id = $mdb2->lastInsertID('tt_projects', 'id');
825 // Insert binds into tt_project_task_binds table.
826 if (is_array($tasks)) {
827 foreach ($tasks as $task_id) {
828 $sql = "insert into tt_project_task_binds (project_id, task_id, group_id, org_id)".
829 " values($last_id, $task_id, $group_id, $org_id)";
830 $affected = $mdb2->exec($sql);
831 if (is_a($affected, 'PEAR_Error'))
839 // insertRole - inserts a role into tt_roles table.
840 private function insertRole($fields)
842 $mdb2 = getConnection();
844 $group_id = (int) $fields['group_id'];
845 $org_id = (int) $fields['org_id'];
846 $name = $fields['name'];
847 $rank = (int) $fields['rank'];
848 $description = $fields['description'];
849 $rights = $fields['rights'];
850 $status = $fields['status'];
852 $sql = "insert into tt_roles (group_id, org_id, name, rank, description, rights, status)
853 values ($group_id, $org_id, ".$mdb2->quote($name).", $rank, ".$mdb2->quote($description).", ".$mdb2->quote($rights).", ".$mdb2->quote($status).")";
854 $affected = $mdb2->exec($sql);
855 if (is_a($affected, 'PEAR_Error'))
858 $last_id = $mdb2->lastInsertID('tt_roles', 'id');
862 // insertInvoice - inserts an invoice in database.
863 private function insertInvoice($fields)
865 $mdb2 = getConnection();
867 $group_id = (int) $fields['group_id'];
868 $org_id = (int) $fields['org_id'];
869 $name = $fields['name'];
870 $client_id = (int) $fields['client_id'];
871 $date = $fields['date'];
872 $status = $fields['status'];
874 // Insert a new invoice record.
875 $sql = "insert into tt_invoices (group_id, org_id, name, date, client_id, status)".
876 " values($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id, ".$mdb2->quote($fields['status']).")";
877 $affected = $mdb2->exec($sql);
878 if (is_a($affected, 'PEAR_Error')) return false;
880 $last_id = $mdb2->lastInsertID('tt_invoices', 'id');
884 // The insertClient function inserts a new client as well as client to project binds.
885 private function insertClient($fields)
887 $mdb2 = getConnection();
889 $group_id = (int) $fields['group_id'];
890 $org_id = (int) $fields['org_id'];
891 $name = $fields['name'];
892 $address = $fields['address'];
893 $tax = $fields['tax'];
894 $projects = $fields['projects'];
896 $comma_separated = implode(',', $projects); // This is a comma-separated list of associated projects ids.
897 $status = $fields['status'];
899 $tax = str_replace(',', '.', $tax);
900 if ($tax == '') $tax = 0;
902 $sql = "insert into tt_clients (group_id, org_id, name, address, tax, projects, status)".
903 " values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($address).", $tax, ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
905 $affected = $mdb2->exec($sql);
906 if (is_a($affected, 'PEAR_Error'))
909 $last_id = $mdb2->lastInsertID('tt_clients', 'id');
911 if (count($projects) > 0)
912 foreach ($projects as $p_id) {
913 $sql = "insert into tt_client_project_binds (client_id, project_id, group_id, org_id) values($last_id, $p_id, $group_id, $org_id)";
914 $affected = $mdb2->exec($sql);
915 if (is_a($affected, 'PEAR_Error'))
922 // insertFavReport - inserts a favorite report in database.
923 private function insertFavReport($fields) {
924 $mdb2 = getConnection();
926 $group_id = (int) $fields['group_id'];
927 $org_id = (int) $fields['org_id'];
929 $sql = "insert into tt_fav_reports".
930 " (name, user_id, group_id, org_id, client_id, cf_1_option_id, project_id, task_id,".
931 " billable, invoice, paid_status, users, period, period_start, period_end,".
932 " show_client, show_invoice, show_paid, show_ip,".
933 " show_project, show_start, show_duration, show_cost,".
934 " show_task, show_end, show_note, show_custom_field_1, show_work_units,".
935 " group_by1, group_by2, group_by3, show_totals_only)".
937 $mdb2->quote($fields['name']).", ".$fields['user_id'].", $group_id, $org_id, ".
938 $mdb2->quote($fields['client']).", ".$mdb2->quote($fields['option']).", ".
939 $mdb2->quote($fields['project']).", ".$mdb2->quote($fields['task']).", ".
940 $mdb2->quote($fields['billable']).", ".$mdb2->quote($fields['invoice']).", ".
941 $mdb2->quote($fields['paid_status']).", ".
942 $mdb2->quote($fields['users']).", ".$mdb2->quote($fields['period']).", ".
943 $mdb2->quote($fields['from']).", ".$mdb2->quote($fields['to']).", ".
944 $fields['chclient'].", ".$fields['chinvoice'].", ".$fields['chpaid'].", ".$fields['chip'].", ".
945 $fields['chproject'].", ".$fields['chstart'].", ".$fields['chduration'].", ".$fields['chcost'].", ".
946 $fields['chtask'].", ".$fields['chfinish'].", ".$fields['chnote'].", ".$fields['chcf_1'].", ".$fields['chunits'].", ".
947 $mdb2->quote($fields['group_by1']).", ".$mdb2->quote($fields['group_by2']).", ".
948 $mdb2->quote($fields['group_by3']).", ".$fields['chtotalsonly'].")";
949 $affected = $mdb2->exec($sql);
950 if (is_a($affected, 'PEAR_Error'))
953 $last_id = $mdb2->lastInsertID('tt_fav_reports', 'id');
957 // insertNotification function inserts a new notification into database.
958 private function insertNotification($fields)
960 $mdb2 = getConnection();
962 $group_id = (int) $fields['group_id'];
963 $org_id = (int) $fields['org_id'];
964 $cron_spec = $fields['cron_spec'];
965 $last = (int) $fields['last'];
966 $next = (int) $fields['next'];
967 $report_id = (int) $fields['report_id'];
968 $email = $fields['email'];
970 $subject = $fields['subject'];
971 $report_condition = $fields['report_condition'];
972 $status = $fields['status'];
974 $sql = "insert into tt_cron".
975 " (group_id, org_id, cron_spec, last, next, report_id, email, cc, subject, report_condition, status)".
976 " 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).")";
977 $affected = $mdb2->exec($sql);
978 return (!is_a($affected, 'PEAR_Error'));
981 // insertUserParam - a helper function to insert a user parameter.
982 private function insertUserParam($fields) {
983 $mdb2 = getConnection();
985 $group_id = (int) $fields['group_id'];
986 $org_id = (int) $fields['org_id'];
987 $user_id = (int) $fields['user_id'];
988 $param_name = $fields['param_name'];
989 $param_value = $fields['param_value'];
991 $sql = "insert into tt_config".
992 " (user_id, group_id, org_id, param_name, param_value)".
993 " values ($user_id, $group_id, $org_id, ".$mdb2->quote($param_name).", ".$mdb2->quote($param_value).")";
994 $affected = $mdb2->exec($sql);
995 return (!is_a($affected, 'PEAR_Error'));
998 // insertCustomField - a helper function to insert a custom field.
999 private function insertCustomField($fields) {
1000 $mdb2 = getConnection();
1002 $group_id = (int) $fields['group_id'];
1003 $org_id = (int) $fields['org_id'];
1004 $type = (int) $fields['type'];
1005 $label = $fields['label'];
1006 $required = (int) $fields['required'];
1007 $status = $fields['status'];
1009 $sql = "insert into tt_custom_fields".
1010 " (group_id, org_id, type, label, required, status)".
1011 " values($group_id, $org_id, $type, ".$mdb2->quote($label).", $required, ".$mdb2->quote($status).")";
1012 $affected = $mdb2->exec($sql);
1013 if (is_a($affected, 'PEAR_Error'))
1016 $last_id = $mdb2->lastInsertID('tt_custom_fields', 'id');
1020 // insertCustomFieldOption - a helper function to insert a custom field option.
1021 private function insertCustomFieldOption($fields) {
1022 $mdb2 = getConnection();
1024 $group_id = (int) $fields['group_id'];
1025 $org_id = (int) $fields['org_id'];
1026 $field_id = (int) $fields['field_id'];
1027 $value = $fields['value'];
1029 $sql = "insert into tt_custom_field_options (group_id, org_id, field_id, value)".
1030 " values ($group_id, $org_id, $field_id, ".$mdb2->quote($value).")";
1031 $affected = $mdb2->exec($sql);
1032 if (is_a($affected, 'PEAR_Error'))
1035 $last_id = $mdb2->lastInsertID('tt_custom_field_options', 'id');
1039 // insertLogEntry - a helper function to insert a time log entry.
1040 private function insertLogEntry($fields) {
1042 $mdb2 = getConnection();
1044 $group_id = (int) $fields['group_id'];
1045 $org_id = (int) $fields['org_id'];
1046 $user_id = (int) $fields['user_id'];
1047 $date = $fields['date'];
1048 $start = $fields['start'];
1049 $duration = $fields['duration'];
1050 $client_id = $fields['client_id'];
1051 $project_id = $fields['project_id'];
1052 $task_id = $fields['task_id'];
1053 $invoice_id = $fields['invoice_id'];
1054 $comment = $fields['comment'];
1055 $billable = (int) $fields['billable'];
1056 $paid = (int) $fields['paid'];
1057 $status = $fields['status'];
1059 $sql = "insert into tt_log".
1060 " (user_id, group_id, org_id, date, start, duration, client_id, project_id, task_id, invoice_id, comment".
1061 ", billable, paid, created, created_ip, created_by, status)".
1062 " values ($user_id, $group_id, $org_id".
1063 ", ".$mdb2->quote($date).
1064 ", ".$mdb2->quote($start).
1065 ", ".$mdb2->quote($duration).
1066 ", ".$mdb2->quote($client_id).
1067 ", ".$mdb2->quote($project_id).
1068 ", ".$mdb2->quote($task_id).
1069 ", ".$mdb2->quote($invoice_id).
1070 ", ".$mdb2->quote($comment).
1071 ", $billable, $paid".
1072 ", now(), ".$mdb2->quote($_SERVER['REMOTE_ADDR']).", ".$user->id.
1073 ", ". $mdb2->quote($status).")";
1074 $affected = $mdb2->exec($sql);
1075 if (is_a($affected, 'PEAR_Error')) {
1076 $this->errors->add($i18n->get('error.db')); // TODO: review whether or not to add error here in all insert calls.
1080 $log_id = $mdb2->lastInsertID('tt_log', 'id');
1084 // insertCustomFieldLogEntry - a helper function to insert a custom field log entry.
1085 private function insertCustomFieldLogEntry($fields) {
1086 $mdb2 = getConnection();
1088 $group_id = (int) $fields['group_id'];
1089 $org_id = (int) $fields['org_id'];
1090 $log_id = (int) $fields['log_id'];
1091 $field_id = (int) $fields['field_id'];
1092 $option_id = $fields['option_id'];
1093 $value = $fields['value'];
1094 $status = $fields['status'];
1096 $sql = "insert into tt_custom_field_log (group_id, org_id, log_id, field_id, option_id, value, status)".
1097 " values ($group_id, $org_id, $log_id, $field_id, ".$mdb2->quote($option_id).", ".$mdb2->quote($value).", ".$mdb2->quote($status).")";
1098 $affected = $mdb2->exec($sql);
1099 return (!is_a($affected, 'PEAR_Error'));
1102 // getTopRole returns top role id.
1103 private function getTopRole() {
1104 $mdb2 = getConnection();
1106 $sql = "select id from tt_roles where group_id = 0 and rank = ".MAX_RANK." and status = 1";
1107 $res = $mdb2->query($sql);
1109 if (!is_a($res, 'PEAR_Error')) {
1110 $val = $res->fetchRow();
1117 // The loginExists function detrmines if a login already exists.
1118 private function loginExists($login) {
1119 $mdb2 = getConnection();
1121 $sql = "select id from tt_users where login = ".$mdb2->quote($login)." and (status = 1 or status = 0)";
1122 $res = $mdb2->query($sql);
1123 if (!is_a($res, 'PEAR_Error')) {
1124 if ($val = $res->fetchRow()) {