Fixed handling user limit for admin.
[timetracker.git] / WEB-INF / lib / ttOrgImportHelper.class.php
1 <?php
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.
10 // |
11 // | There are only two ways to violate the license:
12 // |
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).
16 // |
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).
20 // |
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
23 // |
24 // +----------------------------------------------------------------------+
25 // | Contributors:
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
28
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 $num_users            = 0;    // A number of active and inactive users we are importing.
35   var $conflicting_logins   = null; // A comma-separated list of logins we cannot import.
36   var $canImport      = true;    // False if we cannot import data due to a conflict such as login collision.
37   var $firstPass      = true;    // True during first pass through the file.
38   var $org_id         = null;    // Organization id (same as top group_id).
39   var $current_group_id        = null; // Current group id during parsing.
40   var $parents        = array(); // A stack of parent group ids for current group all the way to the root including self.
41   var $top_role_id    = 0;       // Top role id.
42
43   // Entity maps for current group. They map XML ids with database ids.
44   var $currentGroupRoleMap    = array();
45   var $currentGroupTaskMap    = array();
46   var $currentGroupProjectMap = array();
47   var $currentGroupClientMap  = array();
48   var $currentGroupUserMap    = array();
49   var $currentGroupInvoiceMap = array();
50   var $currentGroupLogMap     = array();
51   var $currentGroupCustomFieldMap = array();
52   var $currentGroupCustomFieldOptionMap = array();
53   var $currentGroupFavReportMap = array();
54
55   // Constructor.
56   function __construct(&$errors) {
57     $this->errors = &$errors;
58     $this->top_role_id = $this->getTopRole();
59   }
60
61   // startElement - callback handler for opening tags in XML.
62   function startElement($parser, $name, $attrs) {
63     global $i18n;
64
65     // First pass through the file determines if we can import data.
66     // We require 2 things:
67     //   1) Database schema version must be set. This ensures we have a compatible file.
68     //   2) No login coillisions are allowed.
69     if ($this->firstPass) {
70       if ($name == 'ORG' && $this->canImport) {
71          if ($attrs['SCHEMA'] == null) {
72            // We need (database) schema attribute to be available for import to work.
73            // Old Time Tracker export files don't have this.
74            // Current import code does not work with old format because we had to
75            // restructure data in export files for subgroup support.
76            $this->canImport = false;
77            $this->errors->add($i18n->get('error.format'));
78            return;
79          }
80       }
81
82       // In first pass we check user logins for potential collisions with existing.
83       if ($name == 'USER' && $this->canImport) {
84         $login = $attrs['LOGIN'];
85         if ('' != $attrs['STATUS']) $this->num_users++;
86         if ('' != $attrs['STATUS'] && $this->loginExists($login)) {
87           // We have a login collision. Append colliding login to a list of things we cannot import.
88           $this->conflicting_logins .= ($this->conflicting_logins ? ", $login" : $login);
89           // The above is printed in error message with all found colliding logins.
90         }
91       }
92     }
93
94     // Second pass processing. We import data here, one tag at a time.
95     if (!$this->firstPass && $this->canImport && $this->errors->no()) {
96       $mdb2 = getConnection();
97
98       // We are in second pass and can import data.
99       if ($name == 'GROUP') {
100         // Create a new group.
101         $this->current_group_id = $this->createGroup(array(
102           'parent_id' => $this->current_group_id, // Note: after insert current_group_id changes.
103           'org_id' => $this->org_id,
104           'name' => $attrs['NAME'],
105           'description' => $attrs['DESCRIPTION'],
106           'currency' => $attrs['CURRENCY'],
107           'decimal_mark' => $attrs['DECIMAL_MARK'],
108           'lang' => $attrs['LANG'],
109           'date_format' => $attrs['DATE_FORMAT'],
110           'time_format' => $attrs['TIME_FORMAT'],
111           'week_start' => $attrs['WEEK_START'],
112           'tracking_mode' => $attrs['TRACKING_MODE'],
113           'project_required' => $attrs['PROJECT_REQUIRED'],
114           'task_required' => $attrs['TASK_REQUIRED'],
115           'record_type' => $attrs['RECORD_TYPE'],
116           'bcc_email' => $attrs['BCC_EMAIL'],
117           'allow_ip' => $attrs['ALLOW_IP'],
118           'password_complexity' => $attrs['PASSWORD_COMPLEXITY'],
119           'plugins' => $attrs['PLUGINS'],
120           'lock_spec' => $attrs['LOCK_SPEC'],
121           'workday_minutes' => $attrs['WORKDAY_MINUTES'],
122           'custom_logo' => $attrs['CUSTOM_LOGO'],
123           'config' => $attrs['CONFIG']));
124
125         // Special handling for top group.
126         if (!$this->org_id && $this->current_group_id) {
127           $this->org_id = $this->current_group_id;
128           $sql = "update tt_groups set org_id = $this->current_group_id where org_id is NULL and id = $this->current_group_id";
129           $affected = $mdb2->exec($sql);
130         }
131         // Add self to parent stack.
132         array_push($this->parents, $this->current_group_id);
133
134         // Recycle all maps as we are starting to work on new group.
135         // Note that for this to work properly all nested groups must be last entries in xml for each group.
136         unset($this->currentGroupRoleMap); $this->currentGroupRoleMap = array();
137         unset($this->currentGroupTaskMap); $this->currentGroupTaskMap = array();
138         unset($this->currentGroupProjectMap); $this->currentGroupProjectMap = array();
139         unset($this->currentGroupClientMap); $this->currentGroupClientMap = array();
140         unset($this->currentGroupUserMap); $this->currentGroupUserMap = array();
141         unset($this->currentGroupInvoiceMap); $this->currentGroupInvoiceMap = array();
142         unset($this->currentGroupLogMap); $this->currentGroupLogMap = array();
143         unset($this->currentGroupCustomFieldMap); $this->currentGroupCustomFieldMap = array();
144         unset($this->currentGroupCustomFieldOptionMap); $this->currentGroupCustomFieldOptionMap = array();
145         unset($this->currentGroupFavReportMap); $this->currentGroupCustomFavReportMap = array();
146         return;
147       }
148
149       if ($name == 'ROLE') {
150         // We get here when processing <role> tags for the current group.
151         $role_id = $this->insertRole(array(
152           'group_id' => $this->current_group_id,
153           'org_id' => $this->org_id,
154           'name' => $attrs['NAME'],
155           'description' => $attrs['DESCRIPTION'],
156           'rank' => $attrs['RANK'],
157           'rights' => $attrs['RIGHTS'],
158           'status' => $attrs['STATUS']));
159         if ($role_id) {
160           // Add a mapping.
161           $this->currentGroupRoleMap[$attrs['ID']] = $role_id;
162         } else {
163           $this->errors->add($i18n->get('error.db'));
164         }
165         return;
166       }
167
168       if ($name == 'TASK') {
169         // We get here when processing <task> tags for the current group.
170         $task_id = $this->insertTask(array(
171           'group_id' => $this->current_group_id,
172           'org_id' => $this->org_id,
173           'name' => $attrs['NAME'],
174           'description' => $attrs['DESCRIPTION'],
175           'status' => $attrs['STATUS']));
176         if ($task_id) {
177           // Add a mapping.
178           $this->currentGroupTaskMap[$attrs['ID']] = $task_id;
179         } else {
180           $this->errors->add($i18n->get('error.db'));
181         }
182         return;
183       }
184
185       if ($name == 'PROJECT') {
186         // We get here when processing <project> tags for the current group.
187
188         // Prepare a list of task ids.
189         if ($attrs['TASKS']) {
190           $tasks = explode(',', $attrs['TASKS']);
191           foreach ($tasks as $id)
192             $mapped_tasks[] = $this->currentGroupTaskMap[$id];
193         }
194
195         $project_id = $this->insertProject(array(
196           'group_id' => $this->current_group_id,
197           'org_id' => $this->org_id,
198           'name' => $attrs['NAME'],
199           'description' => $attrs['DESCRIPTION'],
200           'tasks' => $mapped_tasks,
201           'status' => $attrs['STATUS']));
202         if ($project_id) {
203           // Add a mapping.
204           $this->currentGroupProjectMap[$attrs['ID']] = $project_id;
205         } else {
206           $this->errors->add($i18n->get('error.db'));
207         }
208         return;
209       }
210
211       if ($name == 'CLIENT') {
212         // We get here when processing <client> tags for the current group.
213
214         // Prepare a list of project ids.
215         if ($attrs['PROJECTS']) {
216           $projects = explode(',', $attrs['PROJECTS']);
217           foreach ($projects as $id)
218             $mapped_projects[] = $this->currentGroupProjectMap[$id];
219         }
220
221         $client_id = $this->insertClient(array(
222           'group_id' => $this->current_group_id,
223           'org_id' => $this->org_id,
224           'name' => $attrs['NAME'],
225           'address' => $attrs['ADDRESS'],
226           'tax' => $attrs['TAX'],
227           'projects' => $mapped_projects,
228           'status' => $attrs['STATUS']));
229         if ($client_id) {
230           // Add a mapping.
231           $this->currentGroupClientMap[$attrs['ID']] = $client_id;
232         } else {
233           $this->errors->add($i18n->get('error.db'));
234         }
235         return;
236       }
237
238       if ($name == 'USER') {
239         // We get here when processing <user> tags for the current group.
240
241         $role_id = $attrs['ROLE_ID'] === '0' ? $this->top_role_id :  $this->currentGroupRoleMap[$attrs['ROLE_ID']]; // 0 (not null) means top manager role.
242
243         $user_id = $this->insertUser(array(
244           'group_id' => $this->current_group_id,
245           'org_id' => $this->org_id,
246           'role_id' => $role_id,
247           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
248           'name' => $attrs['NAME'],
249           'login' => $attrs['LOGIN'],
250           'password' => $attrs['PASSWORD'],
251           'rate' => $attrs['RATE'],
252           'quota_percent' => $attrs['QUOTA_PERCENT'],
253           'email' => $attrs['EMAIL'],
254           'status' => $attrs['STATUS']), false);
255         if ($user_id) {
256           // Add a mapping.
257           $this->currentGroupUserMap[$attrs['ID']] = $user_id;
258         } else {
259           $this->errors->add($i18n->get('error.db'));
260         }
261         return;
262       }
263
264       if ($name == 'USER_PROJECT_BIND') {
265         if (!$this->insertUserProjectBind(array(
266           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
267           'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
268           'group_id' => $this->current_group_id,
269           'org_id' => $this->org_id,
270           'rate' => $attrs['RATE'],
271           'status' => $attrs['STATUS']))) {
272           $this->errors->add($i18n->get('error.db'));
273         }
274         return;
275       }
276
277       if ($name == 'INVOICE') {
278         // We get here when processing <invoice> tags for the current group.
279         $invoice_id = $this->insertInvoice(array(
280           'group_id' => $this->current_group_id,
281           'org_id' => $this->org_id,
282           'name' => $attrs['NAME'],
283           'date' => $attrs['DATE'],
284           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
285           'status' => $attrs['STATUS']));
286         if ($invoice_id) {
287           // Add a mapping.
288           $this->currentGroupInvoiceMap[$attrs['ID']] = $invoice_id;
289         } else {
290           $this->errors->add($i18n->get('error.db'));
291         }
292         return;
293       }
294
295       if ($name == 'LOG_ITEM') {
296         // We get here when processing <log_item> tags for the current group.
297         $log_item_id = $this->insertLogEntry(array(
298           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
299           'group_id' => $this->current_group_id,
300           'org_id' => $this->org_id,
301           'date' => $attrs['DATE'],
302           'start' => $attrs['START'],
303           'finish' => $attrs['FINISH'],
304           'duration' => $attrs['DURATION'],
305           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
306           'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
307           'task_id' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
308           'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
309           'comment' => (isset($attrs['COMMENT']) ? $attrs['COMMENT'] : ''),
310           'billable' => $attrs['BILLABLE'],
311           'paid' => $attrs['PAID'],
312           'status' => $attrs['STATUS']));
313         if ($log_item_id) {
314           // Add a mapping.
315           $this->currentGroupLogMap[$attrs['ID']] = $log_item_id;
316         } else $this->errors->add($i18n->get('error.db'));
317         return;
318       }
319
320       if ($name == 'CUSTOM_FIELD') {
321         // We get here when processing <custom_field> tags for the current group.
322         $custom_field_id = $this->insertCustomField(array(
323           'group_id' => $this->current_group_id,
324           'org_id' => $this->org_id,
325           'type' => $attrs['TYPE'],
326           'label' => $attrs['LABEL'],
327           'required' => $attrs['REQUIRED'],
328           'status' => $attrs['STATUS']));
329         if ($custom_field_id) {
330           // Add a mapping.
331           $this->currentGroupCustomFieldMap[$attrs['ID']] = $custom_field_id;
332         } else $this->errors->add($i18n->get('error.db'));
333         return;
334       }
335
336       if ($name == 'CUSTOM_FIELD_OPTION') {
337         // We get here when processing <custom_field_option> tags for the current group.
338         $custom_field_option_id = $this->insertCustomFieldOption(array(
339           'group_id' => $this->current_group_id,
340           'org_id' => $this->org_id,
341           'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
342           'value' => $attrs['VALUE']));
343         if ($custom_field_option_id) {
344           // Add a mapping.
345           $this->currentGroupCustomFieldOptionMap[$attrs['ID']] = $custom_field_option_id;
346         } else $this->errors->add($i18n->get('error.db'));
347         return;
348       }
349
350       if ($name == 'CUSTOM_FIELD_LOG_ENTRY') {
351         // We get here when processing <custom_field_log_entry> tags for the current group.
352         if (!$this->insertCustomFieldLogEntry(array(
353           'group_id' => $this->current_group_id,
354           'org_id' => $this->org_id,
355           'log_id' => $this->currentGroupLogMap[$attrs['LOG_ID']],
356           'field_id' => $this->currentGroupCustomFieldMap[$attrs['FIELD_ID']],
357           'option_id' => $this->currentGroupCustomFieldOptionMap[$attrs['OPTION_ID']],
358           'value' => $attrs['VALUE'],
359           'status' => $attrs['STATUS']))) {
360           $this->errors->add($i18n->get('error.db'));
361         }
362         return;
363       }
364
365       if ($name == 'EXPENSE_ITEM') {
366         // We get here when processing <expense_item> tags for the current group.
367         $expense_item_id = $this->insertExpense(array(
368           'date' => $attrs['DATE'],
369           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
370           'group_id' => $this->current_group_id,
371           'org_id' => $this->org_id,
372           'client_id' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
373           'project_id' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
374           'name' => $attrs['NAME'],
375           'cost' => $attrs['COST'],
376           'invoice_id' => $this->currentGroupInvoiceMap[$attrs['INVOICE_ID']],
377           'paid' => $attrs['PAID'],
378           'status' => $attrs['STATUS']));
379         if (!$expense_item_id) $this->errors->add($i18n->get('error.db'));
380         return;
381       }
382
383       if ($name == 'PREDEFINED_EXPENSE') {
384         if (!$this->insertPredefinedExpense(array(
385           'group_id' => $this->current_group_id,
386           'org_id' => $this->org_id,
387           'name' => $attrs['NAME'],
388           'cost' => $attrs['COST']))) {
389           $this->errors->add($i18n->get('error.db'));
390         }
391         return;
392       }
393
394       if ($name == 'MONTHLY_QUOTA') {
395         if (!$this->insertMonthlyQuota(array(
396           'group_id' => $this->current_group_id,
397           'org_id' => $this->org_id,
398           'year' => $attrs['YEAR'],
399           'month' => $attrs['MONTH'],
400           'minutes' => $attrs['MINUTES']))) {
401           $this->errors->add($i18n->get('error.db'));
402         }
403         return;
404       }
405
406       if ($name == 'FAV_REPORT') {
407         $user_list = '';
408         if (strlen($attrs['USERS']) > 0) {
409           $arr = explode(',', $attrs['USERS']);
410           foreach ($arr as $v)
411             $user_list .= (strlen($user_list) == 0 ? '' : ',').$this->currentGroupUserMap[$v];
412         }
413         $fav_report_id = $this->insertFavReport(array(
414           'name' => $attrs['NAME'],
415           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
416           'group_id' => $this->current_group_id,
417           'org_id' => $this->org_id,
418           'client' => $this->currentGroupClientMap[$attrs['CLIENT_ID']],
419           'option' => $this->currentGroupCustomFieldOptionMap[$attrs['CF_1_OPTION_ID']],
420           'project' => $this->currentGroupProjectMap[$attrs['PROJECT_ID']],
421           'task' => $this->currentGroupTaskMap[$attrs['TASK_ID']],
422           'billable' => $attrs['BILLABLE'],
423           'users' => $user_list,
424           'period' => $attrs['PERIOD'],
425           'from' => $attrs['PERIOD_START'],
426           'to' => $attrs['PERIOD_END'],
427           'chclient' => (int) $attrs['SHOW_CLIENT'],
428           'chinvoice' => (int) $attrs['SHOW_INVOICE'],
429           'chpaid' => (int) $attrs['SHOW_PAID'],
430           'chip' => (int) $attrs['SHOW_IP'],
431           'chproject' => (int) $attrs['SHOW_PROJECT'],
432           'chstart' => (int) $attrs['SHOW_START'],
433           'chduration' => (int) $attrs['SHOW_DURATION'],
434           'chcost' => (int) $attrs['SHOW_COST'],
435           'chtask' => (int) $attrs['SHOW_TASK'],
436           'chfinish' => (int) $attrs['SHOW_END'],
437           'chnote' => (int) $attrs['SHOW_NOTE'],
438           'chcf_1' => (int) $attrs['SHOW_CUSTOM_FIELD_1'],
439           'chunits' => (int) $attrs['SHOW_WORK_UNITS'],
440           'group_by1' => $attrs['GROUP_BY1'],
441           'group_by2' => $attrs['GROUP_BY2'],
442           'group_by3' => $attrs['GROUP_BY3'],
443           'chtotalsonly' => (int) $attrs['SHOW_TOTALS_ONLY']));
444         if ($fav_report_id) {
445           // Add a mapping.
446           $this->currentGroupFavReportMap[$attrs['ID']] = $fav_report_id;
447           } else $this->errors->add($i18n->get('error.db'));
448         return;
449       }
450
451       if ($name == 'NOTIFICATION') {
452         if (!$this->insertNotification(array(
453           'group_id' => $this->current_group_id,
454           'org_id' => $this->org_id,
455           'cron_spec' => $attrs['CRON_SPEC'],
456           'last' => $attrs['LAST'],
457           'next' => $attrs['NEXT'],
458           'report_id' => $this->currentGroupFavReportMap[$attrs['REPORT_ID']],
459           'email' => $attrs['EMAIL'],
460           'cc' => $attrs['CC'],
461           'subject' => $attrs['SUBJECT'],
462           'report_condition' => $attrs['REPORT_CONDITION'],
463           'status' => $attrs['STATUS']))) {
464           $this->errors->add($i18n->get('error.db'));
465         }
466         return;
467       }
468
469       if ($name == 'USER_PARAM') {
470         if (!$this->insertUserParam(array(
471           'group_id' => $this->current_group_id,
472           'org_id' => $this->org_id,
473           'user_id' => $this->currentGroupUserMap[$attrs['USER_ID']],
474           'param_name' => $attrs['PARAM_NAME'],
475           'param_value' => $attrs['PARAM_VALUE']))) {
476           $this->errors->add($i18n->get('error.db'));
477         }
478         return;
479       }
480     }
481   }
482
483   // endElement - callback handler for ending tags in XML.
484   // We use this only for process </group> element endings and
485   // set current_group_id to an immediate parent.
486   // This is required to import group hierarchy correctly.
487   function endElement($parser, $name) {
488     // No need to care about first or second pass, as this is used only in second pass.
489     // See 2nd xml_set_element_handler, where this handler is set.
490     if ($name == 'GROUP') {
491       // Remove self from the parent stack.
492       $self = array_pop($this->parents);
493       // Set current group id to an immediate parent.
494       $len = count($this->parents);
495       $this->current_group_id = $len ? $this->parents[$len-1] : null;
496     }
497   }
498
499   // importXml - uncompresses the file, reads and parses its content.
500   // It goes through the file 2 times.
501   //
502   // During 1st pass, it determines whether we can import data.
503   // In 1st pass, startElement function is called as many times as necessary.
504   //
505   // Actual import occurs during 2nd pass.
506   // In 2nd pass, startElement and endElement are called many times.
507   // We only use endElement to finish current group processing.
508   //
509   // The above allows us to export/import complex orgs with nested groups,
510   // while by design all data are in attributes of the elements (no CDATA).
511   //
512   // There is currently at least one problem with keeping all data in attributes:
513   // a vertical tab character 0xB anywhere breaks parsing, making import impossible.
514   // See https://github.com/sparklemotion/nokogiri/issues/1581 - looks like
515   // an XML standard thing. Apparently, other invalid characters break parsing too.
516   // This problem needs to be addressed at some point but how exactly without
517   // complicating export-import too much with CDATA and dataElement processing?
518   function importXml() {
519     global $i18n;
520
521     if (!$_FILES['xmlfile']['name']) {
522       $this->errors->add($i18n->get('error.upload'));
523       return; // There is nothing to do if we don't have a file.
524     }
525
526     // Do we have a compressed file?
527     $compressed = false;
528     $file_ext = substr($_FILES['xmlfile']['name'], strrpos($_FILES['xmlfile']['name'], '.') + 1);
529     if (in_array($file_ext, array('bz','tbz','bz2','tbz2'))) {
530       $compressed = true;
531     }
532
533     // Create a temporary file.
534     $dirName = dirname(TEMPLATE_DIR . '_c/.');
535     $filename = tempnam($dirName, 'import_');
536
537     // If the file is compressed - uncompress it.
538     if ($compressed) {
539       if (!$this->uncompress($_FILES['xmlfile']['tmp_name'], $filename)) {
540         $this->errors->add($i18n->get('error.sys'));
541         return;
542       }
543       unlink($_FILES['xmlfile']['tmp_name']);
544     } else {
545       if (!move_uploaded_file($_FILES['xmlfile']['tmp_name'], $filename)) {
546         $this->errors->add($i18n->get('error.upload'));
547         return;
548       }
549     }
550
551     // Initialize XML parser.
552     $parser = xml_parser_create();
553     xml_set_object($parser, $this);
554     xml_set_element_handler($parser, 'startElement', false); // No need to process end tags in 1st pass.
555
556     // We need to parse the file 2 times:
557     //   1) First pass: determine if import is possible.
558     //   2) Second pass: import data, one tag at a time.
559
560     // Read and parse the content of the file. During parsing, startElement is called back for each tag.
561     $file = fopen($filename, 'r');
562     while (($data = fread($file, 4096)) && $this->errors->no()) {
563       if (!xml_parse($parser, $data, feof($file))) {
564         $this->errors->add(sprintf($i18n->get('error.xml'),
565           xml_get_current_line_number($parser),
566           xml_error_string(xml_get_error_code($parser))));
567       }
568     }
569     if ($this->conflicting_logins) {
570       $this->canImport = false;
571       $this->errors->add($i18n->get('error.user_exists'));
572       $this->errors->add(sprintf($i18n->get('error.cannot_import'), $this->conflicting_logins));
573     }
574     if (!ttUserHelper::canAdd($this->num_users)) {
575       $this->canImport = false;
576       $this->errors->add($i18n->get('error.user_count'));
577     }
578
579     $this->firstPass = false; // We are done with 1st pass.
580     xml_parser_free($parser);
581     if ($file) fclose($file);
582     if ($this->errors->yes()) {
583       // Remove the file and exit if we have errors.
584       unlink($filename);
585       return;
586     }
587
588     // Now we can do a second pass, where real work is done.
589     $parser = xml_parser_create();
590     xml_set_object($parser, $this);
591     xml_set_element_handler($parser, 'startElement', 'endElement'); // Need to process ending tags too.
592
593     // Read and parse the content of the file. During parsing, startElement and endElement are called back for each tag.
594     $file = fopen($filename, 'r');
595     while (($data = fread($file, 4096)) && $this->errors->no()) {
596       if (!xml_parse($parser, $data, feof($file))) {
597         $this->errors->add(sprintf($i18n->get('error.xml'),
598           xml_get_current_line_number($parser),
599           xml_error_string(xml_get_error_code($parser))));
600       }
601     }
602     xml_parser_free($parser);
603     if ($file) fclose($file);
604     unlink($filename);
605   }
606
607   // uncompress - uncompresses the content of the $in file into the $out file.
608   function uncompress($in, $out) {
609     // Do we have the uncompress function?
610     if (!function_exists('bzopen'))
611       return false;
612
613     // Initial checks of file names and permissions.
614     if (!file_exists($in) || !is_readable ($in))
615       return false;
616     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
617       return false;
618
619     if (!$out_file = fopen($out, 'wb'))
620       return false;
621     if (!$in_file = bzopen ($in, 'r'))
622       return false;
623
624     while (!feof($in_file)) {
625       $buffer = bzread($in_file, 4096);
626       fwrite($out_file, $buffer, 4096);
627     }
628     bzclose($in_file);
629     fclose ($out_file);
630     return true;
631   }
632
633   // createGroup function creates a new group.
634   private function createGroup($fields) {
635     global $user;
636     global $i18n;
637     $mdb2 = getConnection();
638
639     $columns = '(parent_id, org_id, name, description, currency, decimal_mark, lang, date_format, time_format'.
640       ', week_start, tracking_mode, project_required, task_required, record_type, bcc_email'.
641       ', allow_ip, password_complexity, plugins, lock_spec'.
642       ', workday_minutes, config, created, created_ip, created_by)';
643
644     $values = ' values (';
645     $values .= $mdb2->quote($fields['parent_id']);
646     $values .= ', '.$mdb2->quote($fields['org_id']);
647     $values .= ', '.$mdb2->quote(trim($fields['name']));
648     $values .= ', '.$mdb2->quote(trim($fields['description']));
649     $values .= ', '.$mdb2->quote(trim($fields['currency']));
650     $values .= ', '.$mdb2->quote($fields['decimal_mark']);
651     $values .= ', '.$mdb2->quote($fields['lang']);
652     $values .= ', '.$mdb2->quote($fields['date_format']);
653     $values .= ', '.$mdb2->quote($fields['time_format']);
654     $values .= ', '.(int)$fields['week_start'];
655     $values .= ', '.(int)$fields['tracking_mode'];
656     $values .= ', '.(int)$fields['project_required'];
657     $values .= ', '.(int)$fields['task_required'];
658     $values .= ', '.(int)$fields['record_type'];
659     $values .= ', '.$mdb2->quote($fields['bcc_email']);
660     $values .= ', '.$mdb2->quote($fields['allow_ip']);
661     $values .= ', '.$mdb2->quote($fields['password_complexity']);
662     $values .= ', '.$mdb2->quote($fields['plugins']);
663     $values .= ', '.$mdb2->quote($fields['lock_spec']);
664     $values .= ', '.(int)$fields['workday_minutes'];
665     $values .= ', '.$mdb2->quote($fields['config']);
666     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
667     $values .= ')';
668
669     $sql = 'insert into tt_groups '.$columns.$values;
670     $affected = $mdb2->exec($sql);
671     if (is_a($affected, 'PEAR_Error')) {
672       $this->errors->add($i18n->get('error.db'));
673       return false;
674     }
675
676     $group_id = $mdb2->lastInsertID('tt_groups', 'id');
677     return $group_id;
678   }
679
680   // insertMonthlyQuota - a helper function to insert a monthly quota.
681   private function insertMonthlyQuota($fields) {
682     $mdb2 = getConnection();
683
684     $group_id = (int) $fields['group_id'];
685     $org_id = (int) $fields['org_id'];
686     $year = (int) $fields['year'];
687     $month = (int) $fields['month'];
688     $minutes = (int) $fields['minutes'];
689
690     $sql = "INSERT INTO tt_monthly_quotas (group_id, org_id, year, month, minutes)".
691       " values ($group_id, $org_id, $year, $month, $minutes)";
692     $affected = $mdb2->exec($sql);
693     return (!is_a($affected, 'PEAR_Error'));
694   }
695
696   // insertPredefinedExpense - a helper function to insert a predefined expense.
697   private function insertPredefinedExpense($fields) {
698     $mdb2 = getConnection();
699
700     $group_id = (int) $fields['group_id'];
701     $org_id = (int) $fields['org_id'];
702     $name = $mdb2->quote($fields['name']);
703     $cost = $mdb2->quote($fields['cost']);
704
705     $sql = "INSERT INTO tt_predefined_expenses (group_id, org_id, name, cost)".
706       " values ($group_id, $org_id, $name, $cost)";
707     $affected = $mdb2->exec($sql);
708     return (!is_a($affected, 'PEAR_Error'));
709   }
710
711   // insertExpense - a helper function to insert an expense item.
712   private function insertExpense($fields) {
713     global $user;
714     $mdb2 = getConnection();
715
716     $group_id = (int) $fields['group_id'];
717     $org_id = (int) $fields['org_id'];
718     $date = $fields['date'];
719     $user_id = (int) $fields['user_id'];
720     $client_id = $fields['client_id'];
721     $project_id = $fields['project_id'];
722     $name = $fields['name'];
723     $cost = str_replace(',', '.', $fields['cost']);
724     $invoice_id = $fields['invoice_id'];
725     $status = $fields['status'];
726     $paid = (int) $fields['paid'];
727     $created = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
728
729     $sql = "insert into tt_expense_items".
730       " (date, user_id, group_id, org_id, client_id, project_id, name, cost, invoice_id, paid, created, created_ip, created_by, status)".
731       " values (".$mdb2->quote($date).", $user_id, $group_id, $org_id, ".$mdb2->quote($client_id).", ".$mdb2->quote($project_id).
732       ", ".$mdb2->quote($name).", ".$mdb2->quote($cost).", ".$mdb2->quote($invoice_id).", $paid $created, ".$mdb2->quote($status).")";
733     $affected = $mdb2->exec($sql);
734     return (!is_a($affected, 'PEAR_Error'));
735   }
736
737   // insertTask function inserts a new task into database.
738   private function insertTask($fields)
739   {
740     $mdb2 = getConnection();
741
742     $group_id = (int) $fields['group_id'];
743     $org_id = (int) $fields['org_id'];
744     $name = $fields['name'];
745     $description = $fields['description'];
746     $projects = $fields['projects'];
747     $status = $fields['status'];
748
749     $sql = "insert into tt_tasks (group_id, org_id, name, description, status)
750       values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($status).")";
751     $affected = $mdb2->exec($sql);
752     $last_id = 0;
753     if (is_a($affected, 'PEAR_Error'))
754       return false;
755
756     $last_id = $mdb2->lastInsertID('tt_tasks', 'id');
757     return $last_id;
758   }
759
760   // insertUserProjectBind - inserts a user to project bind into tt_user_project_binds table.
761   private function insertUserProjectBind($fields) {
762     $mdb2 = getConnection();
763
764     $group_id = (int) $fields['group_id'];
765     $org_id = (int) $fields['org_id'];
766     $user_id = (int) $fields['user_id'];
767     $project_id = (int) $fields['project_id'];
768     $rate = $mdb2->quote($fields['rate']);
769     $status = $mdb2->quote($fields['status']);
770
771     $sql = "insert into tt_user_project_binds (user_id, project_id, group_id, org_id, rate, status)".
772       " values($user_id, $project_id, $group_id, $org_id, $rate, $status)";
773     $affected = $mdb2->exec($sql);
774     return (!is_a($affected, 'PEAR_Error'));
775   }
776
777   // insertUser - inserts a user into database.
778   private function insertUser($fields) {
779     global $user;
780     $mdb2 = getConnection();
781
782     $group_id = (int) $fields['group_id'];
783     $org_id = (int) $fields['org_id'];
784
785     $columns = '(login, password, name, group_id, org_id, role_id, client_id, rate, quota_percent, email, created, created_ip, created_by, status)';
786
787     $values = 'values (';
788     $values .= $mdb2->quote($fields['login']);
789     $values .= ', '.$mdb2->quote($fields['password']);
790     $values .= ', '.$mdb2->quote($fields['name']);
791     $values .= ', '.$group_id;
792     $values .= ', '.$org_id;
793     $values .= ', '.(int)$fields['role_id'];
794     $values .= ', '.$mdb2->quote($fields['client_id']);
795     $values .= ', '.$mdb2->quote($fields['rate']);
796     $values .= ', '.$mdb2->quote($fields['quota_percent']);
797     $values .= ', '.$mdb2->quote($fields['email']);
798     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
799     $values .= ', '.$mdb2->quote($fields['status']);
800     $values .= ')';
801
802     $sql = "insert into tt_users $columns $values";
803     $affected = $mdb2->exec($sql);
804     if (is_a($affected, 'PEAR_Error')) return false;
805
806     $last_id = $mdb2->lastInsertID('tt_users', 'id');
807     return $last_id;
808   }
809
810   // insertProject - a helper function to insert a project as well as project to task binds.
811   private function insertProject($fields)
812   {
813     $mdb2 = getConnection();
814
815     $group_id = (int) $fields['group_id'];
816     $org_id = (int) $fields['org_id'];
817     $name = $fields['name'];
818     $description = $fields['description'];
819     $tasks = $fields['tasks'];
820     $comma_separated = implode(',', $tasks); // This is a comma-separated list of associated task ids.
821     $status = $fields['status'];
822
823     $sql = "insert into tt_projects (group_id, org_id, name, description, tasks, status)
824       values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($description).", ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
825     $affected = $mdb2->exec($sql);
826     if (is_a($affected, 'PEAR_Error'))
827       return false;
828
829     $last_id = $mdb2->lastInsertID('tt_projects', 'id');
830
831     // Insert binds into tt_project_task_binds table.
832     if (is_array($tasks)) {
833       foreach ($tasks as $task_id) {
834         $sql = "insert into tt_project_task_binds (project_id, task_id, group_id, org_id)".
835           " values($last_id, $task_id, $group_id, $org_id)";
836         $affected = $mdb2->exec($sql);
837         if (is_a($affected, 'PEAR_Error'))
838           return false;
839       }
840     }
841
842     return $last_id;
843   }
844
845   // insertRole - inserts a role into tt_roles table.
846   private function insertRole($fields)
847   {
848     $mdb2 = getConnection();
849
850     $group_id = (int) $fields['group_id'];
851     $org_id = (int) $fields['org_id'];
852     $name = $fields['name'];
853     $rank = (int) $fields['rank'];
854     $description = $fields['description'];
855     $rights = $fields['rights'];
856     $status = $fields['status'];
857
858     $sql = "insert into tt_roles (group_id, org_id, name, rank, description, rights, status)
859       values ($group_id, $org_id, ".$mdb2->quote($name).", $rank, ".$mdb2->quote($description).", ".$mdb2->quote($rights).", ".$mdb2->quote($status).")";
860     $affected = $mdb2->exec($sql);
861     if (is_a($affected, 'PEAR_Error'))
862       return false;
863
864     $last_id = $mdb2->lastInsertID('tt_roles', 'id');
865     return $last_id;
866   }
867
868   // insertInvoice - inserts an invoice in database.
869   private function insertInvoice($fields)
870   {
871     $mdb2 = getConnection();
872
873     $group_id = (int) $fields['group_id'];
874     $org_id = (int) $fields['org_id'];
875     $name = $fields['name'];
876     $client_id = (int) $fields['client_id'];
877     $date = $fields['date'];
878     $status = $fields['status'];
879
880     // Insert a new invoice record.
881     $sql = "insert into tt_invoices (group_id, org_id, name, date, client_id, status)".
882       " values($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($date).", $client_id, ".$mdb2->quote($fields['status']).")";
883     $affected = $mdb2->exec($sql);
884     if (is_a($affected, 'PEAR_Error')) return false;
885
886     $last_id = $mdb2->lastInsertID('tt_invoices', 'id');
887     return $last_id;
888   }
889
890   // The insertClient function inserts a new client as well as client to project binds.
891   private function insertClient($fields)
892   {
893     $mdb2 = getConnection();
894
895     $group_id = (int) $fields['group_id'];
896     $org_id = (int) $fields['org_id'];
897     $name = $fields['name'];
898     $address = $fields['address'];
899     $tax = $fields['tax'];
900     $projects = $fields['projects'];
901     if ($projects)
902       $comma_separated = implode(',', $projects); // This is a comma-separated list of associated projects ids.
903     $status = $fields['status'];
904
905     $tax = str_replace(',', '.', $tax);
906     if ($tax == '') $tax = 0;
907
908     $sql = "insert into tt_clients (group_id, org_id, name, address, tax, projects, status)".
909       " values ($group_id, $org_id, ".$mdb2->quote($name).", ".$mdb2->quote($address).", $tax, ".$mdb2->quote($comma_separated).", ".$mdb2->quote($status).")";
910
911     $affected = $mdb2->exec($sql);
912     if (is_a($affected, 'PEAR_Error'))
913       return false;
914
915     $last_id = $mdb2->lastInsertID('tt_clients', 'id');
916
917     if (count($projects) > 0)
918       foreach ($projects as $p_id) {
919         $sql = "insert into tt_client_project_binds (client_id, project_id, group_id, org_id) values($last_id, $p_id, $group_id, $org_id)";
920         $affected = $mdb2->exec($sql);
921         if (is_a($affected, 'PEAR_Error'))
922           return false;
923       }
924
925     return $last_id;
926   }
927
928   // insertFavReport - inserts a favorite report in database.
929   private function insertFavReport($fields) {
930     $mdb2 = getConnection();
931
932     $group_id = (int) $fields['group_id'];
933     $org_id = (int) $fields['org_id'];
934
935     $sql = "insert into tt_fav_reports".
936       " (name, user_id, group_id, org_id, client_id, cf_1_option_id, project_id, task_id,".
937       " billable, invoice, paid_status, users, period, period_start, period_end,".
938       " show_client, show_invoice, show_paid, show_ip,".
939       " show_project, show_start, show_duration, show_cost,".
940       " show_task, show_end, show_note, show_custom_field_1, show_work_units,".
941       " group_by1, group_by2, group_by3, show_totals_only)".
942       " values(".
943       $mdb2->quote($fields['name']).", ".$fields['user_id'].", $group_id, $org_id, ".
944       $mdb2->quote($fields['client']).", ".$mdb2->quote($fields['option']).", ".
945       $mdb2->quote($fields['project']).", ".$mdb2->quote($fields['task']).", ".
946       $mdb2->quote($fields['billable']).", ".$mdb2->quote($fields['invoice']).", ".
947       $mdb2->quote($fields['paid_status']).", ".
948       $mdb2->quote($fields['users']).", ".$mdb2->quote($fields['period']).", ".
949       $mdb2->quote($fields['from']).", ".$mdb2->quote($fields['to']).", ".
950       $fields['chclient'].", ".$fields['chinvoice'].", ".$fields['chpaid'].", ".$fields['chip'].", ".
951       $fields['chproject'].", ".$fields['chstart'].", ".$fields['chduration'].", ".$fields['chcost'].", ".
952       $fields['chtask'].", ".$fields['chfinish'].", ".$fields['chnote'].", ".$fields['chcf_1'].", ".$fields['chunits'].", ".
953       $mdb2->quote($fields['group_by1']).", ".$mdb2->quote($fields['group_by2']).", ".
954       $mdb2->quote($fields['group_by3']).", ".$fields['chtotalsonly'].")";
955     $affected = $mdb2->exec($sql);
956     if (is_a($affected, 'PEAR_Error'))
957       return false;
958
959     $last_id = $mdb2->lastInsertID('tt_fav_reports', 'id');
960     return $last_id;
961   }
962
963   // insertNotification function inserts a new notification into database.
964   private function insertNotification($fields)
965   {
966     $mdb2 = getConnection();
967
968     $group_id = (int) $fields['group_id'];
969     $org_id = (int) $fields['org_id'];
970     $cron_spec = $fields['cron_spec'];
971     $last = (int) $fields['last'];
972     $next = (int) $fields['next'];
973     $report_id = (int) $fields['report_id'];
974     $email = $fields['email'];
975     $cc = $fields['cc'];
976     $subject = $fields['subject'];
977     $report_condition = $fields['report_condition'];
978     $status = $fields['status'];
979
980     $sql = "insert into tt_cron".
981       " (group_id, org_id, cron_spec, last, next, report_id, email, cc, subject, report_condition, status)".
982       " 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).")";
983     $affected = $mdb2->exec($sql);
984     return (!is_a($affected, 'PEAR_Error'));
985   }
986
987   // insertUserParam - a helper function to insert a user parameter.
988   private function insertUserParam($fields) {
989     $mdb2 = getConnection();
990
991     $group_id = (int) $fields['group_id'];
992     $org_id = (int) $fields['org_id'];
993     $user_id = (int) $fields['user_id'];
994     $param_name = $fields['param_name'];
995     $param_value = $fields['param_value'];
996
997     $sql = "insert into tt_config".
998       " (user_id, group_id, org_id, param_name, param_value)".
999       " values ($user_id, $group_id, $org_id, ".$mdb2->quote($param_name).", ".$mdb2->quote($param_value).")";
1000     $affected = $mdb2->exec($sql);
1001     return (!is_a($affected, 'PEAR_Error'));
1002   }
1003
1004   // insertCustomField - a helper function to insert a custom field.
1005   private function insertCustomField($fields) {
1006     $mdb2 = getConnection();
1007
1008     $group_id = (int) $fields['group_id'];
1009     $org_id = (int) $fields['org_id'];
1010     $type = (int) $fields['type'];
1011     $label = $fields['label'];
1012     $required = (int) $fields['required'];
1013     $status = $fields['status'];
1014
1015     $sql = "insert into tt_custom_fields".
1016       " (group_id, org_id, type, label, required, status)".
1017       " values($group_id, $org_id, $type, ".$mdb2->quote($label).", $required, ".$mdb2->quote($status).")";
1018     $affected = $mdb2->exec($sql);
1019     if (is_a($affected, 'PEAR_Error'))
1020       return false;
1021
1022     $last_id = $mdb2->lastInsertID('tt_custom_fields', 'id');
1023     return $last_id;
1024   }
1025
1026   // insertCustomFieldOption - a helper function to insert a custom field option.
1027   private function insertCustomFieldOption($fields) {
1028     $mdb2 = getConnection();
1029
1030     $group_id = (int) $fields['group_id'];
1031     $org_id = (int) $fields['org_id'];
1032     $field_id = (int) $fields['field_id'];
1033     $value = $fields['value'];
1034
1035     $sql = "insert into tt_custom_field_options (group_id, org_id, field_id, value)".
1036       " values ($group_id, $org_id, $field_id, ".$mdb2->quote($value).")";
1037     $affected = $mdb2->exec($sql);
1038     if (is_a($affected, 'PEAR_Error'))
1039       return false;
1040
1041     $last_id = $mdb2->lastInsertID('tt_custom_field_options', 'id');
1042     return $last_id;
1043   }
1044
1045   // insertLogEntry - a helper function to insert a time log entry.
1046   private function insertLogEntry($fields) {
1047     global $user;
1048     $mdb2 = getConnection();
1049
1050     $group_id = (int) $fields['group_id'];
1051     $org_id = (int) $fields['org_id'];
1052     $user_id = (int) $fields['user_id'];
1053     $date = $fields['date'];
1054     $start = $fields['start'];
1055     $duration = $fields['duration'];
1056     $client_id = $fields['client_id'];
1057     $project_id = $fields['project_id'];
1058     $task_id = $fields['task_id'];
1059     $invoice_id = $fields['invoice_id'];
1060     $comment = $fields['comment'];
1061     $billable = (int) $fields['billable'];
1062     $paid = (int) $fields['paid'];
1063     $status = $fields['status'];
1064
1065     $sql = "insert into tt_log".
1066       " (user_id, group_id, org_id, date, start, duration, client_id, project_id, task_id, invoice_id, comment".
1067       ", billable, paid, created, created_ip, created_by, status)".
1068       " values ($user_id, $group_id, $org_id".
1069       ", ".$mdb2->quote($date).
1070       ", ".$mdb2->quote($start).
1071       ", ".$mdb2->quote($duration).
1072       ", ".$mdb2->quote($client_id).
1073       ", ".$mdb2->quote($project_id).
1074       ", ".$mdb2->quote($task_id).
1075       ", ".$mdb2->quote($invoice_id).
1076       ", ".$mdb2->quote($comment).
1077       ", $billable, $paid".
1078       ", now(), ".$mdb2->quote($_SERVER['REMOTE_ADDR']).", ".$user->id.
1079       ", ". $mdb2->quote($status).")";
1080     $affected = $mdb2->exec($sql);
1081     if (is_a($affected, 'PEAR_Error')) {
1082       $this->errors->add($i18n->get('error.db')); // TODO: review whether or not to add error here in all insert calls.
1083       return false;
1084     }
1085
1086     $log_id = $mdb2->lastInsertID('tt_log', 'id');
1087     return $log_id;
1088   }
1089
1090   // insertCustomFieldLogEntry - a helper function to insert a custom field log entry.
1091   private function insertCustomFieldLogEntry($fields) {
1092     $mdb2 = getConnection();
1093
1094     $group_id = (int) $fields['group_id'];
1095     $org_id = (int) $fields['org_id'];
1096     $log_id = (int) $fields['log_id'];
1097     $field_id = (int) $fields['field_id'];
1098     $option_id = $fields['option_id'];
1099     $value = $fields['value'];
1100     $status = $fields['status'];
1101
1102     $sql = "insert into tt_custom_field_log (group_id, org_id, log_id, field_id, option_id, value, status)".
1103       " values ($group_id, $org_id, $log_id, $field_id, ".$mdb2->quote($option_id).", ".$mdb2->quote($value).", ".$mdb2->quote($status).")";
1104     $affected = $mdb2->exec($sql);
1105     return (!is_a($affected, 'PEAR_Error'));
1106   }
1107
1108   // getTopRole returns top role id.
1109   private function getTopRole() {
1110     $mdb2 = getConnection();
1111
1112     $sql = "select id from tt_roles where group_id = 0 and rank = ".MAX_RANK." and status = 1";
1113     $res = $mdb2->query($sql);
1114
1115     if (!is_a($res, 'PEAR_Error')) {
1116       $val = $res->fetchRow();
1117       if ($val['id'])
1118         return $val['id'];
1119     }
1120     return false;
1121   }
1122
1123   // The loginExists function detrmines if a login already exists.
1124   private function loginExists($login) {
1125     $mdb2 = getConnection();
1126
1127     $sql = "select id from tt_users where login = ".$mdb2->quote($login)." and (status = 1 or status = 0)";
1128     $res = $mdb2->query($sql);
1129     if (!is_a($res, 'PEAR_Error')) {
1130       if ($val = $res->fetchRow()) {
1131         return true;
1132       }
1133     }
1134     return false;
1135   }
1136 }