Completed
Push — master ( 98c16a...17e47f )
by Julito
36:20
created

StudentPublicationLink::is_valid_link()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 0
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Gradebook link to student publication item
6
 * @author Bert Steppé
7
 * @package chamilo.gradebook
8
 */
9
class StudentPublicationLink extends AbstractLink
10
{
11
    private $studpub_table = null;
12
    private $itemprop_table = null;
13
14
    /**
15
     * Constructor
16
     */
17
    public function __construct()
18
    {
19
        parent::__construct();
20
        $this->set_type(LINK_STUDENTPUBLICATION);
21
    }
22
23
	/**
24
	 *
25
	 * Returns the URL of a document
26
	 * This function is loaded when using a gradebook as a tab (gradebook = -1)
27
	 * see issue #2705
28
	 *
29
	 */
30
	public function get_view_url($stud_id)
31
	{
32
        return null;
33
		// find a file uploaded by the given student,
34
		// with the same title as the evaluation name
35
36
		$eval = $this->get_evaluation();
0 ignored issues
show
Unused Code introduced by
// find a file uploaded ...this->get_evaluation(); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
37
		$stud_id = intval($stud_id);
38
        $itemProperty = $this->get_itemprop_table();
39
        $workTable = $this->get_studpub_table();
40
        $courseId = $this->course_id;
41
42
        $sql = "SELECT pub.url
43
                FROM $itemProperty prop INNER JOIN $workTable pub
44
                ON (prop.c_id = pub.c_id AND prop.ref = pub.id)
45
                WHERE
46
                    prop.c_id = ".$courseId." AND
47
                    pub.c_id = ".$courseId." AND
48
                    prop.tool = 'work' AND 
49
                    prop.insert_user_id = $stud_id AND                     
50
                    pub.title = '".Database::escape_string($eval->get_name())."' AND 
51
                    pub.session_id=".api_get_session_id();
52
53
		$result = Database::query($sql);
54
		if ($fileurl = Database::fetch_row($result)) {
55
			return null;
56
		} else {
57
			return null;
58
		}
59
	}
60
61
    /**
62
     * @return string
63
     */
64
	public function get_type_name()
65
	{
66
		return get_lang('Works');
67
	}
68
69
	public function is_allowed_to_change_name()
70
	{
71
		return false;
72
	}
73
74
	/**
75
	 * Generate an array of exercises that a teacher hasn't created a link for.
76
	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
77
	 */
78 View Code Duplication
	public function get_not_created_links()
79
	{
80
		return false;
81
		if (empty($this->course_code)) {
0 ignored issues
show
Unused Code introduced by
if (empty($this->course_...ourse code not set'); } does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
82
			die('Error in get_not_created_links() : course code not set');
83
		}
84
		$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
85
86
		$sql = 'SELECT id, url from '.$this->get_studpub_table()
87
			.' pup WHERE c_id = '.$this->course_id.' AND has_properties != '."''".' AND id NOT IN'
88
			.' (SELECT ref_id FROM '.$tbl_grade_links
89
			.' WHERE type = '.LINK_STUDENTPUBLICATION
90
			." AND c_id = '".intval($this->course_id)."'"
91
			.') AND pub.session_id='.api_get_session_id().'';
92
93
		$result = Database::query($sql);
94
95
		$cats=array();
96
        while ($data = Database::fetch_array($result)) {
97
            $cats[] = array($data['id'], $data['url']);
98
		}
99
		return $cats;
100
	}
101
102
	/**
103
	 * Generate an array of all exercises available.
104
	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
105
	 */
106
	public function get_all_links()
107
	{
108
		if (empty($this->course_code)) {
109
			die('Error in get_not_created_links() : course code not set');
110
		}
111
        $em = Database::getManager();
112
        $session = $em->find('ChamiloCoreBundle:Session', api_get_session_id());
113
		/*
114
        if (empty($session_id)) {
115
            $session_condition = api_get_session_condition(0, true);
116
        } else {
117
            $session_condition = api_get_session_condition($session_id, true, true);
118
        }
119
        $sql = "SELECT id, url, title FROM $tbl_grade_links
120
                WHERE c_id = {$this->course_id}  AND filetype='folder' AND active = 1 $session_condition ";*/
121
122
		//Only show works from the session
123
		//AND has_properties != ''
124
        $links = $em
125
            ->getRepository('ChamiloCourseBundle:CStudentPublication')
126
            ->findBy([
127
                'cId' => $this->course_id,
128
                'active' => true,
129
                'filetype' => 'folder',
130
                'session' => $session
131
            ]);
132
133
        foreach ($links as $data) {
134
            $work_name = $data->getTitle();
135
			if (empty($work_name)) {
136
                $work_name = basename($data->getUrl());
137
			}
138
            $cats[] = array ($data->getId(), $work_name);
139
		}
140
		$cats=isset($cats) ? $cats : array();
141
		return $cats;
142
	}
143
144
	/**
145
	 * Has anyone done this exercise yet ?
146
	 */
147
	public function has_results()
148
	{
149
        $data = $this->get_exercise_data();
150
151
        if (empty($data)) {
152
            return '';
153
        }
154
        $id = $data['id'];
155
156
        $em = Database::getManager();
157
        $session = $em->find('ChamiloCoreBundle:Session', api_get_session_id());
158
        $results = $em
159
            ->getRepository('ChamiloCourseBundle:CStudentPublication')
160
            ->findBy([
161
                'cId' => $this->course_id,
162
                'parentId' => $id,
163
                'session' => $session
164
            ]);
165
166
        return count($results) != 0;
167
	}
168
169
	/**
170
	 * @param null $stud_id
171
	 * @return array|null
172
	 */
173
	public function calc_score($stud_id = null, $type = null)
174
	{
175
        $stud_id = (int) $stud_id;
176
        $em = Database::getManager();
177
        $data = $this->get_exercise_data();
178
179
        if (empty($data)) {
180
            return '';
181
        }
182
        $id = $data['id'];
183
184
        $session = $em->find('ChamiloCoreBundle:Session', api_get_session_id());
185
186
        $assignment = $em
187
            ->getRepository('ChamiloCourseBundle:CStudentPublication')
188
            ->findOneBy([
189
                'cId' => $this->course_id,
190
                'id' => $id,
191
                'session' => $session
192
            ])
193
		;
194
195
        $parentId = !$assignment ? 0 : $assignment->getId();
196
197
        if (empty($session)) {
198
           $dql = 'SELECT a FROM ChamiloCourseBundle:CStudentPublication a
199
                   WHERE
200
                        a.cId = :course AND
201
                        a.active = :active AND
202
                        a.parentId = :parent AND
203
                        a.session is null AND
204
                        a.qualificatorId <> 0
205
                    ';
206
207
            $params = [
208
                'course' => $this->course_id,
209
                'parent' => $parentId,
210
                'active' => true
211
            ];
212
		} else {
213
            $dql = 'SELECT a FROM ChamiloCourseBundle:CStudentPublication a
214
                    WHERE
215
                        a.cId = :course AND
216
                        a.active = :active AND
217
                        a.parentId = :parent AND
218
                        a.session = :session AND
219
                        a.qualificatorId <> 0
220
                    ';
221
222
            $params = [
223
                'course' => $this->course_id,
224
                'parent' => $parentId,
225
                'session' => $session,
226
                'active' => true,
227
            ];
228
		}
229
230
		if (!empty($stud_id)) {
231
            $dql .= ' AND a.userId = :student ';
232
            $params['student'] = $stud_id;
233
		}
234
235
        $order = api_get_setting('student_publication_to_take_in_gradebook');
236
237
		switch ($order) {
238
			case 'last':
239
				// latest attempt
240
                $dql .= ' ORDER BY a.sentDate DESC';
241
				break;
242
			case 'first':
243
			default:
244
				// first attempt
245
                $dql .= ' ORDER BY a.id';
246
				break;
247
		}
248
249
        $scores = $em->createQuery($dql)->execute($params);
250
251
		// for 1 student
252
		if (!empty($stud_id)) {
253
            if (!count($scores)) {
254
				return '';
255
			}
256
            $data = $scores[0];
257
258
            return [
259
                $data->getQualification(),
260
                $assignment->getQualification()
261
            ];
262
        }
263
			$students = array();  // user list, needed to make sure we only
264
			// take first attempts into account
265
			$rescount = 0;
266
			$sum = 0;
267
			$bestResult = 0;
268
			$weight = 0;
269
			$sumResult = 0;
270
271
        foreach ($scores as $data) {
272
            if (!(array_key_exists($data->getUserId(), $students))) {
273
                if ($assignment->getQualification() != 0) {
274
                    $students[$data->getUserId()] = $data->getQualification();
275
						$rescount++;
276
                    $sum += $data->getQualification() / $assignment->getQualification();
277
                    $sumResult += $data->getQualification();
278
279
                    if ($data->getQualification() > $bestResult) {
280
                        $bestResult = $data->getQualification();
281
						}
282
                    $weight = $assignment->getQualification();
283
					}
284
				}
285
			}
286
287
			if ($rescount == 0) {
288
				return null;
289
            }
290
			switch ($type) {
291
				case 'best':
292
					return array($bestResult, $weight);
293
					break;
294
				case 'average':
295
					return array($sumResult/$rescount, $weight);
296
					break;
297
				case 'ranking':
298
					return AbstractLink::getCurrentUserRanking($stud_id, $students);
299
					break;
300
				default:
301
					return array($sum, $rescount);
302
					break;
303
		    }
304
	}
305
306
	/**
307
	 * Lazy load function to get the database table of the student publications
308
	 */
309
	private function get_studpub_table()
310
	{
311
		return $this->studpub_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
312
	}
313
314
	/**
315
	 * Lazy load function to get the database table of the item properties
316
	 */
317
	private function get_itemprop_table()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
318
	{
319
		return $this->itemprop_table = Database :: get_course_table(TABLE_ITEM_PROPERTY);
320
	}
321
322
	public function needs_name_and_description()
323
	{
324
		return false;
325
	}
326
327
	public function get_name()
328
	{
329
		$this->get_exercise_data();
330
        $name = isset($this->exercise_data['title']) && !empty($this->exercise_data['title']) ? $this->exercise_data['title'] : get_lang('Untitled');
331
        return $name;
332
	}
333
334
	public function get_description()
335
	{
336
		$this->get_exercise_data();
337
		return isset($this->exercise_data['description']) ? $this->exercise_data['description'] : null;
338
	}
339
340
	public function get_test_id()
341
	{
342
		return 'DEBUG:ID';
343
	}
344
345
	public function get_link()
346
	{
347
		$session_id = api_get_session_id();
348
        $url = api_get_path(WEB_PATH).'main/work/work.php?'.api_get_cidreq_params($this->get_course_code(), $session_id).'&id='.$this->exercise_data['id'].'&gradebook=view';
349
		return $url;
350
	}
351
352
    /**
353
     * @return array
354
     */
355
	private function get_exercise_data()
356
	{
357
		$course_info = api_get_course_info($this->get_course_code());
358
        if (!isset($this->exercise_data)) {
359
			$sql = 'SELECT * FROM '.$this->get_studpub_table()."
360
					WHERE
361
					 	c_id ='".$course_info['real_id']."' AND
362
                        id = '".$this->get_ref_id()."' ";
363
            $query = Database::query($sql);
364
            $this->exercise_data = Database::fetch_array($query);
365
366
            // Try with iid
367 View Code Duplication
            if (empty($this->exercise_data)) {
368
                $sql = 'SELECT * FROM '.$this->get_studpub_table()."
369
                        WHERE
370
                            c_id ='".$course_info['real_id']."' AND
371
                            iid = '".$this->get_ref_id()."' ";
372
			    $query = Database::query($sql);
373
			    $this->exercise_data = Database::fetch_array($query);
374
		    }
375
        }
376
		return $this->exercise_data;
377
	}
378
379
	public function needs_max()
380
	{
381
		return false;
382
	}
383
384
	public function needs_results()
385
	{
386
		return false;
387
	}
388
389
	public function is_valid_link()
390
	{
391
        $data = $this->get_exercise_data();
392
393
        if (empty($data)) {
394
            return '';
395
        }
396
        $id = $data['id'];
397
		$sql = 'SELECT count(id) FROM '.$this->get_studpub_table().'
398
                WHERE 
399
                    c_id = "'.$this->course_id.'" AND 
400
                    id = '.$id.'';
401
		$result = Database::query($sql);
402
		$number = Database::fetch_row($result);
403
		return ($number[0] != 0);
404
	}
405
406
	public function get_icon_name()
407
	{
408
		return 'studentpublication';
409
	}
410
411
	public function save_linked_data()
412
	{
413
        $data = $this->get_exercise_data();
414
415
        if (empty($data)) {
416
            return '';
417
        }
418
        $id = $data['id'];
419
420
        $weight = (float) $this->get_weight();
421
        if (!empty($id)) {
422
			//Cleans works
423
            $sql = 'UPDATE '.$this->get_studpub_table().' 
424
                    SET weight= '.$weight.'
425
                    WHERE c_id = '.$this->course_id.' AND id ='.$id;
426
			Database::query($sql);
427
		}
428
	}
429
430 View Code Duplication
	public function delete_linked_data()
431
	{
432
        $data = $this->get_exercise_data();
433
434
        if (empty($data)) {
435
            return '';
436
        }
437
438
        if (!empty($id)) {
0 ignored issues
show
Bug introduced by
The variable $id seems to never exist, and therefore empty should always return true. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
439
			//Cleans works
440
            $sql = 'UPDATE '.$this->get_studpub_table().' 
441
                    SET weight=0
442
                    WHERE c_id = '.$this->course_id.' AND id ='.$id;
443
			Database::query($sql);
444
		}
445
	}
446
}
447