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