Passed
Push — 1.10.x ( 6b51fa...7f42c3 )
by
unknown
49:18
created

TestCategory::getQuestionsByCat()   C

Complexity

Conditions 14
Paths 42

Size

Total Lines 78
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 78
rs 5.1581
cc 14
eloc 46
nc 42
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class TestCategory
6
 * @author hubert.borderiou
7
 * @author Julio Montoya - several fixes
8
 * @todo rename to ExerciseCategory
9
 */
10
class TestCategory
11
{
12
    public $id;
13
    public $name;
14
    public $description;
15
16
	/**
17
	 * Constructor of the class Category
18
	 * If you give an in_id and no in_name, you get info concerning the category of id=in_id
19
	 * otherwise, you've got an category objet avec your in_id, in_name, in_descr
20
	 *
21
     * @param int    $id
22
     * @param string $name
23
     * @param string $description
24
     *
25
     * @author - Hubert Borderiou
26
     */
27
    public function __construct($id = 0, $name = '', $description = "")
28
    {
29
        if ($id != 0 && $name == "") {
30
            $obj = new TestCategory();
31
            $obj->getCategory($id);
32
            $this->id = $obj->id;
33
            $this->name = $obj->name;
34
            $this->description = $obj->description;
35
        } else {
36
            $this->id = $id;
37
            $this->name = $name;
38
            $this->description = $description;
39
        }
40
    }
41
42
    /**
43
     * return the TestCategory object with id=in_id
44
     * @param int $id
45
     *
46
     * @return TestCategory
47
     */
48
    public function getCategory($id)
49
    {
50
        $table = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
51
        $id = intval($id);
52
        $sql = "SELECT * FROM $table
53
                WHERE id = $id AND c_id=".api_get_course_int_id();
54
        $res = Database::query($sql);
55
56
        if (Database::num_rows($res)) {
57
            $row = Database::fetch_array($res);
58
            $this->id = $row['id'];
59
            $this->name = $row['title'];
60
            $this->description  = $row['description'];
61
        }
62
    }
63
64
	/**
65
     * add TestCategory in the database if name doesn't already exists
66
	 */
67
    public function addCategoryInBDD()
68
    {
69
        $table = Database :: get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
70
        $v_name = $this->name;
71
        $v_name = Database::escape_string($v_name);
72
        $v_description = $this->description;
73
        $v_description = Database::escape_string($v_description);
74
        // check if name already exists
75
        $sql = "SELECT count(*) AS nb FROM $table
76
                WHERE title = '$v_name' AND c_id=".api_get_course_int_id();
77
        $result_verif = Database::query($sql);
78
        $data_verif = Database::fetch_array($result_verif);
79
        // lets add in BDD if not the same name
80
        if ($data_verif['nb'] <= 0) {
81
            $c_id = api_get_course_int_id();
82
            $params = [
83
                'c_id' => $c_id,
84
                'title' => $v_name,
85
                'description' => $v_description,
86
            ];
87
            $new_id = Database::insert($table, $params);
88
89
            if ($new_id) {
90
91
                $sql = "UPDATE $table SET id = iid WHERE iid = $new_id";
92
                Database::query($sql);
93
94
                // add test_category in item_property table
95
                $course_id = api_get_course_int_id();
96
                $course_info = api_get_course_info_by_id($course_id);
97
                api_item_property_update(
98
                    $course_info,
99
                    TOOL_TEST_CATEGORY,
100
                    $new_id,
101
                    'TestCategoryAdded',
102
                    api_get_user_id()
103
                );
104
            }
105
106
            return $new_id;
107
        } else {
108
109
            return false;
110
        }
111
	}
112
113
	/**
114
     * Removes the category from the database
115
     * if there were question in this category, the link between question and category is removed
116
	 */
117
    public function removeCategory()
118
    {
119
        $table = Database :: get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
120
        $tbl_question_rel_cat = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
121
        $v_id = intval($this->id);
122
        $course_id = api_get_course_int_id();
123
124
        $sql = "DELETE FROM $table
125
                WHERE id= $v_id AND c_id=".$course_id;
126
        $result = Database::query($sql);
127
        if (Database::affected_rows($result) <= 0) {
128
            return false;
129
        } else {
130
            // remove link between question and category
131
            $sql2 = "DELETE FROM $tbl_question_rel_cat
132
                     WHERE category_id = $v_id AND c_id=".$course_id;
133
            Database::query($sql2);
134
            // item_property update
135
            $course_info = api_get_course_info_by_id($course_id);
136
            api_item_property_update(
137
                $course_info,
138
                TOOL_TEST_CATEGORY,
139
                $this->id,
140
                'TestCategoryDeleted',
141
                api_get_user_id()
142
            );
143
144
            return true;
145
        }
146
	}
147
148
	/**
149
     * Modify category name or description of category with id=in_id
150
	 */
151
    public function modifyCategory()
152
    {
153
        $table = Database :: get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
154
        $v_id = intval($this->id);
155
        $v_name = Database::escape_string($this->name);
156
        $v_description = Database::escape_string($this->description);
157
        $sql = "UPDATE $table SET
158
                title = '$v_name',
159
                description = '$v_description'
160
                WHERE id = $v_id AND c_id=".api_get_course_int_id();
161
        $result = Database::query($sql);
162
        if (Database::affected_rows($result) <= 0) {
163
            return false;
164
        } else {
165
            // item_property update
166
            $course_id = api_get_course_int_id();
167
            $course_info = api_get_course_info_by_id($course_id);
168
            api_item_property_update(
169
                $course_info,
170
                TOOL_TEST_CATEGORY,
171
                $this->id,
172
                'TestCategoryModified',
173
                api_get_user_id()
174
            );
175
176
            return true;
177
        }
178
	}
179
180
	/**
181
     * Gets the number of question of category id=in_id
182
	 */
183
    public function getCategoryQuestionsNumber()
184
    {
185
		$table = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
186
		$in_id = intval($this->id);
187
		$sql = "SELECT count(*) AS nb
188
		        FROM $table
189
		        WHERE category_id=$in_id AND c_id=".api_get_course_int_id();
190
		$res = Database::query($sql);
191
		$row = Database::fetch_array($res);
192
193
		return $row['nb'];
194
	}
195
196
    /**
197
     * @param string $in_color
198
     */
199
    public function display($in_color="#E0EBF5")
200
    {
201
		echo "<textarea style='background-color:$in_color; width:60%; height:100px;'>";
202
		print_r($this);
203
		echo "</textarea>";
204
	}
205
206
	/**
207
     * Return an array of all Category objects in the database
208
	 * If in_field=="" Return an array of all category objects in the database
209
	 * Otherwise, return an array of all in_field value
210
	 * in the database (in_field = id or name or description)
211
	 */
212
    public static function getCategoryListInfo($in_field = "", $courseId = "")
213
    {
214
        if (empty($courseId) || $courseId=="") {
215
            $courseId = api_get_course_int_id();
216
        }
217
        $table = Database :: get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
218
        $in_field = Database::escape_string($in_field);
219
        $tabres = array();
220
        if ($in_field == "") {
221
            $sql = "SELECT * FROM $table
222
                    WHERE c_id=$courseId ORDER BY title ASC";
223
            $res = Database::query($sql);
224
            while ($row = Database::fetch_array($res)) {
225
                $tmpcat = new TestCategory(
226
                    $row['id'],
227
                    $row['title'],
228
                    $row['description']
229
                );
230
                $tabres[] = $tmpcat;
231
            }
232
        } else {
233
            $sql = "SELECT $in_field FROM $table
234
                    WHERE c_id = $courseId
235
                    ORDER BY $in_field ASC";
236
            $res = Database::query($sql);
237
            while ($row = Database::fetch_array($res)) {
238
                $tabres[] = $row[$in_field];
239
            }
240
        }
241
242
		return $tabres;
243
	}
244
245
    /**
246
     * Return the TestCategory id for question with question_id = $questionId
247
     * In this version, a question has only 1 TestCategory.
248
     * Return the TestCategory id, 0 if none
249
     * @param int $questionId
250
     * @param int $courseId
251
     *
252
     * @return int
253
     */
254 View Code Duplication
	public static function getCategoryForQuestion($questionId, $courseId ="")
255
    {
256
		$result = 0;
257
        if (empty($courseId) || $courseId == "") {
258
            $courseId = api_get_course_int_id();
259
        }
260
		$table = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
261
        $questionId = intval($questionId);
262
		$sql = "SELECT category_id
263
		        FROM $table
264
		        WHERE question_id = $questionId AND c_id = $courseId";
265
		$res = Database::query($sql);
266
		if (Database::num_rows($res) > 0) {
267
            $data = Database::fetch_array($res);
268
			$result = $data['category_id'];
269
		}
270
271
		return $result;
272
	}
273
274
	/**
275
	 * true if question id has a category
276
	 */
277
	public static function isQuestionHasCategory($questionId)
278
    {
279
		if (TestCategory::getCategoryForQuestion($questionId) > 0) {
280
			return true;
281
		}
282
		return false;
283
	}
284
285
	/**
286
	 Return the category name for question with question_id = $questionId
287
	 In this version, a question has only 1 category.
288
	 Return the category id, "" if none
289
	 */
290
    public static function getCategoryNameForQuestion(
291
        $questionId,
292
        $courseId = ""
293
    ) {
294
		if (empty($courseId) || $courseId=="") {
295
			$courseId = api_get_course_int_id();
296
		}
297
		$catid = TestCategory::getCategoryForQuestion($questionId, $courseId);
298
		$result = "";	// result
299
		$table = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
300
		$catid = intval($catid);
301
		$sql = "SELECT title FROM $table
302
		        WHERE id = $catid  AND c_id = $courseId";
303
		$res = Database::query($sql);
304
		$data = Database::fetch_array($res);
305
		if (Database::num_rows($res) > 0) {
306
			$result = $data['title'];
307
		}
308
309
		return $result;
310
	}
311
312
	/**
313
	 * Return the list of differents categories ID for a test in the current course
314
	 * input : test_id
315
	 * return : array of category id (integer)
316
	 * hubert.borderiou 07-04-2011
317
	 * @param int $exerciseId
318
	 */
319
	public static function getListOfCategoriesIDForTest($exerciseId)
320
    {
321
		// parcourir les questions d'un test, recup les categories uniques dans un tableau
322
		$exercise = new Exercise();
323
		$exercise->read($exerciseId, false);
324
		$categoriesInExercise = $exercise->getQuestionWithCategories();
325
		// the array given by selectQuestionList start at indice 1 and not at indice 0 !!! ???
326
		$categories = array();
327
        if (!empty($categoriesInExercise)) {
328
			foreach ($categoriesInExercise as $category) {
329
				//$category['id'] = $category['iid'];
330
				$categories[$category['id']] = $category;
331
			}
332
		}
333
334
		return $categories;
335
	}
336
337
	/**
338
	 * @param Exercise $exercise_obj
339
	 * @return array
340
	 */
341
	public static function getListOfCategoriesIDForTestObject(Exercise $exercise_obj)
342
	{
343
		// parcourir les questions d'un test, recup les categories uniques dans un tableau
344
		$categories_in_exercise = array();
345
		// $question_list = $exercise_obj->getQuestionList();
346
		$question_list = $exercise_obj->getQuestionOrderedListByName();
347
348
		// the array given by selectQuestionList start at indice 1 and not at indice 0 !!! ???
349
		foreach ($question_list as $questionInfo) {
350
			$question_id = $questionInfo['question_id'];
351
			$category_list = self::getCategoryForQuestion($question_id);
352
			if (is_numeric($category_list)) {
353
				$category_list = array($category_list);
354
			}
355
356
			if (!empty($category_list)) {
357
				$categories_in_exercise = array_merge($categories_in_exercise, $category_list);
358
			}
359
		}
360
		if (!empty($categories_in_exercise)) {
361
			$categories_in_exercise = array_unique(array_filter($categories_in_exercise));
362
		}
363
		return $categories_in_exercise;
364
	}
365
366
	/**
367
	 * Return the list of differents categories NAME for a test
368
	 * @param int exercise id
369
	 * @param bool
370
	 * @return array of string
371
	 *
372
     * @author function rewrote by jmontoya
373
	 */
374
	public static function getListOfCategoriesNameForTest($exercise_id, $grouped_by_category = true)
375
    {
376
		$result = array();
377
		$categories = self::getListOfCategoriesIDForTest($exercise_id, $grouped_by_category);
378
379
		foreach ($categories as $catInfo) {
380
			$categoryId = $catInfo['id'];
381
			if (!empty($categoryId)) {
382
				$result[$categoryId] = array(
383
                    'title' => $catInfo['title'],
384
                    //'parent_id' =>  $catInfo['parent_id'],
385
					'parent_id' => '',
386
                    'c_id' => $catInfo['c_id']
387
                );
388
		}
389
		}
390
391
		return $result;
392
	}
393
394
	/**
395
	 * @param Exercise $exercise_obj
396
	 * @return array
397
	 */
398
	public static function getListOfCategoriesForTest(Exercise $exercise_obj)
399
	{
400
		$result = array();
401
		$categories = self::getListOfCategoriesIDForTestObject($exercise_obj);
402
		foreach ($categories as $cat_id) {
403
			$cat = new TestCategory($cat_id);
404
			$cat = (array)$cat;
405
			$cat['iid'] = $cat['id'];
406
			$cat['title'] = $cat['name'];
407
			$result[$cat['id']] = $cat;
408
		}
409
		return $result;
410
	}
411
412
	/**
413
	 * return the number of differents categories for a test
414
	 * input : test_id
415
	 * return : integer
416
	 * hubert.borderiou 07-04-2011
417
	 */
418
	public static function getNumberOfCategoriesForTest($id)
419
    {
420
		return count(TestCategory::getListOfCategoriesIDForTest($id));
421
	}
422
423
	/**
424
	 * return the number of question of a category id in a test
425
	 * @param int $exerciseId
426
     * @param int $categoryId
427
     *
428
	 * @return integer
429
     *
430
	 * @author hubert.borderiou 07-04-2011
431
	 */
432
	public static function getNumberOfQuestionsInCategoryForTest($exerciseId, $categoryId)
433
    {
434
		$nbCatResult = 0;
435
		$quiz = new Exercise();
436
		$quiz->read($exerciseId);
437
		$tabQuestionList = $quiz->selectQuestionList();
438
		// the array given by selectQuestionList start at indice 1 and not at indice 0 !!! ? ? ?
439
		for ($i=1; $i <= count($tabQuestionList); $i++) {
440
			if (TestCategory::getCategoryForQuestion($tabQuestionList[$i]) == $categoryId) {
441
				$nbCatResult++;
442
			}
443
		}
444
445
		return $nbCatResult;
446
	}
447
448
	/**
449
	 * return the number of question for a test using random by category
450
	 * input  : test_id, number of random question (min 1)
451
	 * hubert.borderiou 07-04-2011
452
	 * question without categories are not counted
453
	 */
454
	public static function getNumberOfQuestionRandomByCategory($exerciseId, $in_nbrandom)
455
    {
456
		$nbquestionresult = 0;
457
		$tabcatid = TestCategory::getListOfCategoriesIDForTest($exerciseId);
458
		for ($i=0; $i < count($tabcatid); $i++) {
459
			if ($tabcatid[$i] > 0 && $tabcatid[$i] > 0) {	// 0 = no category for this questio
460
				$nbQuestionInThisCat = TestCategory::getNumberOfQuestionsInCategoryForTest($exerciseId, $tabcatid[$i]);
461
				if ($nbQuestionInThisCat > $in_nbrandom) {
462
					$nbquestionresult += $in_nbrandom;
463
				}
464
				else {
465
					$nbquestionresult += $nbQuestionInThisCat;
466
				}
467
			}
468
		}
469
470
		return $nbquestionresult;
471
	}
472
473
	/**
474
	 * Return an array (id=>name)
475
	 * tabresult[0] = get_lang('NoCategory');
476
     *
477
     * @param int $courseId
478
     *
479
     * @return array
480
	 *
481
	 */
482
    public static function getCategoriesIdAndName($courseId = "")
483
    {
484
		if (empty($courseId)) {
485
			$courseId = api_get_course_int_id();
486
		}
487
	 	$tabcatobject = TestCategory::getCategoryListInfo("", $courseId);
488
	 	$tabresult = array("0"=>get_lang('NoCategorySelected'));
489
	 	for ($i=0; $i < count($tabcatobject); $i++) {
490
	 		$tabresult[$tabcatobject[$i]->id] = $tabcatobject[$i]->name;
491
	 	}
492
	 	return $tabresult;
493
	}
494
495
    /**
496
     * Returns an array of question ids for each category
497
     * $categories[1][30] = 10, array with category id = 1 and question_id = 10
498
     * A question has "n" categories
499
     * @param int exercise
500
     * @param array $check_in_question_list
501
     * @param array $categoriesAddedInExercise
502
    *
503
    * @param int $exerciseId
504
    * @return array
505
    */
506
    static function getQuestionsByCat(
507
        $exerciseId,
508
        $check_in_question_list = array(),
509
        $categoriesAddedInExercise = array()
510
    ) {
511
        $tableQuestion = Database::get_course_table(TABLE_QUIZ_QUESTION);
512
        $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
513
        $TBL_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
514
        $categoryTable = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
515
        $exerciseId = intval($exerciseId);
516
        $courseId = api_get_course_int_id();
517
518
        $sql = "SELECT DISTINCT qrc.question_id, qrc.category_id
519
                FROM $TBL_QUESTION_REL_CATEGORY qrc
520
                INNER JOIN $TBL_EXERCICE_QUESTION eq
521
                ON (eq.question_id = qrc.question_id)
522
                INNER JOIN $categoryTable c
523
                ON (c.id = qrc.category_id)
524
                INNER JOIN $tableQuestion q
525
                ON (q.id = qrc.question_id )
526
                WHERE
527
                  exercice_id = $exerciseId AND
528
                  qrc.c_id = ".$courseId."
529
                ";
530
531
        $res = Database::query($sql);
532
        $categories = array();
533
        while ($data = Database::fetch_array($res)) {
534
            if (!empty($check_in_question_list)) {
535
                if (!in_array($data['question_id'], $check_in_question_list)) {
536
                    continue;
537
                }
538
            }
539
540
            if (!isset($categories[$data['category_id']]) ||
541
                !is_array($categories[$data['category_id']])
542
            ) {
543
                $categories[$data['category_id']] = array();
544
            }
545
546
            $categories[$data['category_id']][] = $data['question_id'];
547
        }
548
549
        if (!empty($categoriesAddedInExercise)) {
550
            $newCategoryList = array();
551
            foreach ($categoriesAddedInExercise as $category) {
552
                $categoryId = $category['category_id'];
553
                if (isset($categories[$categoryId])) {
554
                    $newCategoryList[$categoryId] = $categories[$categoryId];
555
                }
556
            }
557
558
            $checkQuestionsWithNoCategory = false;
559
            foreach ($categoriesAddedInExercise as $category) {
560
                if (empty($category['category_id'])) {
561
                    // Check
562
                    $checkQuestionsWithNoCategory = true;
563
                    break;
564
                }
565
            }
566
567
            // Select questions that don't have any category related
568
            if ($checkQuestionsWithNoCategory) {
569
                $originalQuestionList = $check_in_question_list;
570
                foreach ($originalQuestionList as $questionId) {
571
                    $categoriesFlatten = array_flatten($categories);
572
                    if (!in_array($questionId, $categoriesFlatten)) {
573
                        $newCategoryList[0][] = $questionId;
574
                    }
575
                }
576
            }
577
578
            $categories = $newCategoryList;
579
580
        }
581
582
        return $categories;
583
	}
584
585
	/**
586
	 * return a tab of $in_number random elements of $in_tab
587
	 */
588
    public static function getNElementsFromArray($in_tab, $in_number)
589
    {
590
		$tabres = $in_tab;
591
		shuffle($tabres);
592
		if ($in_number < count($tabres)) {
593
			$tabres = array_slice($tabres, 0, $in_number);
594
		}
595
		return $tabres;
596
	}
597
598
	/**
599
	 * display the category
600
	 */
601
	public static function displayCategoryAndTitle($questionId, $in_display_category_name = 1)
602
    {
603
        echo self::returnCategoryAndTitle($questionId, $in_display_category_name);
604
	}
605
606
    /**
607
     * @param int $questionId
608
     * @param int $in_display_category_name
609
     * @return null|string
610
     */
611
    public static function returnCategoryAndTitle($questionId, $in_display_category_name = 1)
612
    {
613
        $is_student = !(api_is_allowed_to_edit(null,true) || api_is_session_admin());
614
        // @todo fix $_SESSION['objExercise']
615
        $objExercise = isset($_SESSION['objExercise']) ? $_SESSION['objExercise'] : null;
616
        if (!empty($objExercise)) {
617
            $in_display_category_name = $objExercise->display_category_name;
618
        }
619
        $content = null;
620
		if (TestCategory::getCategoryNameForQuestion($questionId) != "" && ($in_display_category_name == 1 || !$is_student)) {
621
            $content .= '<div class="page-header">';
622
            $content .= '<h4>'.get_lang('Category').": ".TestCategory::getCategoryNameForQuestion($questionId).'</h4>';
623
            $content .= "</div>";
624
		}
625
        return $content;
626
	}
627
628
    /**
629
    * Display signs [+] and/or (>0) after question title if question has options
630
    * scoreAlwaysPositive and/or uncheckedMayScore
631
    */
632
    public function displayQuestionOption($in_objQuestion)
633
    {
634
		if ($in_objQuestion->type == MULTIPLE_ANSWER && $in_objQuestion->scoreAlwaysPositive) {
635
			echo "<span style='font-size:75%'> (>0)</span>";
636
		}
637
		if ($in_objQuestion->type == MULTIPLE_ANSWER && $in_objQuestion->uncheckedMayScore) {
638
			echo "<span style='font-size:75%'> [+]</span>";
639
		}
640
	}
641
642
	/**
643
	 * sortTabByBracketLabel ($tabCategoryQuestions)
644
	 * key of $tabCategoryQuestions are the category id (0 for not in a category)
645
	 * value is the array of question id of this category
646
	 * Sort question by Category
647
	*/
648
    public static function sortTabByBracketLabel($in_tab)
649
    {
650
		$tabResult = array();
651
		$tabCatName = array();	// tab of category name
652
		while (list($cat_id, $tabquestion) = each($in_tab)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $tabquestion is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
653
			$catTitle = new TestCategory($cat_id);
654
			$tabCatName[$cat_id] = $catTitle->name;
655
		}
656
		reset($in_tab);
657
		// sort table by value, keeping keys as they are
658
		asort($tabCatName);
659
		// keys of $tabCatName are keys order for $in_tab
660
		while (list($key, $val) = each($tabCatName)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $val is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
661
			$tabResult[$key] = $in_tab[$key];
662
		}
663
		return $tabResult;
664
	}
665
666
    /**
667
	 * return total score for test exe_id for all question in the category $in_cat_id for user
668
	 * If no question for this category, return ""
669
	 */
670 View Code Duplication
	public static function getCatScoreForExeidForUserid($in_cat_id, $in_exe_id, $in_user_id)
671
	{
672
		$tbl_track_attempt		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
673
		$tbl_question_rel_category = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
674
		$in_cat_id = intval($in_cat_id);
675
		$in_exe_id = intval($in_exe_id);
676
		$in_user_id = intval($in_user_id);
677
678
		$query = "SELECT DISTINCT
679
		            marks, exe_id, user_id, ta.question_id, category_id
680
                  FROM $tbl_track_attempt ta , $tbl_question_rel_category qrc
681
                  WHERE
682
                    ta.question_id=qrc.question_id AND
683
                    qrc.category_id=$in_cat_id AND
684
                    exe_id=$in_exe_id AND user_id=$in_user_id";
685
		$res = Database::query($query);
686
		$totalcatscore = "";
687
		while ($data = Database::fetch_array($res)) {
688
			$totalcatscore += $data['marks'];
689
		}
690
		return $totalcatscore;
691
	}
692
693
	/**
694
     * return the number max of question in a category
695
     * count the number of questions in all categories, and return the max
696
     * @param int $exerciseId
697
     * @author - hubert borderiou
698
    */
699
    public static function getNumberMaxQuestionByCat($exerciseId)
700
    {
701
        $res_num_max = 0;
702
        // foreach question
703
		$tabcatid = TestCategory::getListOfCategoriesIDForTest($exerciseId);
704
		for ($i=0; $i < count($tabcatid); $i++) {
705
			if ($tabcatid[$i] > 0) {	// 0 = no category for this question
706
				$nbQuestionInThisCat = TestCategory::getNumberOfQuestionsInCategoryForTest($exerciseId, $tabcatid[$i]);
707
                if ($nbQuestionInThisCat > $res_num_max) {
708
                    $res_num_max = $nbQuestionInThisCat;
709
                }
710
			}
711
		}
712
        return $res_num_max;
713
    }
714
715
    /**
716
     * Returns a category summary report
717
     * @params int exercise id
718
     * @params array pre filled array with the category_id, score, and weight
719
     * example: array(1 => array('score' => '10', 'total' => 20));
720
     */
721
    public static function get_stats_table_by_attempt($exercise_id, $category_list = array())
722
    {
723
        if (empty($category_list)) {
724
            return null;
725
        }
726
        $category_name_list = TestCategory::getListOfCategoriesNameForTest($exercise_id);
727
728
        $table = new HTML_Table(array('class' => 'data_table'));
729
        $table->setHeaderContents(0, 0, get_lang('Categories'));
730
        $table->setHeaderContents(0, 1, get_lang('AbsoluteScore'));
731
        $table->setHeaderContents(0, 2, get_lang('RelativeScore'));
732
        $row = 1;
733
734
        $none_category = array();
735
        if (isset($category_list['none'])) {
736
            $none_category = $category_list['none'];
737
            unset($category_list['none']);
738
        }
739
740
        $total = array();
741
        if (isset($category_list['total'])) {
742
            $total = $category_list['total'];
743
            unset($category_list['total']);
744
        }
745
        if (count($category_list) > 1) {
746
            foreach ($category_list as $category_id => $category_item) {
747
                $table->setCellContents($row, 0, $category_name_list[$category_id]);
748
                $table->setCellContents($row, 1, ExerciseLib::show_score($category_item['score'], $category_item['total'], false));
749
                $table->setCellContents($row, 2, ExerciseLib::show_score($category_item['score'], $category_item['total'], true, false, true));
750
                $row++;
751
            }
752
753 View Code Duplication
            if (!empty($none_category)) {
754
                $table->setCellContents($row, 0, get_lang('None'));
755
                $table->setCellContents($row, 1, ExerciseLib::show_score($none_category['score'], $none_category['total'], false));
756
                $table->setCellContents($row, 2, ExerciseLib::show_score($none_category['score'], $none_category['total'], true, false, true));
757
                $row++;
758
            }
759 View Code Duplication
            if (!empty($total)) {
760
                $table->setCellContents($row, 0, get_lang('Total'));
761
                $table->setCellContents($row, 1, ExerciseLib::show_score($total['score'], $total['total'], false));
762
                $table->setCellContents($row, 2, ExerciseLib::show_score($total['score'], $total['total'], true, false, true));
763
            }
764
            return $table->toHtml();
765
        }
766
767
        return null;
768
    }
769
770
    /**
771
	 * @return array
772
	 */
773 View Code Duplication
	function get_all_categories()
774
	{
775
		$table = Database::get_course_table(TABLE_QUIZ_CATEGORY);
776
		$sql = "SELECT * FROM $table ORDER BY title ASC";
777
		$res = Database::query($sql);
778
		while ($row = Database::fetch_array($res,'ASSOC')) {
779
			$array[] = $row;
780
		}
781
		return $array;
782
	}
783
784
	/**
785
	 * @param Exercise $exercise
786
	 * @param int $course_id
787
	 * @param string $order
788
	 * @param bool $shuffle
789
	 * @param bool $excludeCategoryWithNoQuestions
790
	 * @return array|bool
791
	 */
792
	public function getCategoryExerciseTree(
793
		$exercise,
794
		$course_id,
795
		$order = null,
796
		$shuffle = false,
797
		$excludeCategoryWithNoQuestions = true
798
	) {
799
        if (empty($exercise)) {
800
            return array();
801
        }
802
803
        if (!$exercise->specialCategoryOrders) {
804
            return false;
805
        }
806
807
        $course_id = intval($course_id);
808
		$table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
809
        $categoryTable = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
810
		$sql = "SELECT * FROM $table qc
811
              	LEFT JOIN $categoryTable c
812
                ON (qc.c_id = c.c_id AND c.id = qc.category_id)
813
                WHERE qc.c_id = $course_id AND exercise_id = {$exercise->id} ";
814
815
		if (!empty($order)) {
816
			$sql .= "ORDER BY $order";
817
		}
818
819
		$categories = array();
820
821
		$result = Database::query($sql);
822
		if (Database::num_rows($result)) {
823
			while ($row = Database::fetch_array($result, 'ASSOC')) {
824
				if ($excludeCategoryWithNoQuestions) {
825
					if ($row['count_questions'] == 0) {
826
						continue;
827
					}
828
				}
829
				if (empty($row['title']) && empty($row['category_id'])) {
830
					$row['title'] = get_lang('NoCategory');
831
				}
832
                $categories[$row['category_id']] = $row;
833
			}
834
		}
835
836
		if ($shuffle) {
837
			shuffle_assoc($categories);
838
		}
839
840
		return $categories;
841
	}
842
843
	public function getForm(& $form, $action = 'new')
844
	{
845
		switch($action) {
846
			case 'new':
847
				$header = get_lang('AddACategory');
848
				$submit = get_lang('AddTestCategory');
849
				break;
850
			case 'edit':
851
				$header = get_lang('EditCategory');
852
				$submit = get_lang('ModifyCategory');
853
				break;
854
		}
855
856
		// settting the form elements
857
		$form->addElement('header', $header);
858
		$form->addElement('hidden', 'category_id');
859
		$form->addElement('text', 'category_name', get_lang('CategoryName'), array('class' => 'span6'));
860
		$form->add_html_editor('category_description', get_lang('CategoryDescription'), false, false, array('ToolbarSet' => 'test_category', 'Width' => '90%', 'Height' => '200'));
861
		$category_parent_list = array();
862
863
		$options = array(
864
				'1' => get_lang('Visible'),
865
				'0' => get_lang('Hidden')
866
		);
867
		$form->addElement('select', 'visibility', get_lang('Visibility'), $options);
868
		$script = null;
869
		if (!empty($this->parent_id)) {
870
			$parent_cat = new TestCategory($this->parent_id);
871
			$category_parent_list = array($parent_cat->id => $parent_cat->name);
872
			$script .= '<script>$(function() { $("#parent_id").trigger("addItem",[{"title": "'.$parent_cat->name.'", "value": "'.$parent_cat->id.'"}]); });</script>';
873
		}
874
		$form->addElement('html', $script);
875
876
		$form->addElement('select', 'parent_id', get_lang('Parent'), $category_parent_list, array('id' => 'parent_id'));
877
		$form->addElement('style_submit_button', 'SubmitNote', $submit, 'class="add"');
878
879
		// setting the defaults
880
		$defaults = array();
881
		$defaults["category_id"] = $this->id;
882
		$defaults["category_name"] = $this->name;
883
		$defaults["category_description"] = $this->description;
884
		$defaults["parent_id"] = $this->parent_id;
885
		$defaults["visibility"] = $this->visibility;
886
		$form->setDefaults($defaults);
887
888
		// setting the rules
889
		$form->addRule('category_name', get_lang('ThisFieldIsRequired'), 'required');
890
	}
891
892
	/**
893
	 * Returns the category form.
894
	 * @param Exercise $exercise_obj
895
	 * @return string
896
	 */
897
	public function returnCategoryForm(Exercise $exercise_obj)
898
	{
899
		$categories = $this->getListOfCategoriesForTest($exercise_obj);
900
901
		$saved_categories = $exercise_obj->get_categories_in_exercise();
902
		$return = null;
903
904
		if (!empty($categories)) {
905
			$nbQuestionsTotal = $exercise_obj->getNumberQuestionExerciseCategory();
906
			$exercise_obj->setCategoriesGrouping(true);
907
			$real_question_count = count($exercise_obj->getQuestionList());
908
909
			$warning = null;
910
			if ($nbQuestionsTotal != $real_question_count) {
911
				$warning = Display::return_message(get_lang('CheckThatYouHaveEnoughQuestionsInYourCategories'), 'warning');
912
			}
913
914
			$return .= $warning;
915
			$return .= '<table class="data_table">';
916
			$return .= '<tr>';
917
			$return .= '<th height="24">' . get_lang('Categories') . '</th>';
918
			$return .= '<th width="70" height="24">' . get_lang('Number') . '</th></tr>';
919
920
			$emptyCategory = array(
921
				'id' => '0',
922
				'name' => get_lang('NoCategory'),
923
				'description' => '',
924
				'iid' => '0',
925
				'title' => get_lang('NoCategory')
926
			);
927
928
			$categories[] = $emptyCategory;
929
930
			foreach ($categories as $category) {
931
				$cat_id = $category['iid'];
932
				$return .= '<tr>';
933
				$return .= '<td>';
934
				//$return .= Display::div(isset($category['parent_path']) ? $category['parent_path'] : '');
935
				$return .= Display::div($category['name']);
936
				$return .= '</td>';
937
				$return .= '<td>';
938
				$value = isset($saved_categories) && isset($saved_categories[$cat_id]) ? $saved_categories[$cat_id]['count_questions'] : -1;
939
				$return .= '<input name="category['.$cat_id.']" value="' .$value.'" />';
940
				$return .= '</td>';
941
				$return .= '</tr>';
942
			}
943
944
			$return .= '</table>';
945
			$return .= get_lang('ZeroMeansNoQuestionWillBeSelectedMinusOneMeansThatAllQuestionsWillBeSelected');
946
			return $return;
947
		}
948
	}
949
950
	/**
951
	 * Sorts an array
952
	 * @param $array
953
	 * @return mixed
954
	 */
955
	public function sort_tree_array($array)
956
	{
957
		foreach ($array as $key => $row) {
958
			$parent[$key] = $row['parent_id'];
959
		}
960
		if (count($array) > 0) {
961
			array_multisort($parent, SORT_ASC, $array);
962
		}
963
		return $array;
964
	}
965
966
	/**
967
     * Return true if a category already exists with the same name
968
     * @param string $in_name
969
     *
970
     * @return bool
971
     */
972
    public static function category_exists_with_title($in_name)
973
    {
974
        $tab_test_category = TestCategory::getCategoryListInfo("title");
975
        foreach ($tab_test_category as $title) {
976
            if ($title == $in_name) {
977
                return true;
978
            }
979
        }
980
        return false;
981
    }
982
983
    /**
984
     * Return the id of the test category with title = $in_title
985
     * @param $in_title
986
     * @param int $in_c_id
0 ignored issues
show
Bug introduced by
There is no parameter named $in_c_id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
987
     *
988
     * @return int is id of test category
989
     */
990 View Code Duplication
    public static function get_category_id_for_title($title, $courseId = 0)
991
    {
992
        $out_res = 0;
993
        if (empty($courseId)) {
994
            $courseId = api_get_course_int_id();
995
        }
996
        $courseId = intval($courseId);
997
        $tbl_cat = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
998
        $sql = "SELECT id FROM $tbl_cat
999
                WHERE c_id = $courseId AND title = '".Database::escape_string($title)."'";
1000
        $res = Database::query($sql);
1001
        if (Database::num_rows($res) > 0) {
1002
            $data = Database::fetch_array($res);
1003
            $out_res = $data['id'];
1004
        }
1005
        return $out_res;
1006
    }
1007
1008
    /**
1009
     * Add a relation between question and category in table c_quiz_question_rel_category
1010
     * @param int $categoryId
1011
     * @param int $questionId
1012
     * @param int $courseId
1013
	 *
1014
	 * @return int
1015
     */
1016
    public static function add_category_for_question_id($categoryId, $questionId, $courseId)
1017
    {
1018
        $table = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
1019
        // if question doesn't have a category
1020
        // @todo change for 1.10 when a question can have several categories
1021
        if (TestCategory::getCategoryForQuestion($questionId, $courseId) == 0 &&
1022
			$questionId > 0 &&
1023
			$courseId > 0
1024
        ) {
1025
            $sql = "INSERT INTO $table (c_id, question_id, category_id)
1026
                    VALUES (".intval($courseId).", ".intval($questionId).", ".intval($categoryId).")";
1027
            Database::query($sql);
1028
			$id = Database::insert_id();
1029
1030
			return $id;
1031
        }
1032
1033
		return false;
1034
    }
1035
1036
    /**
1037
     * @param int $courseId
1038
     * @param int $sessionId
1039
     *
1040
     * @return array
1041
     */
1042
    public function getCategories($courseId, $sessionId = 0)
1043
    {
1044
        $table = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
1045
        $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
1046
        $sessionId = intval($sessionId);
1047
        $courseId = intval($courseId);
1048
1049
        if (empty($sessionId)) {
1050
            $sessionCondition = api_get_session_condition($sessionId, true, false, 'i.session_id');
1051
        } else {
1052
            $sessionCondition = api_get_session_condition($sessionId, true, true, 'i.session_id');
1053
        }
1054
1055
        if (empty($courseId)) {
1056
            return array();
1057
        }
1058
1059
        $sql = "SELECT c.* FROM $table c
1060
                INNER JOIN $itemProperty i
1061
                ON c.c_id = i.c_id AND i.ref = c.id
1062
                WHERE
1063
                    c.c_id = $courseId AND
1064
                    i.tool = '".TOOL_TEST_CATEGORY."'
1065
                    $sessionCondition
1066
                ORDER BY title";
1067
        $result = Database::query($sql);
1068
1069
        return Database::store_result($result, 'ASSOC');
1070
    }
1071
1072
    /**
1073
     * @param int $courseId
1074
     * @param int $sessionId
1075
     * @return string
1076
     */
1077
    public function displayCategories($courseId, $sessionId = 0)
1078
    {
1079
        $categories = $this->getCategories($courseId, $sessionId);
1080
        $html = '';
1081
1082
        foreach ($categories as $category) {
1083
            $tmpobj = new TestCategory($category['id']);
1084
            $nb_question = $tmpobj->getCategoryQuestionsNumber();
1085
            $rowname = self::protectJSDialogQuote($category['title']);
1086
            $nb_question_label = $nb_question == 1 ? $nb_question . ' ' . get_lang('Question') : $nb_question . ' ' . get_lang('Questions');
1087
1088
            //$html .= '<div class="sectiontitle" id="id_cat' . $category['id'] . '">';
1089
            $content = "<span style='float:right'>" . $nb_question_label . "</span>";
1090
1091
            $content .= '<div class="sectioncomment">';
1092
            $content .= $category['description'];
1093
            $content .= '</div>';
1094
1095
            $links = '<a href="' . api_get_self() . '?action=editcategory&category_id=' . $category['id'] . '">' .
1096
                Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL) . '</a>';
1097
            $links .= ' <a href="' . api_get_self() . '?action=deletecategory&category_id=' . $category['id'] . '" ';
1098
            $links .= 'onclick="return confirmDelete(\'' . self::protectJSDialogQuote(get_lang('DeleteCategoryAreYouSure') . '[' . $rowname) . '] ?\', \'id_cat' . $category['id'] . '\');">';
1099
            $links .= Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
1100
            $html .= Display::panel($content, $category['title'].$links);
1101
        }
1102
1103
        return $html;
1104
    }
1105
1106
    // To allowed " in javascript dialog box without bad surprises
1107
    // replace " with two '
1108
    public function protectJSDialogQuote($in_txt)
1109
    {
1110
        $res = $in_txt;
1111
        $res = str_replace("'", "\'", $res);
1112
        $res = str_replace('"', "\'\'", $res); // super astuce pour afficher les " dans les boite de dialogue
1113
        return $res;
1114
    }
1115
}
1116