Starting to work on ttExportHelper2 class as part of subgroup support.
[timetracker.git] / WEB-INF / lib / ttExportHelper2.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 import('ttTeamHelper');
30 import('ttTimeHelper');
31
32 // ttExportHelper2 - this class is a future replacement for ttExportHelper.
33 // Currently, it is work in progress.
34 // When done, it should handle exporting of complex groups containing other groups.
35 class ttExportHelper2 {
36   // TODO: we need a constructor...
37   var $fileName    = null;    // Name of the file with data.
38
39   // The following arrays are maps between entity ids in the file versus the database.
40   // We write to the file sequentially (1,2,3...) while in the database the entities have different ids.
41   var $userMap     = array(); // User ids.
42   var $roleMap     = array(); // Role ids.
43   var $projectMap  = array(); // Project ids.
44   var $taskMap     = array(); // Task ids.
45   var $clientMap   = array(); // Client ids.
46   var $invoiceMap  = array(); // Invoice ids.
47   var $customFieldMap       = array(); // Custom field ids.
48   var $customFieldOptionMap = array(); // Custop field option ids.
49   var $logMap      = array(); // Time log ids.
50
51   // createDataFile creates a file with all data for a given group.
52   function createDataFile($compress = false) {
53     global $user;
54
55     // Create a temporary file.
56     $dirName = dirname(TEMPLATE_DIR . '_c/.');
57     $tmp_file = tempnam($dirName, 'tt');
58
59     // Open the file for writing.
60     $file = fopen($tmp_file, 'wb');
61     if (!$file) return false;
62
63     // Write XML to the file.
64     fwrite($file, "<?xml version=\"1.0\"?>\n");
65     fwrite($file, "<pack>\n");
66
67     // Write group info.
68     fwrite($file, "<group currency=\"".$user->currency."\" decimal_mark=\"".$user->decimal_mark."\" lang=\"".$user->lang.
69       "\" date_format=\"".$user->date_format."\" time_format=\"".$user->time_format."\" week_start=\"".$user->week_start.
70       "\" tracking_mode=\"".$user->tracking_mode."\" project_required=\"".$user->project_required."\" task_required=\"".$user->task_required.
71       "\" record_type=\"".$user->record_type."\" bcc_email=\"".$user->bcc_email.
72       "\" plugins=\"".$user->plugins."\" lock_spec=\"".$user->lock_spec."\" workday_minutes=\"".$user->workday_minutes.
73       "\" config=\"".$user->config.
74       "\">\n");
75     fwrite($file, "  <name><![CDATA[".$user->group_name."]]></name>\n");
76     fwrite($file, "  <allow_ip><![CDATA[".$user->allow_ip."]]></allow_ip>\n");
77     fwrite($file, "  <password_complexity><![CDATA[".$user->password_complexity."]]></password_complexity>\n");
78     fwrite($file, "</group>\n");
79
80     // Prepare role map.
81     $roles = $this->getRoles();
82     foreach ($roles as $key=>$role_item)
83       $this->roleMap[$role_item['id']] = $key + 1;
84
85     // Prepare user map.
86     $users = $this->getUsers();
87     foreach ($users as $key=>$user_item)
88       $this->userMap[$user_item['id']] = $key + 1;
89
90     // Prepare project map.
91     $projects = ttTeamHelper::getAllProjects($user->group_id, true);
92     foreach ($projects as $key=>$project_item)
93       $this->projectMap[$project_item['id']] = $key + 1;
94
95     // Prepare task map.
96     $tasks = ttTeamHelper::getAllTasks($user->group_id, true);
97     foreach ($tasks as $key=>$task_item)
98       $this->taskMap[$task_item['id']] = $key + 1;
99
100     // Prepare client map.
101     $clients = ttTeamHelper::getAllClients($user->group_id, true);
102     foreach ($clients as $key=>$client_item)
103       $this->clientMap[$client_item['id']] = $key + 1;
104
105     // Prepare invoice map.
106     $invoices = ttTeamHelper::getAllInvoices();
107     foreach ($invoices as $key=>$invoice_item)
108       $this->invoiceMap[$invoice_item['id']] = $key + 1;
109
110     // Prepare custom fields map.
111     $custom_fields = ttTeamHelper::getAllCustomFields($user->group_id);
112     foreach ($custom_fields as $key=>$custom_field)
113       $this->customFieldMap[$custom_field['id']] = $key + 1;
114
115     // Prepare custom field options map.
116     $custom_field_options = ttTeamHelper::getAllCustomFieldOptions($user->group_id);
117     foreach ($custom_field_options as $key=>$option)
118       $this->customFieldOptionMap[$option['id']] = $key + 1;
119
120     // Write roles.
121     fwrite($file, "<roles>\n");
122     foreach ($roles as $role) {
123       fwrite($file, "  <role id=\"".$this->roleMap[$role['id']]."\" rank=\"".$role['rank']."\"".
124         " rights=\"".$role['rights']."\" status=\"".$role['status']."\">\n");
125       fwrite($file, "    <name><![CDATA[".$role['name']."]]></name>\n");
126       fwrite($file, "  </role>\n");
127     }
128     fwrite($file, "</roles>\n");
129     unset($roles);
130
131     // Write users.
132     fwrite($file, "<users>\n");
133     foreach ($users as $user_item) {
134       $role_id = $user_item['rank'] == 512 ? 0 : $this->roleMap[$user_item['role_id']]; // Special role_id 0 (not null) for top manager.
135       fwrite($file, "  <user id=\"".$this->userMap[$user_item['id']]."\" login=\"".htmlentities($user_item['login'])."\" password=\"".$user_item['password']."\" role_id=\"".$role_id."\" client_id=\"".$this->clientMap[$user_item['client_id']]."\" rate=\"".$user_item['rate']."\" email=\"".$user_item['email']."\" status=\"".$user_item['status']."\">\n");
136       fwrite($file, "    <name><![CDATA[".$user_item['name']."]]></name>\n");
137       fwrite($file, "  </user>\n");
138     }
139     fwrite($file, "</users>\n");
140
141     // Write tasks.
142     fwrite($file, "<tasks>\n");
143     foreach ($tasks as $task_item) {
144       fwrite($file, "  <task id=\"".$this->taskMap[$task_item['id']]."\" status=\"".$task_item['status']."\">\n");
145       fwrite($file, "    <name><![CDATA[".$task_item['name']."]]></name>\n");
146       fwrite($file, "    <description><![CDATA[".$task_item['description']."]]></description>\n");
147       fwrite($file, "  </task>\n");
148     }
149     fwrite($file, "</tasks>\n");
150     unset($tasks);
151
152     // Write projects.
153     fwrite($file, "<projects>\n");
154     foreach ($projects as $project_item) {
155       if($project_item['tasks']){
156         $tasks = explode(',', $project_item['tasks']);
157         $tasks_mapped = array();
158         foreach ($tasks as $item)
159           $tasks_mapped[] = $this->taskMap[$item];
160         $tasks_str = implode(',', $tasks_mapped);
161       }
162       fwrite($file, "  <project id=\"".$this->projectMap[$project_item['id']]."\" tasks=\"".$tasks_str."\" status=\"".$project_item['status']."\">\n");
163       fwrite($file, "    <name><![CDATA[".$project_item['name']."]]></name>\n");
164       fwrite($file, "    <description><![CDATA[".$project_item['description']."]]></description>\n");
165       fwrite($file, "  </project>\n");
166     }
167     fwrite($file, "</projects>\n");
168     unset($projects);
169
170     // Write user to project binds.
171     fwrite($file, "<user_project_binds>\n");
172     $user_binds = ttTeamHelper::getUserToProjectBinds($user->group_id);
173     foreach ($user_binds as $bind) {
174       $user_id = $this->userMap[$bind['user_id']];
175       $project_id = $this->projectMap[$bind['project_id']];
176       fwrite($file, "  <user_project_bind user_id=\"{$user_id}\" project_id=\"{$project_id}\" rate=\"".$bind['rate']."\" status=\"".$bind['status']."\"/>\n");
177     }
178     fwrite($file, "</user_project_binds>\n");
179     unset($user_binds);
180
181     // Write clients.
182     fwrite($file, "<clients>\n");
183     foreach ($clients as $client_item) {
184       if($client_item['projects']){
185         $projects = explode(',', $client_item['projects']);
186         $projects_mapped = array();
187         foreach ($projects as $item)
188           $projects_mapped[] = $this->projectMap[$item];
189         $projects_str = implode(',', $projects_mapped);
190       }
191       fwrite($file, "  <client id=\"".$this->clientMap[$client_item['id']]."\" tax=\"".$client_item['tax']."\" projects=\"".$projects_str."\" status=\"".$client_item['status']."\">\n");
192       fwrite($file, "    <name><![CDATA[".$client_item['name']."]]></name>\n");
193       fwrite($file, "    <address><![CDATA[".$client_item['address']."]]></address>\n");
194       fwrite($file, "  </client>\n");
195     }
196     fwrite($file, "</clients>\n");
197     unset($clients);
198
199     // Write invoices.
200     fwrite($file, "<invoices>\n");
201     foreach ($invoices as $invoice_item) {
202       fwrite($file, "  <invoice id=\"".$this->invoiceMap[$invoice_item['id']]."\" date=\"".$invoice_item['date']."\" client_id=\"".$this->clientMap[$invoice_item['client_id']]."\" status=\"".$invoice_item['status']."\">\n");
203       fwrite($file, "    <name><![CDATA[".$invoice_item['name']."]]></name>\n");
204       fwrite($file, "  </invoice>\n");
205     }
206     fwrite($file, "</invoices>\n");
207     unset($invoices);
208
209     // Write custom fields.
210     fwrite($file, "<custom_fields>\n");
211     foreach ($custom_fields as $custom_field) {
212       fwrite($file, "  <custom_field id=\"".$this->customFieldMap[$custom_field['id']]."\" type=\"".$custom_field['type']."\" required=\"".$custom_field['required']."\" status=\"".$custom_field['status']."\">\n");
213       fwrite($file, "    <label><![CDATA[".$custom_field['label']."]]></label>\n");
214       fwrite($file, "  </custom_field>\n");
215     }
216     fwrite($file, "</custom_fields>\n");
217     unset($custom_fields);
218
219     // Write custom field options.
220     fwrite($file, "<custom_field_options>\n");
221     foreach ($custom_field_options as $option) {
222       fwrite($file, "  <custom_field_option id=\"".$this->customFieldOptionMap[$option['id']]."\" field_id=\"".$this->customFieldMap[$option['field_id']]."\">\n");
223       fwrite($file, "    <value><![CDATA[".$option['value']."]]></value>\n");
224       fwrite($file, "  </custom_field_option>\n");
225     }
226     fwrite($file, "</custom_field_options>\n");
227     unset($custom_field_options);
228
229     // Write monthly quotas.
230     $quotas = ttTeamHelper::getMonthlyQuotas($user->group_id);
231     fwrite($file, "<monthly_quotas>\n");
232     foreach ($quotas as $quota) {
233       fwrite($file, "  <monthly_quota year=\"".$quota['year']."\" month=\"".$quota['month']."\" minutes=\"".$quota['minutes']."\"/>\n");
234     }
235     fwrite($file, "</monthly_quotas>\n");
236
237     // Write time log entries.
238     fwrite($file, "<log>\n");
239     $key = 0;
240     foreach ($users as $user_item) {
241       $records = ttTimeHelper::getAllRecords($user_item['id']);
242       foreach ($records as $record) {
243         $key++;
244         $this->logMap[$record['id']] = $key;
245         fwrite($file, "  <log_item id=\"$key\" user_id=\"".$this->userMap[$record['user_id']]."\" date=\"".$record['date']."\" start=\"".$record['start']."\" finish=\"".$record['finish']."\" duration=\"".($record['start']?"":$record['duration'])."\" client_id=\"".$this->clientMap[$record['client_id']]."\" project_id=\"".$this->projectMap[$record['project_id']]."\" task_id=\"".$this->taskMap[$record['task_id']]."\" invoice_id=\"".$this->invoiceMap[$record['invoice_id']]."\" billable=\"".$record['billable']."\" paid=\"".$record['paid']."\" status=\"".$record['status']."\">\n");
246         fwrite($file, "    <comment><![CDATA[".$record['comment']."]]></comment>\n");
247         fwrite($file, "  </log_item>\n");
248       }
249     }
250     fwrite($file, "</log>\n");
251     unset($records);
252
253     // Write custom field log.
254     $custom_field_log = ttTeamHelper::getCustomFieldLog($user->group_id);
255     fwrite($file, "<custom_field_log>\n");
256     foreach ($custom_field_log as $entry) {
257       fwrite($file, "  <custom_field_log_entry log_id=\"".$this->logMap[$entry['log_id']]."\" field_id=\"".$this->customFieldMap[$entry['field_id']]."\" option_id=\"".$this->customFieldOptionMap[$entry['option_id']]."\" status=\"".$entry['status']."\">\n");
258       fwrite($file, "    <value><![CDATA[".$entry['value']."]]></value>\n");
259       fwrite($file, "  </custom_field_log_entry>\n");
260     }
261     fwrite($file, "</custom_field_log>\n");
262     unset($custom_field_log);
263
264     // Write expense items.
265     $expense_items = ttTeamHelper::getExpenseItems($user->group_id);
266     fwrite($file, "<expense_items>\n");
267     foreach ($expense_items as $expense_item) {
268       fwrite($file, "  <expense_item date=\"".$expense_item['date']."\" user_id=\"".$this->userMap[$expense_item['user_id']]."\" client_id=\"".$this->clientMap[$expense_item['client_id']]."\" project_id=\"".$this->projectMap[$expense_item['project_id']]."\" cost=\"".$expense_item['cost']."\" invoice_id=\"".$this->invoiceMap[$expense_item['invoice_id']]."\" paid=\"".$expense_item['paid']."\" status=\"".$expense_item['status']."\">\n");
269       fwrite($file, "    <name><![CDATA[".$expense_item['name']."]]></name>\n");
270       fwrite($file, "  </expense_item>\n");
271     }
272     fwrite($file, "</expense_items>\n");
273     unset($expense_items);
274
275     // Write fav reports.
276     fwrite($file, "<fav_reports>\n");
277     $fav_reports = ttTeamHelper::getFavReports($user->group_id);
278     foreach ($fav_reports as $fav_report) {
279       $user_list = '';
280       if (strlen($fav_report['users']) > 0) {
281         $arr = explode(',', $fav_report['users']);
282         foreach ($arr as $k=>$v) {
283           if (array_key_exists($arr[$k], $this->userMap))
284             $user_list .= (strlen($user_list) == 0? '' : ',').$this->userMap[$v];
285         }
286       }
287       fwrite($file, "  <fav_report user_id=\"".$this->userMap[$fav_report['user_id']]."\"".
288         " client_id=\"".$this->clientMap[$fav_report['client_id']]."\"".
289         " cf_1_option_id=\"".$this->customFieldOptionMap[$fav_report['cf_1_option_id']]."\"".
290         " project_id=\"".$this->projectMap[$fav_report['project_id']]."\"".
291         " task_id=\"".$this->taskMap[$fav_report['task_id']]."\"".
292         " billable=\"".$fav_report['billable']."\"".
293         " users=\"".$user_list."\"".
294         " period=\"".$fav_report['period']."\"".
295         " period_start=\"".$fav_report['period_start']."\"".
296         " period_end=\"".$fav_report['period_end']."\"".
297         " show_client=\"".$fav_report['show_client']."\"".
298         " show_invoice=\"".$fav_report['show_invoice']."\"".
299         " show_paid=\"".$fav_report['show_paid']."\"".
300         " show_ip=\"".$fav_report['show_ip']."\"".
301         " show_project=\"".$fav_report['show_project']."\"".
302         " show_start=\"".$fav_report['show_start']."\"".
303         " show_duration=\"".$fav_report['show_duration']."\"".
304         " show_cost=\"".$fav_report['show_cost']."\"".
305         " show_task=\"".$fav_report['show_task']."\"".
306         " show_end=\"".$fav_report['show_end']."\"".
307         " show_note=\"".$fav_report['show_note']."\"".
308         " show_custom_field_1=\"".$fav_report['show_custom_field_1']."\"".
309         " show_work_units=\"".$fav_report['show_work_units']."\"".
310         " group_by1=\"".$fav_report['group_by1']."\"".
311         " group_by2=\"".$fav_report['group_by2']."\"".
312         " group_by3=\"".$fav_report['group_by3']."\"".
313         " show_totals_only=\"".$fav_report['show_totals_only']."\">\n");
314       fwrite($file, "    <name><![CDATA[".$fav_report["name"]."]]></name>\n");
315       fwrite($file, "  </fav_report>\n");
316     }
317     fwrite($file, "</fav_reports>\n");
318     unset($fav_reports);
319
320     // Cleanup.
321     unset($users);
322     $this->roleMap = array();
323     $this->userMap = array();
324     $this->projectMap = array();
325     $this->taskMap = array();
326
327     fwrite($file, "</pack>\n");
328     fclose($file);
329
330     if ($compress) {
331       $this->fileName = tempnam($dirName, 'tt');
332       $this->compress($tmp_file, $this->fileName);
333       unlink($tmp_file);
334     } else
335       $this->fileName = $tmp_file;
336
337     return true;
338   }
339
340   // getFileName - returns file name.
341   function getFileName() {
342     return $this->fileName;
343   }
344
345   // compress - compresses the content of the $in file into $out file.
346   function compress($in, $out) {
347     // Initial checks of file names and permissions.
348     if (!file_exists($in) || !is_readable ($in))
349       return false;
350     if ((!file_exists($out) && !is_writable(dirname($out))) || (file_exists($out) && !is_writable($out)))
351       return false;
352
353     $in_file = fopen($in, 'rb');
354
355     if (function_exists('bzopen')) {
356       if (!$out_file = bzopen($out, 'w'))
357         return false;
358
359       while (!feof ($in_file)) {
360         $buffer = fread($in_file, 4096);
361         bzwrite($out_file, $buffer, 4096);
362       }
363       bzclose($out_file);
364     }
365     fclose ($in_file);
366     return true;
367   }
368
369   /*
370    * Note about the utility functions below.
371    * We have roughly 4 groups of operations:
372    *   1) Regular system usage for tracking time, etc.
373    *   2) Registration process - used infrequently.
374    *   3) Admin usage - used infrequently.
375    *   4) Export - used infrequently.
376    *
377    * It is tempting to have a generic function to get things done for
378    * all situations. However, as registration, export and admin access are one-off
379    * operations, while regular system usage is daily and must be efficient,
380    * the current approach is to have SEPARATE functions for each mode.
381    *
382    * This is because each mode requires a slightly different approach,
383    * and we don't want to over-complicate things.
384    */
385
386   // getRoles - obtains all roles defined for group.
387   function getRoles() {
388     global $user;
389     $mdb2 = getConnection();
390
391     $result = array();
392     $sql = "select * from tt_roles where group_id = $user->group_id";
393     $res = $mdb2->query($sql);
394     $result = array();
395     if (!is_a($res, 'PEAR_Error')) {
396       while ($val = $res->fetchRow()) {
397         $result[] = $val;
398       }
399       return $result;
400     }
401     return false;
402   }
403
404   // The getUsers obtains all users in group for the purpose of export.
405   function getUsers() {
406     global $user;
407     $mdb2 = getConnection();
408
409     $sql = "select u.*, r.rank from tt_users u left join tt_roles r on (u.role_id = r.id) where u.group_id = $user->group_id order by upper(u.name)"; // Note: deleted users are included.
410     $res = $mdb2->query($sql);
411     $result = array();
412     if (!is_a($res, 'PEAR_Error')) {
413       while ($val = $res->fetchRow()) {
414         $result[] = $val;
415       }
416       return $result;
417     }
418     return false;
419   }
420 }