Passed
Push — 1.10.x ( e22269...acc912 )
by
unknown
49:56
created

Dropbox_Person::deleteAllReceivedWork()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 13
Ratio 100 %
Metric Value
dl 13
loc 13
rs 9.4285
cc 2
eloc 8
nc 2
nop 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Dropbox module for Chamilo
6
 * Classes for the dropbox module.
7
 *
8
 * 3 classes have been defined:
9
 * - Dropbox_Work:
10
 * 		. id
11
 * 		. uploader_id	=> who sent it
12
 * 		. uploaderName
13
 * 		. filename		=> name of file stored on the server
14
 * 		. filesize
15
 * 		. title			=> name of file returned to user. This is the original name of the file
16
 * 							except when the original name contained spaces. In that case the spaces
17
 * 							will be replaced by _
18
 * 		. description
19
 * 		. author
20
 * 		. upload_date	=> date when file was first sent
21
 * 		. last_upload_date => date when file was last sent
22
 *  	. isOldWork 	=> has the work already been uploaded before
23
 *
24
 *      . feedback_date  => date of most recent feedback
25
 *      . feedback      => feedback text (or HTML?)
26
 *
27
 * - Dropbox_SentWork extends Dropbox_Work
28
 * 		. recipients	=> array of ["id"]["name"] lists the recipients of the work
29
 *
30
 * - Dropbox_Person:
31
 * 		. userId
32
 * 		. receivedWork 	=> array of Dropbox_Work objects
33
 * 		. sentWork 		=> array of Dropbox_SentWork objects
34
 * 		. isCourseTutor
35
 * 		. isCourseAdmin
36
 * 		. _orderBy		=> private property used for determining the field by which the works have to be ordered
37
 *
38
 * @version 1.30
39
 * @copyright 2004
40
 * @author Jan Bols <[email protected]>
41
 * with contributions by René Haentjens <[email protected]>
42
 * @package chamilo.dropbox
43
 */
44
class Dropbox_Work
45
{
46
    public $id;
47
    public $uploader_id;
48
    public $uploaderName;
49
    public $filename;
50
    public $filesize;
51
    public $title;
52
    public $description;
53
    public $author;
54
    public $upload_date;
55
    public $last_upload_date;
56
    public $isOldWork;
57
    public $feedback_date, $feedback;
0 ignored issues
show
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
58
59
    /**
60
     * Constructor calls private functions to create a new work or retreive an existing work from DB
61
     * depending on the number of parameters
62
     *
63
     * @param unknown_type $arg1
64
     * @param unknown_type $arg2
65
     * @param unknown_type $arg3
66
     * @param unknown_type $arg4
67
     * @param unknown_type $arg5
68
     * @param unknown_type $arg6
69
     * @return Dropbox_Work
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
70
     */
71
    public function __construct($arg1, $arg2 = null, $arg3 = null, $arg4 = null, $arg5 = null, $arg6 = null)
72
    {
73
        if (func_num_args() > 1) {
74
            $this->_createNewWork($arg1, $arg2, $arg3, $arg4, $arg5, $arg6);
0 ignored issues
show
Bug introduced by
It seems like $arg2 defined by parameter $arg2 on line 71 can also be of type null; however, Dropbox_Work::_createNewWork() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
Bug introduced by
It seems like $arg3 defined by parameter $arg3 on line 71 can also be of type null; however, Dropbox_Work::_createNewWork() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
Bug introduced by
It seems like $arg4 defined by parameter $arg4 on line 71 can also be of type null; however, Dropbox_Work::_createNewWork() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
Bug introduced by
It seems like $arg5 defined by parameter $arg5 on line 71 can also be of type null; however, Dropbox_Work::_createNewWork() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
Bug introduced by
It seems like $arg6 defined by parameter $arg6 on line 71 can also be of type null; however, Dropbox_Work::_createNewWork() does only seem to accept integer, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
75
        } else {
76
            $this->_createExistingWork($arg1);
77
        }
78
    }
79
80
	/**
81
	 * private function creating a new work object
82
	 *
83
	 * @param int $uploader_id
84
	 * @param string $title
85
	 * @param string $description
86
	 * @param string $author
87
	 * @param string $filename
88
	 * @param int $filesize
89
	 *
90
	 * @todo 	$author was originally a field but this has now been replaced by the first and lastname of the uploader (to prevent anonymous uploads)
91
	 * 			As a consequence this parameter can be removed
92
	 */
93
	public function _createNewWork($uploader_id, $title, $description, $author, $filename, $filesize)
94
    {
95
        $dropbox_cnf = getDropboxConf();
96
97
        // Fill in the properties
98
        $this->uploader_id = intval($uploader_id);
99
        $this->uploaderName = getUserNameFromId($this->uploader_id);
100
        $this->filename = $filename;
101
        $this->filesize = $filesize;
102
        $this->title = $title;
103
        $this->description = $description;
104
        $this->author = $author;
105
        $this->last_upload_date = api_get_utc_datetime();
106
        $course_id = api_get_course_int_id();
107
108
        // Check if object exists already. If it does, the old object is used
109
        // with updated information (authors, description, upload_date)
110
        $this->isOldWork = false;
111
		$sql = "SELECT id, upload_date FROM ".$dropbox_cnf['tbl_file']."
112
				WHERE c_id = $course_id AND filename = '".Database::escape_string($this->filename)."'";
113
        $result = Database::query($sql);
114
		$res = Database::fetch_array($result);
115
		if ($res) {
116
			$this->isOldWork = true;
117
		}
118
		// Insert or update the dropbox_file table and set the id property
119
		if ($this->isOldWork) {
120
			$this->id = $res['id'];
121
			$this->upload_date = $res['upload_date'];
122
123
            $params = [
124
                'filesize' => $this->filesize,
125
                'title' => $this->title,
126
                'description' => $this->description,
127
                'author' => $this->author,
128
                'last_upload_date' => $this->last_upload_date,
129
                'session_id' => api_get_session_id(),
130
            ];
131
132
            Database::update(
133
                $dropbox_cnf['tbl_file'],
134
                $params,
135
                ['c_id = ? AND id = ?' => [$course_id, $this->id]]
136
            );
137
138
		} else {
139
			$this->upload_date = $this->last_upload_date;
140
			$params = [
141
                'c_id' => $course_id,
142
                'uploader_id' => $this->uploader_id,
143
                'filename' => $this->filename,
144
                'filesize' => $this->filesize,
145
                'title' => $this->title,
146
                'description' => $this->description,
147
                'author' => $this->author,
148
                'upload_date' => $this->upload_date,
149
                'last_upload_date' => $this->last_upload_date,
150
                'session_id' => api_get_session_id(),
151
                'cat_id' => 0
152
			];
153
154
			$this->id = Database::insert($dropbox_cnf['tbl_file'], $params);
155
			if ($this->id) {
156
				$sql = "UPDATE ".$dropbox_cnf['tbl_file']." SET id = iid WHERE iid = {$this->id}";
157
				Database::query($sql);
158
			}
159
		}
160
161
        $sql = "SELECT count(file_id) as count
162
        		FROM ".$dropbox_cnf['tbl_person']."
163
				WHERE c_id = $course_id AND file_id = ".intval($this->id)." AND user_id = ".$this->uploader_id;
164
        $result = Database::query($sql);
165
        $row = Database::fetch_array($result);
166
        if ($row['count'] == 0) {
167
168
            // Insert entries into person table
169
            $sql = "INSERT INTO ".$dropbox_cnf['tbl_person']." (c_id, file_id, user_id)
170
                    VALUES ($course_id, ".intval($this->id)." , ".intval($this->uploader_id).")";
171
            Database::query($sql);
172
        }
173
	}
174
175
	/**
176
	 * private function creating existing object by retreiving info from db
177
	 *
178
	 * @param int $id
179
	 */
180
	public function _createExistingWork($id)
181
    {
182
	    $course_id = api_get_course_int_id();
183
        $dropbox_cnf = getDropboxConf();
184
185
        $action = isset($_GET['action']) ? $_GET['action'] : null;
186
187
        // Do some sanity checks
188
        $id	= intval($id);
189
190
        // Get the data from DB
191
        $sql = "SELECT uploader_id, filename, filesize, title, description, author, upload_date, last_upload_date, cat_id
192
                FROM ".$dropbox_cnf['tbl_file']."
193
                WHERE c_id = $course_id AND id = ".$id."";
194
        $result = Database::query($sql);
195
        $res = Database::fetch_array($result, 'ASSOC');
196
197
        // Check if uploader is still in Chamilo system
198
        $uploader_id = stripslashes($res['uploader_id']);
199
        $uploaderName = getUserNameFromId($uploader_id);
200
        if (!$uploaderName) {
201
            //deleted user
202
            $this->uploader_id = -1;
203
            $this->uploaderName = get_lang('Unknown', '');
204
        } else {
205
            $this->uploader_id = $uploader_id;
206
            $this->uploaderName = $uploaderName;
207
        }
208
209
        // Fill in properties
210
        $this->id = $id;
211
        $this->filename = stripslashes($res['filename']);
212
        $this->filesize = stripslashes($res['filesize']);
213
        $this->title = stripslashes($res['title']);
214
        $this->description = stripslashes($res['description']);
215
        $this->author = stripslashes($res['author']);
216
        $this->upload_date = stripslashes($res['upload_date']);
217
        $this->last_upload_date = stripslashes($res['last_upload_date']);
218
        $this->category = $res['cat_id'];
219
220
        // Getting the feedback on the work.
221
        if ($action == 'viewfeedback' AND $this->id == $_GET['id']) {
222
            $feedback2 = array();
223
            $sql_feedback = "SELECT * FROM ".$dropbox_cnf['tbl_feedback']."
224
                             WHERE c_id = $course_id AND file_id='".$id."' ORDER BY feedback_id ASC";
225
            $result = Database::query($sql_feedback);
226 View Code Duplication
            while ($row_feedback = Database::fetch_array($result)) {
227
                $row_feedback['feedback'] = Security::remove_XSS($row_feedback['feedback']);
228
                $feedback2[] = $row_feedback;
229
            }
230
            $this->feedback2= $feedback2;
231
        }
232
	}
233
}
234
235
class Dropbox_SentWork extends Dropbox_Work
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
236
{
237
	public $recipients;	//array of ['id']['name'] arrays
238
239
	/**
240
	 * Constructor calls private functions to create a new work or retreive an existing work from DB
241
	 * depending on the number of parameters
242
	 *
243
	 * @param unknown_type $arg1
244
	 * @param unknown_type $arg2
245
	 * @param unknown_type $arg3
246
	 * @param unknown_type $arg4
247
	 * @param unknown_type $arg5
248
	 * @param unknown_type $arg6
249
	 * @param unknown_type $arg7
250
	 * @return Dropbox_SentWork
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
251
	 */
252
	public function __construct($arg1, $arg2 = null, $arg3 = null, $arg4 = null, $arg5 = null, $arg6 = null, $arg7 = null)
253
    {
254
		if (func_num_args() > 1) {
255
		    $this->_createNewSentWork($arg1, $arg2, $arg3, $arg4, $arg5, $arg6, $arg7);
0 ignored issues
show
Bug introduced by
It seems like $arg2 defined by parameter $arg2 on line 252 can also be of type null; however, Dropbox_SentWork::_createNewSentWork() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
Bug introduced by
It seems like $arg3 defined by parameter $arg3 on line 252 can also be of type null; however, Dropbox_SentWork::_createNewSentWork() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
Bug introduced by
It seems like $arg4 defined by parameter $arg4 on line 252 can also be of type null; however, Dropbox_SentWork::_createNewSentWork() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
Bug introduced by
It seems like $arg5 defined by parameter $arg5 on line 252 can also be of type null; however, Dropbox_SentWork::_createNewSentWork() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
Bug introduced by
It seems like $arg6 defined by parameter $arg6 on line 252 can also be of type null; however, Dropbox_SentWork::_createNewSentWork() does only seem to accept integer, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
Bug introduced by
It seems like $arg7 defined by parameter $arg7 on line 252 can also be of type null; however, Dropbox_SentWork::_createNewSentWork() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
256
		} else {
257
			$this->_createExistingSentWork($arg1);
258
		}
259
	}
260
261
	/**
262
	 * private function creating a new SentWork object
263
	 *
264
	 * @param int $uploader_id
265
	 * @param string $title
266
	 * @param string $description
267
	 * @param string $author
268
	 * @param string $filename
269
	 * @param int $filesize
270
	 * @param array $recipient_ids
271
	 */
272
	public function _createNewSentWork($uploader_id, $title, $description, $author, $filename, $filesize, $recipient_ids)
273
    {
274
        $dropbox_cnf = getDropboxConf();
275
        $_course = api_get_course_info();
276
277
		// Call constructor of Dropbox_Work object
278
        parent::__construct(
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (__construct() instead of _createNewSentWork()). Are you sure this is correct? If so, you might want to change this to $this->__construct().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
279
            $uploader_id,
280
            $title,
281
            $description,
282
            $author,
283
            $filename,
284
            $filesize
285
        );
286
287
		$course_id = api_get_course_int_id();
288
289
		// Do sanity checks on recipient_ids array & property fillin
290
		// The sanity check for ex-coursemembers is already done in base constructor
291
		settype($uploader_id, 'integer') or die(get_lang('GeneralError').' (code 208)'); // Set $uploader_id to correct type
292
293
		$justSubmit = false;
294
		if ( is_int($recipient_ids)) {
295
			$justSubmit = true;
296
			$recipient_ids = array($recipient_ids + $this->id);
297
		} elseif ( count($recipient_ids) == 0) {
298
			$justSubmit = true;
299
			$recipient_ids = array($uploader_id);
300
		}
301
302
		if (! is_array($recipient_ids) || count($recipient_ids) == 0) {
303
			die(get_lang('GeneralError').' (code 209)');
304
		}
305
306
		foreach ($recipient_ids as $rec) {
307
			if (empty($rec)) die(get_lang('GeneralError').' (code 210)');
308
			//if (!isCourseMember($rec)) die(); //cannot sent document to someone outside of course
309
				//this check is done when validating submitted data
310
			$this->recipients[] = array('id' => $rec, 'name' => getUserNameFromId($rec));
311
		}
312
313
        $table_post = $dropbox_cnf['tbl_post'];
314
        $table_person = $dropbox_cnf['tbl_person'];
315
        $session_id = api_get_session_id();
316
        $uploader_id = $this->uploader_id;
317
        $user  = api_get_user_id();
318
        $now = api_get_utc_datetime();
319
320
		// Insert data in dropbox_post and dropbox_person table for each recipient
321
		foreach ($this->recipients as $rec) {
322
            $file_id = (int)$this->id;
323
            $user_id = (int)$rec['id'];
324
			$sql = "INSERT INTO $table_post (c_id, file_id, dest_user_id, session_id, feedback_date, cat_id)
325
                    VALUES ($course_id, $file_id, $user_id, $session_id, '$now', 0)";
326
	        Database::query($sql);
327
            // If work already exists no error is generated
328
329
            /**
330
             * Poster is already added when work is created - not so good to split logic
331
             */
332
            if ($user_id != $user) {
333
                // Insert entries into person table
334
                $sql = "INSERT INTO $table_person (c_id, file_id, user_id)
335
                        VALUES ($course_id, $file_id, $user_id)";
336
337
                // Do not add recipient in person table if mailing zip or just upload.
338
                if (!$justSubmit) {
339
                    Database::query($sql);	// If work already exists no error is generated
340
                }
341
            }
342
343
			// Update item_property table for each recipient
344
			if (($ownerid = $this->uploader_id) > $dropbox_cnf['mailingIdBase']) {
345
			    $ownerid = getUserOwningThisMailing($ownerid);
346
			}
347
			if (($recipid = $rec["id"]) > $dropbox_cnf['mailingIdBase']) {
348
			    $recipid = $ownerid;  // mailing file recipient = mailing id, not a person
349
			}
350
            api_item_property_update(
351
                $_course,
352
                TOOL_DROPBOX,
353
                $this->id,
354
                'DropboxFileAdded',
355
                $ownerid,
356
                null,
357
                $recipid
358
            );
359
		}
360
	}
361
362
	/**
363
	 * private function creating existing object by retreiving info from db
364
	 *
365
	 * @param unknown_type $id
366
	 */
367
	public function _createExistingSentWork($id)
368
    {
369
        $dropbox_cnf = getDropboxConf();
370
        $id = intval($id);
371
372
		$course_id = api_get_course_int_id();
373
374
		// Call constructor of Dropbox_Work object
375
		parent::__construct($id);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (__construct() instead of _createExistingSentWork()). Are you sure this is correct? If so, you might want to change this to $this->__construct().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
376
377
		// Fill in recipients array
378
		$this->recipients = array();
379
		$sql = "SELECT dest_user_id, feedback_date, feedback
380
				FROM ".$dropbox_cnf['tbl_post']."
381
				WHERE c_id = $course_id AND file_id = ".intval($id)."";
382
        $result = Database::query($sql);
383
		while ($res = Database::fetch_array($result, 'ASSOC')) {
384
385
			// Check for deleted users
386
			$dest_user_id = $res['dest_user_id'];
387
			$user_info = api_get_user_info($dest_user_id);
388
			//$this->category = $res['cat_id'];
389
			if (!$user_info) {
390
				$this->recipients[] = array('id' => -1, 'name' => get_lang('Unknown', ''));
391
			} else {
392
				$this->recipients[] = array(
393
                    'id' => $dest_user_id,
394
                    'name' => $user_info['complete_name'],
395
                    'user_id' => $dest_user_id,
396
				    'feedback_date' => $res['feedback_date'],
397
                    'feedback' => $res['feedback']
398
                );
399
			}
400
		}
401
	}
402
}
403
404
class Dropbox_Person
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
405
{
406
	// The receivedWork and the sentWork arrays are sorted.
407
	public $receivedWork;	// an array of Dropbox_Work objects
408
	public $sentWork;		// an array of Dropbox_SentWork objects
409
410
	public $userId = 0;
411
	public $isCourseAdmin = false;
412
	public $isCourseTutor = false;
413
	public $_orderBy = '';	// private property that determines by which field
414
415
	/**
416
	 * Constructor for recreating the Dropbox_Person object
417
	 *
418
	 * @param int $userId
419
	 * @param bool $isCourseAdmin
420
	 * @param bool $isCourseTutor
421
	 * @return Dropbox_Person
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
422
	 */
423
	public function __construct($userId, $isCourseAdmin, $isCourseTutor)
424
    {
425
	    $course_id = api_get_course_int_id();
426
427
		// Fill in properties
428
        $this->userId = $userId;
429
        $this->isCourseAdmin = $isCourseAdmin;
430
        $this->isCourseTutor = $isCourseTutor;
431
        $this->receivedWork = array();
432
        $this->sentWork = array();
433
434
		// Note: perhaps include an ex coursemember check to delete old files
435
436
		$session_id = api_get_session_id();
437
		$condition_session = api_get_session_condition($session_id);
438
439
		$post_tbl = Database::get_course_table(TABLE_DROPBOX_POST);
440
		$person_tbl = Database::get_course_table(TABLE_DROPBOX_PERSON);
441
		$file_tbl = Database::get_course_table(TABLE_DROPBOX_FILE);
442
443
        // Find all entries where this person is the recipient
444
		$sql = "SELECT DISTINCT r.file_id, r.cat_id
445
                FROM $post_tbl r
446
                INNER JOIN $person_tbl p
447
                    ON (r.file_id = p.file_id AND r.c_id = $course_id AND p.c_id = $course_id )
448
                WHERE
449
                     p.user_id = ".intval($this->userId)." AND
450
                     r.dest_user_id = ".intval($this->userId)." $condition_session ";
451
452
        $result = Database::query($sql);
453
		while ($res = Database::fetch_array($result)) {
454
			$temp = new Dropbox_Work($res['file_id']);
455
			$temp->category = $res['cat_id'];
456
			$this->receivedWork[] = $temp;
457
		}
458
		// Find all entries where this person is the sender/uploader
459
        $sql = "SELECT DISTINCT f.id
460
				FROM $file_tbl f
461
				INNER JOIN $person_tbl p
462
				ON (f.id = p.file_id AND f.c_id = $course_id AND p.c_id = $course_id)
463
                WHERE
464
                    f.uploader_id   = ".intval($this->userId)." AND
465
                    p.user_id       = ".intval($this->userId)."
466
                    $condition_session
467
                ";
468
        $result = Database::query($sql);
469
		while ($res = Database::fetch_array($result)) {
470
			$this->sentWork[] = new Dropbox_SentWork($res['id']);
471
		}
472
	}
473
474
	/**
475
	 * This private method is used by the usort function in  the
476
	 * orderSentWork and orderReceivedWork methods.
477
	 * It compares 2 work-objects by 1 of the properties of that object, dictated by the
478
	 * private property _orderBy
479
	 *
480
	 * @param unknown_type $a
481
	 * @param unknown_type $b
482
	 * @return -1, 0 or 1 dependent of the result of the comparison.
0 ignored issues
show
Documentation introduced by
The doc-type -1, could not be parsed: Unknown type name "-1" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
483
	 */
484
	function _cmpWork($a, $b)
485
    {
486
		$sort = $this->_orderBy;
487
		$aval = $a->$sort;
488
		$bval = $b->$sort;
489
		if ($sort == 'recipients') {
490
		    // The recipients property is an array so we do the comparison based
491
		    // on the first item of the recipients array
492
		    $aval = $aval[0]['name'];
493
			$bval = $bval[0]['name'];
494
		}
495
		if ($sort == 'filesize') {    // Filesize is not a string, so we use other comparison technique
496
			return $aval < $bval ? -1 : 1;
497
		} elseif ($sort == 'title') { // Natural order for sorting titles is more "human-friendly"
498
			return api_strnatcmp($aval, $bval);
499
		} else {
500
		    return api_strcasecmp($aval, $bval);
501
		}
502
	}
503
504
	/**
505
	 * A method that sorts the objects in the sentWork array, dependent on the $sort parameter.
506
	 * $sort can be lastDate, firstDate, title, size, ...
507
	 *
508
	 * @param unknown_type $sort
509
	 */
510 View Code Duplication
	function orderSentWork($sort)
511
    {
512
		switch($sort) {
513
			case 'lastDate':
514
				$this->_orderBy = 'last_upload_date';
515
				break;
516
			case 'firstDate':
517
				$this->_orderBy = 'upload_date';
518
				break;
519
			case 'title':
520
				$this->_orderBy = 'title';
521
				break;
522
			case 'size':
523
				$this->_orderBy = 'filesize';
524
				break;
525
			case 'author':
526
				$this->_orderBy = 'author';
527
				break;
528
			case 'recipient':
529
				$this->_orderBy = 'recipients';
530
				break;
531
			default:
532
				$this->_orderBy = 'last_upload_date';
533
		}
534
535
		usort($this->sentWork, array($this, '_cmpWork'));
536
	}
537
538
	/**
539
	 * method that sorts the objects in the receivedWork array, dependent on the $sort parameter.
540
	 * $sort can be lastDate, firstDate, title, size, ...
541
	 * @param unknown_type $sort
542
	 */
543 View Code Duplication
	function orderReceivedWork($sort)
544
    {
545
		switch($sort) {
546
			case 'lastDate':
547
				$this->_orderBy = 'last_upload_date';
548
				break;
549
			case 'firstDate':
550
				$this->_orderBy = 'upload_date';
551
				break;
552
			case 'title':
553
				$this->_orderBy = 'title';
554
				break;
555
			case 'size':
556
				$this->_orderBy = 'filesize';
557
				break;
558
			case 'author':
559
				$this->_orderBy = 'author';
560
				break;
561
			case 'sender':
562
				$this->_orderBy = 'uploaderName';
563
				break;
564
			default:
565
				$this->_orderBy = 'last_upload_date';
566
		}
567
568
		usort($this->receivedWork, array($this, '_cmpWork'));
569
	}
570
571
	/**
572
	 * Deletes all the received work of this person
573
	 */
574 View Code Duplication
	function deleteAllReceivedWork()
575
    {
576
	    $course_id = api_get_course_int_id();
577
        $dropbox_cnf = getDropboxConf();
578
		// Delete entries in person table concerning received works
579
		foreach ($this->receivedWork as $w) {
580
            $sql = "DELETE FROM ".$dropbox_cnf['tbl_person']."
581
			        WHERE c_id = $course_id AND user_id='".$this->userId."' AND file_id='".$w->id."'";
582
			Database::query($sql);
583
		}
584
        // Check for unused files
585
		removeUnusedFiles();
586
	}
587
588
	/**
589
	 * Deletes all the received categories and work of this person
590
	 */
591
	function deleteReceivedWorkFolder($id)
592
    {
593
        $dropbox_cnf = getDropboxConf();
594
        $course_id = api_get_course_int_id();
595
596
		$id = intval($id);
597
		$sql = "DELETE FROM ".$dropbox_cnf['tbl_file']."
598
		        WHERE c_id = $course_id AND cat_id = '".$id."' ";
599
		if (!Database::query($sql)) return false;
600
		$sql = "DELETE FROM ".$dropbox_cnf['tbl_category']."
601
		        WHERE c_id = $course_id AND cat_id = '".$id."' ";
602
		if (!Database::query($sql)) return false;
603
		$sql = "DELETE FROM ".$dropbox_cnf['tbl_post']."
604
		        WHERE c_id = $course_id AND cat_id = '".$id."' ";
605
		if (!Database::query($sql)) return false;
606
		return true;
607
	}
608
609
	/**
610
	 * Deletes a received dropbox file of this person with id=$id
611
	 *
612
	 * @param integer $id
613
	 */
614 View Code Duplication
	function deleteReceivedWork($id)
615
    {
616
	    $course_id = api_get_course_int_id();
617
        $dropbox_cnf = getDropboxConf();
618
		$id = intval($id);
619
620
		// index check
621
		$found = false;
622
		foreach ($this->receivedWork as $w) {
623
			if ($w->id == $id) {
624
			   $found = true;
625
			   break;
626
			}
627
		}
628
629
		if (!$found) {
630
			if (!$this->deleteReceivedWorkFolder($id)) {
631
				die(get_lang('GeneralError').' (code 216)');
632
			}
633
		}
634
		// Delete entries in person table concerning received works
635
        $sql = "DELETE FROM ".$dropbox_cnf['tbl_person']."
636
                WHERE c_id = $course_id AND user_id = '".$this->userId."' AND file_id ='".$id."'";
637
		Database::query($sql);
638
		removeUnusedFiles();	// Check for unused files
639
	}
640
641
	/**
642
	 * Deletes all the sent dropbox files of this person
643
	 */
644 View Code Duplication
	function deleteAllSentWork()
645
    {
646
	    $course_id = api_get_course_int_id();
647
        $dropbox_cnf = getDropboxConf();
648
		//delete entries in person table concerning sent works
649
		foreach ($this->sentWork as $w) {
650
            $sql = "DELETE FROM ".$dropbox_cnf['tbl_person']."
651
                    WHERE c_id = $course_id AND user_id='".$this->userId."' AND file_id='".$w->id."'";
652
			Database::query($sql);
653
			removeMoreIfMailing($w->id);
654
		}
655
		removeUnusedFiles();	// Check for unused files
656
	}
657
658
	/**
659
	 * Deletes a sent dropbox file of this person with id=$id
660
	 *
661
	 * @param unknown_type $id
662
	 */
663 View Code Duplication
	function deleteSentWork($id)
664
    {
665
	    $course_id = api_get_course_int_id();
666
        $dropbox_cnf = getDropboxConf();
667
668
		$id = intval($id);
669
670
		// index check
671
		$found = false;
672
		foreach ($this->sentWork as $w) {
673
			if ($w->id == $id) {
674
			   $found = true;
675
			   break;
676
			}
677
		}
678
		if (!$found) {
679
			if (!$this->deleteReceivedWorkFolder($id)) {
680
				die(get_lang('GeneralError').' (code 219)');
681
			}
682
		}
683
		//$file_id = $this->sentWork[$index]->id;
684
		// Delete entries in person table concerning sent works
685
        $sql = "DELETE FROM ".$dropbox_cnf['tbl_person']."
686
                WHERE c_id = $course_id AND user_id='".$this->userId."' AND file_id='".$id."'";
687
		Database::query($sql);
688
		removeMoreIfMailing($id);
689
		removeUnusedFiles();	// Check for unused files
690
	}
691
692
	/**
693
	 * Updates feedback for received work of this person with id=$id
694
	 *
695
	 * @param string $id
696
	 * @param string $text
697
	 */
698
	function updateFeedback($id, $text)
699
    {
700
	    $course_id = api_get_course_int_id();
701
        $_course = api_get_course_info();
702
        $dropbox_cnf = getDropboxConf();
703
704
		$id = intval($id);
705
706
		// index check
707
		$found = false;
708
		$wi = -1;
709
		foreach ($this->receivedWork as $w) {
710
			$wi++;
711
			if ($w->id == $id){
712
			   $found = true;
713
			   break;
714
			}  // foreach (... as $wi -> $w) gives error 221! (no idea why...)
715
		}
716
		if (!$found) {
717
			die(get_lang('GeneralError').' (code 221)');
718
		}
719
720
		$feedback_date = api_get_utc_datetime();
721
		$this->receivedWork[$wi]->feedback_date = $feedback_date;
722
		$this->receivedWork[$wi]->feedback = $text;
723
724
        $params = [
725
            'feedback_date' => $feedback_date,
726
            'feedback' => $text,
727
        ];
728
        Database::update(
729
            $dropbox_cnf['tbl_post'],
730
            $params,
731
            [
732
                'c_id = ? AND dest_user_id = ? AND file_id = ?' => [
733
                    $course_id,
734
                    $this->userId,
735
                    $id,
736
                ],
737
            ]
738
        );
739
740
		// Update item_property table
741
742
		if (($ownerid = $this->receivedWork[$wi]->uploader_id) > $dropbox_cnf['mailingIdBase']) {
743
		    $ownerid = getUserOwningThisMailing($ownerid);
744
		}
745
        api_item_property_update(
746
            $_course,
747
            TOOL_DROPBOX,
748
            $this->receivedWork[$wi]->id,
749
            'DropboxFileUpdated',
750
            $this->userId,
751
            null,
752
            $ownerid
753
        );
754
755
	}
756
757
	/**
758
	 * Filter the received work
759
	 * @param string $type
760
	 * @param string $value
761
	 */
762
	function filter_received_work($type, $value)
763
    {
764
        $dropbox_cnf = getDropboxConf();
765
    	$new_received_work = array();
766
		foreach ($this->receivedWork as $work) {
767
			switch ($type) {
768
				case 'uploader_id':
769
					if ($work->uploader_id == $value ||
770
						($work->uploader_id > $dropbox_cnf['mailingIdBase'] &&
771
                        getUserOwningThisMailing($work->uploader_id) == $value)
772
                    ) {
773
						$new_received_work[] = $work;
774
					}
775
					break;
776
				default:
777
					$new_received_work[] = $work;
778
			}
779
		}
780
		$this->receivedWork = $new_received_work;
781
	}
782
}
783