More work in progress on attachment delete.
[timetracker.git] / WEB-INF / lib / ttFileHelper.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 // ttFileHelper class is used for attachment handling.
30 class ttFileHelper {
31   var $errors = null;       // Errors go here. Set in constructor by reference.
32   var $storage_uri = null;  // Location of file storage facility.
33   var $register_uri = null; // URI to register with file storage facility.
34   var $putfile_uri = null;  // URI to put file in file storage.
35   var $getfile_uri = null;  // URI to get file from file storage.
36   var $site_id = null;      // Site id for file storage.
37   var $site_key = null;     // Site key for file storage.
38
39   // Constructor.
40   function __construct(&$errors) {
41     $this->errors = &$errors;
42
43     if (defined('FILE_STORAGE_URI')) {
44       $this->storage_uri = FILE_STORAGE_URI;
45       $this->register_uri = $this->storage_uri.'register';
46       $this->putfile_uri = $this->storage_uri.'putfile';
47       $this->getfile_uri = $this->storage_uri.'getfile';
48       $this->checkSiteRegistration();
49     }
50   }
51
52   // checkSiteRegistration - obtains site id and key from local database.
53   // If not found, it tries to register with file storage facility.
54   function checkSiteRegistration() {
55
56     global $i18n;
57     $mdb2 = getConnection();
58
59     // Obtain site id.
60     $sql = "select param_value as id from tt_site_config where param_name = 'locker_id'";
61     $res = $mdb2->query($sql);
62     $val = $res->fetchRow();
63     if (!$val) {
64       // No site id found, need to register.
65       $fields = array('name' => urlencode('time tracker'),
66         'origin' => urlencode('time tracker source'));
67
68       // Urlify the data for the POST.
69       foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
70       $fields_string = rtrim($fields_string, '&');
71
72       // Open connection.
73       $ch = curl_init();
74
75       // Set the url, number of POST vars, POST data.
76       curl_setopt($ch, CURLOPT_URL, $this->register_uri);
77       curl_setopt($ch, CURLOPT_POST, count($fields));
78       curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
79       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
80
81       // Execute a post request.
82       $result = curl_exec($ch);
83
84       // Close connection.
85       curl_close($ch);
86
87       $result_array = json_decode($result, true);
88       if (!$result_array) {
89         $this->errors->add($i18n->get('error.file_storage'));
90       }
91       else if ($result_array['error']) {
92         // Add an error from file storage facility if we have it.
93         $this->errors->add($result_array['error']);
94       }
95       else if ($result_array['id'] && $result_array['key']) {
96         $this->site_id = $result_array['id'];
97         $this->site_key = $result_array['key'];
98
99         // Registration successful. Store id and key locally for future use.
100         $sql = "insert into tt_site_config values('locker_id', $this->site_id, now(), null)";
101         $mdb2->exec($sql);
102         $sql = "insert into tt_site_config values('locker_key', ".$mdb2->quote($this->site_key).", now(), null)";
103         $mdb2->exec($sql);
104       } else {
105         $this->errors->add($i18n->get('error.file_storage'));
106       }
107     } else {
108       // Site id found.
109       $this->site_id = $val['id'];
110
111       // Obtain site key.
112       $sql = "select param_value as site_key from tt_site_config where param_name = 'locker_key'";
113       $res = $mdb2->query($sql);
114       $val = $res->fetchRow();
115       $this->site_key = $val['site_key'];
116     }
117   }
118
119   // putFile - puts uploaded file in remote storage.
120   function putFile($fields) {
121     global $i18n;
122     global $user;
123     $mdb2 = getConnection();
124
125     $group_id = $user->getGroup();
126     $org_id = $user->org_id;
127
128     $curl_fields = array('site_id' => urlencode($this->site_id),
129       'site_key' => urlencode($this->site_key),
130       'org_id' => urlencode($org_id),
131       'org_key' => urlencode($this->getOrgKey()),
132       'group_id' => urlencode($group_id),
133       'group_key' => urlencode($this->getGroupKey()),
134       'user_id' => urlencode($fields['user_id']),   // May be null.
135       'user_key' => urlencode($fields['user_key']), // May be null.
136       'file_name' => urlencode($fields['file_name']),
137       'description' => urlencode($fields['description']),
138       'content' => urlencode(file_get_contents($_FILES['newfile']['tmp_name']))
139     );
140
141     // url-ify the data for the POST.
142     foreach($curl_fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
143     $fields_string = rtrim($fields_string, '&');
144
145     // Open connection.
146     $ch = curl_init();
147
148     // Set the url, number of POST vars, POST data.
149     curl_setopt($ch, CURLOPT_URL, $this->putfile_uri);
150     curl_setopt($ch, CURLOPT_POST, count($fields));
151     curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
152     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
153
154     // Execute a post request.
155     $result = curl_exec($ch);
156
157     // Close connection.
158     curl_close($ch);
159
160     // Delete uploaded file.
161     unlink($_FILES['newfile']['tmp_name']);
162
163     if (!$result) {
164       $this->errors->add($i18n->get('error.file_storage'));
165       return false;
166     }
167
168     $result_array = json_decode($result, true);
169     $file_id = (int) $result_array['file_id'];
170     $file_key = $result_array['file_key'];
171     $error = $result_array['error'];
172
173     if ($error || !$file_id || !$file_key) {
174       if ($error) {
175         // Add an error from file storage facility if we have it.
176         $this->errors->add($error);
177       }
178       return false;
179     }
180
181     // File put was successful. Store file attributes locally.
182     $entity_type = $mdb2->quote($fields['entity_type']);
183     $entity_id = (int) $fields['entity_id'];
184     $file_name = $mdb2->quote($fields['file_name']);
185     $description = $mdb2->quote($fields['description']);
186     $created = 'now()';
187     $created_ip = $mdb2->quote($_SERVER['REMOTE_ADDR']);
188     $created_by = $user->id;
189
190     $columns = '(group_id, org_id, remote_id, entity_type, entity_id, file_name, description, created, created_ip, created_by)';
191     $values = "values($group_id, $org_id, $file_id, $entity_type, $entity_id, $file_name, $description, $created, $created_ip, $created_by)";
192     $sql = "insert into tt_files $columns $values";
193     $affected = $mdb2->exec($sql);
194     return (!is_a($affected, 'PEAR_Error'));
195   }
196
197   // deleteFile - deletes a file from remote storage and its details from local database.
198   function deleteFile($fields) {
199     global $i18n;
200     global $user;
201     $mdb2 = getConnection();
202
203     $group_id = $user->getGroup();
204     $org_id = $user->org_id;
205
206     $curl_fields = array('site_id' => urlencode($this->site_id),
207       'site_key' => urlencode($this->site_key),
208       'org_id' => urlencode($org_id),
209       'org_key' => urlencode($this->getOrgKey()),
210       'group_id' => urlencode($group_id),
211       'group_key' => urlencode($this->getGroupKey()),
212       'user_id' => urlencode($fields['user_id']),   // May be null.
213       'user_key' => urlencode($fields['user_key']), // May be null.
214       'file_id' => urlencode($fields['remote_id']),
215       'file_key' => urlencode($fields['file_key'])
216     );
217
218     // url-ify the data for the POST.
219     foreach($curl_fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
220     $fields_string = rtrim($fields_string, '&');
221
222     // Open connection.
223     $ch = curl_init();
224
225     // Set the url, number of POST vars, POST data.
226     curl_setopt($ch, CURLOPT_URL, $this->putfile_uri);
227     curl_setopt($ch, CURLOPT_POST, count($fields));
228     curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
229     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
230
231     // Execute a post request.
232     $result = curl_exec($ch);
233
234     // Close connection.
235     curl_close($ch);
236
237     if (!$result) {
238       $this->errors->add($i18n->get('error.file_storage'));
239       return false;
240     }
241
242     $result_array = json_decode($result, true);
243     // $status = (int) $result_array['status'];
244     $error = $result_array['error'];
245
246     if ($error) {
247       // Add an error from file storage facility if we have it.
248       $this->errors->add($error);
249       return false;
250     }
251
252     // Delete file reference from database.
253     $file_id = $file['id'];
254     $sql = "delete from tt_files".
255       " where id = $file_id and org_id = $org_id and group_id = $group_id";
256     $affected = $mdb2->exec($sql);
257     if (is_a($affected, 'PEAR_Error')) {
258       $err->add($i18n->get('error.db'));
259       return false;
260     }
261
262     return true;
263   }
264
265   // getOrgKey obtains organization key from the database.
266   private function getOrgKey() {
267     global $user;
268     $mdb2 = getConnection();
269
270     $org_id = $user->org_id;
271     $sql = "select group_key from tt_groups where id = $org_id and status = 1";
272     $res = $mdb2->query($sql);
273     $val = $res->fetchRow();
274     return $val['group_key'];
275   }
276
277   // getGrtoupKey obtains group key from the database.
278   private function getGroupKey() {
279     global $user;
280     $mdb2 = getConnection();
281
282     $group_id = $user->getGroup();
283     $org_id = $user->org_id;
284
285     $sql = "select group_key from tt_groups where id = $group_id and org_id = $org_id and status = 1";
286     $res = $mdb2->query($sql);
287     $val = $res->fetchRow();
288     return $val['group_key'];
289   }
290
291   // getProjectFiles obtains a list of files for a project.
292   function getProjectFiles($project_id) {
293     global $user;
294     $mdb2 = getConnection();
295
296     $group_id = $user->getGroup();
297     $org_id = $user->org_id;
298
299     $result = array();
300     $sql = "select id, remote_id, file_name as name, description from tt_files".
301       " where entity_type = 'project' and entity_id = $project_id".
302       " and group_id = $group_id and org_id = $org_id and status = 1 order by id";
303     $res = $mdb2->query($sql);
304     if (!is_a($res, 'PEAR_Error')) {
305       while ($val = $res->fetchRow()) {
306         $result[] = $val;
307       }
308     }
309     return $result;
310   }
311
312   // get - obtains file details from local database. 
313   static function get($id) {
314     global $user;
315     $mdb2 = getConnection();
316
317     $group_id = $user->getGroup();
318     $org_id = $user->org_id;
319
320     $sql = "select id, remote_id, file_key, entity_type, entity_id, file_name, description, status from tt_files".
321       " where id = $id and group_id = $group_id and org_id = $org_id and (status = 0 or status = 1)";
322     $res = $mdb2->query($sql);
323     if (!is_a($res, 'PEAR_Error')) {
324       $val = $res->fetchRow();
325       if ($val && $val['id'])
326         return $val;
327     }
328     return false;
329   }
330 }